@ractive-ch/tab-mcp-client 0.16.2 → 0.18.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.
- package/CHANGELOG.md +898 -0
- package/README.md +216 -90
- package/address.d.ts +8 -8
- package/allowed.d.ts +28 -0
- package/allowed.js +14 -0
- package/allowed.js.map +10 -0
- package/always-allowed.d.ts +140 -22
- package/cdn/allowed.min.js +4 -0
- package/cdn/allowed.min.js.map +10 -0
- package/cdn/confirm-f36n8xj5.min.js +4 -0
- package/cdn/confirm-f36n8xj5.min.js.map +10 -0
- package/cdn/connect-ph4xxen4.min.js +6 -0
- package/cdn/connect-ph4xxen4.min.js.map +12 -0
- package/cdn/{connection-w97tf22a.min.js → connection-0xqwz17v.min.js} +7 -7
- package/cdn/{connection-w97tf22a.min.js.map → connection-0xqwz17v.min.js.map} +5 -5
- package/cdn/{index-vt5zk9me.min.js → tab-mcp-client-2vx9mcww.min.js} +20 -9
- package/cdn/tab-mcp-client-2vx9mcww.min.js.map +12 -0
- package/cdn/tab-mcp-client-6gcmd7n8.min.js +5 -0
- package/cdn/tab-mcp-client-6gcmd7n8.min.js.map +10 -0
- package/cdn/tab-mcp-client.min.js +3 -3
- package/cdn/tab-mcp-client.min.js.map +4 -4
- package/{confirm-fgnjgd08.js → confirm-jbyqzy14.js} +29 -19
- package/confirm-jbyqzy14.js.map +10 -0
- package/confirm.d.ts +27 -20
- package/{connect-8jpb0k29.js → connect-13hkdpcx.js} +113 -16
- package/connect-13hkdpcx.js.map +10 -0
- package/connect.d.ts +2 -2
- package/{connection-g91xjjgm.js → connection-gang7f5x.js} +10 -23
- package/{connection-g91xjjgm.js.map → connection-gang7f5x.js.map} +5 -5
- package/connection.d.ts +2 -2
- package/dialog.d.ts +1 -1
- package/{index-jnz7w9xa.js → index-c1c266tm.js} +36 -98
- package/index-c1c266tm.js.map +11 -0
- package/index-dmh5vm5m.js.map +1 -1
- package/index-h8b3dc5p.js +245 -0
- package/index-h8b3dc5p.js.map +10 -0
- package/index.js +33 -22
- package/index.js.map +4 -4
- package/internal.d.ts +2 -0
- package/package.json +7 -2
- package/protocol.d.ts +6 -7
- package/react.d.ts +19 -0
- package/react.js +30 -1
- package/react.js.map +3 -3
- package/secret.d.ts +6 -0
- package/strings.d.ts +13 -4
- package/tab-mcp.d.ts +15 -5
- package/types.d.ts +32 -9
- package/visible.d.ts +1 -1
- package/cdn/confirm-y30cx7e1.min.js +0 -4
- package/cdn/confirm-y30cx7e1.min.js.map +0 -10
- package/cdn/connect-bbhj2y7w.min.js +0 -6
- package/cdn/connect-bbhj2y7w.min.js.map +0 -12
- package/cdn/index-vt5zk9me.min.js.map +0 -13
- package/confirm-fgnjgd08.js.map +0 -10
- package/connect-8jpb0k29.js.map +0 -10
- package/index-jnz7w9xa.js.map +0 -12
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var C={lang:"en",dir:"ltr",and:"and",confirmTitle:"Allow {tool}?",confirmWho:"{client} wants to run {tool}.",deny:"Don't allow",allow:"Allow",alwaysAllow:"Always allow",alwaysAllowNote:"Always allow: {tool} will run for {client} without asking, with any arguments, until you disconnect {client} from this page.",allowUntilReload:"Allow until reload",allowUntilReloadNote:"Allow until reload: {tool} will run for {client} without asking, with any arguments, until you reload this page or disconnect {client}.",argumentsHidden:"The arguments cannot be shown, so this call cannot be allowed.",scrollToAllow:"Scroll to the end of the arguments to allow this call.",waitingOne:"1 more call is waiting after this one.",waitingMany:"{n} more calls are waiting after this one.",titlePrefix:"Allow? – ",clientWebMcp:"An agent in this browser",clientLocal:"{name} (this site's assistant)",clientRelay:"{name} ({host})",copy:"Copy",copied:"Copied",pressMac:"Press ⌘C",pressOther:"Press Ctrl+C",selected:"Selected",copyAddress:"Copy address",copyCode:"Copy code",copyCommand:"Copy {app} command",connectTitle:"Connect your AI app",connecting:"Connecting…",connectAgain:"Connect again",reconnecting:"Connection lost. Reconnecting…",notConnected:"Not connected.",unreachable:"Could not connect. Check your internet connection.",rateLimited:"Too many attempts. Wait a minute, then connect again.",refused:"The connection was refused.",ended:"The session ended.",lost:"The connection was lost.",closed:"The connection was closed.",disconnected:"Disconnected.",checkingSignIn:"Checking your sign-in…",signInFirst:"Sign in to this page first.",signInRefused:"Your sign-in on this page was not accepted.",signInRefusedWhy:"Your sign-in on this page was not accepted ({reason}).",readyApp:"{app} is ready for your AI app.",readyPage:"This page is ready for your AI app.",addressLabel:"Add this address to your AI app:",help:"How do I add it?",guide:"Step by step, and what to do when it fails",codeSentence:"When asked, enter the code {code}",codeNote:"A new code appears every 2 minutes and after each use.",codeUsed:"Code used. Waiting for your AI app…",signIn:"When your AI app asks, sign in with the account you use on this page. No code is needed.",newAddress:"Disconnect all apps",newAddressNote:"An AI app is connected that should not be? This disconnects every AI app from this page; each one has to connect again with a new code.",newAddressQuestionOne:"This disconnects {apps}. To use this page with it again, connect it again and enter a new code.",newAddressQuestionMany:"This disconnects {apps}. To use this page with them again, connect them again and enter a new code.",newAddressConfirm:"Disconnect all",cancel:"Cancel",gettingNewAddress:"Disconnecting…",newAddressDone:"Every AI app is disconnected. Connect yours again.",connectedOne:"{apps} is connected",connectedMany:"{apps} are connected",connectedNextOne:"You can close this now and ask it to use the tools of this page.",connectedNextMany:"You can close this now and ask them to use the tools of this page.",connectAnother:"Connect another app",connectedHeading:"Connected",appConnected:"{app} connected",disconnect:"Disconnect",disconnectApp:"Disconnect {app}",disconnectNote:"To disconnect an app, connect this page again first.",storeUnavailable:"The relay could not save this. Try again.",disconnectFailed:"Could not disconnect the app. Try again.",runsWithoutAsking:"Runs without asking",destructive:"destructive",allowToolApp:"{tool} runs without asking for {app}",allowDestructiveToolApp:"{tool} (destructive) runs without asking for {app}",allowEverything:"Allow everything, no questions asked",allowEverythingApp:"Allow everything, no questions asked, for {app}",allowEverythingNote:"Every tool of this page runs for {app} without asking, with any arguments: also tools you have not seen yet and ones that delete or overwrite.",closeNote:"Closing this stops the code. To connect later, open this again from the page.",close:"Close",done:"Done",replacedSiblingTitle:"Opened in another tab",replacedSibling:"This page is open in another tab, and your AI apps now use that one. To use them here, connect this page again.",replacedTitle:"Another tab or program took over this page",replaced:"Your AI apps now reach that tab or program instead of this page. If you did not open this page in another tab or browser, someone may have copied what this page keeps to connect. “Disconnect all apps” ends that; then connect your AI apps again with a new code.",takenOverAgain:"It was taken over again before its AI apps were disconnected. Try again.",tryAgainOrClose:"{reason} Try again, or close this."};var D=/(?![\t\n ])[\p{Cc}\p{Cf}\p{Default_Ignorable_Code_Point}\p{Co}\p{Cn}\p{Cs}\p{Zl}\p{Zp}\p{Zs}\u{2800}]/gu;function T(r){return r.replace(D,(p)=>{let m="";for(let g=0;g<p.length;g++)m+=`\\u${p.charCodeAt(g).toString(16).toUpperCase().padStart(4,"0")}`;return m})}var I=0;function i(){return`tab-mcp-${++I}`}function a(r){let p={...C};for(let[m,g]of Object.entries(r?.strings??{}))if(typeof g==="string"&&m in p)p[m]=g;return p}function t(r,p){return r.replace(/\{(\w+)\}/g,(m,g)=>p[g]??m)}function o(r,p,m){return p.split(/\{(\w+)\}/).map((g,h)=>{if(h%2===0)return g;let b=m[g];if(b===void 0)return`{${g}}`;return typeof b==="string"?N(r,b):b})}function e(r,p,m={},...g){let h=r.createElement(p);if(m.className!==void 0)h.className=m.className;if(m.id!==void 0)h.id=m.id;if(m.text!==void 0)h.textContent=m.text;return h.append(...g),h}function n(r,p,m,g,h){let b=e(r,"button",{text:p});if(b.type="button",g!==void 0)b.classList.add(g);if(h!==void 0)b.classList.add(`tab-mcp-${h}`);return b.addEventListener("click",m),b}function N(r,p){let m=e(r,"bdi",{text:p});return m.dir="ltr",m}var s=T;function d(r,p){if("kind"in r&&r.kind==="webmcp")return p.clientWebMcp;if("kind"in r&&r.kind==="local")return t(p.clientLocal,{name:s(r.name??r.id)});let m=s(r.host||r.id);return r.name!==void 0&&r.name!==""?t(p.clientRelay,{name:s(r.name),host:m}):m}function u(r,p){return r.length<2?r[0]??"":`${r.slice(0,-1).join(", ")} ${p.and} ${r.at(-1)}`}var M=`.tab-mcp-dialog {
|
|
2
2
|
--_tab-mcp-fg: var(--tab-mcp-color, CanvasText);
|
|
3
3
|
--_tab-mcp-bg: var(--tab-mcp-background, Canvas);
|
|
4
4
|
--_tab-mcp-muted: var(--tab-mcp-muted, color-mix(in srgb, var(--_tab-mcp-fg) 72%, transparent));
|
|
@@ -24,7 +24,7 @@ html dialog.tab-mcp-dialog:where(:focus) { outline: none; }
|
|
|
24
24
|
.tab-mcp-dialog :where(h2) { font-size: var(--tab-mcp-title-size, 1.25em); line-height: 1.3; font-weight: 600; overflow-wrap: anywhere; }
|
|
25
25
|
.tab-mcp-dialog :where(h3) { font-size: 0.875em; font-weight: 600; color: var(--_tab-mcp-muted); margin-bottom: 0.5rem; }
|
|
26
26
|
.tab-mcp-dialog :where(small) { font-size: 0.875em; }
|
|
27
|
-
.tab-mcp-dialog :where(small, .tab-mcp-status, .tab-mcp-description, .tab-mcp-always-note, .tab-mcp-apps-note, .tab-mcp-success-next, .tab-mcp-waiting, .tab-mcp-scroll-note
|
|
27
|
+
.tab-mcp-dialog :where(small, .tab-mcp-status, .tab-mcp-description, .tab-mcp-always-note, .tab-mcp-apps-note, .tab-mcp-success-next, .tab-mcp-waiting, .tab-mcp-scroll-note) { color: var(--_tab-mcp-muted); }
|
|
28
28
|
html dialog.tab-mcp-dialog :where(:focus-visible) { outline: 2px solid var(--tab-mcp-focus, var(--_tab-mcp-fg)); outline-offset: 2px; }
|
|
29
29
|
.tab-mcp-dialog :where(button) { font: inherit; font-size: 0.9375em; line-height: 1.25; text-transform: none; letter-spacing: normal; width: auto; min-height: 2.5rem; padding: 0.5rem 1rem; margin: 0; border: 1px solid color-mix(in srgb, currentColor 35%, transparent); border-radius: var(--_tab-mcp-small-radius); background: transparent; color: inherit; cursor: pointer; }
|
|
30
30
|
html dialog.tab-mcp-dialog :where(button:hover:not(:disabled)) { color: inherit; background: color-mix(in srgb, currentColor 8%, transparent); }
|
|
@@ -59,7 +59,18 @@ html button.tab-mcp-danger { color: var(--_tab-mcp-danger); border-color: color-
|
|
|
59
59
|
.tab-mcp-help :where(code) { font: 0.875em var(--_tab-mcp-mono); padding: 0.125em 0.375em; background: var(--_tab-mcp-surface); border-radius: 0.25rem; -webkit-box-decoration-break: clone; box-decoration-break: clone; }
|
|
60
60
|
.tab-mcp-apps :where(li) { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 0.5rem 0.75rem; padding: 0.5rem 0.5rem 0.5rem 0.75rem; border: 1px solid var(--_tab-mcp-line); border-radius: var(--_tab-mcp-small-radius); }
|
|
61
61
|
.tab-mcp-app { flex: 1 1 10rem; min-width: 0; overflow-wrap: anywhere; }
|
|
62
|
-
.tab-mcp-allowed { display:
|
|
62
|
+
.tab-mcp-allowed { display: grid; flex-basis: 100%; gap: 0.25rem; padding-top: 0.5rem; border-top: 1px solid var(--_tab-mcp-line); font-size: 0.875em; overflow-wrap: anywhere; }
|
|
63
|
+
.tab-mcp-allowed-title { font-weight: 600; color: var(--_tab-mcp-muted); }
|
|
64
|
+
.tab-mcp-switches { display: grid; gap: 0.125rem; }
|
|
65
|
+
.tab-mcp-switch { display: flex; align-items: center; gap: 0.625rem; min-height: 2rem; cursor: pointer; }
|
|
66
|
+
.tab-mcp-switch > :where(input) { appearance: none; -webkit-appearance: none; flex: none; position: relative; width: 2.25rem; height: 1.25rem; margin: 0; padding: 0; border: 1px solid var(--_tab-mcp-line); border-radius: 0.625rem; background: var(--_tab-mcp-surface); cursor: pointer; }
|
|
67
|
+
.tab-mcp-switch > :where(input)::before { content: ""; position: absolute; top: 2px; left: 2px; width: calc(1.25rem - 6px); height: calc(1.25rem - 6px); border-radius: 50%; background: var(--_tab-mcp-muted); }
|
|
68
|
+
.tab-mcp-switch > :where(input:checked) { background: var(--tab-mcp-accent, var(--_tab-mcp-fg)); border-color: transparent; }
|
|
69
|
+
.tab-mcp-switch > :where(input:checked)::before { left: calc(100% - 1.25rem + 4px); background: var(--tab-mcp-accent-text, var(--_tab-mcp-bg)); }
|
|
70
|
+
html dialog.tab-mcp-dialog :where(.tab-mcp-switch > input:disabled) { opacity: 0.45; cursor: not-allowed; }
|
|
71
|
+
.tab-mcp-destructive { color: var(--_tab-mcp-danger); }
|
|
72
|
+
.tab-mcp-everything { font-weight: 600; }
|
|
73
|
+
.tab-mcp-everything-note { color: var(--_tab-mcp-muted); }
|
|
63
74
|
.tab-mcp-apps-note { margin-top: 0.5rem; }
|
|
64
75
|
.tab-mcp-success { display: flex; align-items: center; gap: 0.875rem; padding: 1rem; background: color-mix(in srgb, var(--_tab-mcp-success) 10%, transparent); border: 1px solid color-mix(in srgb, var(--_tab-mcp-success) 45%, transparent); border-radius: var(--_tab-mcp-small-radius); }
|
|
65
76
|
.tab-mcp-success-icon { flex: none; display: grid; place-items: center; width: 2.75rem; height: 2.75rem; border-radius: 50%; font-size: 1.5em; font-weight: 700; line-height: 1; color: var(--_tab-mcp-success); background: color-mix(in srgb, var(--_tab-mcp-success) 16%, transparent); }
|
|
@@ -80,12 +91,12 @@ html button.tab-mcp-danger { color: var(--_tab-mcp-danger); border-color: color-
|
|
|
80
91
|
.tab-mcp-arguments { box-sizing: content-box; font: 0.875em / 1.45 var(--_tab-mcp-mono); padding: 0.75rem; background: var(--_tab-mcp-surface); border: 1px solid var(--_tab-mcp-line); border-radius: var(--_tab-mcp-small-radius); }
|
|
81
92
|
.tab-mcp-always-note, .tab-mcp-waiting, .tab-mcp-scroll-note { font-size: 0.875em; }
|
|
82
93
|
@media (max-width: 30rem) { .tab-mcp-actions > :where(button) { flex: 1 1 auto; } .tab-mcp-connect > :where(.tab-mcp-actions) > :where(button) { flex: 0 0 auto; } .tab-mcp-code { grid-template-columns: minmax(0, 1fr); } .tab-mcp-code > :where(button) { justify-self: start; } }
|
|
83
|
-
@media (prefers-reduced-motion: no-preference) { .tab-mcp-dialog:where([open]) { animation: tab-mcp-in 0.15s ease-out; } .tab-mcp-success-icon { animation: tab-mcp-pop 0.4s cubic-bezier(0.3, 1.4, 0.6, 1); } }
|
|
84
|
-
@media (forced-colors: active) { html button.tab-mcp-primary { border-color: ButtonText; } }
|
|
94
|
+
@media (prefers-reduced-motion: no-preference) { .tab-mcp-dialog:where([open]) { animation: tab-mcp-in 0.15s ease-out; } .tab-mcp-success-icon { animation: tab-mcp-pop 0.4s cubic-bezier(0.3, 1.4, 0.6, 1); } .tab-mcp-switch > :where(input)::before { transition: left 0.15s ease-out; } }
|
|
95
|
+
@media (forced-colors: active) { html button.tab-mcp-primary { border-color: ButtonText; } .tab-mcp-switch > :where(input) { forced-color-adjust: none; background: Canvas; border-color: ButtonText; } .tab-mcp-switch > :where(input)::before { forced-color-adjust: none; background: ButtonText; } .tab-mcp-switch > :where(input:checked) { background: Highlight; } .tab-mcp-switch > :where(input:checked)::before { background: HighlightText; } }
|
|
85
96
|
@keyframes tab-mcp-in { from { opacity: 0; transform: translateY(0.5rem); } }
|
|
86
97
|
@keyframes tab-mcp-pop { from { opacity: 0; transform: scale(0.4); } }
|
|
87
|
-
`,
|
|
88
|
-
export{
|
|
98
|
+
`,A=new WeakMap;function E(r){try{let p=A.get(r);if(p===void 0){let m=r.defaultView?.CSSStyleSheet;if(m===void 0||!Array.isArray(r.adoptedStyleSheets))return;p=new m,p.replaceSync(M),A.set(r,p)}if(!r.adoptedStyleSheets.includes(p))r.adoptedStyleSheets=[...r.adoptedStyleSheets,p]}catch{}}function l(r,p,m,...g){let h=i(),b=e(r,"dialog",{className:`tab-mcp-dialog ${p}`});b.setAttribute("aria-labelledby",`${h}-title`),b.lang=m.lang,b.dir=m.dir,E(r);let y=e(r,"h2",{id:`${h}-title`},...g);return b.append(y),{dialog:b,heading:y,id:h}}var L=2000,z=8000;function O(r,p){let m=r.defaultView;if(m?.matchMedia?.("(pointer: coarse)").matches===!0)return p.selected;let g=m?.navigator.platform??"";return/^(Mac|iP)/.test(g)?p.pressMac:p.pressOther}function c(r,p,m,g,h,b,y,S){let v,_=(w,x)=>{f.textContent=w,f.removeAttribute("aria-label"),b(w),clearTimeout(v),v=setTimeout(k,x)},f=n(r,p.copy,()=>{let w=r.defaultView?.navigator?.clipboard,x=()=>{h(),_(O(r,p),z)};if(w!==void 0)w.writeText(g()).then(()=>_(p.copied,L),x);else x()},y,S);f.classList.add("tab-mcp-copy");let k=()=>{clearTimeout(v),v=void 0,f.textContent=p.copy,f.setAttribute("aria-label",m)};return k(),{button:f,reset:k}}
|
|
99
|
+
export{i,a,t,o,e,n,s,d,u,l,c};
|
|
89
100
|
|
|
90
|
-
//# debugId=
|
|
91
|
-
//# sourceMappingURL=
|
|
101
|
+
//# debugId=629F0D40B666F40F64756E2164756E21
|
|
102
|
+
//# sourceMappingURL=tab-mcp-client-2vx9mcww.min.js.map
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/strings.ts", "../../src/visible.ts", "../../src/dialog.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"/**\n * Every text of the library's dialogs, in one table (CU 5). A page passes\n * its own for some or all keys (`ui: { strings }`); the dialogs use these for\n * the rest. `{name}` is a placeholder the dialog fills in: names of tools\n * and AI apps (isolated, so that they cannot reorder the sentence), the\n * code, counts. Where English needs two forms, there are two keys\n * (`…One` for one, `…Many` for more). `lang` and `dir` are the language and\n * direction of the texts, set on every dialog.\n */\nexport const STRINGS = {\n\tlang: \"en\",\n\tdir: \"ltr\",\n\t/** Between the last two items of a list (\"A, B and C\"). */\n\tand: \"and\",\n\n\t// The confirmation of a consequential tool call.\n\tconfirmTitle: \"Allow {tool}?\",\n\tconfirmWho: \"{client} wants to run {tool}.\",\n\tdeny: \"Don't allow\",\n\tallow: \"Allow\",\n\t/** `alwaysAllow: true`: kept until the app is disconnected. */\n\talwaysAllow: \"Always allow\",\n\talwaysAllowNote:\n\t\t\"Always allow: {tool} will run for {client} without asking, with any arguments, until you disconnect {client} from this page.\",\n\t/** `alwaysAllow: \"until-reload\"`, or kept in memory only (`storage: null`). */\n\tallowUntilReload: \"Allow until reload\",\n\tallowUntilReloadNote:\n\t\t\"Allow until reload: {tool} will run for {client} without asking, with any arguments, until you reload this page or disconnect {client}.\",\n\targumentsHidden:\n\t\t\"The arguments cannot be shown, so this call cannot be allowed.\",\n\tscrollToAllow: \"Scroll to the end of the arguments to allow this call.\",\n\twaitingOne: \"1 more call is waiting after this one.\",\n\twaitingMany: \"{n} more calls are waiting after this one.\",\n\t/** Before the page's title while a confirmation waits in a hidden tab. */\n\ttitlePrefix: \"Allow? – \",\n\n\t// How the dialogs name a caller.\n\tclientWebMcp: \"An agent in this browser\",\n\tclientLocal: \"{name} (this site's assistant)\",\n\t/** An AI app through the relay: its name and the host of its client id. */\n\tclientRelay: \"{name} ({host})\",\n\n\t// Copy buttons.\n\tcopy: \"Copy\",\n\tcopied: \"Copied\",\n\t/** On the button after a refused Copy: the text is selected instead. */\n\tpressMac: \"Press ⌘C\",\n\tpressOther: \"Press Ctrl+C\",\n\t/** The same on a touch screen, where there is no key to press. */\n\tselected: \"Selected\",\n\tcopyAddress: \"Copy address\",\n\tcopyCode: \"Copy code\",\n\tcopyCommand: \"Copy {app} command\",\n\n\t// The connect dialog.\n\tconnectTitle: \"Connect your AI app\",\n\tconnecting: \"Connecting…\",\n\tconnectAgain: \"Connect again\",\n\treconnecting: \"Connection lost. Reconnecting…\",\n\tnotConnected: \"Not connected.\",\n\tunreachable: \"Could not connect. Check your internet connection.\",\n\trateLimited: \"Too many attempts. Wait a minute, then connect again.\",\n\trefused: \"The connection was refused.\",\n\tended: \"The session ended.\",\n\tlost: \"The connection was lost.\",\n\tclosed: \"The connection was closed.\",\n\tdisconnected: \"Disconnected.\",\n\tcheckingSignIn: \"Checking your sign-in…\",\n\tsignInFirst: \"Sign in to this page first.\",\n\tsignInRefused: \"Your sign-in on this page was not accepted.\",\n\t/** `{reason}`: the relay's reason, as it gave it. */\n\tsignInRefusedWhy: \"Your sign-in on this page was not accepted ({reason}).\",\n\treadyApp: \"{app} is ready for your AI app.\",\n\treadyPage: \"This page is ready for your AI app.\",\n\taddressLabel: \"Add this address to your AI app:\",\n\thelp: \"How do I add it?\",\n\tguide: \"Step by step, and what to do when it fails\",\n\tcodeSentence: \"When asked, enter the code {code}\",\n\tcodeNote: \"A new code appears every 2 minutes and after each use.\",\n\tcodeUsed: \"Code used. Waiting for your AI app…\",\n\tsignIn:\n\t\t\"When your AI app asks, sign in with the account you use on this page. No code is needed.\",\n\tnewAddress: \"Disconnect all apps\",\n\tnewAddressNote:\n\t\t\"An AI app is connected that should not be? This disconnects every AI app from this page; each one has to connect again with a new code.\",\n\tnewAddressQuestionOne:\n\t\t\"This disconnects {apps}. To use this page with it again, connect it again and enter a new code.\",\n\tnewAddressQuestionMany:\n\t\t\"This disconnects {apps}. To use this page with them again, connect them again and enter a new code.\",\n\tnewAddressConfirm: \"Disconnect all\",\n\tcancel: \"Cancel\",\n\tgettingNewAddress: \"Disconnecting…\",\n\tnewAddressDone: \"Every AI app is disconnected. Connect yours again.\",\n\tconnectedOne: \"{apps} is connected\",\n\tconnectedMany: \"{apps} are connected\",\n\tconnectedNextOne:\n\t\t\"You can close this now and ask it to use the tools of this page.\",\n\tconnectedNextMany:\n\t\t\"You can close this now and ask them to use the tools of this page.\",\n\tconnectAnother: \"Connect another app\",\n\tconnectedHeading: \"Connected\",\n\tappConnected: \"{app} connected\",\n\tdisconnect: \"Disconnect\",\n\tdisconnectApp: \"Disconnect {app}\",\n\tdisconnectNote: \"To disconnect an app, connect this page again first.\",\n\t/** Disconnect failed: the relay could not save it (`store_unavailable`). */\n\tstoreUnavailable: \"The relay could not save this. Try again.\",\n\t/** Disconnect failed for another reason. */\n\tdisconnectFailed: \"Could not disconnect the app. Try again.\",\n\t// Under a connected app: a switch per tool that asks, and one for all.\n\trunsWithoutAsking: \"Runs without asking\",\n\t/** After a tool's name: it may delete or overwrite (`destructiveHint`). */\n\tdestructive: \"destructive\",\n\t/** A tool's switch, as read out: starts with what it shows (WCAG 2.5.3). */\n\tallowToolApp: \"{tool} runs without asking for {app}\",\n\tallowDestructiveToolApp: \"{tool} (destructive) runs without asking for {app}\",\n\tallowEverything: \"Allow everything, no questions asked\",\n\tallowEverythingApp: \"Allow everything, no questions asked, for {app}\",\n\tallowEverythingNote:\n\t\t\"Every tool of this page runs for {app} without asking, with any arguments: also tools you have not seen yet and ones that delete or overwrite.\",\n\tcloseNote:\n\t\t\"Closing this stops the code. To connect later, open this again from the page.\",\n\tclose: \"Close\",\n\tdone: \"Done\",\n\n\t// The notice when another tab or program took over the address.\n\treplacedSiblingTitle: \"Opened in another tab\",\n\treplacedSibling:\n\t\t\"This page is open in another tab, and your AI apps now use that one. To use them here, connect this page again.\",\n\treplacedTitle: \"Another tab or program took over this page\",\n\treplaced:\n\t\t\"Your AI apps now reach that tab or program instead of this page. If you did not open this page in another tab or browser, someone may have copied what this page keeps to connect. “Disconnect all apps” ends that; then connect your AI apps again with a new code.\",\n\ttakenOverAgain:\n\t\t\"It was taken over again before its AI apps were disconnected. Try again.\",\n\t/** `{reason}`: why disconnecting all apps failed, one of the texts above. */\n\ttryAgainOrClose: \"{reason} Try again, or close this.\",\n};\n\n/** The texts of the dialogs: the keys of {@link STRINGS}, each a string. */\nexport type DialogStrings = { [K in keyof typeof STRINGS]: string };\n",
|
|
6
|
+
"/**\n * Text an AI app or a page wrote, made safe to show to the user before they\n * approve something: characters that are invisible, blank or turn the text's\n * direction are written as escapes, so the text cannot look like something\n * else. Shared by the library's confirmation dialog and the tab-mcp browser extension.\n */\n\n/**\n * Characters that are invisible, blank or change the direction of the text\n * around them: controls (C0 and C1, but tab and line feed, which are only\n * JSON's layout), format characters (bidi controls and isolates, zero-width\n * ones, tags), the other default-ignorable ones (variation selectors, U+034F,\n * the Hangul fillers), private-use, unassigned and lone surrogate code\n * points, line and paragraph separators, every space but the plain one\n * (U+00A0, U+2007, U+3000…) and the Braille blank (U+2800).\n */\nconst INVISIBLE =\n\t/(?![\\t\\n ])[\\p{Cc}\\p{Cf}\\p{Default_Ignorable_Code_Point}\\p{Co}\\p{Cn}\\p{Cs}\\p{Zl}\\p{Zp}\\p{Zs}\\u{2800}]/gu;\n\n/**\n * `text` with each such character as `\\uXXXX` (a surrogate pair for one\n * beyond U+FFFF), as JSON would write it: JSON stays JSON for the same value.\n */\nexport function escapeInvisible(text: string): string {\n\treturn text.replace(INVISIBLE, (ch) => {\n\t\tlet escaped = \"\";\n\t\tfor (let i = 0; i < ch.length; i++)\n\t\t\tescaped += `\\\\u${ch.charCodeAt(i).toString(16).toUpperCase().padStart(4, \"0\")}`;\n\t\treturn escaped;\n\t});\n}\n",
|
|
7
|
+
"/**\n * What the library's dialogs share: the stylesheet, elements, buttons, the\n * texts (`strings.ts`) and how a caller is named. The confirmation\n * (`confirm.ts`) and the connect dialog (`connect.ts`) are chunks of their\n * own, loaded on demand; pages with their own UI use the events and methods\n * of `TabMcp` instead.\n */\n\nimport { type DialogStrings, STRINGS } from \"./strings.ts\";\nimport type { DialogOptions, Grant, ToolCallClient } from \"./types.ts\";\nimport { escapeInvisible } from \"./visible.ts\";\n\nlet counter = 0;\n\n/** A new id for the elements of one dialog. */\nexport function nextId(): string {\n\treturn `tab-mcp-${++counter}`;\n}\n\n/** The texts: the page's own where it gave them, else the English ones. */\nexport function stringsOf(options: DialogOptions | undefined): DialogStrings {\n\tconst s: DialogStrings = { ...STRINGS };\n\t// Only strings: a missing translation (`undefined`) keeps the English text.\n\tfor (const [key, value] of Object.entries(options?.strings ?? {}))\n\t\tif (typeof value === \"string\" && key in s)\n\t\t\ts[key as keyof DialogStrings] = value;\n\treturn s;\n}\n\n/** `template` with its `{name}` placeholders filled in, as text. */\nexport function format(\n\ttemplate: string,\n\tvalues: Record<string, string>,\n): string {\n\treturn template.replace(\n\t\t/\\{(\\w+)\\}/g,\n\t\t(all, key: string) => values[key] ?? all,\n\t);\n}\n\n/**\n * `template` with its `{name}` placeholders filled in, as nodes: a string\n * value is a name, isolated so that it cannot reorder the words around it\n * (and may stand twice); a node is put in as it is.\n */\nexport function fill(\n\tdoc: Document,\n\ttemplate: string,\n\tvalues: Record<string, string | Node>,\n): (Node | string)[] {\n\treturn template.split(/\\{(\\w+)\\}/).map((part, i) => {\n\t\tif (i % 2 === 0) return part;\n\t\tconst value = values[part];\n\t\tif (value === undefined) return `{${part}}`;\n\t\treturn typeof value === \"string\" ? name(doc, value) : value;\n\t});\n}\n\nexport function el<K extends keyof HTMLElementTagNameMap>(\n\tdoc: Document,\n\ttag: K,\n\tprops: { className?: string; text?: string; id?: string } = {},\n\t...children: (Node | string)[]\n): HTMLElementTagNameMap[K] {\n\tconst node = doc.createElement(tag);\n\tif (props.className !== undefined) node.className = props.className;\n\tif (props.id !== undefined) node.id = props.id;\n\tif (props.text !== undefined) node.textContent = props.text;\n\tnode.append(...children);\n\treturn node;\n}\n\n/**\n * A button. `className` is its own class; `kind` marks the one next step\n * (`tab-mcp-primary`) or one that disconnects (`tab-mcp-danger`); without\n * one it is a plain, outlined button.\n */\nexport function button(\n\tdoc: Document,\n\ttext: string,\n\tonClick: () => void,\n\tclassName?: string,\n\tkind?: \"primary\" | \"danger\",\n): HTMLButtonElement {\n\tconst node = el(doc, \"button\", { text });\n\tnode.type = \"button\";\n\tif (className !== undefined) node.classList.add(className);\n\tif (kind !== undefined) node.classList.add(`tab-mcp-${kind}`);\n\tnode.addEventListener(\"click\", onClick);\n\treturn node;\n}\n\n/** A name in a sentence, isolated so that it cannot reorder the words around it. */\nexport function name(doc: Document, text: string): HTMLElement {\n\tconst node = el(doc, \"bdi\", { text });\n\tnode.dir = \"ltr\";\n\treturn node;\n}\n\n/** Invisible, blank and direction characters as `\\uXXXX` (`visible.ts`). */\nexport const visible: (text: string) => string = escapeInvisible;\n\n/**\n * How the dialogs name a caller: an AI app's name and verified host; for\n * the caller of a served port, the name the page gave it and what it is.\n */\nexport function clientLabel(\n\tclient: ToolCallClient | Grant[\"client\"],\n\ts: DialogStrings,\n): string {\n\tif (\"kind\" in client && client.kind === \"webmcp\") return s.clientWebMcp;\n\tif (\"kind\" in client && client.kind === \"local\")\n\t\treturn format(s.clientLocal, { name: visible(client.name ?? client.id) });\n\tconst host = visible(client.host || client.id);\n\treturn client.name !== undefined && client.name !== \"\"\n\t\t? format(s.clientRelay, { name: visible(client.name), host })\n\t\t: host;\n}\n\n/** \"A and B\", \"A, B and C\". */\nexport function listOf(items: string[], s: DialogStrings): string {\n\treturn items.length < 2\n\t\t? (items[0] ?? \"\")\n\t\t: `${items.slice(0, -1).join(\", \")} ${s.and} ${items.at(-1)}`;\n}\n\n/**\n * The look of the dialogs. Every selector has the specificity of one class\n * (the rest is in `:where()`), so rules of the page for elements, such as\n * `button { … }` or a reset's `* { border-width: 0 }`, do not change the\n * dialogs. The rules for states (hover, focus, disabled) and the primary\n * and danger buttons add two elements (`html dialog.…`, `html button.…`),\n * so `button:hover`, `button:focus` or `button:disabled` of the page do not\n * either. A page overrides with two classes, `.tab-mcp-dialog .tab-mcp-x`,\n * which wins over all of them; one class does not. The `--tab-mcp-*`\n * custom properties (on `:root` or on `.tab-mcp-dialog`) change single\n * values; the library only reads them. The defaults use system colours and the\n * page's `color-scheme`, so the dialogs follow its light or dark scheme. The\n * `--_tab-mcp-*` properties are internal. Order matters among equals.\n */\nexport const DIALOG_CSS = `.tab-mcp-dialog {\n--_tab-mcp-fg: var(--tab-mcp-color, CanvasText);\n--_tab-mcp-bg: var(--tab-mcp-background, Canvas);\n--_tab-mcp-muted: var(--tab-mcp-muted, color-mix(in srgb, var(--_tab-mcp-fg) 72%, transparent));\n--_tab-mcp-line: color-mix(in srgb, var(--_tab-mcp-fg) 22%, transparent);\n--_tab-mcp-surface: var(--tab-mcp-surface, color-mix(in srgb, var(--_tab-mcp-fg) 6%, transparent));\n--_tab-mcp-danger: var(--tab-mcp-danger, light-dark(#b3261e, #ffb4ab));\n--_tab-mcp-success: var(--tab-mcp-success, light-dark(#1a7f37, #6fdd8b));\n--_tab-mcp-mono: var(--tab-mcp-mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace);\n--_tab-mcp-small-radius: calc(var(--tab-mcp-radius, 0.75rem) * 0.6);\nbox-sizing: border-box; margin: auto; width: calc(100% - 2rem); max-width: var(--tab-mcp-max-width, 34rem); max-height: calc(100% - 2rem); overflow: auto;\nfont: var(--tab-mcp-font, inherit); line-height: 1.5; color: var(--_tab-mcp-fg); background: var(--_tab-mcp-bg);\nborder: var(--tab-mcp-border, 1px solid var(--_tab-mcp-line)); border-radius: var(--tab-mcp-radius, 0.75rem);\npadding: var(--tab-mcp-padding, clamp(1rem, 5vw, 1.5rem)); box-shadow: var(--tab-mcp-shadow, 0 1rem 3rem rgb(0 0 0 / 0.3));\npointer-events: auto;\n}\n.tab-mcp-dialog::backdrop { background: var(--tab-mcp-backdrop, rgb(0 0 0 / 0.4)); }\n.tab-mcp-dialog:where([open]) { display: flex; flex-direction: column; gap: 1rem; }\n.tab-mcp-dialog:where([open]) > * { flex-shrink: 0; }\n.tab-mcp-dialog :where([hidden]) { display: none !important; }\nhtml dialog.tab-mcp-dialog:where(:focus) { outline: none; }\n.tab-mcp-dialog :where(*) { box-sizing: border-box; color: inherit; }\n.tab-mcp-dialog :where(h2, h3, p, ul, li, pre) { margin: 0; }\n.tab-mcp-dialog :where(h2) { font-size: var(--tab-mcp-title-size, 1.25em); line-height: 1.3; font-weight: 600; overflow-wrap: anywhere; }\n.tab-mcp-dialog :where(h3) { font-size: 0.875em; font-weight: 600; color: var(--_tab-mcp-muted); margin-bottom: 0.5rem; }\n.tab-mcp-dialog :where(small) { font-size: 0.875em; }\n.tab-mcp-dialog :where(small, .tab-mcp-status, .tab-mcp-description, .tab-mcp-always-note, .tab-mcp-apps-note, .tab-mcp-success-next, .tab-mcp-waiting, .tab-mcp-scroll-note) { color: var(--_tab-mcp-muted); }\nhtml dialog.tab-mcp-dialog :where(:focus-visible) { outline: 2px solid var(--tab-mcp-focus, var(--_tab-mcp-fg)); outline-offset: 2px; }\n.tab-mcp-dialog :where(button) { font: inherit; font-size: 0.9375em; line-height: 1.25; text-transform: none; letter-spacing: normal; width: auto; min-height: 2.5rem; padding: 0.5rem 1rem; margin: 0; border: 1px solid color-mix(in srgb, currentColor 35%, transparent); border-radius: var(--_tab-mcp-small-radius); background: transparent; color: inherit; cursor: pointer; }\nhtml dialog.tab-mcp-dialog :where(button:hover:not(:disabled)) { color: inherit; background: color-mix(in srgb, currentColor 8%, transparent); }\nhtml dialog.tab-mcp-dialog :where(button:disabled) { opacity: 0.45; cursor: not-allowed; }\nhtml button.tab-mcp-primary { background: var(--tab-mcp-accent, var(--_tab-mcp-fg)); color: var(--tab-mcp-accent-text, var(--_tab-mcp-bg)); border-color: transparent; font-weight: 600; }\nhtml button.tab-mcp-primary:where(:hover:not(:disabled)) { background: var(--tab-mcp-accent, var(--_tab-mcp-fg)); opacity: 0.85; }\nhtml button.tab-mcp-danger { color: var(--_tab-mcp-danger); border-color: color-mix(in srgb, currentColor 45%, transparent); }\n.tab-mcp-copy { min-width: 6em; }\n.tab-mcp-close { font-size: 0.875em; }\n.tab-mcp-status { margin-top: -0.5rem; }\n.tab-mcp-description:where(:empty) { display: none; }\n.tab-mcp-actions { display: flex; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: 0.5rem; }\n.tab-mcp-address { display: flex; flex-wrap: wrap; align-items: center; gap: 0.5rem; }\n.tab-mcp-address :where(label) { flex-basis: 100%; font-weight: 600; }\n.tab-mcp-address :where(input) { flex: 1 1 12rem; min-width: 0; min-height: 2.5rem; margin: 0; padding: 0.5rem 0.625rem; font: 0.875em var(--_tab-mcp-mono); text-overflow: ellipsis; color: inherit; background: var(--_tab-mcp-surface); border: 1px solid var(--_tab-mcp-line); border-radius: var(--_tab-mcp-small-radius); }\n.tab-mcp-code { display: grid; grid-template-columns: 1fr auto; align-items: end; gap: 0.25rem 1rem; padding: 1rem; background: var(--_tab-mcp-surface); border-radius: var(--_tab-mcp-small-radius); }\n.tab-mcp-code > :where(span) { font-weight: 600; }\n.tab-mcp-code :where(br) { display: none; }\n.tab-mcp-code :where(small) { grid-column: 1 / -1; }\n.tab-mcp-code-value { display: block; font: 700 var(--tab-mcp-code-size, 2em) / 1.2 var(--_tab-mcp-mono); letter-spacing: 0.12em; font-variant-numeric: tabular-nums; }\n.tab-mcp-help { border: 1px solid var(--_tab-mcp-line); border-radius: var(--_tab-mcp-small-radius); }\n.tab-mcp-help :where(summary) { padding: 0.75rem 1rem; font-weight: 600; cursor: pointer; }\n.tab-mcp-help > :where(:not(summary)) { margin-inline: 1rem; }\n.tab-mcp-help > :where(:last-child:not(summary)) { margin-bottom: 1rem; }\n.tab-mcp-dialog :where(.tab-mcp-help ul, .tab-mcp-apps ul) { list-style: none; padding: 0; display: grid; gap: 0.5rem; }\n.tab-mcp-help :where(ul) { margin-top: 0.25rem; margin-bottom: 0.75rem; gap: 0.75rem; }\n.tab-mcp-help :where(li) { overflow-wrap: anywhere; }\n.tab-mcp-help :where(strong) { display: block; font-weight: 600; }\n.tab-mcp-command { display: flex; flex-wrap: wrap; justify-content: flex-end; align-items: flex-start; gap: 0.5rem; margin-top: 0.375rem; }\n.tab-mcp-command > :where(pre) { flex: 1 1 16rem; min-width: 0; margin: 0; padding: 0.5rem 0.625rem; font: 0.8125em / 1.5 var(--_tab-mcp-mono); white-space: pre-wrap; word-break: break-all; background: var(--_tab-mcp-surface); border: 1px solid var(--_tab-mcp-line); border-radius: var(--_tab-mcp-small-radius); }\n.tab-mcp-command-note { display: block; margin-top: 0.375rem; }\n.tab-mcp-help :where(code) { font: 0.875em var(--_tab-mcp-mono); padding: 0.125em 0.375em; background: var(--_tab-mcp-surface); border-radius: 0.25rem; -webkit-box-decoration-break: clone; box-decoration-break: clone; }\n.tab-mcp-apps :where(li) { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 0.5rem 0.75rem; padding: 0.5rem 0.5rem 0.5rem 0.75rem; border: 1px solid var(--_tab-mcp-line); border-radius: var(--_tab-mcp-small-radius); }\n.tab-mcp-app { flex: 1 1 10rem; min-width: 0; overflow-wrap: anywhere; }\n.tab-mcp-allowed { display: grid; flex-basis: 100%; gap: 0.25rem; padding-top: 0.5rem; border-top: 1px solid var(--_tab-mcp-line); font-size: 0.875em; overflow-wrap: anywhere; }\n.tab-mcp-allowed-title { font-weight: 600; color: var(--_tab-mcp-muted); }\n.tab-mcp-switches { display: grid; gap: 0.125rem; }\n.tab-mcp-switch { display: flex; align-items: center; gap: 0.625rem; min-height: 2rem; cursor: pointer; }\n.tab-mcp-switch > :where(input) { appearance: none; -webkit-appearance: none; flex: none; position: relative; width: 2.25rem; height: 1.25rem; margin: 0; padding: 0; border: 1px solid var(--_tab-mcp-line); border-radius: 0.625rem; background: var(--_tab-mcp-surface); cursor: pointer; }\n.tab-mcp-switch > :where(input)::before { content: \"\"; position: absolute; top: 2px; left: 2px; width: calc(1.25rem - 6px); height: calc(1.25rem - 6px); border-radius: 50%; background: var(--_tab-mcp-muted); }\n.tab-mcp-switch > :where(input:checked) { background: var(--tab-mcp-accent, var(--_tab-mcp-fg)); border-color: transparent; }\n.tab-mcp-switch > :where(input:checked)::before { left: calc(100% - 1.25rem + 4px); background: var(--tab-mcp-accent-text, var(--_tab-mcp-bg)); }\nhtml dialog.tab-mcp-dialog :where(.tab-mcp-switch > input:disabled) { opacity: 0.45; cursor: not-allowed; }\n.tab-mcp-destructive { color: var(--_tab-mcp-danger); }\n.tab-mcp-everything { font-weight: 600; }\n.tab-mcp-everything-note { color: var(--_tab-mcp-muted); }\n.tab-mcp-apps-note { margin-top: 0.5rem; }\n.tab-mcp-success { display: flex; align-items: center; gap: 0.875rem; padding: 1rem; background: color-mix(in srgb, var(--_tab-mcp-success) 10%, transparent); border: 1px solid color-mix(in srgb, var(--_tab-mcp-success) 45%, transparent); border-radius: var(--_tab-mcp-small-radius); }\n.tab-mcp-success-icon { flex: none; display: grid; place-items: center; width: 2.75rem; height: 2.75rem; border-radius: 50%; font-size: 1.5em; font-weight: 700; line-height: 1; color: var(--_tab-mcp-success); background: color-mix(in srgb, var(--_tab-mcp-success) 16%, transparent); }\n.tab-mcp-success-icon::before { content: \"\\\\2713\"; }\n.tab-mcp-success-text { display: grid; gap: 0.125rem; min-width: 0; }\n.tab-mcp-success-title { font-size: 1.125em; line-height: 1.3; font-weight: 600; overflow-wrap: anywhere; }\n.tab-mcp-setup { display: flex; flex-direction: column; gap: 1rem; }\n.tab-mcp-setup-toggle { display: flex; align-items: center; gap: 0.75rem; width: 100%; padding: 0.75rem 1rem; text-align: start; font-weight: 600; border-color: var(--_tab-mcp-line); }\n.tab-mcp-setup-toggle::before { content: \"\"; flex: none; width: 0.45em; height: 0.45em; border: solid currentColor; border-width: 0 2px 2px 0; transform: translateX(-0.1em) rotate(-45deg); }\n.tab-mcp-setup-toggle:where([aria-expanded=\"true\"])::before { transform: translateY(-0.15em) rotate(45deg); }\n.tab-mcp-code-used { display: flex; align-items: center; min-height: calc(var(--tab-mcp-code-size, 2em) * 1.2); }\n.tab-mcp-new-address-row { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 0.5rem 1rem; }\n.tab-mcp-new-address-row > :where(small) { flex: 1 1 14rem; color: var(--_tab-mcp-muted); }\n.tab-mcp-new-address-question { display: grid; gap: 0.75rem; padding: 1rem; border: 1px solid color-mix(in srgb, var(--_tab-mcp-danger) 50%, transparent); border-radius: var(--_tab-mcp-small-radius); }\n.tab-mcp-connect > :where(.tab-mcp-actions) { gap: 0.75rem; padding-top: 1rem; border-top: 1px solid var(--_tab-mcp-line); }\n.tab-mcp-close-note { flex: 1 1 12rem; }\n.tab-mcp-confirm :where(p bdi) { font-weight: 600; }\n.tab-mcp-arguments { box-sizing: content-box; font: 0.875em / 1.45 var(--_tab-mcp-mono); padding: 0.75rem; background: var(--_tab-mcp-surface); border: 1px solid var(--_tab-mcp-line); border-radius: var(--_tab-mcp-small-radius); }\n.tab-mcp-always-note, .tab-mcp-waiting, .tab-mcp-scroll-note { font-size: 0.875em; }\n@media (max-width: 30rem) { .tab-mcp-actions > :where(button) { flex: 1 1 auto; } .tab-mcp-connect > :where(.tab-mcp-actions) > :where(button) { flex: 0 0 auto; } .tab-mcp-code { grid-template-columns: minmax(0, 1fr); } .tab-mcp-code > :where(button) { justify-self: start; } }\n@media (prefers-reduced-motion: no-preference) { .tab-mcp-dialog:where([open]) { animation: tab-mcp-in 0.15s ease-out; } .tab-mcp-success-icon { animation: tab-mcp-pop 0.4s cubic-bezier(0.3, 1.4, 0.6, 1); } .tab-mcp-switch > :where(input)::before { transition: left 0.15s ease-out; } }\n@media (forced-colors: active) { html button.tab-mcp-primary { border-color: ButtonText; } .tab-mcp-switch > :where(input) { forced-color-adjust: none; background: Canvas; border-color: ButtonText; } .tab-mcp-switch > :where(input)::before { forced-color-adjust: none; background: ButtonText; } .tab-mcp-switch > :where(input:checked) { background: Highlight; } .tab-mcp-switch > :where(input:checked)::before { background: HighlightText; } }\n@keyframes tab-mcp-in { from { opacity: 0; transform: translateY(0.5rem); } }\n@keyframes tab-mcp-pop { from { opacity: 0; transform: scale(0.4); } }\n`;\n\nconst sheets = new WeakMap<Document, CSSStyleSheet>();\n\n/**\n * Adopts `DIALOG_CSS` into the document once, next to the page's own adopted\n * sheets. A constructed stylesheet needs no `style-src` exception under a\n * strict CSP. Where constructed stylesheets are not supported, the dialogs\n * keep the browser's default look and work the same.\n */\nfunction adoptStyles(doc: Document): void {\n\ttry {\n\t\tlet sheet = sheets.get(doc);\n\t\tif (sheet === undefined) {\n\t\t\tconst Sheet = (doc.defaultView as (Window & typeof globalThis) | null)\n\t\t\t\t?.CSSStyleSheet;\n\t\t\tif (Sheet === undefined || !Array.isArray(doc.adoptedStyleSheets)) return;\n\t\t\tsheet = new Sheet();\n\t\t\tsheet.replaceSync(DIALOG_CSS);\n\t\t\tsheets.set(doc, sheet);\n\t\t}\n\t\t// The page may have replaced the list since.\n\t\tif (!doc.adoptedStyleSheets.includes(sheet))\n\t\t\tdoc.adoptedStyleSheets = [...doc.adoptedStyleSheets, sheet];\n\t} catch {\n\t\t// Not supported: the default look.\n\t}\n}\n\n/**\n * A dialog with its heading (`title`, or filled in by the caller). It\n * carries the texts' language and direction (`lang`, `dir` of the\n * strings), whatever the page's: read out with that voice, laid out that way.\n */\nexport function newDialog(\n\tdoc: Document,\n\tclassName: string,\n\ts: DialogStrings,\n\t...title: (Node | string)[]\n): { dialog: HTMLDialogElement; heading: HTMLHeadingElement; id: string } {\n\tconst id = nextId();\n\tconst dialog = el(doc, \"dialog\", {\n\t\tclassName: `tab-mcp-dialog ${className}`,\n\t});\n\tdialog.setAttribute(\"aria-labelledby\", `${id}-title`);\n\tdialog.lang = s.lang;\n\tdialog.dir = s.dir;\n\tadoptStyles(doc);\n\tconst heading = el(doc, \"h2\", { id: `${id}-title` }, ...title);\n\tdialog.append(heading);\n\treturn { dialog, heading, id };\n}\n\n/** How long a Copy button says \"Copied\", and how long it says to press Ctrl+C. */\nexport const COPIED_MS = 2000;\nexport const SELECTED_MS = 8000;\n\n/** What the button says after a refused Copy, by the user's device. */\nfunction pressToCopy(doc: Document, s: DialogStrings): string {\n\tconst view = doc.defaultView;\n\tif (view?.matchMedia?.(\"(pointer: coarse)\").matches === true)\n\t\treturn s.selected;\n\tconst platform = view?.navigator.platform ?? \"\";\n\treturn /^(Mac|iP)/.test(platform) ? s.pressMac : s.pressOther;\n}\n\n/**\n * A Copy button for `value()`, read at click time. Says \"Copied\" for a\n * moment once the clipboard took it; without a clipboard (or when it refuses)\n * `select()` puts the text in the selection and the button says to press\n * Ctrl+C (⌘C on Apple devices). `label` names it for assistive technology\n * (\"Copy code\"), as the dialog has more than one Copy; while it says what\n * happened, that is its name, and `announce` says it too.\n */\nexport function copyButton(\n\tdoc: Document,\n\ts: DialogStrings,\n\tlabel: string,\n\tvalue: () => string,\n\tselect: () => void,\n\tannounce: (text: string) => void,\n\tclassName: string,\n\tkind?: \"primary\",\n): { button: HTMLButtonElement; reset: () => void } {\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\tconst say = (text: string, ms: number) => {\n\t\tnode.textContent = text;\n\t\tnode.removeAttribute(\"aria-label\");\n\t\tannounce(text);\n\t\tclearTimeout(timer);\n\t\ttimer = setTimeout(reset, ms);\n\t};\n\tconst node = button(\n\t\tdoc,\n\t\ts.copy,\n\t\t() => {\n\t\t\tconst clipboard = (doc.defaultView?.navigator as Navigator | undefined)\n\t\t\t\t?.clipboard;\n\t\t\tconst selected = () => {\n\t\t\t\tselect();\n\t\t\t\tsay(pressToCopy(doc, s), SELECTED_MS);\n\t\t\t};\n\t\t\tif (clipboard !== undefined)\n\t\t\t\tclipboard\n\t\t\t\t\t.writeText(value())\n\t\t\t\t\t.then(() => say(s.copied, COPIED_MS), selected);\n\t\t\telse selected();\n\t\t},\n\t\tclassName,\n\t\tkind,\n\t);\n\t// The same width for \"Copy\" and \"Copied\": nothing moves.\n\tnode.classList.add(\"tab-mcp-copy\");\n\tconst reset = () => {\n\t\tclearTimeout(timer);\n\t\ttimer = undefined;\n\t\tnode.textContent = s.copy;\n\t\tnode.setAttribute(\"aria-label\", label);\n\t};\n\treset();\n\treturn { button: node, reset };\n}\n"
|
|
8
|
+
],
|
|
9
|
+
"mappings": "AASO,IAAM,EAAU,CACtB,KAAM,KACN,IAAK,MAEL,IAAK,MAGL,aAAc,gBACd,WAAY,gCACZ,KAAM,cACN,MAAO,QAEP,YAAa,eACb,gBACC,+HAED,iBAAkB,qBAClB,qBACC,0IACD,gBACC,iEACD,cAAe,yDACf,WAAY,yCACZ,YAAa,6CAEb,YAAa,YAGb,aAAc,2BACd,YAAa,iCAEb,YAAa,kBAGb,KAAM,OACN,OAAQ,SAER,SAAU,WACV,WAAY,eAEZ,SAAU,WACV,YAAa,eACb,SAAU,YACV,YAAa,qBAGb,aAAc,sBACd,WAAY,cACZ,aAAc,gBACd,aAAc,iCACd,aAAc,iBACd,YAAa,qDACb,YAAa,wDACb,QAAS,8BACT,MAAO,qBACP,KAAM,2BACN,OAAQ,6BACR,aAAc,gBACd,eAA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,EACjC,IAAM,EAAQ,IAAM,CACnB,aAAa,CAAK,EAClB,EAAQ,OACR,EAAK,YAAc,EAAE,KACrB,EAAK,aAAa,aAAc,CAAK,GAGtC,OADA,EAAM,EACC,CAAE,OAAQ,EAAM,OAAM",
|
|
10
|
+
"debugId": "629F0D40B666F40F64756E2164756E21",
|
|
11
|
+
"names": []
|
|
12
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
function v(t){if(t===void 0)return"";let e=2166136261;for(let n=0;n<t.length;n++)e=Math.imul(e^t.charCodeAt(n),16777619)>>>0;return e.toString(16)}var g=(t)=>typeof t==="string";function w(t){let e={secret:"",grants:new Map},n;try{n=JSON.parse(t)}catch{return e}let s=n;if(!g(s?.secret)||!Array.isArray(s.grants))return e;let o=new Map;for(let i of s.grants){let l=i;if(!g(l?.grantId)||typeof l.everything!=="boolean"||!Array.isArray(l.tools))return e;let d=[];for(let p of l.tools){let a=p;if(!g(a?.name)||!g(a.description)||a.title!==void 0&&!g(a.title))return e;d.push(f(a))}o.set(l.grantId,{everything:l.everything,tools:d})}return{secret:s.secret,grants:o}}function m(t){return JSON.stringify({secret:t.secret,grants:[...t.grants].map(([e,n])=>({grantId:e,...n}))})}function f(t){let e={name:t.name,description:t.description};if(t.title!==void 0)e.title=t.title;return e}var u=(t,e)=>t.title===e.title&&t.description===e.description,h=(t,e)=>e===void 0||u(t,e);class y{kept;offered;#d;#o;#a;#n;#r;#e={secret:"",grants:new Map};#g=!1;#i=new Set;#l;constructor(t){let[e,n,s]=t._allowed;this.#d=t,this.#o=e,this.#a=()=>v(n?.current()),this.#n=s==="until-reload"?null:n?.storage??null,this.#r=`${n?.key}#allowed`,this.kept=this.#n!==null,this.offered=s===!0||s==="until-reload"}tools=()=>this.#o.list().filter((t)=>t.annotations.consequentialHint===!0&&(t.callers?.includes("relay")??!0)).map((t)=>{let e={name:t.name,description:t.description,destructive:t.annotations.destructiveHint===!0};if(t.title!==void 0)e.title=t.title;return e});list=(t)=>(this.#t().get(t)?.tools??[]).filter((e)=>h(e,this.#o.get(e.name))).map((e)=>e.name);has=(t,e)=>{let n=this.#o.get(e);return this.everything(t)||n!==void 0&&this.allows(t,n)};allows(t,e){let n=this.#t().get(t);if(n===void 0)return!1;if(n.everything)return!0;let s=n.tools.find((o)=>o.name===e.name);return s!==void 0&&u(s,e)}allow=(t,e)=>{let n=this.tools().find((s)=>s.name===e);if(n!==void 0)this.keep(t,n)};keep(t,e){if(!this.#h(t))return;let n=this.#t(),s=n.get(t)??{everything:!1,tools:[]};s.tools=[...s.tools.filter((o)=>o.name!==e.name),f(e)],n.set(t,s),this.#s(n)}ask=(t,e)=>{let n=this.#t(),s=n.get(t);if(s===void 0)return;let o=s.tools.filter((i)=>i.name!==e);if(!s.everything&&o.length===s.tools.length)return;if(s.everything=!1,s.tools=o,o.length===0)n.delete(t);this.#s(n)};everything=(t)=>this.#t().get(t)?.everything===!0;setEverything=(t,e)=>{if(e&&!this.#h(t))return;let n=this.#t(),s=n.get(t)??{everything:!1,tools:[]};if(s.everything===e)return;if(s.everything=e,e||s.tools.length>0)n.set(t,s);else n.delete(t);this.#s(n)};forget=(t)=>{let e=this.#t();if(e.delete(t))this.#s(e)};keepGrants(t){let e=new Set(t),n=this.#t(),s=this.#e.grants!==n&&this.#e.grants.size>0;for(let o of[...n.keys()])if(!e.has(o))s=n.delete(o)||s;if(s)this.#s(n)}toolsChanged(){let t=this.#t(),e=!1;for(let[n,s]of[...t]){let o=s.tools.filter((i)=>h(i,this.#o.get(i.name)));if(o.length===s.tools.length)continue;if(e=!0,s.tools=o,!s.everything&&o.length===0)t.delete(n)}if(e)this.#s(t);else this.#c()}onChange=(t)=>(this.#i.add(t),this.#f(),()=>{if(this.#i.delete(t),this.#i.size===0)this.#l?.(),this.#l=void 0});#f(){if(this.#l!==void 0||this.#n===null)return;let t=globalThis,e=(n)=>{if(n.key===this.#r)this.toolsChanged()};t.addEventListener?.("storage",e),this.#l=()=>t.removeEventListener?.("storage",e)}#h(t){return this.#d.grants.some((e)=>e.grantId===t)}#t(){if(this.#n!==null&&!this.#g)try{let t=this.#n.getItem(this.#r);if(t!==null)this.#e=w(t)}catch{}return this.#e.secret===this.#a()?this.#e.grants:new Map}#s(t){this.#e={secret:this.#a(),grants:t};try{this.#n?.setItem(this.#r,m(this.#e)),this.#g=!1}catch{this.#g=!0}this.#c()}#c(){for(let t of[...this.#i])t()}}var c=new WeakMap;function r(t){let e=c.get(t);if(e!==void 0)return e;let n=new y(t);if(c.set(t,n),t.addEventListener("grantschange",(s)=>n.keepGrants(s.detail.grants.map((o)=>o.grantId))),t._allowed[0].onChange(()=>n.toolsChanged()),n.toolsChanged(),t.session!==void 0)n.keepGrants(t.grants.map((s)=>s.grantId));return n}
|
|
2
|
+
export{r};
|
|
3
|
+
|
|
4
|
+
//# debugId=F41620924049606564756E2164756E21
|
|
5
|
+
//# sourceMappingURL=tab-mcp-client-6gcmd7n8.min.js.map
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/always-allowed.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"/**\n * The tools that run without asking, per AI app (grant), DEC-096 and\n * DEC-200: the ones the user allowed one by one, each with what the user\n * saw of it (title and description; a tool that changed since is asked\n * again and leaves the list), and \"everything\", which covers every tool of\n * the page, also ones the user has not seen.\n *\n * Kept in the page's `storage` under the secret's key with `#allowed`, so\n * that they outlive a reload; in memory with `alwaysAllow: \"until-reload\"`,\n * with `storage: null` and without a relay. Storage is read first on every\n * question, so that a change in another tab of the same address counts at\n * once (only one tab at a time holds the connection, DEC-095).\n *\n * An allowance ends with its grant, and only on what the relay says: the\n * grants of a new session, a removed grant, `newAddress()` (the relay\n * revoked them all). A dropped connection, or a page that has not connected\n * yet, keeps them: `grantschange` does not fire then. They also belong to\n * the address secret they were made under, so a new secret (`newAddress()`\n * here or in another tab) ends them even where nothing listened.\n *\n * Out of the core: the confirmation (`confirm.ts`, which the core loads for\n * every consequential call), the connect dialog and\n * `@ractive-ch/tab-mcp-client/allowed` import it.\n */\n\nimport type { ToolRegistry } from \"./registry.ts\";\nimport type { TabMcp } from \"./tab-mcp.ts\";\nimport type { ConfirmRequest, SecretStorage } from \"./types.ts\";\n\n/** What the user saw of a tool: its name, title and description. */\ntype ToolSeen = ConfirmRequest[\"tool\"];\n/** A tool as the registry or a call names it. */\ntype ToolNow = {\n\tname: string;\n\ttitle?: string | undefined;\n\tdescription: string;\n};\n\n/** A tool that asks before it runs, for a page's switch. */\nexport interface AllowedTool {\n\tname: string;\n\ttitle?: string;\n\tdescription: string;\n\t/** Marked `destructiveHint`: it may delete or overwrite. */\n\tdestructive: boolean;\n}\n\n/**\n * The tools that run without asking, per connected AI app (`Grant.grantId`),\n * for a page that draws its own switches: `allowedTools(mcp)` of\n * `@ractive-ch/tab-mcp-client/allowed`. The library's dialogs use the same.\n * The methods are bound: `const { allow } = allowedTools(mcp)` works. The\n * queries (`tools`, `list`, `has`, `everything`) only read: safe while\n * drawing.\n */\nexport interface AllowedTools {\n\t/**\n\t * `true`: kept in the page's `storage` until the app is disconnected;\n\t * `false`: in memory, until the page is reloaded or the app is\n\t * disconnected (`alwaysAllow: \"until-reload\"`, `storage: null`).\n\t */\n\treadonly kept: boolean;\n\t/**\n\t * The page's tools that ask before they run (`consequentialHint`, callable\n\t * by AI apps through the relay), in the order registered.\n\t */\n\ttools(): AllowedTool[];\n\t/**\n\t * The names of the tools allowed one by one for this app, in the order\n\t * allowed; also one that is not registered right now (it runs without\n\t * asking again once it is back unchanged). One registered now with another\n\t * title or description than the user allowed is not in it (it asks).\n\t */\n\tlist(grantId: string): string[];\n\t/**\n\t * Whether a call of this tool by this app runs without asking now:\n\t * \"everything\" is on, or the tool is allowed and registered unchanged.\n\t */\n\thas(grantId: string, name: string): boolean;\n\t/**\n\t * Allow one tool for this app from now on, as it is registered now (its\n\t * title and description). Nothing happens for an app that is not in\n\t * `mcp.grants` or a tool that is not in `tools()`.\n\t */\n\tallow(grantId: string, name: string): void;\n\t/**\n\t * Ask again before this app runs this tool. While \"everything\" is on for\n\t * the app, that goes off too (asking again errs towards asking); the\n\t * other tools allowed one by one stay allowed.\n\t */\n\task(grantId: string, name: string): void;\n\t/** Whether \"Allow everything, no questions asked\" is on for this app. */\n\teverything(grantId: string): boolean;\n\t/**\n\t * \"Allow everything, no questions asked\" for this app: every tool runs\n\t * without asking, with any arguments, also tools registered later, changed\n\t * ones and destructive ones. Turning it on does nothing for an app that\n\t * is not in `mcp.grants`.\n\t */\n\tsetEverything(grantId: string, on: boolean): void;\n\t/** Ask again for everything of this app: its tools and \"everything\". */\n\tforget(grantId: string): void;\n\t/**\n\t * Calls `listener` on every change of the allowances (also one in\n\t * another tab of the same address) and of `tools()`; returns what stops it.\n\t */\n\tonChange(listener: () => void): () => void;\n}\n\n/** One app's allowances. */\ninterface Entry {\n\teverything: boolean;\n\t/** In the order allowed; `title` and `description` as the user saw them. */\n\ttools: ToolSeen[];\n}\n\n/** What is kept: the grants' entries and the secret they belong to. */\ninterface State {\n\t/** {@link fingerprint} of the address secret. */\n\tsecret: string;\n\tgrants: Map<string, Entry>;\n}\n\n/**\n * A short fingerprint of the address secret (FNV-1a, 32 bits): enough to\n * tell that the secret changed, too short to say anything about it.\n */\nfunction fingerprint(secret: string | undefined): string {\n\tif (secret === undefined) return \"\";\n\tlet hash = 0x811c9dc5;\n\tfor (let i = 0; i < secret.length; i++)\n\t\thash = Math.imul(hash ^ secret.charCodeAt(i), 0x01000193) >>> 0;\n\treturn hash.toString(16);\n}\n\nconst isString = (v: unknown): v is string => typeof v === \"string\";\n\n/**\n * The kept text as a state; anything that is not exactly what\n * {@link serialize} writes allows nothing.\n */\nfunction parse(text: string): State {\n\tconst none: State = { secret: \"\", grants: new Map() };\n\tlet value: unknown;\n\ttry {\n\t\tvalue = JSON.parse(text);\n\t} catch {\n\t\treturn none;\n\t}\n\tconst v = value as { secret?: unknown; grants?: unknown } | null;\n\tif (!isString(v?.secret) || !Array.isArray(v.grants)) return none;\n\tconst grants = new Map<string, Entry>();\n\tfor (const g of v.grants as unknown[]) {\n\t\tconst e = g as {\n\t\t\tgrantId?: unknown;\n\t\t\teverything?: unknown;\n\t\t\ttools?: unknown;\n\t\t} | null;\n\t\tif (\n\t\t\t!isString(e?.grantId) ||\n\t\t\ttypeof e.everything !== \"boolean\" ||\n\t\t\t!Array.isArray(e.tools)\n\t\t)\n\t\t\treturn none;\n\t\tconst tools: ToolSeen[] = [];\n\t\tfor (const t of e.tools as unknown[]) {\n\t\t\tconst tool = t as Partial<Record<keyof ToolSeen, unknown>> | null;\n\t\t\tif (\n\t\t\t\t!isString(tool?.name) ||\n\t\t\t\t!isString(tool.description) ||\n\t\t\t\t(tool.title !== undefined && !isString(tool.title))\n\t\t\t)\n\t\t\t\treturn none;\n\t\t\ttools.push(seenOf(tool as ToolSeen));\n\t\t}\n\t\tgrants.set(e.grantId, { everything: e.everything, tools });\n\t}\n\treturn { secret: v.secret, grants };\n}\n\n/** Grant ids, tool names and what the user saw of each: no arguments, no results. */\nfunction serialize(state: State): string {\n\treturn JSON.stringify({\n\t\tsecret: state.secret,\n\t\tgrants: [...state.grants].map(([grantId, e]) => ({ grantId, ...e })),\n\t});\n}\n\n/** Only what the user saw, as plain strings. */\nfunction seenOf(tool: ToolSeen): ToolSeen {\n\tconst seen: ToolSeen = { name: tool.name, description: tool.description };\n\tif (tool.title !== undefined) seen.title = tool.title;\n\treturn seen;\n}\n\nconst sameSeen = (a: ToolSeen, b: ToolNow) =>\n\ta.title === b.title && a.description === b.description;\n\n/**\n * Whether a tool allowed as `kept` still counts against what is registered\n * now (`now`, `undefined` when it is not): unchanged, or not registered. The\n * one rule for drawing (`list`) and for deciding (`has`).\n */\nconst counts = (kept: ToolSeen, now: ToolNow | undefined) =>\n\tnow === undefined || sameSeen(kept, now);\n\n/**\n * The allowances of one `TabMcp`. The public methods are arrow fields, so\n * that they work taken off the object; the queries never write.\n */\nexport class Allowances implements AllowedTools {\n\treadonly kept: boolean;\n\t/** The library's dialogs offer allowing (`alwaysAllow` on). */\n\treadonly offered: boolean;\n\treadonly #mcp: TabMcp;\n\treadonly #registry: ToolRegistry;\n\treadonly #secret: () => string;\n\t/** `null`: in memory only. */\n\treadonly #storage: SecretStorage | null;\n\treadonly #key: string;\n\t#memory: State = { secret: \"\", grants: new Map() };\n\t/**\n\t * The last write to storage failed (quota, blocked): memory holds what the\n\t * user chose, for the page's lifetime, and storage is not read over it\n\t * until a write succeeds again.\n\t */\n\t#unsaved = false;\n\treadonly #listeners = new Set<() => void>();\n\t#unwatch: (() => void) | undefined;\n\n\tconstructor(mcp: TabMcp) {\n\t\tconst [registry, secrets, alwaysAllow] = mcp._allowed;\n\t\tthis.#mcp = mcp;\n\t\tthis.#registry = registry;\n\t\tthis.#secret = () => fingerprint(secrets?.current());\n\t\tthis.#storage =\n\t\t\talwaysAllow === \"until-reload\" ? null : (secrets?.storage ?? null);\n\t\tthis.#key = `${secrets?.key}#allowed`;\n\t\tthis.kept = this.#storage !== null;\n\t\tthis.offered = alwaysAllow === true || alwaysAllow === \"until-reload\";\n\t}\n\n\treadonly tools = (): AllowedTool[] =>\n\t\tthis.#registry\n\t\t\t.list()\n\t\t\t.filter(\n\t\t\t\t(t) =>\n\t\t\t\t\tt.annotations.consequentialHint === true &&\n\t\t\t\t\t(t.callers?.includes(\"relay\") ?? true),\n\t\t\t)\n\t\t\t.map((t) => {\n\t\t\t\tconst tool: AllowedTool = {\n\t\t\t\t\tname: t.name,\n\t\t\t\t\tdescription: t.description,\n\t\t\t\t\tdestructive: t.annotations.destructiveHint === true,\n\t\t\t\t};\n\t\t\t\tif (t.title !== undefined) tool.title = t.title;\n\t\t\t\treturn tool;\n\t\t\t});\n\n\treadonly list = (grantId: string): string[] =>\n\t\t(this.#read().get(grantId)?.tools ?? [])\n\t\t\t.filter((t) => counts(t, this.#registry.get(t.name)))\n\t\t\t.map((t) => t.name);\n\n\treadonly has = (grantId: string, name: string): boolean => {\n\t\tconst tool = this.#registry.get(name);\n\t\treturn (\n\t\t\tthis.everything(grantId) ||\n\t\t\t(tool !== undefined && this.allows(grantId, tool))\n\t\t);\n\t};\n\n\t/**\n\t * Whether this call runs without asking: \"everything\", or this tool as\n\t * the user saw it. Only reads: a tool that changed since asks, and leaves\n\t * the list when the registry or another tab's change is seen\n\t * (`toolsChanged`).\n\t */\n\tallows(grantId: string, tool: ToolNow): boolean {\n\t\tconst entry = this.#read().get(grantId);\n\t\tif (entry === undefined) return false;\n\t\tif (entry.everything) return true;\n\t\tconst kept = entry.tools.find((t) => t.name === tool.name);\n\t\treturn kept !== undefined && sameSeen(kept, tool);\n\t}\n\n\treadonly allow = (grantId: string, name: string): void => {\n\t\tconst tool = this.tools().find((t) => t.name === name);\n\t\tif (tool !== undefined) this.keep(grantId, tool);\n\t};\n\n\t/** Allow `tool` as the user saw it, for an app the relay still lists. */\n\tkeep(grantId: string, tool: ToolSeen): void {\n\t\tif (!this.#granted(grantId)) return;\n\t\tconst grants = this.#read();\n\t\tconst entry = grants.get(grantId) ?? { everything: false, tools: [] };\n\t\tentry.tools = [\n\t\t\t...entry.tools.filter((t) => t.name !== tool.name),\n\t\t\tseenOf(tool),\n\t\t];\n\t\tgrants.set(grantId, entry);\n\t\tthis.#write(grants);\n\t}\n\n\treadonly ask = (grantId: string, name: string): void => {\n\t\tconst grants = this.#read();\n\t\tconst entry = grants.get(grantId);\n\t\tif (entry === undefined) return;\n\t\tconst tools = entry.tools.filter((t) => t.name !== name);\n\t\t// Under \"everything\" this tool ran without asking too: asking again\n\t\t// for it turns that off; the tools allowed one by one stay.\n\t\tif (!entry.everything && tools.length === entry.tools.length) return;\n\t\tentry.everything = false;\n\t\tentry.tools = tools;\n\t\tif (tools.length === 0) grants.delete(grantId);\n\t\tthis.#write(grants);\n\t};\n\n\treadonly everything = (grantId: string): boolean =>\n\t\tthis.#read().get(grantId)?.everything === true;\n\n\treadonly setEverything = (grantId: string, on: boolean): void => {\n\t\tif (on && !this.#granted(grantId)) return;\n\t\tconst grants = this.#read();\n\t\tconst entry = grants.get(grantId) ?? { everything: false, tools: [] };\n\t\tif (entry.everything === on) return;\n\t\tentry.everything = on;\n\t\tif (on || entry.tools.length > 0) grants.set(grantId, entry);\n\t\telse grants.delete(grantId);\n\t\tthis.#write(grants);\n\t};\n\n\treadonly forget = (grantId: string): void => {\n\t\tconst grants = this.#read();\n\t\tif (grants.delete(grantId)) this.#write(grants);\n\t};\n\n\t/**\n\t * Only the grants the relay lists now: the others ended. What was kept\n\t * under another secret is dropped from storage too (it allowed nothing\n\t * already).\n\t */\n\tkeepGrants(grantIds: Iterable<string>): void {\n\t\tconst keep = new Set(grantIds);\n\t\tconst grants = this.#read();\n\t\t// Kept under another secret: nothing to write unless something was kept.\n\t\tlet changed =\n\t\t\tthis.#memory.grants !== grants && this.#memory.grants.size > 0;\n\t\tfor (const grantId of [...grants.keys()])\n\t\t\tif (!keep.has(grantId)) changed = grants.delete(grantId) || changed;\n\t\tif (changed) this.#write(grants);\n\t}\n\n\t/**\n\t * The registry changed, or another tab changed the allowances: a tool\n\t * registered with another title or description than the user saw leaves\n\t * every list. One that is not registered stays (a reload registers them\n\t * all again, a page may offer some only on some views). Tells the\n\t * listeners in any case.\n\t */\n\ttoolsChanged(): void {\n\t\tconst grants = this.#read();\n\t\tlet changed = false;\n\t\tfor (const [grantId, entry] of [...grants]) {\n\t\t\tconst tools = entry.tools.filter((t) =>\n\t\t\t\tcounts(t, this.#registry.get(t.name)),\n\t\t\t);\n\t\t\tif (tools.length === entry.tools.length) continue;\n\t\t\tchanged = true;\n\t\t\tentry.tools = tools;\n\t\t\tif (!entry.everything && tools.length === 0) grants.delete(grantId);\n\t\t}\n\t\tif (changed) this.#write(grants);\n\t\telse this.#changed();\n\t}\n\n\treadonly onChange = (listener: () => void): (() => void) => {\n\t\tthis.#listeners.add(listener);\n\t\tthis.#watch();\n\t\treturn () => {\n\t\t\tthis.#listeners.delete(listener);\n\t\t\tif (this.#listeners.size === 0) {\n\t\t\t\tthis.#unwatch?.();\n\t\t\t\tthis.#unwatch = undefined;\n\t\t\t}\n\t\t};\n\t};\n\n\t/**\n\t * Another tab changed them: clean up against this page's tools and tell\n\t * the listeners (only while there are some).\n\t */\n\t#watch(): void {\n\t\tif (this.#unwatch !== undefined || this.#storage === null) return;\n\t\tconst g = globalThis as Partial<EventTarget>;\n\t\tconst changed = (event: Event) => {\n\t\t\tif ((event as StorageEvent).key === this.#key) this.toolsChanged();\n\t\t};\n\t\tg.addEventListener?.(\"storage\", changed);\n\t\tthis.#unwatch = () => g.removeEventListener?.(\"storage\", changed);\n\t}\n\n\t#granted(grantId: string): boolean {\n\t\treturn this.#mcp.grants.some((g) => g.grantId === grantId);\n\t}\n\n\t/**\n\t * The allowances now: storage first, so that another tab's change counts;\n\t * memory where storage cannot be read or the last write to it failed.\n\t * None once the secret changed.\n\t */\n\t#read(): Map<string, Entry> {\n\t\tif (this.#storage !== null && !this.#unsaved) {\n\t\t\ttry {\n\t\t\t\tconst text = this.#storage.getItem(this.#key);\n\t\t\t\tif (text !== null) this.#memory = parse(text);\n\t\t\t} catch {\n\t\t\t\t// unreadable: what this page kept in memory\n\t\t\t}\n\t\t}\n\t\treturn this.#memory.secret === this.#secret()\n\t\t\t? this.#memory.grants\n\t\t\t: new Map();\n\t}\n\n\t#write(grants: Map<string, Entry>): void {\n\t\tthis.#memory = { secret: this.#secret(), grants };\n\t\ttry {\n\t\t\tthis.#storage?.setItem(this.#key, serialize(this.#memory));\n\t\t\tthis.#unsaved = false;\n\t\t} catch {\n\t\t\t// quota or blocked: kept in memory for the page's lifetime\n\t\t\tthis.#unsaved = true;\n\t\t}\n\t\tthis.#changed();\n\t}\n\n\t#changed(): void {\n\t\tfor (const listener of [...this.#listeners]) listener();\n\t}\n}\n\n/** The allowances per `TabMcp`. */\nconst allowances = new WeakMap<TabMcp, Allowances>();\n\n/**\n * The allowances of `mcp`, made on first use. They follow its grants (only\n * when the relay names them, see above) and its tools.\n */\nexport function allowedFor(mcp: TabMcp): Allowances {\n\tconst kept = allowances.get(mcp);\n\tif (kept !== undefined) return kept;\n\tconst made = new Allowances(mcp);\n\tallowances.set(mcp, made);\n\tmcp.addEventListener(\"grantschange\", (e) =>\n\t\tmade.keepGrants(e.detail.grants.map((g) => g.grantId)),\n\t);\n\tmcp._allowed[0].onChange(() => made.toolsChanged());\n\tmade.toolsChanged(); // tools may have changed since the last page kept them\n\t// Made while connected: the grants are the relay's, the others ended.\n\tif (mcp.session !== undefined)\n\t\tmade.keepGrants(mcp.grants.map((g) => g.grantId));\n\treturn made;\n}\n"
|
|
6
|
+
],
|
|
7
|
+
"mappings": "AA+HA,SAAS,CAAW,CAAC,EAAoC,CACxD,GAAI,IAAW,OAAW,MAAO,GACjC,IAAI,EAAO,WACX,QAAS,EAAI,EAAG,EAAI,EAAO,OAAQ,IAClC,EAAO,KAAK,KAAK,EAAO,EAAO,WAAW,CAAC,EAAG,QAAU,IAAM,EAC/D,OAAO,EAAK,SAAS,EAAE,EAGxB,IAAM,EAAW,CAAC,IAA4B,OAAO,IAAM,SAM3D,SAAS,CAAK,CAAC,EAAqB,CACnC,IAAM,EAAc,CAAE,OAAQ,GAAI,OAAQ,IAAI,GAAM,EAChD,EACJ,GAAI,CACH,EAAQ,KAAK,MAAM,CAAI,EACtB,KAAM,CACP,OAAO,EAER,IAAM,EAAI,EACV,GAAI,CAAC,EAAS,GAAG,MAAM,GAAK,CAAC,MAAM,QAAQ,EAAE,MAAM,EAAG,OAAO,EAC7D,IAAM,EAAS,IAAI,IACnB,QAAW,KAAK,EAAE,OAAqB,CACtC,IAAM,EAAI,EAKV,GACC,CAAC,EAAS,GAAG,OAAO,GACpB,OAAO,EAAE,aAAe,WACxB,CAAC,MAAM,QAAQ,EAAE,KAAK,EAEtB,OAAO,EACR,IAAM,EAAoB,CAAC,EAC3B,QAAW,KAAK,EAAE,MAAoB,CACrC,IAAM,EAAO,EACb,GACC,CAAC,EAAS,GAAM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EACzC,KAAK,GAAQ,OACb,IAAI,IAGR,EAAM,CAAC,EAAkC,CACxC,KAAK,GAAU,CAAE,OAAQ,KAAK,GAAQ,EAAG,QAAO,EAChD,GAAI,CACH,KAAK,IAAU,QAAQ,KAAK,GAAM,EAAU,KAAK,EAAO,CAAC,EACzD,KAAK,GAAW,GACf,KAAM,CAEP,KAAK,GAAW,GAEjB,KAAK,GAAS,EAGf,EAAQ,EAAS,CAChB,QAAW,IAAY,CAAC,GAAG,KAAK,EAAU,EAAG,EAAS,EAExD,CAGA,IAAM,EAAa,IAAI,QAMhB,SAAS,CAAU,CAAC,EAAyB,CACnD,IAAM,EAAO,EAAW,IAAI,CAAG,EAC/B,GAAI,IAAS,OAAW,OAAO,EAC/B,IAAM,EAAO,IAAI,EAAW,CAAG,EAQ/B,GAPA,EAAW,IAAI,EAAK,CAAI,EACxB,EAAI,iBAAiB,eAAgB,CAAC,IACrC,EAAK,WAAW,EAAE,OAAO,OAAO,IAAI,CAAC,IAAM,EAAE,OAAO,CAAC,CACtD,EACA,EAAI,SAAS,GAAG,SAAS,IAAM,EAAK,aAAa,CAAC,EAClD,EAAK,aAAa,EAEd,EAAI,UAAY,OACnB,EAAK,WAAW,EAAI,OAAO,IAAI,CAAC,IAAM,EAAE,OAAO,CAAC,EACjD,OAAO",
|
|
8
|
+
"debugId": "F41620924049606564756E2164756E21",
|
|
9
|
+
"names": []
|
|
10
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var
|
|
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 I(e,t,n=0,i=!1){if(n>64||typeof e!=="object"||e===null)return;if(i||=Array.isArray(e),!i)t(e);for(let[r,o]of Object.entries(e))if(i||!D.test(r))I(o,t,n+1,!i&&j.test(r))}function N(e,t){let n=e;for(let i of t.split("/").slice(1)){let r;try{r=decodeURIComponent(i)}catch{return}if(r=r.replaceAll("~1","/").replaceAll("~0","~"),typeof n!=="object"||n===null||!Object.hasOwn(n,r))return;n=n[r]}return n}function H(e){let t=new Set,n=[],i=[],r=!1;if(I(e,(o)=>{if(typeof o.$anchor==="string")t.add(o.$anchor);if(typeof o.$ref==="string")n.push(o.$ref);if(typeof o.pattern==="string")i.push(o.pattern);let s=o.patternProperties;if(g(s))i.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 i)try{new RegExp(o,"u")}catch{return`pattern ${JSON.stringify(o)} is not a valid regular expression`}for(let o of n){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:n,description:i,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 i!=="string"||i.trim()==="")throw TypeError(`registerTool: tool ${t} needs a description`);if(n!==void 0&&typeof n!=="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=(l,h)=>{if(!g(l)||l.type!=="object")throw TypeError(`registerTool: the ${h} of ${t} must be a JSON Schema object with "type": "object"`);let y;try{y=JSON.parse(JSON.stringify(l))}catch{throw TypeError(`registerTool: the ${h} of ${t} must be JSON`)}let C=H(y);if(C!==void 0)throw TypeError(`registerTool: the ${h} of ${t}: ${C}`);return y},c=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[l,h]of Object.entries(a??{}))if(typeof h==="boolean")u[l]=h;else if(h!==void 0&&/Hint$|^debugging$/.test(l))throw TypeError(`registerTool: ${l} of ${t} must be a boolean`);return{name:t,title:n,description:i,inputSchema:c,outputSchema:o===void 0?void 0:d(o,"outputSchema"),annotations:u,execute:s}}class w{#e=new Map;#i=new Set;#a;register(e,t={}){let{signal:n,exposedTo:i}=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:i};if(n?.throwIfAborted(),this.#e.has(o.name))throw new DOMException(`registerTool: a tool named ${o.name} is already registered`,"InvalidStateError");this.#a?.(o),this.#e.set(o.name,o),n?.addEventListener("abort",()=>this.remove(o),{once:!0}),this.#f()}setCompiler(e){this.#a??=e}remove(e){if(this.#e.get(e.name)!==e)return;this.#e.delete(e.name),this.#f()}get(e){return this.#e.get(e)}list(){return[...this.#e.values()]}onChange(e){return this.#i.add(e),()=>this.#i.delete(e)}#f(){for(let e of[...this.#i])e()}}var J=/^[A-Za-z0-9_-]{43}$/;function K(e){return btoa(String.fromCharCode(...e)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function U(){return K(crypto.getRandomValues(new Uint8Array(32)))}function G(e){return typeof e==="string"&&J.test(e)}function z(){try{return globalThis.localStorage??null}catch{return null}}class b{#e;#i;#a;constructor(e,t){this.#e=e===void 0?z():e,this.#i=t}current(){let e=null;try{e=this.#e?.getItem(this.#i)??null}catch{}if(G(e))return this.#a=e,e;return this.#a}rotate(){let e=U();this.#a=e;try{this.#e?.setItem(this.#i,e)}catch{}return e}}var O="0.16.2";var M="@ractive-ch/tab-mcp-client",T=O;function q(){try{return Object.getOwnPropertyDescriptor(Document.prototype,"modelContext")?.get?.call(document)}catch{return}}var V=new Set(["localhost","127.0.0.1","[::1]"]),S={reconnectDelaysMs:[5000,1e4,20000,40000,60000],answerTimeoutMs:15000},P=new Set(["network","heartbeat","shutdown"]);function B(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 n=t.codePointAt(0)??0;return n<32||n>=127&&n<=159})}function Z(e){let t;try{t=new URL(e)}catch{throw TypeError(`TabMcp: relay is not a URL: ${e}`)}let n=t.protocol==="https:"||t.protocol==="wss:";if(!n&&t.protocol!=="http:"&&t.protocol!=="ws:")throw TypeError(`TabMcp: relay must be an https: or wss: URL: ${e}`);if(!n&&!V.has(t.hostname))throw TypeError(`TabMcp: relay must use https: or wss: (http: only for localhost): ${e}`);let i=`${n?"https:":"http:"}//${t.host}`,r=t.pathname.replace(/\/+$/,"");return t.protocol=n?"wss:":"ws:",t.pathname=r.endsWith("/tab")?r:`${r}/tab`,t.search="",t.hash="",{url:t.href,origin:i}}function F(e){try{return new URL(e).host}catch{return""}}function Q(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 m(){return Promise.reject(TypeError("TabMcp: this TabMcp has no relay"))}function A(e,t){return Object.assign(Object(e),{addressChanged:t})}function E(){return Promise.reject(new DOMException("TabMcp: not connected","InvalidStateError"))}class x extends EventTarget{#e=new w;#i;#a;#f;#$;#I;#y;#v;#j;#w=!1;#b;#O;#T="none";#M;#c=0;#o="disconnected";#d;#h=Object.freeze([]);#m=!1;#P;#t;#r;#u=0;#N;#p;#g;#S;#E;#A={registry:this.#e,confirm:(e)=>this.#W(e),ownConfirm:()=>!!this.#f,toolCallStarted:(e)=>this.#n("toolcall",e),toolCallEnded:(e)=>this.#n("toolcallend",e)};constructor(e){super();let{server:t,appName:n}=e,i=e.relay===void 0?void 0:Z(e.relay);if(typeof t?.name!=="string"||typeof t.version!=="string")throw TypeError("TabMcp: server needs a name and a version");if(n!==void 0&&!Y(n))throw TypeError("TabMcp: appName must be 1-64 characters without control characters");if(this.#y=i?.url,this.#i={...t},this.#a=n,this.#f=e.onConfirm,this.#$=e.alwaysAllow===!0,this.#I=e.ui,this.#O=e.identityAssertion,this.#N=e.reconnect!==!1,i!==void 0){let o=e.storageKey??`tab-mcp:secret:${i.origin}:${encodeURIComponent(t.name)}`;this.#v=new b(e.storage,o),this.#j=e.storage===null?void 0:`${o}#tabs`}this.#e.onChange(()=>this.#n("toolschange",{tools:this.tools}));let r=e.webmcp===!0?q():void 0;if(r!==void 0)(f("khy4f5rj"),import("./webmcp-khy4f5rj.min.js")).then((o)=>o.mirror(this.#e,r,(s,a,d)=>this.#k().then((c)=>c.callFromWebMcp(this.#A,s,a,d))),(o)=>console.warn("tab-mcp: no tools are offered through WebMCP:",o))}registerTool(e,t={}){try{this.#e.register(e,t)}catch(n){return Promise.reject(n)}return Promise.resolve()}get tools(){return this.#e.list().map((e)=>e.name)}get state(){return this.#o}get session(){return this.#d}get grants(){return this.#h}get reconnecting(){return this.#p}get identity(){return this.#T}get identityMessage(){return this.#M}refreshIdentity(){let e=this.#d,t=this.#O;if(t===void 0)return Promise.reject(TypeError("TabMcp: no identityAssertion"));if(e===void 0)return E();let n=++this.#c,i=this.#t;this.#s("pending");let r=setTimeout(()=>{if(n!==this.#c||this.#T!=="pending")return;this.#c++,this.#s("none")},S.answerTimeoutMs);return new Promise((o)=>{let s=(a)=>{let{identity:d}=a.detail;if(d==="pending")return;this.removeEventListener("identitychange",s),clearTimeout(r),o(d)};this.addEventListener("identitychange",s),Promise.resolve().then(()=>t({address:e.address,sessionId:e.sessionId})).then((a)=>{if(n!==this.#c||this.#t!==i)return;if(typeof a!=="string"||a===""){this.#s("none");return}if(i?.send({type:"identity",assertion:a,round:n})!==!0)this.#s("none")},(a)=>{if(n!==this.#c)return;this.#n("error",{error:a instanceof Error?a:Error(String(a))}),this.#s("none")})})}signOut(){return this.#c++,this.#s("none"),this.#d?.pairing==="oidc"?this.#K({type:"identity.logout"},()=>!this.#h.length):E()}get pairingCode(){return this.#P}connect(e={}){if(this.#y===void 0)return m();if(this.#o==="connected"&&this.#d!==void 0)return Promise.resolve(this.#d);if(this.#r!==void 0)return this.#r;if(this.#p!==void 0)return this.#L();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.#b?this.#b.then(()=>this.connect({resume:!0})):this.#x()}#x(){if(!this.#p)this.#l("connecting");let e=this.#H(this.#u);return this.#r=e,e.then(()=>{if(this.#r===e)this.#r=void 0},()=>{if(this.#r!==e)return;if(this.#r=void 0,this.#t=void 0,!this.#p)this.#l("disconnected")}),e}async#k(){let e=await (f("w97tf22a"),import("./connection-w97tf22a.min.js"));for(let t of e.compileRegistry(this.#e))this.#n("error",{error:t});return e}async#H(e,t){let{openConnection:n,addressIdOf:i,withAddress:r}=await this.#k(),o=this.#y;if(o===void 0||this.#v===void 0)return m();let s=t??this.#v.current()??this.#v.rotate(),a=await i(s);if(e!==this.#u)throw new DOMException("The connection was cancelled","AbortError");let d={},c=n(this.#q(d),r(o,a),s,{address:a,revokeAll:!!t});if(!t)d.connection=c;return this.#t=c,c.ready}get hasRelay(){return this.#y!==void 0}serve(e,t){return this.#k().then((n)=>n.servePort({...this.#A,server:this.#i,error:(i)=>this.#n("error",{error:i})},e,t))}disconnect(){this.#_("user")}newAddress(){let e=this.#v;if(!e)return m();return this.#b??=this.#U(e).finally(()=>{this.#b=void 0})}async#U(e){let t=this.#o!=="disconnected"||this.#w,n=e.current();this.#_("new_address");let i=this.#u;if(n){this.#l("connecting");try{await this.#H(i,n)}catch(r){if(i===this.#u)this.#l("disconnected"),this.#w=t;throw A(r,!1)}finally{if(i===this.#u)this.#t?.close("new_address"),this.#t=void 0}}if(e.rotate(),this.#R([]),t)await this.#x().catch((r)=>{throw A(r,!0)});else this.#l("disconnected")}#_(e){this.#D(),this.#w=!1,this.#u++;let t=this.#t;if(this.#t=void 0,this.#r=void 0,t?.close(e),this.#o==="disconnected")return;this.#d=void 0,this.#C(void 0),this.#c++,this.#s("none"),this.#l("disconnected",e)}#J(e,t){let n=S.reconnectDelaysMs,i=(n[Math.min(t,n.length)-1]??0)*(0.8+0.4*Math.random());clearTimeout(this.#g),this.#g=setTimeout(()=>{this.#L().catch(()=>{})},i),this.#G(),this.#p={reason:e,attempt:t,at:Date.now()+i},this.#l("reconnecting",t>1?void 0:e)}#L(){if(clearTimeout(this.#g),this.#g=void 0,this.#r!==void 0)return this.#r;let e=this.#x();return e.catch((t)=>{let n=this.#p;if(n===void 0||this.#r!==void 0)return;let i=t?.reason;if(i===void 0||P.has(i)){this.#J(n.reason,n.attempt+1);return}if(this.#D(),this.#o="disconnected",this.#n("error",{error:t instanceof Error?t:Error(String(t))}),this.#o==="disconnected")this.#n("statechange",{state:"disconnected"})}),e}#G(){if(this.#S!==void 0)return;let e=globalThis,t=globalThis.document,n=()=>{if(this.#g!==void 0)this.#L().catch(()=>{})},i=()=>{if(t?.visibilityState!=="hidden")n()};t?.addEventListener("visibilitychange",i),e.addEventListener?.("online",n),this.#S=()=>{t?.removeEventListener("visibilitychange",i),e.removeEventListener?.("online",n)}}#D(){clearTimeout(this.#g),this.#g=void 0,this.#S?.(),this.#S=void 0,this.#p=void 0}startPairing(){if(this.#m)return;if(this.#m=!0,this.#o==="connected")this.#t?.send({type:"pairing.start"})}stopPairing(){if(!this.#m)return;if(this.#m=!1,this.#o==="connected")this.#t?.send({type:"pairing.stop"});this.#C(void 0)}revoke(e){let t=()=>!this.#h.some((n)=>n.grantId===e);return t()?Promise.resolve():this.#K({type:"grant.revoke",grantId:e},t)}#K(e,t){if(!this.#d||this.#t?.send(e)!==!0)return E();return new Promise((n,i)=>{let r=["grantschange","statechange","error"],o=(d)=>{clearTimeout(a);for(let c of r)this.removeEventListener(c,s);if(d)i(d);else n()},s=(d)=>{let c=d?.detail?.error;if(t())o();else if((c?.code==="store_unavailable"||c?.code==="unknown_id")&&(c.for===void 0||c.for===e.type&&c.grantId===e.grantId))o(c);else if(this.#o!=="connected")o(new DOMException("TabMcp: the session ended before the relay answered","NetworkError"))},a=setTimeout(()=>o(new DOMException("TabMcp: the relay did not answer","TimeoutError")),S.answerTimeoutMs);for(let d of r)this.addEventListener(d,s);s()})}showConnectDialog(e={}){if(this.#y===void 0)return m();let t=e.document??globalThis.document,n=this.#E;if(n!==void 0)return n.doc===t?n.shown:Promise.reject(new DOMException("showConnectDialog: the dialog is already open in another document","InvalidStateError"));let i=this.#z(t).finally(()=>{if(this.#E?.shown===i)this.#E=void 0});return this.#E={doc:t,shown:i},i}async#z(e){let t=this.connect();t.catch(()=>{});let{showConnectDialog:n}=await (f("bbhj2y7w"),import("./connect-bbhj2y7w.min.js"));await n(this,t,e,this.#i.name,this.#I)}addEventListener(e,t,n){super.addEventListener(e,t,n)}removeEventListener(e,t,n){super.removeEventListener(e,t,n)}#n(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))}#l(e,t){if(this.#o===e&&e!=="reconnecting")return;this.#o=e,this.#n("statechange",t?{state:e,reason:t}:{state:e})}#s(e,t){if(this.#T===e&&t===void 0)return;this.#T=e,this.#M=e==="refused"?t:void 0,this.#n("identitychange",{identity:e,identityMessage:this.#M})}#C(e){if(this.#P===void 0&&e===void 0)return;this.#P=e,this.#n("pairingcode",{pairingCode:e})}#R(e){this.#h=Object.freeze(e.map(B)),this.#n("grantschange",{grants:this.#h})}#W(e){if(this.#f!==void 0){let t=this.#f;return Promise.resolve().then(()=>t(e)).then((n)=>n==="unanswered"?n:n===!0)}return this.confirmInPage(e)}confirmInPage(e,t={}){let n=t.document??globalThis.document;if(n===void 0)return Promise.resolve(!1);return (f("y30cx7e1"),import("./confirm-y30cx7e1.min.js")).then((i)=>i.confirmInPage(this,e,n,{alwaysAllow:this.#$,ui:this.#I}))}#q(e){let t=()=>e.connection!==void 0&&this.#t===e.connection,n=!1;return{...this.#A,server:this.#i,appName:this.#a,tabs:this.#j,library:{name:M,version:T},clientFor:(i)=>{let r=this.#h.find((s)=>s.grantId===i.grantId),o={kind:"relay",grantId:i.grantId,id:i.clientId,host:F(i.clientId)};if(r!==void 0)o.name=r.client.name;return o},sessionStarted:(i)=>{let r=Q(i);if(!t())return r;if(this.#d=r,this.#w=!1,this.#D(),this.#R([...i.grants]),this.#m)this.#t?.send({type:"pairing.start"});if(this.#l("connected"),r.pairing==="oidc"&&this.#O)this.refreshIdentity();return r},pairingCode:(i)=>{if(t()&&this.#m)this.#C(i)},grantAdded:(i)=>{if(!t())return;this.#R([...this.#h.filter((r)=>r.grantId!==i.grantId),i])},grantRemoved:(i)=>{if(!t())return;this.#R(this.#h.filter((r)=>r.grantId!==i))},replaced:(i)=>{if(n)this.#n("replaced",i)},identityResult:(i,r,o)=>{if(!t())return;if(r!==this.#c)return;if(i)this.#s("bound");else this.#s("refused",o??"")},error:(i)=>{if(t())this.#n("error",{error:i})},closed:(i)=>{if(!t())return;if(i==="replaced")this.#w=n=!0;this.#t=void 0,this.#d=void 0;let r=this.#u;if(this.#C(void 0),this.#c++,this.#s("none"),r!==this.#u)return;if(this.#N&&P.has(i))this.#J(i,1);else this.#l("disconnected",i)}}}}export{x as TabMcp,T as VERSION};
|
|
1
|
+
var O,v,p,f=(e,t)=>{for(var[n,i,r]of O||[])for(var o=[e],s=globalThis,a=s.document,c,d,u,l,h;d=o.pop();)if(!v[d]&&(u=i[d])){v[d]=1;for(l=1;l<u.length;l++)o.push(r[u[l]]);if(!t&&d!==e&&(c=a&&a.head)){if(p===void 0)p=(l=a.querySelector("meta[property=csp-nonce]"))&&(l.nonce||l.getAttribute("nonce"))||"";if(h=a.createElement("link"),h.rel="modulepreload",h.crossOrigin="",p)h.nonce=p;h.href=new s.URL(u[0],n),c.appendChild(h)}}},k=(e,t,n,i)=>{for(var r={},o=0;o<t.length;o++)r[t[o]]=n[o];(O||=[]).push([e,r,t]),v||={},f(t[i],1)};k(import.meta.url,["rjbee49n","khy4f5rj","0xqwz17v","ph4xxen4","f36n8xj5","2vx9mcww","6gcmd7n8"],[["./tab-mcp-client.min.js"],["./webmcp-khy4f5rj.min.js"],["./connection-0xqwz17v.min.js"],["./connect-ph4xxen4.min.js",5,6],["./confirm-f36n8xj5.min.js",5,6],["./tab-mcp-client-2vx9mcww.min.js"],["./tab-mcp-client-6gcmd7n8.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,n=0,i=!1){if(n>64||typeof e!=="object"||e===null)return;if(i||=Array.isArray(e),!i)t(e);for(let[r,o]of Object.entries(e))if(i||!D.test(r))R(o,t,n+1,!i&&j.test(r))}function N(e,t){let n=e;for(let i of t.split("/").slice(1)){let r;try{r=decodeURIComponent(i)}catch{return}if(r=r.replaceAll("~1","/").replaceAll("~0","~"),typeof n!=="object"||n===null||!Object.hasOwn(n,r))return;n=n[r]}return n}function H(e){let t=new Set,n=[],i=[],r=!1;if(R(e,(o)=>{if(typeof o.$anchor==="string")t.add(o.$anchor);if(typeof o.$ref==="string")n.push(o.$ref);if(typeof o.pattern==="string")i.push(o.pattern);let s=o.patternProperties;if(g(s))i.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 i)try{new RegExp(o,"u")}catch{return`pattern ${JSON.stringify(o)} is not a valid regular expression`}for(let o of n){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:n,description:i,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 i!=="string"||i.trim()==="")throw TypeError(`registerTool: tool ${t} needs a description`);if(n!==void 0&&typeof n!=="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 c=(l,h)=>{if(!g(l)||l.type!=="object")throw TypeError(`registerTool: the ${h} of ${t} must be a JSON Schema object with "type": "object"`);let y;try{y=JSON.parse(JSON.stringify(l))}catch{throw TypeError(`registerTool: the ${h} of ${t} must be JSON`)}let C=H(y);if(C!==void 0)throw TypeError(`registerTool: the ${h} of ${t}: ${C}`);return y},d=c(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[l,h]of Object.entries(a??{}))if(typeof h==="boolean")u[l]=h;else if(h!==void 0&&/Hint$|^debugging$/.test(l))throw TypeError(`registerTool: ${l} of ${t} must be a boolean`);return{name:t,title:n,description:i,inputSchema:d,outputSchema:o===void 0?void 0:c(o,"outputSchema"),annotations:u,execute:s}}class w{#e=new Map;#d=new Set;#m;register(e,t={}){let{signal:n,exposedTo:i}=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:i};if(n?.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),n?.addEventListener("abort",()=>this.remove(o),{once:!0}),this.#y()}setCompiler(e){this.#m??=e}remove(e){if(this.#e.get(e.name)!==e)return;this.#e.delete(e.name),this.#y()}get(e){return this.#e.get(e)}list(){return[...this.#e.values()]}onChange(e){return this.#d.add(e),()=>this.#d.delete(e)}#y(){for(let e of[...this.#d])e()}}var z=/^[A-Za-z0-9_-]{43}$/;function J(e){return btoa(String.fromCharCode(...e)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function K(){return J(crypto.getRandomValues(new Uint8Array(32)))}function G(e){return typeof e==="string"&&z.test(e)}function U(){try{return globalThis.localStorage??null}catch{return null}}class b{storage;key;#e;constructor(e,t){this.storage=e===void 0?U():e,this.key=t}current(){let e=null;try{e=this.storage?.getItem(this.key)??null}catch{}if(G(e))return this.#e=e,e;return this.#e}rotate(){let e=K();this.#e=e;try{this.storage?.setItem(this.key,e)}catch{}return e}}var I="0.18.0";var M="@ractive-ch/tab-mcp-client",T=I;function q(){try{return Object.getOwnPropertyDescriptor(Document.prototype,"modelContext")?.get?.call(document)}catch{return}}var V=new Set(["localhost","127.0.0.1","[::1]"]),S={reconnectDelaysMs:[5000,1e4,20000,40000,60000],answerTimeoutMs:15000},P=new Set(["network","heartbeat","shutdown"]);function B(e){return Object.freeze({...e,client:Object.freeze({...e.client})})}function F(e){return typeof e==="string"&&e.trim().length>0&&e.length<=64&&![...e].some((t)=>{let n=t.codePointAt(0)??0;return n<32||n>=127&&n<=159})}var Y=/^[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?$/;function Z(e){return e.normalize("NFKD").replace(/\p{M}/gu,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,32).replace(/-$/,"")}function Q(e){let t;try{t=new URL(e)}catch{throw TypeError(`TabMcp: relay is not a URL: ${e}`)}let n=t.protocol==="https:"||t.protocol==="wss:";if(!n&&t.protocol!=="http:"&&t.protocol!=="ws:")throw TypeError(`TabMcp: relay must be an https: or wss: URL: ${e}`);if(!n&&!V.has(t.hostname))throw TypeError(`TabMcp: relay must use https: or wss: (http: only for localhost): ${e}`);let i=`${n?"https:":"http:"}//${t.host}`,r=t.pathname.replace(/\/+$/,"");return t.protocol=n?"wss:":"ws:",t.pathname=r.endsWith("/tab")?r:`${r}/tab`,t.search="",t.hash="",{url:t.href,origin:i}}function X(e){try{return new URL(e).host}catch{return""}}function ee(e){let t={sessionId:e.sessionId,address:e.address,origin:e.origin,pairing:e.pairing==="oidc"?"oidc":"code",expiresAt:e.expiresAt,limits:e.limits};if(e.appName!==void 0)t.appName=e.appName;return t}function m(){return Promise.reject(TypeError("TabMcp: this TabMcp has no relay"))}function A(e,t){return Object.assign(Object(e),{addressChanged:t})}function E(){return Promise.reject(new DOMException("TabMcp: not connected","InvalidStateError"))}class x extends EventTarget{#e=new w;#d;#m;#y;#R;#j;#I;#v;#p;#N;#w=!1;#b;#M;#T="none";#P;#s=0;#i="disconnected";#a;#l=Object.freeze([]);#g=!1;#A;#t;#r;#h=0;#H;#u;#f;#S;#E;#x={registry:this.#e,confirm:(e)=>this.#q(e),ownConfirm:()=>!!this.#R,toolCallStarted:(e)=>this.#n("toolcall",e),toolCallEnded:(e)=>this.#n("toolcallend",e)};constructor(e){super();let{server:t,appName:n}=e,i=e.relay===void 0?void 0:Q(e.relay);if(typeof t?.name!=="string"||typeof t.version!=="string")throw TypeError("TabMcp: server needs a name and a version");if(n!==void 0&&!F(n))throw TypeError("TabMcp: appName must be 1-64 characters without control characters");let r=e.app??Z(t.name);if(e.app!==void 0?typeof r!=="string"||!Y.test(r):i&&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.#v=i?.url,this.#d={...t},this.#y=n,this.#R=e.onConfirm,this.#j=e.alwaysAllow,this.#I=e.ui,this.#M=e.identityAssertion,this.#H=e.reconnect!==!1,i!==void 0){let s=e.storageKey??`tab-mcp:secret:${i.origin}:${encodeURIComponent(t.name)}`;this.#p=new b(e.storage,s),this.#N=e.storage===null?void 0:`${s}#tabs`}this.#e.onChange(()=>this.#n("toolschange",{tools:this.tools}));let o=e.webmcp===!0?q():void 0;if(o!==void 0)(f("khy4f5rj"),import("./webmcp-khy4f5rj.min.js")).then((s)=>s.mirror(this.#e,o,(a,c,d)=>this.#L().then((u)=>u.callFromWebMcp(this.#x,a,c,d))),(s)=>console.warn("tab-mcp: no tools are offered through WebMCP:",s))}registerTool(e,t={}){try{this.#e.register(e,t)}catch(n){return Promise.reject(n)}return Promise.resolve()}get tools(){return this.#e.list().map((e)=>e.name)}get state(){return this.#i}get session(){return this.#a}get grants(){return this.#l}get reconnecting(){return this.#u}get identity(){return this.#T}get identityMessage(){return this.#P}refreshIdentity(){let e=this.#a,t=this.#M;if(t===void 0)return Promise.reject(TypeError("TabMcp: no identityAssertion"));if(e===void 0)return E();let n=++this.#s,i=this.#t;this.#o("pending");let r=setTimeout(()=>{if(n!==this.#s||this.#T!=="pending")return;this.#s++,this.#o("none")},S.answerTimeoutMs);return new Promise((o)=>{let s=(a)=>{let{identity:c}=a.detail;if(c==="pending")return;this.removeEventListener("identitychange",s),clearTimeout(r),o(c)};this.addEventListener("identitychange",s),Promise.resolve().then(()=>t({address:e.address,sessionId:e.sessionId})).then((a)=>{if(n!==this.#s||this.#t!==i)return;if(typeof a!=="string"||a===""){this.#o("none");return}if(i?.send({type:"identity",assertion:a,round:n})!==!0)this.#o("none")},(a)=>{if(n!==this.#s)return;this.#n("error",{error:a instanceof Error?a:Error(String(a))}),this.#o("none")})})}signOut(){return this.#s++,this.#o("none"),this.#a?.pairing==="oidc"?this.#K({type:"identity.logout"},()=>!this.#l.length):E()}get pairingCode(){return this.#A}connect(e={}){if(this.#v===void 0)return m();if(this.#i==="connected"&&this.#a!==void 0)return Promise.resolve(this.#a);if(this.#r!==void 0)return this.#r;if(this.#u!==void 0)return this.#D();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.#b?this.#b.then(()=>this.connect({resume:!0})):this.#k()}#k(){if(!this.#u)this.#c("connecting");let e=this.#_(this.#h);return this.#r=e,e.then(()=>{if(this.#r===e)this.#r=void 0},()=>{if(this.#r!==e)return;if(this.#r=void 0,this.#t=void 0,!this.#u)this.#c("disconnected")}),e}async#L(){let e=await (f("0xqwz17v"),import("./connection-0xqwz17v.min.js"));for(let t of e.compileRegistry(this.#e))this.#n("error",{error:t});return e}async#_(e,t){let{openConnection:n,addressIdOf:i}=await this.#L(),r=this.#v;if(r===void 0||this.#p===void 0)return m();let o=t??this.#p.current()??this.#p.rotate(),s=await i(o);if(e!==this.#h)throw new DOMException("The connection was cancelled","AbortError");let a={},c=n(this.#V(a),r,o,{address:s,revokeAll:!!t});if(!t)a.connection=c;return this.#t=c,c.ready}get hasRelay(){return this.#v!==void 0}serve(e,t){return this.#L().then((n)=>n.servePort({...this.#x,server:this.#d,error:(i)=>this.#n("error",{error:i})},e,t))}disconnect(){this.#z("user")}newAddress(){let e=this.#p;if(!e)return m();return this.#b??=this.#G(e).finally(()=>{this.#b=void 0})}async#G(e){let t=this.#i!=="disconnected"||this.#w,n=e.current();this.#z("new_address");let i=this.#h;if(n){this.#c("connecting");try{await this.#_(i,n)}catch(r){if(i===this.#h)this.#c("disconnected"),this.#w=t;throw A(r,!1)}finally{if(i===this.#h)this.#t?.close("new_address"),this.#t=void 0}}if(e.rotate(),this.#O([]),t)await this.#k().catch((r)=>{throw A(r,!0)});else this.#c("disconnected")}#z(e){this.#$(),this.#w=!1,this.#h++;let t=this.#t;if(this.#t=void 0,this.#r=void 0,t?.close(e),this.#i==="disconnected")return;this.#a=void 0,this.#C(void 0),this.#s++,this.#o("none"),this.#c("disconnected",e)}#J(e,t){let n=S.reconnectDelaysMs,i=(n[Math.min(t,n.length)-1]??0)*(0.8+0.4*Math.random());clearTimeout(this.#f),this.#f=setTimeout(()=>{this.#D().catch(()=>{})},i),this.#U(),this.#u={reason:e,attempt:t,at:Date.now()+i},this.#c("reconnecting",t>1?void 0:e)}#D(){if(clearTimeout(this.#f),this.#f=void 0,this.#r!==void 0)return this.#r;let e=this.#k();return e.catch((t)=>{let n=this.#u;if(n===void 0||this.#r!==void 0)return;let i=t?.reason;if(i===void 0||P.has(i)){this.#J(n.reason,n.attempt+1);return}if(this.#$(),this.#i="disconnected",this.#n("error",{error:t instanceof Error?t:Error(String(t))}),this.#i==="disconnected")this.#n("statechange",{state:"disconnected"})}),e}#U(){if(this.#S!==void 0)return;let e=globalThis,t=globalThis.document,n=()=>{if(this.#f!==void 0)this.#D().catch(()=>{})},i=()=>{if(t?.visibilityState!=="hidden")n()};t?.addEventListener("visibilitychange",i),e.addEventListener?.("online",n),this.#S=()=>{t?.removeEventListener("visibilitychange",i),e.removeEventListener?.("online",n)}}#$(){clearTimeout(this.#f),this.#f=void 0,this.#S?.(),this.#S=void 0,this.#u=void 0}startPairing(){if(this.#g)return;if(this.#g=!0,this.#i==="connected")this.#t?.send({type:"pairing.start"})}stopPairing(){if(!this.#g)return;if(this.#g=!1,this.#i==="connected")this.#t?.send({type:"pairing.stop"});this.#C(void 0)}revoke(e){let t=()=>!this.#l.some((n)=>n.grantId===e);return t()?Promise.resolve():this.#K({type:"grant.revoke",grantId:e},t)}#K(e,t){if(!this.#a||this.#t?.send(e)!==!0)return E();return new Promise((n,i)=>{let r=["grantschange","statechange","error"],o=(c)=>{clearTimeout(a);for(let d of r)this.removeEventListener(d,s);if(c)i(c);else n()},s=(c)=>{let d=c?.detail?.error;if(t())o();else if((d?.code==="store_unavailable"||d?.code==="unknown_id")&&(d.for===void 0||d.for===e.type&&d.grantId===e.grantId))o(d);else if(this.#i!=="connected")o(new DOMException("TabMcp: the session ended before the relay answered","NetworkError"))},a=setTimeout(()=>o(new DOMException("TabMcp: the relay did not answer","TimeoutError")),S.answerTimeoutMs);for(let c of r)this.addEventListener(c,s);s()})}showConnectDialog(e={}){if(this.#v===void 0)return m();let t=e.document??globalThis.document,n=this.#E;if(n!==void 0)return n.doc===t?n.shown:Promise.reject(new DOMException("showConnectDialog: the dialog is already open in another document","InvalidStateError"));let i=this.#W(t).finally(()=>{if(this.#E?.shown===i)this.#E=void 0});return this.#E={doc:t,shown:i},i}async#W(e){let t=this.connect();t.catch(()=>{});let{showConnectDialog:n}=await (f("ph4xxen4"),import("./connect-ph4xxen4.min.js"));await n(this,t,e,this.#d.name,this.#I)}addEventListener(e,t,n){super.addEventListener(e,t,n)}removeEventListener(e,t,n){super.removeEventListener(e,t,n)}#n(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))}#c(e,t){if(this.#i===e&&e!=="reconnecting")return;this.#i=e,this.#n("statechange",t?{state:e,reason:t}:{state:e})}#o(e,t){if(this.#T===e&&t===void 0)return;this.#T=e,this.#P=e==="refused"?t:void 0,this.#n("identitychange",{identity:e,identityMessage:this.#P})}#C(e){if(this.#A===void 0&&e===void 0)return;this.#A=e,this.#n("pairingcode",{pairingCode:e})}#O(e){this.#l=Object.freeze(e.map(B)),this.#n("grantschange",{grants:this.#l})}#q(e){let t=this.#R;return (f("f36n8xj5"),import("./confirm-f36n8xj5.min.js")).then((n)=>n.confirmCall(this,e,t),()=>t?.(e)??!1)}get _allowed(){return[this.#e,this.#p,this.#j]}confirmInPage(e,t={}){let n=t.document??globalThis.document;if(n===void 0)return Promise.resolve(!1);return (f("f36n8xj5"),import("./confirm-f36n8xj5.min.js")).then((i)=>i.confirmInPage(this,e,n,this.#I))}#V(e){let t=()=>e.connection!==void 0&&this.#t===e.connection,n=!1;return{...this.#x,server:this.#d,app:this.#m,appName:this.#y,tabs:this.#N,library:{name:M,version:T},clientFor:(i)=>{let r=this.#l.find((s)=>s.grantId===i.grantId),o={kind:"relay",grantId:i.grantId,id:i.clientId,host:X(i.clientId)};if(r!==void 0)o.name=r.client.name;return o},sessionStarted:(i)=>{let r=ee(i);if(!t())return r;if(this.#a=r,this.#w=!1,this.#$(),this.#O([...i.grants]),this.#g)this.#t?.send({type:"pairing.start"});if(this.#c("connected"),r.pairing==="oidc"&&this.#M)this.refreshIdentity();return r},pairingCode:(i)=>{if(t()&&this.#g)this.#C(i)},grantAdded:(i)=>{if(!t())return;this.#O([...this.#l.filter((r)=>r.grantId!==i.grantId),i])},grantRemoved:(i)=>{if(!t())return;this.#O(this.#l.filter((r)=>r.grantId!==i))},replaced:(i)=>{if(n)this.#n("replaced",i)},identityResult:(i,r,o)=>{if(!t())return;if(r!==this.#s)return;if(i)this.#o("bound");else this.#o("refused",o??"")},error:(i)=>{if(t())this.#n("error",{error:i})},closed:(i)=>{if(!t())return;if(i==="replaced")this.#w=n=!0;this.#t=void 0,this.#a=void 0;let r=this.#h;if(this.#C(void 0),this.#s++,this.#o("none"),r!==this.#h)return;if(this.#H&&P.has(i))this.#J(i,1);else this.#c("disconnected",i)}}}}export{x as TabMcp,T as VERSION};
|
|
3
3
|
|
|
4
|
-
//# debugId=
|
|
4
|
+
//# debugId=57BABC9C6D2ADDC464756E2164756E21
|
|
5
5
|
//# sourceMappingURL=tab-mcp-client.min.js.map
|