@ractive-ch/tab-mcp-client 0.18.0 → 0.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,43 @@ the Git tag `client-v<version>`. The format follows
6
6
  [Semantic Versioning](https://semver.org/). The relay has its own
7
7
  [changelog](https://github.com/ractive/tab-mcp/blob/main/packages/tab-mcp/CHANGELOG.md).
8
8
 
9
+ ## [0.18.1][client-0.18.1] - 2026-11-20
10
+
11
+ ### Fixed
12
+
13
+ - **The confirmation chunk's `confirmInPage` works with a host of the caller's own
14
+ again.** Code that loads the built confirmation chunk (`confirm-<hash>.js`) and calls
15
+ its `confirmInPage(mcp, request, document, options)` with a stand-in for the `TabMcp`
16
+ (a desktop app's own MCP endpoint, say) broke in 0.18.0, which the 0.18.0 entry did
17
+ not say:
18
+ - it read the internal `_allowed` of the host, so a host without it threw;
19
+ - its fourth argument became the dialog texts (`ui`) alone, so the 0.17 options
20
+ `{ alwaysAllow, ui, allowDelayMs }` were silently ignored: no third button per
21
+ call, no translated texts, no other delay.
22
+
23
+ Now the fourth argument is again `{ alwaysAllow?, ui?, allowDelayMs? }`, as in 0.17.
24
+ A host needs only `grants`; it may send `grantschange` (any event: the allowances
25
+ are then pruned against `grants` as they are, whatever the event carries). It needs
26
+ no `_allowed` and no `session`. For a host that is not a `TabMcp`, nothing is
27
+ allowed or kept unless the call offers it with `alwaysAllow`; then the button says
28
+ "Allow until reload" (`true` and `"until-reload"` alike: nothing of a stand-in
29
+ outlives a reload), and an allowance is kept in memory for the host's grants only,
30
+ until a reload or until its grant leaves `grants`, and applies to that app's later
31
+ calls of the tool. A call counts as allowed only while its grant is in the host's
32
+ `grants` at that moment, also without an event. For a `TabMcp`, `alwaysAllow`
33
+ overrides the page's option for that call. As since 0.13, only a client with
34
+ `kind: "relay"` can be allowed. Hosts that added `_allowed` or `session` for 0.18.0
35
+ can drop them; an `_allowed` that is not a `TabMcp`'s (such as that workaround's)
36
+ now makes the host a stand-in, so pass `alwaysAllow` to keep offering the button.
37
+ `TabMcp.confirmInPage(request, { document })` is unchanged.
38
+
39
+ ### Changed
40
+
41
+ - `allowedTools(mcp).has(grantId, name)`, and a call, count an allowance only while
42
+ the app is in `mcp.grants`: before the first connect after a reload, `has` is
43
+ `false` (the allowance is still kept, `list` shows it). Calls only come while
44
+ connected, so for them nothing changes.
45
+
9
46
  ## [0.18.0][client-0.18.0] - 2026-11-20
10
47
 
11
48
  ### Added
@@ -870,6 +907,7 @@ First alpha of the browser library, on the npm dist-tag `alpha`.
870
907
  `<script type="module">` under `@ractive-ch/tab-mcp-client/cdn`.
871
908
  - The connect dialog shows the pairing code from the relay.
872
909
 
910
+ [client-0.18.1]: https://github.com/ractive/tab-mcp/releases/tag/client-v0.18.1
873
911
  [client-0.18.0]: https://github.com/ractive/tab-mcp/releases/tag/client-v0.18.0
874
912
  [client-0.17.0]: https://github.com/ractive/tab-mcp/releases/tag/client-v0.17.0
875
913
  [client-0.16.2]: https://github.com/ractive/tab-mcp/releases/tag/client-v0.16.2
package/README.md CHANGED
@@ -15,7 +15,7 @@ How the library, the relay and the tab-mcp browser extension fit together, with
15
15
  picture:
16
16
  [How the parts fit together](https://github.com/ractive/tab-mcp#how-the-parts-fit-together).
17
17
 
18
- **Status: 0.18.0.** Until 1.0, a new minor version can still change the API. Which AI apps
18
+ **Status: 0.18.1.** Until 1.0, a new minor version can still change the API. Which AI apps
19
19
  work is listed in [compatibility](https://github.com/ractive/tab-mcp/blob/main/docs/compatibility.md).
20
20
 
21
21
  ## You need a relay
@@ -50,7 +50,7 @@ Or without a bundler, from a CDN as an ES module:
50
50
 
51
51
  ```html
52
52
  <script type="module">
53
- import { TabMcp } from "https://cdn.jsdelivr.net/npm/@ractive-ch/tab-mcp-client@0.18.0/cdn/tab-mcp-client.min.js";
53
+ import { TabMcp } from "https://cdn.jsdelivr.net/npm/@ractive-ch/tab-mcp-client@0.18.1/cdn/tab-mcp-client.min.js";
54
54
  </script>
55
55
  ```
56
56
 
@@ -546,6 +546,19 @@ outcome `unanswered`. Any other value, and a throw, is a refusal.
546
546
 
547
547
  `mcp.confirmInPage(request, { document })` is the library's own dialog, for an
548
548
  `onConfirm` that handles only some calls itself (`document` defaults to the global one).
549
+ A call the user allowed for its AI app resolves `true` without the dialog.
550
+
551
+ An app that shows the dialog for an MCP endpoint of its own, without a `TabMcp` (a
552
+ desktop app, say), can load the built confirmation chunk (`confirm-<hash>.js`; its name
553
+ changes with each build) and call its `confirmInPage(host, request, document, options)`.
554
+ `host` is a stand-in with `grants` (the AI apps it allows for, `{ grantId }`), optionally
555
+ an `EventTarget` that sends `grantschange` when they change (any event: the allowances
556
+ are pruned against `grants` as they are then). A call counts as allowed only while its
557
+ grant is in `grants`, also without an event. `options` are
558
+ `alwaysAllow` (`true` or `"until-reload"` offers "Allow until reload" for that call;
559
+ without it nothing is allowed or kept), `ui` (the dialog's texts) and `allowDelayMs`
560
+ (tests only). Such allowances live in memory, for the host's grants, until a reload; only
561
+ a client with `kind: "relay"` can be allowed.
549
562
 
550
563
  ### Tools that run without asking
551
564
 
@@ -621,7 +634,8 @@ mcp.addEventListener("grantschange", drawSwitches);
621
634
 
622
635
  - `tools()`: the tools that ask (`consequentialHint`, callable through the relay), each
623
636
  `{ name, title?, description, destructive }`.
624
- - `has(grantId, name)`: whether a call runs without asking now. `list(grantId)`: the
637
+ - `has(grantId, name)`: whether a call runs without asking now (only for an app in
638
+ `mcp.grants`). `list(grantId)`: the
625
639
  names allowed one by one (one registered now with another title or description is
626
640
  not in it). `everything(grantId)`. These only read, so they are safe while drawing.
627
641
  - `allow(grantId, name)` (as the tool is registered now), `ask(grantId, name)`,
@@ -638,8 +652,8 @@ mcp.addEventListener("grantschange", drawSwitches);
638
652
  that does not import it loads nothing of it. Take both from the same version:
639
653
 
640
654
  ```js
641
- import { TabMcp } from "https://cdn.jsdelivr.net/npm/@ractive-ch/tab-mcp-client@0.18.0/cdn/tab-mcp-client.min.js";
642
- import { allowedTools } from "https://cdn.jsdelivr.net/npm/@ractive-ch/tab-mcp-client@0.18.0/cdn/allowed.min.js";
655
+ import { TabMcp } from "https://cdn.jsdelivr.net/npm/@ractive-ch/tab-mcp-client@0.18.1/cdn/tab-mcp-client.min.js";
656
+ import { allowedTools } from "https://cdn.jsdelivr.net/npm/@ractive-ch/tab-mcp-client@0.18.1/cdn/allowed.min.js";
643
657
  ```
644
658
 
645
659
  **The risk.** An allowance outlives the user's attention: for up to the grant's 90 days,
package/allowed.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  allowedFor
3
- } from "./index-h8b3dc5p.js";
3
+ } from "./index-s31xrfa2.js";
4
4
 
5
5
  // src/allowed.ts
6
6
  function allowedTools(mcp) {
@@ -68,8 +68,9 @@ export interface AllowedTools {
68
68
  */
69
69
  list(grantId: string): string[];
70
70
  /**
71
- * Whether a call of this tool by this app runs without asking now:
72
- * "everything" is on, or the tool is allowed and registered unchanged.
71
+ * Whether a call of this tool by this app runs without asking now: the
72
+ * app is in `mcp.grants`, and "everything" is on or the tool is allowed
73
+ * and registered unchanged.
73
74
  */
74
75
  has(grantId: string, name: string): boolean;
75
76
  /**
@@ -102,15 +103,29 @@ export interface AllowedTools {
102
103
  onChange(listener: () => void): () => void;
103
104
  }
104
105
  /**
105
- * The allowances of one `TabMcp`. The public methods are arrow fields, so
106
- * that they work taken off the object; the queries never write.
106
+ * A caller's own stand-in for a `TabMcp` in the confirmation chunk's
107
+ * `confirmInPage` (a desktop app with an MCP endpoint of its own, say): the
108
+ * AI apps it allows for, and optionally `grantschange` events (with
109
+ * `detail.grants`) when they change. Its allowances live in memory, for
110
+ * those grants only, until the page is reloaded.
111
+ */
112
+ export interface ConfirmHost {
113
+ readonly grants: readonly {
114
+ readonly grantId: string;
115
+ }[];
116
+ addEventListener?(type: string, listener: (event: Event) => void): void;
117
+ }
118
+ /**
119
+ * The allowances of one `TabMcp` (or a caller's stand-in, `ConfirmHost`).
120
+ * The public methods are arrow fields, so that they work taken off the
121
+ * object; the queries never write.
107
122
  */
108
123
  export declare class Allowances implements AllowedTools {
109
124
  #private;
110
125
  readonly kept: boolean;
111
126
  /** The library's dialogs offer allowing (`alwaysAllow` on). */
112
127
  readonly offered: boolean;
113
- constructor(mcp: TabMcp);
128
+ constructor(mcp: TabMcp | ConfirmHost);
114
129
  readonly tools: () => AllowedTool[];
115
130
  readonly list: (grantId: string) => string[];
116
131
  readonly has: (grantId: string, name: string) => boolean;
@@ -146,7 +161,8 @@ export declare class Allowances implements AllowedTools {
146
161
  }
147
162
  /**
148
163
  * The allowances of `mcp`, made on first use. They follow its grants (only
149
- * when the relay names them, see above) and its tools.
164
+ * when the relay names them, see above; a stand-in's `grantschange`) and
165
+ * its tools.
150
166
  */
151
- export declare function allowedFor(mcp: TabMcp): Allowances;
167
+ export declare function allowedFor(mcp: TabMcp | ConfirmHost): Allowances;
152
168
  export {};
@@ -1,4 +1,4 @@
1
- import{r}from"./tab-mcp-client-6gcmd7n8.min.js";function e(o){return r(o)}export{e as allowedTools};
1
+ import{r}from"./tab-mcp-client-5j3brdf3.min.js";function e(o){return r(o)}export{e as allowedTools};
2
2
 
3
3
  //# debugId=276A38D7EC2846AF64756E2164756E21
4
4
  //# sourceMappingURL=allowed.min.js.map
@@ -0,0 +1,4 @@
1
+ import{a,t,o,e,n,s,d,l}from"./tab-mcp-client-2vx9mcww.min.js";import{r}from"./tab-mcp-client-5j3brdf3.min.js";function ee(u){try{return s(JSON.stringify(u,null,2))}catch{return}}var ne=750,te=500,J=new WeakMap;function K(u,i,b={}){if(u.signal.aborted)return Promise.resolve("deny");let g=J.get(i);if(g===void 0)g={shown:!1,waiting:[]},J.set(i,g);let f=g,c=()=>{let h=f.waiting.shift();f.shown=h!==void 0,h?.(),f.changed?.()},L=()=>{try{return ie(u,i,b,f,c)}catch(h){return c(),Promise.reject(h)}};if(!f.shown)return f.shown=!0,L();return new Promise((h)=>{let v=()=>{if(u.signal.removeEventListener("abort",E),b.allowedNow?.()===!0){h("allow"),c();return}h(L())},E=()=>{f.waiting.splice(f.waiting.indexOf(v),1),f.changed?.(),h("deny")};u.signal.addEventListener("abort",E,{once:!0}),f.waiting.push(v),f.changed?.()})}function ie(u,i,b,g,f){let c=b.strings??a(void 0),L=b.allowDelayMs??ne,h=u.tool.title??u.tool.name,v=d(u.client,c),E={tool:h,client:v},{dialog:m,id:C}=l(i,"tab-mcp-confirm",c,...o(i,c.confirmTitle,E)),H=e(i,"p",{className:"tab-mcp-waiting"}),I=()=>{let p=g.waiting.length;H.hidden=p===0,H.textContent=p===1?c.waitingOne:t(c.waitingMany,{n:String(p)})};g.changed=I,I();let z=n(i,c.deny,()=>m.close("deny"),"tab-mcp-deny","primary"),B=(p,j,R)=>{let A=n(i,p,()=>{if(!A.disabled)m.close(j)},R);return A},k=[B(c.allow,"allow","tab-mcp-allow")],W=[],Q=b.alwaysAllow;if(Q===!0||Q==="until-reload"){let p=Q===!0;k.unshift(B(p?c.alwaysAllow:c.allowUntilReload,"always","tab-mcp-always")),W.push(e(i,"p",{className:"tab-mcp-always-note"},...o(i,p?c.alwaysAllowNote:c.allowUntilReloadNote,E)))}let Y=e(i,"div",{className:"tab-mcp-actions"},z,...k.flatMap((p)=>[" ",p])),N=!1,U=!1,M=()=>{for(let p of k)p.disabled=!(N&&U)};M();let O=ee(u.arguments),y=e(i,"pre",{className:"tab-mcp-arguments",id:`${C}-arguments`,text:O??c.argumentsHidden});if(O===void 0)for(let p of[...k,...W])p.hidden=!0;y.dir="ltr",y.style.setProperty("white-space","pre-wrap"),y.style.setProperty("overflow-wrap","anywhere"),y.style.setProperty("max-height","var(--tab-mcp-arguments-height, min(50vh, 24rem))"),y.style.setProperty("overflow","auto"),y.hidden=Object.keys(u.arguments).length===0;let T=e(i,"p",{className:"tab-mcp-scroll-note",text:c.scrollToAllow});T.hidden=!0;let _=e(i,"p",{id:`${C}-who`},...o(i,c.confirmWho,E));m.setAttribute("aria-describedby",O!==void 0&&!y.hidden&&O.length<=te?`${_.id} ${y.id}`:_.id),m.append(_,e(i,"p",{className:"tab-mcp-description",text:u.tool.description}),y,T,Y,...W,H),i.body.append(m);let x=i.defaultView;return new Promise((p,j)=>{let R=()=>m.close("deny");u.signal.addEventListener("abort",R,{once:!0});let A,P,F=()=>{if(P!==void 0&&i.title===P.shown)i.title=P.page;P=void 0},X=()=>{if(i.visibilityState!=="hidden")F();else if(P===void 0)P={page:i.title,shown:`${c.titlePrefix}${i.title}`},i.title=P.shown},D=(w)=>{if(w?.type==="close"&&w.target===m)return;if(X(),clearTimeout(A),A=void 0,N=!1,M(),w?.type==="blur"||i.visibilityState==="hidden"||!i.hasFocus())return;A=setTimeout(()=>{N=!0,M()},L)},S=()=>{if(U)return;if(y.scrollTop+y.clientHeight<y.scrollHeight-2){T.hidden=!1,y.tabIndex=0;return}U=!0,T.hidden=!0,M()},V=(w)=>{if(N)return;let q=w.target?.localName==="button";if(w.key==="Escape"||q&&(w.key==="Enter"||w.key===" "))w.preventDefault()},Z=(w)=>{if(!N)w.preventDefault()};i.addEventListener("visibilitychange",D),i.addEventListener("close",D,!0),x?.addEventListener("focus",D),x?.addEventListener("blur",D),x?.addEventListener("resize",S),y.addEventListener("scroll",S),m.addEventListener("keydown",V),m.addEventListener("keyup",V),m.addEventListener("cancel",Z);let G=()=>{if(clearTimeout(A),F(),i.removeEventListener("visibilitychange",D),i.removeEventListener("close",D,!0),x?.removeEventListener("focus",D),x?.removeEventListener("blur",D),x?.removeEventListener("resize",S),u.signal.removeEventListener("abort",R),m.remove(),g.changed===I)g.changed=void 0};m.addEventListener("close",()=>{let w=m.returnValue;G(),p(w==="allow"||w==="always"?w:"deny"),f()},{once:!0});try{m.showModal()}catch(w){G(),j(w),f();return}z.focus(),D(),S()})}function ae(u,i,b,g={}){let{client:f}=i,c=a(g.ui),{allowDelayMs:L}=g;if(f.kind!=="relay")return K(i,b,{strings:c,allowDelayMs:L}).then((C)=>C==="allow");let{grantId:h}=f,v=r(u),E=()=>v.allows(h,i.tool);if(E())return Promise.resolve(!0);let m=g.alwaysAllow??v.offered;return K(i,b,{strings:c,allowDelayMs:L,alwaysAllow:m!==!1&&(m===!0&&v.kept?!0:"until-reload"),allowedNow:E}).then((C)=>{if(C==="always")v.keep(h,i.tool);return C!=="deny"})}function se(u,i,b){let{client:g}=i;if(g.kind==="relay"&&r(u).allows(g.grantId,i.tool))return Promise.resolve(!0);if(b===void 0)return u.confirmInPage(i);return Promise.resolve().then(()=>b(i)).then((f)=>f==="unanswered"?f:f===!0)}export{se as confirmCall,ae as confirmInPage};
2
+
3
+ //# debugId=D0E23A81AC714FF364756E2164756E21
4
+ //# sourceMappingURL=confirm-d722a9eb.min.js.map
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/confirm.ts"],
4
+ "sourcesContent": [
5
+ "/**\n * The confirmation of consequential tools, loaded on demand: a `<dialog>`\n * per call, one shown at a time per document, and Always allow (or Allow\n * until reload) for the tools a user allows (`always-allowed.ts`).\n */\n\nimport { allowedFor, type ConfirmHost } from \"./always-allowed.ts\";\nimport {\n\tbutton,\n\tclientLabel,\n\tel,\n\tfill,\n\tformat,\n\tnewDialog,\n\tstringsOf,\n\tvisible,\n} from \"./dialog.ts\";\nimport type { DialogStrings } from \"./strings.ts\";\nimport type { TabMcp } from \"./tab-mcp.ts\";\nimport type {\n\tConfirmAnswer,\n\tConfirmHandler,\n\tConfirmRequest,\n\tDialogOptions,\n} from \"./types.ts\";\n\n/**\n * The arguments as text, in full: what the user approves must be visible.\n * (The relay caps a request at 1 MiB, so this stays bounded.) Invisible and\n * direction characters are shown as escapes, so the text is still JSON for\n * the same arguments; the tool gets them unchanged. `undefined` when they\n * cannot be shown, and then \"Allow\" is not offered.\n */\nfunction showArguments(args: Record<string, unknown>): string | undefined {\n\ttry {\n\t\treturn visible(JSON.stringify(args, null, 2));\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * How long \"Allow\" stays disabled after the confirmation is shown, while the\n * page is visible and focused (CU 17: a constant; tests pass `allowDelayMs`).\n */\nexport const ALLOW_DELAY_MS = 750;\n\n/** The user's answer: \"always\" allows this tool for this AI app (Always allow, or until reload). */\nexport type DialogAnswer = \"allow\" | \"always\" | \"deny\";\n\n/** Arguments up to this many characters are read out with the question. */\nconst DESCRIBED_ARGUMENTS = 500;\n\n/** Options of `confirmDialog`. */\nexport interface ConfirmDialogOptions {\n\t/** Tests only: another delay than {@link ALLOW_DELAY_MS}. */\n\tallowDelayMs?: number | undefined;\n\t/**\n\t * Offer a third button: `true` \"Always allow\" (kept until the app is\n\t * disconnected), `\"until-reload\"` \"Allow until reload\" (kept in memory).\n\t */\n\talwaysAllow?: boolean | \"until-reload\" | undefined;\n\t/** Asked when a waiting call's turn comes: `true` answers \"allow\" unseen. */\n\tallowedNow?: () => boolean;\n\tstrings?: DialogStrings;\n}\n\n/**\n * The confirmations of one document: one is shown at a time, the others\n * wait in order, so that the click that answered one cannot answer the next\n * (each starts its own delay when it is shown).\n */\ninterface ConfirmQueue {\n\tshown: boolean;\n\twaiting: (() => void)[];\n\t/** Updates the shown dialog's line about the calls that wait. */\n\tchanged?: (() => void) | undefined;\n}\n\nconst queues = new WeakMap<Document, ConfirmQueue>();\n\n/**\n * Ask whether a consequential tool may run. \"Always allow\" (or \"Allow until\n * reload\") is offered only with `alwaysAllow` (DEC-096, DEC-200); never\n * \"allow everything\": that is a deliberate act in the connect dialog, not\n * an answer to one question. One confirmation is shown at a time per\n * document; the others wait their turn, and a call cancelled while it waits\n * is never shown. \"Allow\" and \"Always allow\" stay disabled until the\n * page has been visible and focused for 750 ms while the dialog is open and\n * is the top one, so a click meant for the page, the click that brings the\n * tab or window back, or the one that closed another dialog, cannot\n * approve; leaving the page disables them again. They also wait until the\n * arguments have been scrolled to their end. Before the delay has run out,\n * Enter or Space on a button and Escape are ignored, so typing meant for the\n * page cannot refuse either. Everything else (Don't allow, Escape, an\n * aborted call) is \"deny\". `allowedNow` is asked when a waiting call's turn\n * comes: `true` (the user allowed it meanwhile) answers \"allow\"\n * without showing it.\n */\nexport function confirmDialog(\n\trequest: ConfirmRequest,\n\tdoc: Document,\n\toptions: ConfirmDialogOptions = {},\n): Promise<DialogAnswer> {\n\tif (request.signal.aborted) return Promise.resolve(\"deny\");\n\tlet queue = queues.get(doc);\n\tif (queue === undefined) {\n\t\tqueue = { shown: false, waiting: [] };\n\t\tqueues.set(doc, queue);\n\t}\n\tconst q = queue;\n\t/** The shown confirmation closed: the next one, if any. */\n\tconst next = () => {\n\t\tconst start = q.waiting.shift();\n\t\tq.shown = start !== undefined;\n\t\tstart?.();\n\t\tq.changed?.();\n\t};\n\tconst show = () => {\n\t\ttry {\n\t\t\treturn showConfirm(request, doc, options, q, next);\n\t\t} catch (error) {\n\t\t\tnext(); // not shown: the queue goes on\n\t\t\treturn Promise.reject(error);\n\t\t}\n\t};\n\tif (!q.shown) {\n\t\tq.shown = true;\n\t\treturn show();\n\t}\n\treturn new Promise((resolve) => {\n\t\tconst start = () => {\n\t\t\trequest.signal.removeEventListener(\"abort\", onAbort);\n\t\t\tif (options.allowedNow?.() === true) {\n\t\t\t\tresolve(\"allow\");\n\t\t\t\tnext();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tresolve(show());\n\t\t};\n\t\tconst onAbort = () => {\n\t\t\tq.waiting.splice(q.waiting.indexOf(start), 1);\n\t\t\tq.changed?.();\n\t\t\tresolve(\"deny\");\n\t\t};\n\t\trequest.signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\tq.waiting.push(start);\n\t\tq.changed?.();\n\t});\n}\n\n/** `confirmDialog` once it is this request's turn; calls `next` when it closes. */\nfunction showConfirm(\n\trequest: ConfirmRequest,\n\tdoc: Document,\n\toptions: ConfirmDialogOptions,\n\tqueue: ConfirmQueue,\n\tnext: () => void,\n): Promise<DialogAnswer> {\n\tconst s = options.strings ?? stringsOf(undefined);\n\tconst delay = options.allowDelayMs ?? ALLOW_DELAY_MS;\n\tconst tool = request.tool.title ?? request.tool.name;\n\tconst client = clientLabel(request.client, s);\n\tconst names = { tool, client };\n\tconst { dialog, id } = newDialog(\n\t\tdoc,\n\t\t\"tab-mcp-confirm\",\n\t\ts,\n\t\t...fill(doc, s.confirmTitle, names),\n\t);\n\tconst waiting = el(doc, \"p\", { className: \"tab-mcp-waiting\" });\n\tconst showWaiting = () => {\n\t\tconst n = queue.waiting.length;\n\t\twaiting.hidden = n === 0;\n\t\twaiting.textContent =\n\t\t\tn === 1 ? s.waitingOne : format(s.waitingMany, { n: String(n) });\n\t};\n\tqueue.changed = showWaiting;\n\tshowWaiting();\n\t// The safe choice is the default: focused, and the one that stands out.\n\tconst deny = button(\n\t\tdoc,\n\t\ts.deny,\n\t\t() => dialog.close(\"deny\"),\n\t\t\"tab-mcp-deny\",\n\t\t\"primary\",\n\t);\n\tconst approving = (text: string, answer: DialogAnswer, className: string) => {\n\t\tconst node = button(\n\t\t\tdoc,\n\t\t\ttext,\n\t\t\t() => {\n\t\t\t\tif (!node.disabled) dialog.close(answer);\n\t\t\t},\n\t\t\tclassName,\n\t\t);\n\t\treturn node;\n\t};\n\t// The approving buttons: Allow, and Always allow (or Allow until reload)\n\t// when the page offers it, saying how long it lasts.\n\tconst approve = [approving(s.allow, \"allow\", \"tab-mcp-allow\")];\n\tconst extra: HTMLElement[] = [];\n\tconst mode = options.alwaysAllow;\n\tif (mode === true || mode === \"until-reload\") {\n\t\tconst kept = mode === true;\n\t\t// Left of Allow: not where most platforms put the default (CU 11).\n\t\tapprove.unshift(\n\t\t\tapproving(\n\t\t\t\tkept ? s.alwaysAllow : s.allowUntilReload,\n\t\t\t\t\"always\",\n\t\t\t\t\"tab-mcp-always\",\n\t\t\t),\n\t\t);\n\t\textra.push(\n\t\t\tel(\n\t\t\t\tdoc,\n\t\t\t\t\"p\",\n\t\t\t\t{ className: \"tab-mcp-always-note\" },\n\t\t\t\t...fill(doc, kept ? s.alwaysAllowNote : s.allowUntilReloadNote, names),\n\t\t\t),\n\t\t);\n\t}\n\tconst actions = el(\n\t\tdoc,\n\t\t\"div\",\n\t\t{ className: \"tab-mcp-actions\" },\n\t\tdeny,\n\t\t...approve.flatMap((b) => [\" \", b]),\n\t);\n\t// Approving needs both: the delay ran out while the user saw the page\n\t// (`settled`), and the arguments were seen to their end (`seen`).\n\tlet settled = false;\n\tlet seen = false;\n\tconst enable = () => {\n\t\tfor (const b of approve) b.disabled = !(settled && seen);\n\t};\n\tenable();\n\tconst shown = showArguments(request.arguments);\n\tconst args = el(doc, \"pre\", {\n\t\tclassName: \"tab-mcp-arguments\",\n\t\tid: `${id}-arguments`,\n\t\ttext: shown ?? s.argumentsHidden,\n\t});\n\tif (shown === undefined) {\n\t\tfor (const node of [...approve, ...extra]) node.hidden = true;\n\t}\n\targs.dir = \"ltr\";\n\t// Inline, so the arguments stay readable in full without the stylesheet:\n\t// wrapped (also a long word, at 360 px), scrolling when long.\n\targs.style.setProperty(\"white-space\", \"pre-wrap\");\n\targs.style.setProperty(\"overflow-wrap\", \"anywhere\");\n\targs.style.setProperty(\n\t\t\"max-height\",\n\t\t\"var(--tab-mcp-arguments-height, min(50vh, 24rem))\",\n\t);\n\targs.style.setProperty(\"overflow\", \"auto\");\n\targs.hidden = Object.keys(request.arguments).length === 0;\n\t// The caller chooses the order of the keys, so what matters may come\n\t// last: below the end of the box, the user is told, and Allow waits.\n\tconst scrollNote = el(doc, \"p\", {\n\t\tclassName: \"tab-mcp-scroll-note\",\n\t\ttext: s.scrollToAllow,\n\t});\n\tscrollNote.hidden = true;\n\tconst who = el(\n\t\tdoc,\n\t\t\"p\",\n\t\t{ id: `${id}-who` },\n\t\t...fill(doc, s.confirmWho, names),\n\t);\n\tdialog.setAttribute(\n\t\t\"aria-describedby\",\n\t\tshown !== undefined && !args.hidden && shown.length <= DESCRIBED_ARGUMENTS\n\t\t\t? `${who.id} ${args.id}`\n\t\t\t: who.id,\n\t);\n\tdialog.append(\n\t\twho,\n\t\tel(doc, \"p\", {\n\t\t\tclassName: \"tab-mcp-description\",\n\t\t\ttext: request.tool.description,\n\t\t}),\n\t\targs,\n\t\tscrollNote,\n\t\tactions,\n\t\t...extra,\n\t\twaiting,\n\t);\n\tdoc.body.append(dialog);\n\tconst view = doc.defaultView;\n\treturn new Promise((resolve, reject) => {\n\t\tconst onAbort = () => dialog.close(\"deny\");\n\t\trequest.signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\t// In a hidden tab, the tab's title says that the page asks (CU 9): the\n\t\t// AI app waits meanwhile. Put back when the tab is shown or the dialog\n\t\t// closes, unless the page changed its title since.\n\t\tlet title: { page: string; shown: string } | undefined;\n\t\tconst untitle = () => {\n\t\t\tif (title !== undefined && doc.title === title.shown)\n\t\t\t\tdoc.title = title.page;\n\t\t\ttitle = undefined;\n\t\t};\n\t\tconst retitle = () => {\n\t\t\tif (doc.visibilityState !== \"hidden\") untitle();\n\t\t\telse if (title === undefined) {\n\t\t\t\ttitle = { page: doc.title, shown: `${s.titlePrefix}${doc.title}` };\n\t\t\t\tdoc.title = title.shown;\n\t\t\t}\n\t\t};\n\t\t// The delay counts only while the user can see the page: tools are\n\t\t// called while the user is in the AI app, so the dialog often opens in\n\t\t// a background tab or window. Any change starts it again from zero\n\t\t// (DEC-087), and so does another dialog of the page that closes over\n\t\t// this one.\n\t\tconst arm = (event?: Event) => {\n\t\t\tif (event?.type === \"close\" && event.target === dialog) return;\n\t\t\tretitle();\n\t\t\tclearTimeout(timer);\n\t\t\ttimer = undefined;\n\t\t\tsettled = false;\n\t\t\tenable();\n\t\t\tif (\n\t\t\t\tevent?.type === \"blur\" ||\n\t\t\t\tdoc.visibilityState === \"hidden\" ||\n\t\t\t\t!doc.hasFocus()\n\t\t\t)\n\t\t\t\treturn;\n\t\t\ttimer = setTimeout(() => {\n\t\t\t\tsettled = true;\n\t\t\t\tenable();\n\t\t\t}, delay);\n\t\t};\n\t\t// Scrolled to the end, or nothing to scroll (also without layout).\n\t\tconst check = () => {\n\t\t\tif (seen) return;\n\t\t\tif (args.scrollTop + args.clientHeight < args.scrollHeight - 2) {\n\t\t\t\tscrollNote.hidden = false;\n\t\t\t\targs.tabIndex = 0; // to scroll it with the keyboard\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tseen = true;\n\t\t\tscrollNote.hidden = true;\n\t\t\tenable();\n\t\t};\n\t\t// Not answered by a key before the delay has run out.\n\t\tconst guard = (event: KeyboardEvent) => {\n\t\t\tif (settled) return;\n\t\t\tconst onButton = (event.target as Element | null)?.localName === \"button\";\n\t\t\tif (\n\t\t\t\tevent.key === \"Escape\" ||\n\t\t\t\t(onButton && (event.key === \"Enter\" || event.key === \" \"))\n\t\t\t)\n\t\t\t\tevent.preventDefault();\n\t\t};\n\t\tconst onCancel = (event: Event) => {\n\t\t\tif (!settled) event.preventDefault();\n\t\t};\n\t\tdoc.addEventListener(\"visibilitychange\", arm);\n\t\tdoc.addEventListener(\"close\", arm, true); // `close` does not bubble\n\t\tview?.addEventListener(\"focus\", arm);\n\t\tview?.addEventListener(\"blur\", arm);\n\t\tview?.addEventListener(\"resize\", check);\n\t\targs.addEventListener(\"scroll\", check);\n\t\tdialog.addEventListener(\"keydown\", guard);\n\t\tdialog.addEventListener(\"keyup\", guard);\n\t\tdialog.addEventListener(\"cancel\", onCancel);\n\t\tconst cleanup = () => {\n\t\t\tclearTimeout(timer);\n\t\t\tuntitle();\n\t\t\tdoc.removeEventListener(\"visibilitychange\", arm);\n\t\t\tdoc.removeEventListener(\"close\", arm, true);\n\t\t\tview?.removeEventListener(\"focus\", arm);\n\t\t\tview?.removeEventListener(\"blur\", arm);\n\t\t\tview?.removeEventListener(\"resize\", check);\n\t\t\trequest.signal.removeEventListener(\"abort\", onAbort);\n\t\t\tdialog.remove();\n\t\t\tif (queue.changed === showWaiting) queue.changed = undefined;\n\t\t};\n\t\tdialog.addEventListener(\n\t\t\t\"close\",\n\t\t\t() => {\n\t\t\t\tconst value = dialog.returnValue;\n\t\t\t\tcleanup();\n\t\t\t\tresolve(value === \"allow\" || value === \"always\" ? value : \"deny\");\n\t\t\t\tnext();\n\t\t\t},\n\t\t\t{ once: true },\n\t\t);\n\t\ttry {\n\t\t\tdialog.showModal();\n\t\t} catch (error) {\n\t\t\t// Never shown, so never closed: the queue must not wait for it.\n\t\t\tcleanup();\n\t\t\treject(error);\n\t\t\tnext();\n\t\t\treturn;\n\t\t}\n\t\tdeny.focus(); // the safe choice is the default\n\t\t// Counted from when the dialog is shown, not from when it was built.\n\t\tarm();\n\t\tcheck();\n\t});\n}\n\n/** Options of this chunk's `confirmInPage`. */\nexport interface ConfirmInPageOptions {\n\t/**\n\t * The third button, for an AI app through the relay (`kind: \"relay\"`):\n\t * `true` \"Always allow\" (kept in the `TabMcp`'s `storage`; \"Allow until\n\t * reload\" where it is kept in memory, as for a stand-in), `\"until-reload\"`\n\t * \"Allow until reload\", `false` none. Default: the `TabMcp`'s\n\t * `alwaysAllow`; none for a stand-in.\n\t */\n\talwaysAllow?: boolean | \"until-reload\" | undefined;\n\t/** Texts of the dialog, as `TabMcpOptions.ui`. */\n\tui?: DialogOptions | undefined;\n\t/** Tests only: another delay than {@link ALLOW_DELAY_MS}. */\n\tallowDelayMs?: number | undefined;\n}\n\n/**\n * `TabMcp.confirmInPage`: the confirmation, and the tools the user allowed\n * (`always-allowed.ts`), which run unasked. Only for an AI app through the\n * relay: an agent in the browser and a served port have no identity to\n * remember an answer for (DEC-115, DEC-124).\n *\n * Code that loads this chunk itself may pass a stand-in of its own for\n * `mcp` (`ConfirmHost`: `grants`, optionally `grantschange` events). Its\n * allowances live in memory, for its grants only, until the page is\n * reloaded, and exist only where the caller offers them with\n * `options.alwaysAllow`; without it nothing is allowed and nothing is kept.\n */\nexport function confirmInPage(\n\tmcp: TabMcp | ConfirmHost,\n\trequest: ConfirmRequest,\n\tdoc: Document,\n\toptions: ConfirmInPageOptions = {},\n): Promise<boolean> {\n\tconst { client } = request;\n\tconst strings = stringsOf(options.ui);\n\tconst { allowDelayMs } = options;\n\tif (client.kind !== \"relay\")\n\t\treturn confirmDialog(request, doc, { strings, allowDelayMs }).then(\n\t\t\t(answer) => answer === \"allow\",\n\t\t);\n\tconst { grantId } = client;\n\tconst allowed = allowedFor(mcp);\n\tconst allowedNow = () => allowed.allows(grantId, request.tool);\n\tif (allowedNow()) return Promise.resolve(true);\n\tconst offer = options.alwaysAllow ?? allowed.offered;\n\t// Asked again when its turn comes: the call before it in the queue may\n\t// have been allowed meanwhile.\n\treturn confirmDialog(request, doc, {\n\t\tstrings,\n\t\tallowDelayMs,\n\t\t// \"Always\" only where it outlives a reload.\n\t\talwaysAllow:\n\t\t\toffer !== false &&\n\t\t\t(offer === true && allowed.kept ? true : \"until-reload\"),\n\t\tallowedNow,\n\t}).then((answer) => {\n\t\t// Only while the grant is still there: a revoked app gets nothing\n\t\t// (`keep` checks).\n\t\tif (answer === \"always\") allowed.keep(grantId, request.tool);\n\t\treturn answer !== \"deny\";\n\t});\n}\n\n/**\n * The core's question about a consequential call: an AI app's call that the\n * user allowed runs without asking, with the dialog and with the page's own\n * `onConfirm` alike; any other goes to `onConfirm`, else to the dialog.\n * Only AI apps through the relay have a grant to allow for.\n */\nexport function confirmCall(\n\tmcp: TabMcp,\n\trequest: ConfirmRequest,\n\tonConfirm: ConfirmHandler | undefined,\n): Promise<ConfirmAnswer> {\n\tconst { client } = request;\n\tif (\n\t\tclient.kind === \"relay\" &&\n\t\tallowedFor(mcp).allows(client.grantId, request.tool)\n\t)\n\t\treturn Promise.resolve(true);\n\tif (onConfirm === undefined) return mcp.confirmInPage(request);\n\t// Anything but true or \"unanswered\" is a refusal.\n\treturn Promise.resolve()\n\t\t.then(() => onConfirm(request))\n\t\t.then((answer) => (answer === \"unanswered\" ? answer : answer === true));\n}\n"
6
+ ],
7
+ "mappings": "8GAiCA,SAAS,EAAa,CAAC,EAAmD,CACzE,GAAI,CACH,OAAO,EAAQ,KAAK,UAAU,EAAM,KAAM,CAAC,CAAC,E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GACC,EAAO,OAAS,SAChB,EAAW,CAAG,EAAE,OAAO,EAAO,QAAS,EAAQ,IAAI,EAEnD,OAAO,QAAQ,QAAQ,EAAI,EAC5B,GAAI,IAAc,OAAW,OAAO,EAAI,cAAc,CAAO,EAE7D,OAAO,QAAQ,QAAQ,EACrB,KAAK,IAAM,EAAU,CAAO,CAAC,EAC7B,KAAK,CAAC,IAAY,IAAW,aAAe,EAAS,IAAW,EAAK",
8
+ "debugId": "D0E23A81AC714FF364756E2164756E21",
9
+ "names": []
10
+ }
@@ -1,6 +1,6 @@
1
- import{i,a,t,o,e,n,s,d,u,l,c}from"./tab-mcp-client-2vx9mcww.min.js";import{r}from"./tab-mcp-client-6gcmd7n8.min.js";function ze(m){let h=m.normalize("NFKD").replace(/\p{M}/gu,"").toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"").slice(0,40).replace(/-+$/,"");return h===""?"tools":h}function Qe(m){try{let h=new URL(m).href;return/^https?:\/\/[A-Za-z0-9.:[\]/_~-]+$/.test(h)?h:void 0}catch{return}}var Ve="https://ractive.ch/tab-mcp/connect/",Ke="mcp_2026_07_28";function Xe(m,h){let p=ze(m),x=Qe(h),v=(f)=>x===void 0?{}:{text:"Run:",command:f};return[{id:"claude",app:"Claude (claude.ai and the desktop app)",text:"Settings → Connectors → Add custom connector, then paste the address."},{id:"chatgpt",app:"ChatGPT",text:"On chatgpt.com: Plugins, add an MCP server with the address, then Connect. The Mac app needs more steps: see the guide."},{id:"claude-code",app:"Claude Code",text:"Add the address with claude mcp add --transport http.",...v(`claude mcp add --transport http ${p} ${x}`),note:[{text:"Then type "},{code:"/mcp"},{text:" in Claude Code and choose Authenticate."}]},{id:"codex",app:"Codex",text:`Run codex features enable ${Ke}, then add the address with codex mcp add --url and sign in with codex mcp login.`,...v(`codex features enable ${Ke}
1
+ import{i,a,t,o,e,n,s,d,u,l,c}from"./tab-mcp-client-2vx9mcww.min.js";import{r}from"./tab-mcp-client-5j3brdf3.min.js";function ze(m){let h=m.normalize("NFKD").replace(/\p{M}/gu,"").toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"").slice(0,40).replace(/-+$/,"");return h===""?"tools":h}function Qe(m){try{let h=new URL(m).href;return/^https?:\/\/[A-Za-z0-9.:[\]/_~-]+$/.test(h)?h:void 0}catch{return}}var Ve="https://ractive.ch/tab-mcp/connect/",Ke="mcp_2026_07_28";function Xe(m,h){let p=ze(m),x=Qe(h),v=(f)=>x===void 0?{}:{text:"Run:",command:f};return[{id:"claude",app:"Claude (claude.ai and the desktop app)",text:"Settings → Connectors → Add custom connector, then paste the address."},{id:"chatgpt",app:"ChatGPT",text:"On chatgpt.com: Plugins, add an MCP server with the address, then Connect. The Mac app needs more steps: see the guide."},{id:"claude-code",app:"Claude Code",text:"Add the address with claude mcp add --transport http.",...v(`claude mcp add --transport http ${p} ${x}`),note:[{text:"Then type "},{code:"/mcp"},{text:" in Claude Code and choose Authenticate."}]},{id:"codex",app:"Codex",text:`Run codex features enable ${Ke}, then add the address with codex mcp add --url and sign in with codex mcp login.`,...v(`codex features enable ${Ke}
2
2
  codex mcp add ${p} --url ${x}
3
3
  codex mcp login ${p}`),note:[{text:"The last line opens the sign-in that asks for the code. Start a new chat in Codex after it connects."}]}]}function Ze(m,h,p){let x=e(m,"input");return x.type="checkbox",x.setAttribute("role","switch"),x.addEventListener("change",()=>p(x.checked)),{label:e(m,"label",{className:"tab-mcp-switch"},x,h),input:x}}function dt(m,h,p,x,v){let f=e(m,"p",{className:"tab-mcp-allowed-title",id:`${i()}-allowed`,text:h.runsWithoutAsking}),L=e(m,"div",{className:"tab-mcp-switches"}),y=Ze(m,e(m,"span",{text:h.allowEverything}),(D)=>{if(!D||p.offered)p.setEverything(x,D);R()});y.label.classList.add("tab-mcp-everything"),y.input.setAttribute("aria-label",t(h.allowEverythingApp,{app:v}));let M=e(m,"small",{className:"tab-mcp-everything-note",id:`${f.id}-note`},...o(m,h.allowEverythingNote,{app:v}));y.input.setAttribute("aria-describedby",M.id);let E=e(m,"div",{className:"tab-mcp-allowed"});E.setAttribute("role","group"),E.setAttribute("aria-labelledby",f.id);let S=new Map,R=()=>{let D=p.everything(x),X=p.list(x),ie=new Set(X),Z=new Map(p.tools().map((b)=>[b.name,b])),B=[];if(p.offered)for(let b of Z.values())B.push({name:b.name,shown:b.title??b.name,destructive:b.destructive,offOnly:!1});for(let b of X){if(p.offered&&Z.has(b))continue;let U=Z.get(b);B.push({name:b,shown:U?.title??b,destructive:U?.destructive===!0,offOnly:!0})}let oe=p.offered||D;if(E.hidden=B.length===0&&!D,E.hidden)return;if(!E.hasChildNodes())E.append(f,L,y.label,M);let F=new Set(B.map((b)=>b.name));for(let[b,{label:U}]of S){if(F.has(b))continue;U.remove(),S.delete(b)}B.forEach((b,U)=>{let A=S.get(b.name);if(A===void 0){let j=e(m,"span"),te=e(m,"small",{className:"tab-mcp-destructive",text:h.destructive});A={...Ze(m,e(m,"span",{},j," ",te),(ce)=>{if(!ce)p.ask(x,b.name);else if(S.get(b.name)?.offOnly===!1)p.allow(x,b.name);R()}),name:j,mark:te,offOnly:b.offOnly},S.set(b.name,A)}A.offOnly=b.offOnly;let W=s(b.shown);if(A.name.textContent=W,A.mark.hidden=!b.destructive,A.input.setAttribute("aria-label",t(b.destructive?h.allowDestructiveToolApp:h.allowToolApp,{tool:W,app:v})),A.input.checked=D||ie.has(b.name),A.input.disabled=D,L.children[U]!==A.label)L.insertBefore(A.label,L.children[U]??null)}),y.label.hidden=M.hidden=!oe,y.input.checked=D};return{box:E,render:R}}function rt(m,h){return[...new Set(m.map((p)=>d(p.client,h)))]}function ae(m,h){console.warn("tab-mcp: could not connect.",m);let p=m?.reason;if(p===void 0)return h.notConnected;if(p==="network")return h.unreachable;if(p==="rate_limited")return h.rateLimited;return h.refused}function lt(m,h){switch(m){case"expired":case"idle":return h.ended;case"user":return h.disconnected;case"network":case"heartbeat":case"shutdown":return h.lost;case"rate_limited":return h.rateLimited;default:return h.closed}}function ut(m,h){switch(m.identity){case"bound":return;case"pending":return h.checkingSignIn;case"refused":return m.identityMessage?t(h.signInRefusedWhy,{reason:m.identityMessage}):h.signInRefused;default:return h.signInFirst}}var Te=new WeakMap;function pt(m,h,p){let x=Te.has(m);if(Te.set(m,p===void 0?{doc:h}:{doc:h,ui:p}),x)return;m.addEventListener("replaced",(v)=>{let f=Te.get(m);if(f!==void 0&&m.state==="disconnected")ft(m,f.doc,v.detail.sibling,f.ui)})}function ft(m,h,p,x){let v=a(x);h.querySelector("dialog.tab-mcp-replaced")?.close();let{dialog:f}=l(h,"tab-mcp-replaced",v,p?v.replacedSiblingTitle:v.replacedTitle),L=e(h,"p",{className:"tab-mcp-status"});L.setAttribute("role","status"),L.hidden=!0;let y=n(h,v.close,()=>f.close(),"tab-mcp-replaced-close",p?"primary":void 0),M=e(h,"div",{className:"tab-mcp-actions"},y),E=y;if(!p){let S=n(h,v.newAddress,()=>{S.disabled=!0,L.hidden=!1,L.textContent=v.gettingNewAddress,m.newAddress().then(()=>{f.close(),m.showConnectDialog({document:h}).catch(()=>{})},(R)=>{S.disabled=!1,L.textContent=R?.reason==="replaced"?v.takenOverAgain:t(v.tryAgainOrClose,{reason:ae(R,v)})})},"tab-mcp-new-address","primary");M.append(" ",S),E=S}f.append(e(h,"p",{className:"tab-mcp-description",text:p?v.replacedSibling:v.replaced}),L,M),f.addEventListener("close",()=>f.remove(),{once:!0}),h.body.append(f),f.showModal(),E.focus()}var mt=1e4;function xt(m,h,p,x="tools",v){let f=a(v),L=r(m),{dialog:y}=l(p,"tab-mcp-connect",f,f.connectTitle);y.tabIndex=-1;let M=e(p,"p",{className:"tab-mcp-status"});M.setAttribute("role","status");let E=e(p,"span",{className:"tab-mcp-announce"});E.setAttribute("aria-live","polite");for(let[g,w]of[["position","absolute"],["width","1px"],["height","1px"],["overflow","hidden"],["clip-path","inset(50%)"],["white-space","nowrap"]])E.style.setProperty(g,w);let S=(g)=>{E.textContent=E.textContent===g?`${g} `:g},R=`${i()}-success`,D=e(p,"p",{className:"tab-mcp-success-title"}),X=e(p,"p",{className:"tab-mcp-success-next"}),ie=e(p,"span",{className:"tab-mcp-success-icon"});ie.setAttribute("aria-hidden","true");let Z=e(p,"div",{className:"tab-mcp-success",id:R},ie,e(p,"div",{className:"tab-mcp-success-text"},D,X)),B=`${i()}-address`,oe=e(p,"label",{text:f.addressLabel});oe.htmlFor=B;let F=e(p,"input",{id:B,className:"tab-mcp-address-input"});F.readOnly=!0;let{button:b,reset:U}=c(p,f,f.copyAddress,()=>F.value,()=>F.select(),S,"tab-mcp-address-copy","primary"),A=e(p,"div",{className:"tab-mcp-address"},oe,F," ",b),W=n(p,f.newAddress,()=>at(),"tab-mcp-new-address"),j=e(p,"div",{className:"tab-mcp-new-address-row"},e(p,"small",{text:f.newAddressNote})," ",W),te=`${i()}-new-address`,be=e(p,"p",{id:te}),ce=n(p,f.cancel,()=>{K=!1,C(),W.focus()}),je=n(p,f.newAddressConfirm,()=>He(),"tab-mcp-new-address-confirm","danger"),ne=e(p,"div",{className:"tab-mcp-new-address-question"},be,e(p,"div",{className:"tab-mcp-actions"},ce," ",je));ne.setAttribute("role","group"),ne.setAttribute("aria-labelledby",te);let z=e(p,"strong",{className:"tab-mcp-code-value"});z.style.setProperty("user-select","all"),z.style.setProperty("-webkit-user-select","all");let{button:Le,reset:Je}=c(p,f,f.copyCode,()=>z.textContent??"",()=>p.getSelection()?.selectAllChildren(z),S,"tab-mcp-code-copy"),we=e(p,"span",{},...o(p,f.codeSentence,{code:z}));we.setAttribute("aria-live","polite");let ve=e(p,"span",{className:"tab-mcp-code-used"}),ye=e(p,"p",{className:"tab-mcp-code"},we,ve," ",Le,e(p,"br"),e(p,"small",{className:"tab-mcp-code-note",text:f.codeNote})),ke=e(p,"p",{className:"tab-mcp-sign-in",text:f.signIn}),De=e(p,"ul"),xe=e(p,"details",{className:"tab-mcp-help"},e(p,"summary",{text:f.help}),De),Ie=v?.setup?.guide===void 0?Ve:v.setup.guide;if(Ie!==null){let g=e(p,"a",{text:f.guide});g.href=Ie,g.target="_blank",g.rel="noopener noreferrer",xe.append(e(p,"p",{className:"tab-mcp-guide"},g))}let Ye=v?.setup?.instructions??Xe,Me=`${i()}-setup`,Oe=e(p,"div",{className:"tab-mcp-setup",id:Me},A,xe,ye,ke,j,ne),de=n(p,f.connectAnother,()=>{se=!se,C()},"tab-mcp-setup-toggle");de.setAttribute("aria-controls",Me);let re=e(p,"ul"),le=e(p,"p",{className:"tab-mcp-apps-note"});le.setAttribute("role","status");let $e=e(p,"div",{className:"tab-mcp-apps"},e(p,"h3",{text:f.connectedHeading}),re,le),Pe=e(p,"small",{className:"tab-mcp-close-note",text:f.closeNote}),Q=n(p,f.close,()=>y.close(),"tab-mcp-close"),ue=n(p,f.done,()=>y.close(),"tab-mcp-done","primary"),J=n(p,f.connectAgain,()=>{G=void 0,m.connect().then(()=>{if(p.activeElement===Q)Ne().focus()},(g)=>{if(G=ae(g,f),C(),p.activeElement===Q&&!J.hidden)J.focus()}),C()},"tab-mcp-retry","primary"),et=e(p,"div",{className:"tab-mcp-actions"},Pe," ",Q,J,ue);y.append(Z,M,$e,de,Oe,et,E);let se=!1,K=!1,Y=!1,ee=!1,G,pe,_e=new Set(m.grants.map((g)=>g.grantId)),Re,Ce,P,T=!1,Ue=()=>T?ue:J.hidden?Q:J,Ne=()=>T?ue:b,fe=new Map,tt=(g)=>{let w=d(g.client,f),N=n(p,f.disconnect,()=>{pe=void 0,m.revoke(g.grantId).catch((H)=>{if(m.state==="connected")pe=H?.code==="store_unavailable"?f.storeUnavailable:f.disconnectFailed;C()}),C()},"tab-mcp-disconnect","danger");N.setAttribute("aria-label",t(f.disconnectApp,{app:w}));let I=dt(p,f,L,g.grantId,w);return{item:e(p,"li",{},e(p,"span",{className:"tab-mcp-app"},t(f.appConnected,{app:w}))," ",N,I.box),disconnect:N,renderAllowed:I.render}},nt=(g)=>{if(Re===g.address)return;Re=g.address,De.replaceChildren(...Ye(x,g.address).map(({app:w,text:N,command:I,note:k})=>{let H=e(p,"li",{},e(p,"strong",{text:`${w}:`}),` ${N}`);if(I!==void 0){let O=e(p,"pre",{text:I});O.dir="ltr";let{button:q}=c(p,f,t(f.copyCommand,{app:w}),()=>O.textContent??"",()=>p.getSelection()?.selectAllChildren(O),S,"tab-mcp-command-copy");H.append(e(p,"div",{className:"tab-mcp-command"},O,q))}if(k!==void 0)H.append(e(p,"small",{className:"tab-mcp-command-note"},...k.map((O)=>("code"in O)?e(p,"code",{text:O.code}):O.text)));return H}))},st=(g)=>{let w=m.pairingCode;if(w===void 0||g)clearTimeout(P),P=void 0;else if(w.code!==Ce?.code){if(w.reason==="used"){if(P===void 0)P=setTimeout(()=>{P=void 0,Ce=m.pairingCode,C()},mt),S(f.codeUsed)}else if(P!==void 0)clearTimeout(P),P=void 0}let N=P!==void 0;if(!N){if(z.textContent!==(w?.code??""))Je();z.textContent=w?.code??"",Ce=w}return we.hidden=N,Le.hidden=N,ve.hidden=!N,ve.textContent=N?f.codeUsed:"",w!==void 0},C=()=>{let g=p.activeElement,{state:w,session:N,grants:I}=m,k=w==="connected",H=N?.pairing==="oidc",O=H?ut(m,f):void 0,q=N!==void 0&&O===void 0,qe=new Set(I.map((_)=>_.grantId)),Ee=k&&I.some((_)=>!_e.has(_.grantId));if(_e=qe,Ee){if(ee=!1,!K)se=!1}let he=rt(I,f);if(he.length===0||!q)K=!1;T=!Y&&k&&I.length>0;let Se=he.length===1;if(D.textContent=t(Se?f.connectedOne:f.connectedMany,{apps:u(he,f)}),X.textContent=Se?f.connectedNextOne:f.connectedNextMany,T)y.setAttribute("aria-describedby",R);else y.removeAttribute("aria-describedby");if(Z.hidden=!T,k)G=void 0;let We=N?.appName;M.textContent=Y?f.gettingNewAddress:w==="connecting"?f.connecting:w==="reconnecting"?f.reconnecting:!k?G??f.notConnected:O??(ee?f.newAddressDone:We!==void 0?t(f.readyApp,{app:We}):f.readyPage),M.hidden=T;let ot=!A.hidden;if(q&&F.value!==N.address)F.value=N.address,U();if(q)nt(N);if(A.hidden=xe.hidden=j.hidden=!q,W.disabled=!k,ne.hidden=!K,K)be.textContent=t(Se?f.newAddressQuestionOne:f.newAddressQuestionMany,{apps:u(he,f)});let ct=st(Ee);ye.hidden=H||!ct||!k,ke.hidden=!H||m.identity!=="bound",de.hidden=!T,de.setAttribute("aria-expanded",String(se)),Oe.hidden=T&&!se,b.classList.toggle("tab-mcp-primary",!T);for(let[_,{item:ge}]of fe){if(qe.has(_))continue;ge.remove(),fe.delete(_)}if(I.forEach((_,ge)=>{let V=fe.get(_.grantId);if(V===void 0)V=tt(_),fe.set(_.grantId,V);if(V.disconnect.disabled=!k,V.renderAllowed(),re.children[ge]!==V.item)re.insertBefore(V.item,re.children[ge]??null)}),le.textContent=k?pe??"":f.disconnectNote,le.hidden=k&&pe===void 0,$e.hidden=I.length===0,Pe.hidden=T||ye.hidden,Q.hidden=T,ue.hidden=!T,J.hidden=Y||w!=="disconnected"&&w!=="reconnecting",g!==null&&g!==y&&g!==p.body&&(!g.isConnected||y.contains(g)&&g.closest("[hidden]")!==null))(ne.contains(g)&&!j.hidden?W:Ue()).focus();else if(p.activeElement===y&&(T||q))Ne().focus();else if(ee&&q&&!ot&&p.activeElement===Q)b.focus();if(Ee&&T)S(`${D.textContent}. ${X.textContent}`)},at=()=>{if(m.state!=="connected")return;if(m.grants.length===0){He();return}K=!0,C(),ce.focus()},He=()=>{Y=!0,ee=!1,Q.focus(),K=!1,C(),m.newAddress().then(()=>{if(Y=!1,ee=!0,C(),!A.hidden)b.focus()},(g)=>{Y=!1,G=ae(g,f),C(),Ue().focus()})},me,Ae=m.state==="reconnecting",Be=(g)=>{let{error:w}=g.detail;if(Ae&&w.reason!==void 0)me=w},Fe=(g)=>{let{state:w,reason:N}=g.detail;if(N!==void 0&&N!=="new_address")G=lt(N,f),ee=!1;if(w==="disconnected"&&Ae)G=me===void 0?f.disconnected:ae(me,f);Ae=w==="reconnecting",me=void 0,C()},Ge=()=>y.close();pt(m,p,v);let it=L.onChange(C);return m.addEventListener("statechange",Fe),m.addEventListener("pairingcode",C),m.addEventListener("grantschange",C),m.addEventListener("identitychange",C),m.addEventListener("error",Be),m.addEventListener("replaced",Ge),p.body.append(y),m.startPairing(),C(),h.then(C,(g)=>{G=ae(g,f),C()}),new Promise((g)=>{if(y.addEventListener("close",()=>{clearTimeout(P),m.stopPairing(),it(),m.removeEventListener("statechange",Fe),m.removeEventListener("pairingcode",C),m.removeEventListener("grantschange",C),m.removeEventListener("identitychange",C),m.removeEventListener("error",Be),m.removeEventListener("replaced",Ge),y.remove(),g()},{once:!0}),y.showModal(),T||!A.hidden)Ne().focus();else y.focus()})}export{xt as showConnectDialog};
4
4
 
5
5
  //# debugId=29063111D96E787B64756E2164756E21
6
- //# sourceMappingURL=connect-ph4xxen4.min.js.map
6
+ //# sourceMappingURL=connect-x6ws6wqt.min.js.map
@@ -0,0 +1,5 @@
1
+ function m(e){if(e===void 0)return"";let t=2166136261;for(let n=0;n<e.length;n++)t=Math.imul(t^e.charCodeAt(n),16777619)>>>0;return t.toString(16)}var d=(e)=>typeof e==="string";function T(e){let t={secret:"",grants:new Map},n;try{n=JSON.parse(e)}catch{return t}let s=n;if(!d(s?.secret)||!Array.isArray(s.grants))return t;let o=new Map;for(let i of s.grants){let l=i;if(!d(l?.grantId)||typeof l.everything!=="boolean"||!Array.isArray(l.tools))return t;let g=[];for(let w of l.tools){let a=w;if(!d(a?.name)||!d(a.description)||a.title!==void 0&&!d(a.title))return t;g.push(c(a))}o.set(l.grantId,{everything:l.everything,tools:g})}return{secret:s.secret,grants:o}}function k(e){return JSON.stringify({secret:e.secret,grants:[...e.grants].map(([t,n])=>({grantId:t,...n}))})}function c(e){let t={name:e.name,description:e.description};if(e.title!==void 0)t.title=e.title;return t}var y=(e,t)=>e.title===t.title&&e.description===t.description,f=(e,t)=>t===void 0||y(e,t),S={list:()=>[],get:()=>{return},onChange:()=>()=>{}},h=(e)=>typeof e==="function";function b(e){if(!Array.isArray(e)||e.length!==3)return!1;let[t,n,s]=e,o=t,i=n;return["register","list","get","onChange"].every((l)=>h(o?.[l]))&&(i===void 0||h(i?.current))&&[void 0,!0,!1,"until-reload"].includes(s)}function v(e){let t=e._allowed;return b(t)?t:[S,void 0,void 0]}class p{kept;offered;#f;#o;#d;#n;#r;#t={secret:"",grants:new Map};#g=!1;#i=new Set;#l;constructor(e){let[t,n,s]=v(e);this.#f=e,this.#o=t,this.#d=()=>m(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((e)=>e.annotations.consequentialHint===!0&&(e.callers?.includes("relay")??!0)).map((e)=>{let t={name:e.name,description:e.description,destructive:e.annotations.destructiveHint===!0};if(e.title!==void 0)t.title=e.title;return t});list=(e)=>(this.#e().get(e)?.tools??[]).filter((t)=>f(t,this.#o.get(t.name))).map((t)=>t.name);has=(e,t)=>{let n=this.#o.get(t);return this.#a(e)&&(this.everything(e)||n!==void 0&&this.allows(e,n))};allows(e,t){if(!this.#a(e))return!1;let n=this.#e().get(e);if(n===void 0)return!1;if(n.everything)return!0;let s=n.tools.find((o)=>o.name===t.name);return s!==void 0&&y(s,t)}allow=(e,t)=>{let n=this.tools().find((s)=>s.name===t);if(n!==void 0)this.keep(e,n)};keep(e,t){if(!this.#a(e))return;let n=this.#e(),s=n.get(e)??{everything:!1,tools:[]};s.tools=[...s.tools.filter((o)=>o.name!==t.name),c(t)],n.set(e,s),this.#s(n)}ask=(e,t)=>{let n=this.#e(),s=n.get(e);if(s===void 0)return;let o=s.tools.filter((i)=>i.name!==t);if(!s.everything&&o.length===s.tools.length)return;if(s.everything=!1,s.tools=o,o.length===0)n.delete(e);this.#s(n)};everything=(e)=>this.#e().get(e)?.everything===!0;setEverything=(e,t)=>{if(t&&!this.#a(e))return;let n=this.#e(),s=n.get(e)??{everything:!1,tools:[]};if(s.everything===t)return;if(s.everything=t,t||s.tools.length>0)n.set(e,s);else n.delete(e);this.#s(n)};forget=(e)=>{let t=this.#e();if(t.delete(e))this.#s(t)};keepGrants(e){let t=new Set(e),n=this.#e(),s=this.#t.grants!==n&&this.#t.grants.size>0;for(let o of[...n.keys()])if(!t.has(o))s=n.delete(o)||s;if(s)this.#s(n)}toolsChanged(){let e=this.#e(),t=!1;for(let[n,s]of[...e]){let o=s.tools.filter((i)=>f(i,this.#o.get(i.name)));if(o.length===s.tools.length)continue;if(t=!0,s.tools=o,!s.everything&&o.length===0)e.delete(n)}if(t)this.#s(e);else this.#h()}onChange=(e)=>(this.#i.add(e),this.#u(),()=>{if(this.#i.delete(e),this.#i.size===0)this.#l?.(),this.#l=void 0});#u(){if(this.#l!==void 0||this.#n===null)return;let e=globalThis,t=(n)=>{if(n.key===this.#r)this.toolsChanged()};e.addEventListener?.("storage",t),this.#l=()=>e.removeEventListener?.("storage",t)}#a(e){return this.#f.grants.some((t)=>t.grantId===e)}#e(){if(this.#n!==null&&!this.#g)try{let e=this.#n.getItem(this.#r);if(e!==null)this.#t=T(e)}catch{}return this.#t.secret===this.#d()?this.#t.grants:new Map}#s(e){this.#t={secret:this.#d(),grants:e};try{this.#n?.setItem(this.#r,k(this.#t)),this.#g=!1}catch{this.#g=!0}this.#h()}#h(){for(let e of[...this.#i])e()}}var u=new WeakMap;function r(e){let t=u.get(e);if(t!==void 0)return t;let n=new p(e);if(u.set(e,n),e.addEventListener?.("grantschange",()=>n.keepGrants(e.grants.map((s)=>s.grantId))),v(e)[0].onChange(()=>n.toolsChanged()),n.toolsChanged(),"session"in e&&e.session!==void 0)n.keepGrants(e.grants.map((s)=>s.grantId));return n}
2
+ export{r};
3
+
4
+ //# debugId=43D8C3BAA8BF4CFE64756E2164756E21
5
+ //# sourceMappingURL=tab-mcp-client-5j3brdf3.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: the\n\t * app is in `mcp.grants`, and \"everything\" is on or the tool is allowed\n\t * 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 * A caller's own stand-in for a `TabMcp` in the confirmation chunk's\n * `confirmInPage` (a desktop app with an MCP endpoint of its own, say): the\n * AI apps it allows for, and optionally `grantschange` events (with\n * `detail.grants`) when they change. Its allowances live in memory, for\n * those grants only, until the page is reloaded.\n */\nexport interface ConfirmHost {\n\treadonly grants: readonly { readonly grantId: string }[];\n\taddEventListener?(type: string, listener: (event: Event) => void): void;\n}\n\n/** What the allowances read of their host's tools. */\ntype ToolsOf = Pick<ToolRegistry, \"list\" | \"get\" | \"onChange\">;\n\n/** A stand-in has no tools to list: a tool is allowed as its question showed it. */\nconst NO_TOOLS: ToolsOf = {\n\tlist: () => [],\n\tget: () => undefined,\n\tonChange: () => () => {},\n};\n\nconst isFunction = (v: unknown) => typeof v === \"function\";\n\n/**\n * Whether `value` is what a `TabMcp`'s `_allowed` is: its registry (with\n * `register`), its secret store or none, its `alwaysAllow`. Anything else\n * (a stand-in that copied part of it, as some did for 0.18.0) is a stand-in.\n */\nfunction isInternals(value: unknown): value is TabMcp[\"_allowed\"] {\n\tif (!Array.isArray(value) || value.length !== 3) return false;\n\tconst [registry, secrets, alwaysAllow] = value as unknown[];\n\tconst r = registry as Partial<Record<string, unknown>> | null;\n\tconst s = secrets as { current?: unknown } | null | undefined;\n\treturn (\n\t\t[\"register\", \"list\", \"get\", \"onChange\"].every((k) => isFunction(r?.[k])) &&\n\t\t(s === undefined || isFunction(s?.current)) &&\n\t\t[undefined, true, false, \"until-reload\"].includes(alwaysAllow as never)\n\t);\n}\n\n/** The host's tools, secret store and `alwaysAllow`: a `TabMcp`'s, or none for a stand-in. */\nfunction internalsOf(\n\thost: TabMcp | ConfirmHost,\n): TabMcp[\"_allowed\"] | [ToolsOf, undefined, undefined] {\n\tconst internals = (host as { _allowed?: unknown })._allowed;\n\treturn isInternals(internals) ? internals : [NO_TOOLS, undefined, undefined];\n}\n\n/**\n * The allowances of one `TabMcp` (or a caller's stand-in, `ConfirmHost`).\n * The public methods are arrow fields, so that they work taken off the\n * 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 | ConfirmHost;\n\treadonly #registry: ToolsOf;\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 | ConfirmHost) {\n\t\tconst [registry, secrets, alwaysAllow] = internalsOf(mcp);\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.#granted(grantId) &&\n\t\t\t(this.everything(grantId) ||\n\t\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\t// Only for an app the host lists at this moment: a stand-in may drop\n\t\t// one from `grants` without an event, and for a `TabMcp` a call comes\n\t\t// only while the relay's list is current, so it costs nothing there.\n\t\tif (!this.#granted(grantId)) return false;\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` or stand-in. */\nconst allowances = new WeakMap<TabMcp | ConfirmHost, 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; a stand-in's `grantschange`) and\n * its tools.\n */\nexport function allowedFor(mcp: TabMcp | ConfirmHost): 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\t// Against the host's grants as they are now, whatever the event carries\n\t// (a stand-in may send a plain Event; a TabMcp's detail is its grants).\n\tmcp.addEventListener?.(\"grantschange\", () =>\n\t\tmade.keepGrants(mcp.grants.map((g) => g.grantId)),\n\t);\n\tinternalsOf(mcp)[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 (\"session\" in mcp && mcp.session !== undefined)\n\t\tmade.keepGrants(mcp.grants.map((g) => g.grantId));\n\treturn made;\n}\n"
6
+ ],
7
+ "mapp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&(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};
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,["g0j3a6gn","khy4f5rj","0xqwz17v","x6ws6wqt","d722a9eb","2vx9mcww","5j3brdf3"],[["./tab-mcp-client.min.js"],["./webmcp-khy4f5rj.min.js"],["./connection-0xqwz17v.min.js"],["./connect-x6ws6wqt.min.js",5,6],["./confirm-d722a9eb.min.js",5,6],["./tab-mcp-client-2vx9mcww.min.js"],["./tab-mcp-client-5j3brdf3.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.1";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("x6ws6wqt"),import("./connect-x6ws6wqt.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("d722a9eb"),import("./confirm-d722a9eb.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("d722a9eb"),import("./confirm-d722a9eb.min.js")).then((i)=>i.confirmInPage(this,e,n,{ui: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=57BABC9C6D2ADDC464756E2164756E21
4
+ //# debugId=744E884AE3AFA27364756E2164756E21
5
5
  //# sourceMappingURL=tab-mcp-client.min.js.map