@tollbooth-dpyc/web 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +69 -0
  3. package/dist/avatar.d.ts +20 -0
  4. package/dist/avatar.js +54 -0
  5. package/dist/client.d.ts +42 -0
  6. package/dist/client.js +169 -0
  7. package/dist/config.d.ts +39 -0
  8. package/dist/config.js +33 -0
  9. package/dist/debugLog.d.ts +18 -0
  10. package/dist/debugLog.js +29 -0
  11. package/dist/identity.d.ts +43 -0
  12. package/dist/identity.js +106 -0
  13. package/dist/index.d.ts +12 -0
  14. package/dist/index.js +11 -0
  15. package/dist/inlineProof.d.ts +10 -0
  16. package/dist/inlineProof.js +21 -0
  17. package/dist/nostrProfile.d.ts +13 -0
  18. package/dist/nostrProfile.js +54 -0
  19. package/dist/pagesProxy.d.ts +22 -0
  20. package/dist/pagesProxy.js +54 -0
  21. package/dist/profilePresentation.d.ts +17 -0
  22. package/dist/profilePresentation.js +32 -0
  23. package/dist/react/Avatar.d.ts +6 -0
  24. package/dist/react/Avatar.js +7 -0
  25. package/dist/react/AvatarPicker.d.ts +9 -0
  26. package/dist/react/AvatarPicker.js +64 -0
  27. package/dist/react/NostrProfilePanel.d.ts +8 -0
  28. package/dist/react/NostrProfilePanel.js +116 -0
  29. package/dist/react/NpubGate.d.ts +16 -0
  30. package/dist/react/NpubGate.js +159 -0
  31. package/dist/react/WalletCard.d.ts +11 -0
  32. package/dist/react/WalletCard.js +82 -0
  33. package/dist/react/index.d.ts +6 -0
  34. package/dist/react/index.js +6 -0
  35. package/dist/react/ui.d.ts +9 -0
  36. package/dist/react/ui.js +9 -0
  37. package/dist/react/useSession.d.ts +19 -0
  38. package/dist/react/useSession.js +39 -0
  39. package/dist/sessionNsec.d.ts +23 -0
  40. package/dist/sessionNsec.js +59 -0
  41. package/dist/signInSituation.d.ts +22 -0
  42. package/dist/signInSituation.js +42 -0
  43. package/dist/signedIn.d.ts +26 -0
  44. package/dist/signedIn.js +26 -0
  45. package/dist/standardTools.d.ts +134 -0
  46. package/dist/standardTools.js +68 -0
  47. package/dist/storage.d.ts +14 -0
  48. package/dist/storage.js +46 -0
  49. package/dist/toolResult.d.ts +37 -0
  50. package/dist/toolResult.js +60 -0
  51. package/package.json +60 -0
  52. package/theme.css +47 -0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,69 @@
1
+ # @tollbooth-dpyc/web
2
+
3
+ The browser half of [Tollbooth DPYC](https://github.com/lonniev/tollbooth-dpyc):
4
+ the shared code every operator front end needs, so a site holds only its own
5
+ features. It is the peer of the `tollbooth-dpyc` Python wheel.
6
+
7
+ - **npub sign-in** — a Nostr DM challenge, or an in-browser session key
8
+ - **proofs** — the npub/`dpop_token` envelope on every paid call, a fresh
9
+ kind-27235 inline proof when the tab holds a session key
10
+ - **MCP client** — one shared connection to the operator, typed wrappers for
11
+ the standard tools (balance, top-up, statement, price, profile)
12
+ - **React components** — `NpubGate`, `NostrProfilePanel`, `WalletCard`,
13
+ `AvatarPicker`, `useSession`
14
+ - **Pages proxy** — the `/mcp` Cloudflare Pages Function
15
+
16
+ ## Use
17
+
18
+ ```ts
19
+ // main.tsx — once, before rendering
20
+ import { configureTollbooth } from "@tollbooth-dpyc/web";
21
+
22
+ configureTollbooth({ slug: "chart", appName: "ChartRemotely", mcpUrl: "/mcp" });
23
+ ```
24
+
25
+ ```tsx
26
+ import { callTool, callToolWithContent } from "@tollbooth-dpyc/web";
27
+ import { NpubGate, WalletCard, useSession } from "@tollbooth-dpyc/web/react";
28
+
29
+ const displays = await callTool("agent_status"); // chart_agent_status
30
+ const { data, images } = await callToolWithContent("snapshot_display", { display: "Desk" });
31
+ ```
32
+
33
+ Short tool names are used throughout; the slug is added for you, and the proof
34
+ is bound to the full runtime name.
35
+
36
+ ```js
37
+ // functions/mcp.js
38
+ import { makeMcpProxy } from "@tollbooth-dpyc/web/pages-proxy";
39
+ export const onRequest = makeMcpProxy("https://chartremotely-mcp.fastmcp.app/mcp");
40
+ ```
41
+
42
+ ### Styling
43
+
44
+ Components use Tailwind classes coloured only through CSS variables. Tell
45
+ Tailwind to scan the package, import the default tokens, and override any of
46
+ them after:
47
+
48
+ ```css
49
+ @import "tailwindcss";
50
+ @import "@tollbooth-dpyc/web/theme.css";
51
+ @source "../node_modules/@tollbooth-dpyc/web/dist";
52
+
53
+ :root { --tb-accent: #4cc38a; }
54
+ ```
55
+
56
+ ## Develop
57
+
58
+ ```sh
59
+ npm install
60
+ npm test # node --test, no browser needed
61
+ npm run build # tsc → dist/
62
+ ```
63
+
64
+ Releases publish from a `v*` tag through npm trusted publishing; see
65
+ `.github/workflows/release.yml`.
66
+
67
+ ## Licence
68
+
69
+ Apache-2.0
@@ -0,0 +1,20 @@
1
+ /**
2
+ * The patron's avatar, cached per npub.
3
+ *
4
+ * kind-0 `picture` is the source of truth, but it is a URL and an emoji glyph
5
+ * is not, so a glyph pick stays local. A change dispatches a window event so
6
+ * every avatar on the page updates without a reload.
7
+ */
8
+ export declare const AVATAR_CHOICES: string[];
9
+ export declare const AVATAR_EVENT = "tollbooth:avatar-changed";
10
+ /** http(s) or data:image renders as an image; anything else as a glyph. */
11
+ export declare function isAvatarUrl(value: string): boolean;
12
+ /** First 8 and last 4 characters. */
13
+ export declare function shortNpub(npub?: string | null): string;
14
+ export declare function getStoredAvatar(npub: string): string;
15
+ export declare function setStoredAvatar(npub: string, value: string): void;
16
+ /** A stable glyph from the npub, so a new patron still has a distinct avatar. */
17
+ export declare function defaultAvatar(npub: string): string;
18
+ export declare function avatarFor(npub: string): string;
19
+ /** Seed the cache from kind-0, unless the patron already picked one here. */
20
+ export declare function hydrateAvatarFromNostr(npub: string): Promise<void>;
package/dist/avatar.js ADDED
@@ -0,0 +1,54 @@
1
+ /**
2
+ * The patron's avatar, cached per npub.
3
+ *
4
+ * kind-0 `picture` is the source of truth, but it is a URL and an emoji glyph
5
+ * is not, so a glyph pick stays local. A change dispatches a window event so
6
+ * every avatar on the page updates without a reload.
7
+ */
8
+ import { fetchProfile } from "./nostrProfile.js";
9
+ import { readStored, writeStored } from "./storage.js";
10
+ export const AVATAR_CHOICES = [
11
+ "🐂", "🐻", "🦂", "🦅", "🐺", "🦉",
12
+ "🦊", "🐉", "🦄", "🐢", "🦈", "🦀",
13
+ "🎩", "🎭", "🃏", "🎯", "🪙", "💎",
14
+ "⚡", "🔥", "🌪️", "🌊", "🏔️", "🌋",
15
+ "♟️", "♛", "🛡️", "⚔️", "🗝️", "📜",
16
+ ];
17
+ export const AVATAR_EVENT = "tollbooth:avatar-changed";
18
+ /** http(s) or data:image renders as an image; anything else as a glyph. */
19
+ export function isAvatarUrl(value) {
20
+ return /^(https?:\/\/|data:image\/)/i.test(value);
21
+ }
22
+ /** First 8 and last 4 characters. */
23
+ export function shortNpub(npub) {
24
+ if (!npub)
25
+ return "";
26
+ return npub.length <= 16 ? npub : `${npub.slice(0, 8)}…${npub.slice(-4)}`;
27
+ }
28
+ export function getStoredAvatar(npub) {
29
+ return npub ? readStored(`avatar:${npub}`) : "";
30
+ }
31
+ export function setStoredAvatar(npub, value) {
32
+ if (!npub)
33
+ return;
34
+ writeStored(`avatar:${npub}`, value);
35
+ globalThis.dispatchEvent?.(new CustomEvent(AVATAR_EVENT, { detail: { npub, value } }));
36
+ }
37
+ /** A stable glyph from the npub, so a new patron still has a distinct avatar. */
38
+ export function defaultAvatar(npub) {
39
+ let h = 0;
40
+ for (const c of npub)
41
+ h = (h * 31 + c.charCodeAt(0)) >>> 0;
42
+ return AVATAR_CHOICES[h % AVATAR_CHOICES.length];
43
+ }
44
+ export function avatarFor(npub) {
45
+ return getStoredAvatar(npub) || defaultAvatar(npub);
46
+ }
47
+ /** Seed the cache from kind-0, unless the patron already picked one here. */
48
+ export async function hydrateAvatarFromNostr(npub) {
49
+ if (!npub || getStoredAvatar(npub))
50
+ return;
51
+ const p = await fetchProfile(npub);
52
+ if (p?.picture)
53
+ setStoredAvatar(npub, p.picture);
54
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * The operator MCP, as a page calls it.
3
+ *
4
+ * 1. One @modelcontextprotocol/sdk Client over StreamableHTTP, shared by the
5
+ * whole page. The SDK handles the initialize handshake and the session.
6
+ * 2. Auth is the uniform npub proof, by one of two tactics, invisible to
7
+ * callers: a session nsec signs a fresh kind-27235 proof per call, bound to
8
+ * the runtime tool name; otherwise the DM proof token cached at
9
+ * `receive_npub_proof` is sent as is.
10
+ * 3. Bootstrap tools take no envelope and are safe before sign-in.
11
+ */
12
+ import { type ImageBlock } from "./toolResult.ts";
13
+ /** A paid call bounced for a lapsed or missing proof. The gate re-arms sign-in. */
14
+ export declare class ProofRequiredError extends Error {
15
+ constructor(message: string);
16
+ }
17
+ type ProofExpiredListener = (message: string) => void;
18
+ /**
19
+ * Subscribe to proof bounces from anywhere in the app. Without this the tree
20
+ * never learns the token was cleared, and the patron is stranded on a page
21
+ * whose data will not load. Returns an unsubscribe function.
22
+ */
23
+ export declare function onProofExpired(cb: ProofExpiredListener): () => void;
24
+ export interface CallOptions {
25
+ /**
26
+ * A non-essential call — diagnostics, personalization. It never logs the
27
+ * patron out, whatever it gets back.
28
+ */
29
+ bestEffort?: boolean;
30
+ timeoutMs?: number;
31
+ }
32
+ export interface ToolAnswer<T> {
33
+ data: T;
34
+ images: ImageBlock[];
35
+ }
36
+ /**
37
+ * Call a tool by its short name ("snapshot_display", not
38
+ * "chart_snapshot_display") and get both its answer and any images it sent.
39
+ */
40
+ export declare function callToolWithContent<T = unknown>(tool: string, args?: Record<string, unknown>, opts?: CallOptions): Promise<ToolAnswer<T>>;
41
+ export declare function callTool<T = unknown>(tool: string, args?: Record<string, unknown>, opts?: CallOptions): Promise<T>;
42
+ export {};
package/dist/client.js ADDED
@@ -0,0 +1,169 @@
1
+ /**
2
+ * The operator MCP, as a page calls it.
3
+ *
4
+ * 1. One @modelcontextprotocol/sdk Client over StreamableHTTP, shared by the
5
+ * whole page. The SDK handles the initialize handshake and the session.
6
+ * 2. Auth is the uniform npub proof, by one of two tactics, invisible to
7
+ * callers: a session nsec signs a fresh kind-27235 proof per call, bound to
8
+ * the runtime tool name; otherwise the DM proof token cached at
9
+ * `receive_npub_proof` is sent as is.
10
+ * 3. Bootstrap tools take no envelope and are safe before sign-in.
11
+ */
12
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
13
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
14
+ import { tollboothConfig, toolName } from "./config.js";
15
+ import { debugPush } from "./debugLog.js";
16
+ import { clearStoredProof, forgetRecentLogin, getStoredNpub, getStoredProof, } from "./identity.js";
17
+ import { signInlineProof } from "./inlineProof.js";
18
+ import { clearSessionNsec, hasSessionNsec, sessionNsecNpub } from "./sessionNsec.js";
19
+ import { errorText, looksFailed, proofBounceMessage, readToolResult, } from "./toolResult.js";
20
+ /**
21
+ * Standard tools whose wheel signature takes no npub/proof envelope. Pydantic
22
+ * strict mode rejects unexpected kwargs, so they must not get one.
23
+ */
24
+ const STANDARD_BOOTSTRAP = [
25
+ "request_npub_proof",
26
+ "receive_npub_proof",
27
+ "service_status",
28
+ "session_status",
29
+ "get_nostr_profile",
30
+ "publish_nostr_profile",
31
+ "get_operator_onboarding_status",
32
+ "check_authority_balance",
33
+ "list_canonical_identities",
34
+ "check_proof_status",
35
+ "get_patron_onboarding_status",
36
+ "request_patron_credentials",
37
+ "receive_patron_credentials",
38
+ ];
39
+ const STANDARD_QUIET = ["service_status", "get_nostr_profile"];
40
+ let client = null;
41
+ let connecting = null;
42
+ function mcpUrl() {
43
+ const url = tollboothConfig().mcpUrl;
44
+ if (!url)
45
+ throw new Error("mcpUrl is not configured (e.g. \"/mcp\").");
46
+ return url.startsWith("/") ? `${globalThis.location.origin}${url}` : url;
47
+ }
48
+ async function getClient() {
49
+ if (client)
50
+ return client;
51
+ if (!connecting) {
52
+ // Cleared whether it worked or not. Cleared only on success, one failed
53
+ // connect — no signal, a cold server — was awaited again by every later
54
+ // call, and nothing reached the server until the page was reloaded.
55
+ connecting = (async () => {
56
+ const c = new Client({ name: `${tollboothConfig().slug}-frontend`, version: "1" });
57
+ await c.connect(new StreamableHTTPClientTransport(new URL(mcpUrl())));
58
+ client = c;
59
+ })().finally(() => {
60
+ connecting = null;
61
+ });
62
+ }
63
+ await connecting;
64
+ if (!client)
65
+ throw new Error("Could not connect to the service.");
66
+ return client;
67
+ }
68
+ /**
69
+ * The proof for one call: a fresh inline proof when this tab's session key
70
+ * derives to the signed-in npub, else the cached DM token. A session key left
71
+ * from a previous identity is evicted rather than allowed to sign.
72
+ */
73
+ function proofFor(tool) {
74
+ try {
75
+ const npub = getStoredNpub();
76
+ const sessionNpub = hasSessionNsec() ? sessionNsecNpub() : null;
77
+ if (sessionNpub && sessionNpub === npub)
78
+ return signInlineProof(toolName(tool));
79
+ if (sessionNpub)
80
+ clearSessionNsec();
81
+ }
82
+ catch {
83
+ /* fall through to the cached token */
84
+ }
85
+ return getStoredProof();
86
+ }
87
+ /** A paid call bounced for a lapsed or missing proof. The gate re-arms sign-in. */
88
+ export class ProofRequiredError extends Error {
89
+ constructor(message) {
90
+ super(message);
91
+ this.name = "ProofRequiredError";
92
+ }
93
+ }
94
+ const proofExpiredListeners = new Set();
95
+ /**
96
+ * Subscribe to proof bounces from anywhere in the app. Without this the tree
97
+ * never learns the token was cleared, and the patron is stranded on a page
98
+ * whose data will not load. Returns an unsubscribe function.
99
+ */
100
+ export function onProofExpired(cb) {
101
+ proofExpiredListeners.add(cb);
102
+ return () => proofExpiredListeners.delete(cb);
103
+ }
104
+ function emitProofExpired(message) {
105
+ for (const cb of proofExpiredListeners) {
106
+ try {
107
+ cb(message);
108
+ }
109
+ catch {
110
+ /* a listener error must not swallow the throw that follows */
111
+ }
112
+ }
113
+ }
114
+ /**
115
+ * Call a tool by its short name ("snapshot_display", not
116
+ * "chart_snapshot_display") and get both its answer and any images it sent.
117
+ */
118
+ export async function callToolWithContent(tool, args = {}, opts = {}) {
119
+ const cfg = tollboothConfig();
120
+ const name = toolName(tool);
121
+ const quiet = STANDARD_QUIET.includes(tool) || cfg.quietTools.includes(tool);
122
+ // `args` holds only the caller's own parameters — the envelope is added
123
+ // below — so it is safe to log.
124
+ if (!quiet)
125
+ debugPush("call", `${name}(${JSON.stringify(args).slice(0, 140)})`);
126
+ const bootstrap = STANDARD_BOOTSTRAP.includes(tool) || cfg.extraBootstrapTools.includes(tool);
127
+ const merged = bootstrap
128
+ ? { ...args }
129
+ : { npub: getStoredNpub(), dpop_token: proofFor(tool), ...args };
130
+ let result;
131
+ try {
132
+ const c = await getClient();
133
+ result = (await c.callTool({ name, arguments: merged }, undefined, { timeout: opts.timeoutMs ?? 120_000 }));
134
+ }
135
+ catch (e) {
136
+ if (!quiet)
137
+ debugPush("error", `${name}: ${e.message}`);
138
+ throw new Error(`${name}: ${e.message}`);
139
+ }
140
+ if (result.isError) {
141
+ const text = errorText(result);
142
+ if (!quiet)
143
+ debugPush("error", `${name}: ${text.slice(0, 200)}`);
144
+ throw new Error(text);
145
+ }
146
+ const { payload, images } = readToolResult(result);
147
+ if (!quiet) {
148
+ const preview = typeof payload === "string" ? payload : JSON.stringify(payload);
149
+ const tail = images.length ? ` +${images.length} image` : "";
150
+ debugPush(looksFailed(payload) ? "error" : "result", `${name} → ${String(preview).slice(0, 220)}${tail}`);
151
+ }
152
+ if (!opts.bestEffort) {
153
+ const bounced = proofBounceMessage(payload);
154
+ if (bounced !== null) {
155
+ // The token just refused is the same one the recent-login shortcut
156
+ // would replay, so it goes too, or a returning patron re-bounces.
157
+ const npub = getStoredNpub();
158
+ clearStoredProof();
159
+ if (npub)
160
+ forgetRecentLogin(npub);
161
+ emitProofExpired(bounced);
162
+ throw new ProofRequiredError(bounced);
163
+ }
164
+ }
165
+ return { data: payload, images };
166
+ }
167
+ export async function callTool(tool, args = {}, opts = {}) {
168
+ return (await callToolWithContent(tool, args, opts)).data;
169
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The one thing that differs between operator front ends.
3
+ *
4
+ * Every copy of this code in the fleet differed from its siblings in the same
5
+ * few places: the tool-name slug, the brand in a sign-in DM and a heading, and
6
+ * the prefix on its localStorage keys. Those are configuration, so they live
7
+ * here and nowhere else. A site calls `configureTollbooth` once, before it
8
+ * renders, and everything in the package reads from it.
9
+ */
10
+ export interface TollboothConfig {
11
+ /** Tool-name prefix the operator registers under, e.g. "chart" or "goodearth". */
12
+ slug: string;
13
+ /** The name a patron knows the service by, e.g. "ChartRemotely". */
14
+ appName: string;
15
+ /** Prefix for localStorage keys. Defaults to the slug. */
16
+ storagePrefix?: string;
17
+ /**
18
+ * Where the MCP endpoint is. A path ("/mcp") is resolved against the page's
19
+ * origin, which is how every site reaches its Pages proxy.
20
+ */
21
+ mcpUrl: string;
22
+ /**
23
+ * Free tools this operator adds that take no npub/proof envelope, on top of
24
+ * the standard ones. Pydantic rejects unexpected kwargs, so a tool listed
25
+ * here must truly not accept `npub`.
26
+ */
27
+ extraBootstrapTools?: string[];
28
+ /** Tools too routine to log in the debug panel. */
29
+ quietTools?: string[];
30
+ }
31
+ interface Resolved extends Required<Omit<TollboothConfig, "extraBootstrapTools" | "quietTools">> {
32
+ extraBootstrapTools: string[];
33
+ quietTools: string[];
34
+ }
35
+ export declare function configureTollbooth(config: TollboothConfig): void;
36
+ export declare function tollboothConfig(): Resolved;
37
+ /** The runtime tool name a proof must be bound to, e.g. "chart_snapshot_display". */
38
+ export declare function toolName(tool: string): string;
39
+ export {};
package/dist/config.js ADDED
@@ -0,0 +1,33 @@
1
+ /**
2
+ * The one thing that differs between operator front ends.
3
+ *
4
+ * Every copy of this code in the fleet differed from its siblings in the same
5
+ * few places: the tool-name slug, the brand in a sign-in DM and a heading, and
6
+ * the prefix on its localStorage keys. Those are configuration, so they live
7
+ * here and nowhere else. A site calls `configureTollbooth` once, before it
8
+ * renders, and everything in the package reads from it.
9
+ */
10
+ let current = null;
11
+ export function configureTollbooth(config) {
12
+ if (!/^[a-z][a-z0-9_]*$/.test(config.slug)) {
13
+ throw new Error(`slug must be lowercase letters, digits or underscores: ${config.slug}`);
14
+ }
15
+ current = {
16
+ slug: config.slug,
17
+ appName: config.appName,
18
+ storagePrefix: config.storagePrefix ?? config.slug,
19
+ mcpUrl: config.mcpUrl,
20
+ extraBootstrapTools: config.extraBootstrapTools ?? [],
21
+ quietTools: config.quietTools ?? [],
22
+ };
23
+ }
24
+ export function tollboothConfig() {
25
+ if (!current) {
26
+ throw new Error("configureTollbooth() must be called before the app renders.");
27
+ }
28
+ return current;
29
+ }
30
+ /** The runtime tool name a proof must be bound to, e.g. "chart_snapshot_display". */
31
+ export function toolName(tool) {
32
+ return `${tollboothConfig().slug}_${tool}`;
33
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * An in-memory activity log of MCP calls, for a site's debug panel.
3
+ *
4
+ * A ring buffer with subscribers, so the one `callTool` can push and any panel
5
+ * can listen. It survives route changes and is gone on reload. Arguments are
6
+ * logged only as the wrapper's own parameters — the npub/proof envelope is
7
+ * added after logging, so no proof ever lands here.
8
+ */
9
+ export interface DebugEntry {
10
+ ts: string;
11
+ type: "info" | "call" | "result" | "error";
12
+ message: string;
13
+ }
14
+ export declare function debugPush(type: DebugEntry["type"], message: string): void;
15
+ export declare function clearDebug(): void;
16
+ export declare function debugEntries(): readonly DebugEntry[];
17
+ /** Subscribe to changes. Returns an unsubscribe function. */
18
+ export declare function onDebug(fn: () => void): () => void;