@zackbart/connecta 0.7.9 → 0.8.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 (180) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/README.md +67 -144
  3. package/dist/auth/bearer.d.ts +1 -1
  4. package/dist/auth/bearer.js +4 -4
  5. package/dist/auth/bearer.js.map +1 -1
  6. package/dist/auth/clerk.d.ts +1 -1
  7. package/dist/auth/clerk.js +1 -1
  8. package/dist/call-admission.d.ts.map +1 -1
  9. package/dist/call-admission.js +9 -3
  10. package/dist/call-admission.js.map +1 -1
  11. package/dist/catalog-fingerprint.d.ts +20 -0
  12. package/dist/catalog-fingerprint.d.ts.map +1 -0
  13. package/dist/catalog-fingerprint.js +34 -0
  14. package/dist/catalog-fingerprint.js.map +1 -0
  15. package/dist/catalog-limits.d.ts +10 -0
  16. package/dist/catalog-limits.d.ts.map +1 -0
  17. package/dist/catalog-limits.js +10 -0
  18. package/dist/catalog-limits.js.map +1 -0
  19. package/dist/catalog-service.d.ts +138 -0
  20. package/dist/catalog-service.d.ts.map +1 -0
  21. package/dist/catalog-service.js +407 -0
  22. package/dist/catalog-service.js.map +1 -0
  23. package/dist/catalog.js +2 -2
  24. package/dist/catalog.js.map +1 -1
  25. package/dist/concurrency.d.ts +4 -0
  26. package/dist/concurrency.d.ts.map +1 -0
  27. package/dist/concurrency.js +31 -0
  28. package/dist/concurrency.js.map +1 -0
  29. package/dist/connectors/api.d.ts.map +1 -1
  30. package/dist/connectors/api.js +22 -12
  31. package/dist/connectors/api.js.map +1 -1
  32. package/dist/connectors/remote-mcp.d.ts.map +1 -1
  33. package/dist/connectors/remote-mcp.js +44 -19
  34. package/dist/connectors/remote-mcp.js.map +1 -1
  35. package/dist/credential-health.d.ts +0 -22
  36. package/dist/credential-health.d.ts.map +1 -1
  37. package/dist/credential-health.js +14 -10
  38. package/dist/credential-health.js.map +1 -1
  39. package/dist/credentials.d.ts +3 -2
  40. package/dist/credentials.d.ts.map +1 -1
  41. package/dist/errors.d.ts +1 -1
  42. package/dist/errors.d.ts.map +1 -1
  43. package/dist/errors.js.map +1 -1
  44. package/dist/execute.d.ts +9 -8
  45. package/dist/execute.d.ts.map +1 -1
  46. package/dist/execute.js +144 -321
  47. package/dist/execute.js.map +1 -1
  48. package/dist/executor-result.d.ts +0 -3
  49. package/dist/executor-result.d.ts.map +1 -1
  50. package/dist/executor-result.js +2 -2
  51. package/dist/executor-result.js.map +1 -1
  52. package/dist/executors/quickjs-child.js +3 -3
  53. package/dist/executors/quickjs-child.js.map +1 -1
  54. package/dist/executors/quickjs-protocol.d.ts +4 -1
  55. package/dist/executors/quickjs-protocol.d.ts.map +1 -1
  56. package/dist/executors/quickjs-runtime.d.ts.map +1 -1
  57. package/dist/executors/quickjs-runtime.js +7 -2
  58. package/dist/executors/quickjs-runtime.js.map +1 -1
  59. package/dist/executors/quickjs.d.ts.map +1 -1
  60. package/dist/executors/quickjs.js +4 -1
  61. package/dist/executors/quickjs.js.map +1 -1
  62. package/dist/favicon.js +2 -2
  63. package/dist/favicon.js.map +1 -1
  64. package/dist/index.d.ts +5 -0
  65. package/dist/index.d.ts.map +1 -1
  66. package/dist/index.js +44 -17
  67. package/dist/index.js.map +1 -1
  68. package/dist/invocation.d.ts +96 -0
  69. package/dist/invocation.d.ts.map +1 -0
  70. package/dist/invocation.js +369 -0
  71. package/dist/invocation.js.map +1 -0
  72. package/dist/meta-tools.d.ts +8 -86
  73. package/dist/meta-tools.d.ts.map +1 -1
  74. package/dist/meta-tools.js +145 -583
  75. package/dist/meta-tools.js.map +1 -1
  76. package/dist/operator-ui/generated.d.ts +3 -0
  77. package/dist/operator-ui/generated.d.ts.map +1 -0
  78. package/dist/operator-ui/generated.js +5 -0
  79. package/dist/operator-ui/generated.js.map +1 -0
  80. package/dist/operator-ui/model.d.ts +94 -0
  81. package/dist/operator-ui/model.d.ts.map +1 -0
  82. package/dist/operator-ui/model.js +28 -0
  83. package/dist/operator-ui/model.js.map +1 -0
  84. package/dist/registry.d.ts +22 -6
  85. package/dist/registry.d.ts.map +1 -1
  86. package/dist/registry.js +328 -35
  87. package/dist/registry.js.map +1 -1
  88. package/dist/routes/activity.d.ts +3 -0
  89. package/dist/routes/activity.d.ts.map +1 -0
  90. package/dist/routes/activity.js +173 -0
  91. package/dist/routes/activity.js.map +1 -0
  92. package/dist/routes/credentials.d.ts +3 -0
  93. package/dist/routes/credentials.d.ts.map +1 -0
  94. package/dist/routes/credentials.js +181 -0
  95. package/dist/routes/credentials.js.map +1 -0
  96. package/dist/routes/mcp.d.ts +8 -0
  97. package/dist/routes/mcp.d.ts.map +1 -0
  98. package/dist/routes/mcp.js +383 -0
  99. package/dist/routes/mcp.js.map +1 -0
  100. package/dist/routes/oauth.d.ts +4 -0
  101. package/dist/routes/oauth.d.ts.map +1 -0
  102. package/dist/routes/oauth.js +268 -0
  103. package/dist/routes/oauth.js.map +1 -0
  104. package/dist/routes/shared.d.ts +97 -0
  105. package/dist/routes/shared.d.ts.map +1 -0
  106. package/dist/routes/shared.js +199 -0
  107. package/dist/routes/shared.js.map +1 -0
  108. package/dist/routes/ui.d.ts +3 -0
  109. package/dist/routes/ui.d.ts.map +1 -0
  110. package/dist/routes/ui.js +122 -0
  111. package/dist/routes/ui.js.map +1 -0
  112. package/dist/server.d.ts +9 -40
  113. package/dist/server.d.ts.map +1 -1
  114. package/dist/server.js +63 -1293
  115. package/dist/server.js.map +1 -1
  116. package/dist/skills.d.ts +0 -15
  117. package/dist/skills.d.ts.map +1 -1
  118. package/dist/skills.js +6 -5
  119. package/dist/skills.js.map +1 -1
  120. package/dist/storage/file.d.ts.map +1 -1
  121. package/dist/storage/file.js +3 -1
  122. package/dist/storage/file.js.map +1 -1
  123. package/dist/storage/memory.d.ts.map +1 -1
  124. package/dist/storage/memory.js +3 -1
  125. package/dist/storage/memory.js.map +1 -1
  126. package/dist/toolkits.d.ts +0 -22
  127. package/dist/toolkits.d.ts.map +1 -1
  128. package/dist/toolkits.js +2 -2
  129. package/dist/toolkits.js.map +1 -1
  130. package/dist/types.d.ts +9 -2
  131. package/dist/types.d.ts.map +1 -1
  132. package/dist/ui.d.ts +3 -93
  133. package/dist/ui.d.ts.map +1 -1
  134. package/dist/ui.js +26 -1393
  135. package/dist/ui.js.map +1 -1
  136. package/dist/version.d.ts +1 -1
  137. package/dist/version.js +1 -1
  138. package/package.json +15 -8
  139. package/src/auth/bearer.ts +4 -4
  140. package/src/auth/clerk.ts +1 -1
  141. package/src/call-admission.ts +8 -5
  142. package/src/catalog-fingerprint.ts +52 -0
  143. package/src/catalog-limits.ts +11 -0
  144. package/src/catalog-service.ts +601 -0
  145. package/src/catalog.ts +2 -2
  146. package/src/concurrency.ts +39 -0
  147. package/src/connectors/api.ts +22 -12
  148. package/src/connectors/remote-mcp.ts +52 -22
  149. package/src/credential-health.ts +13 -10
  150. package/src/credentials.ts +2 -2
  151. package/src/errors.ts +1 -1
  152. package/src/execute.ts +194 -409
  153. package/src/executor-result.ts +2 -2
  154. package/src/executors/quickjs-child.ts +8 -4
  155. package/src/executors/quickjs-protocol.ts +1 -1
  156. package/src/executors/quickjs-runtime.ts +5 -1
  157. package/src/executors/quickjs.ts +11 -8
  158. package/src/favicon.ts +2 -2
  159. package/src/index.ts +49 -17
  160. package/src/invocation.ts +527 -0
  161. package/src/meta-tools.ts +366 -906
  162. package/src/operator-ui/browser.css +413 -0
  163. package/src/operator-ui/browser.ts +1121 -0
  164. package/src/operator-ui/generated.ts +4 -0
  165. package/src/operator-ui/model.ts +127 -0
  166. package/src/registry.ts +434 -44
  167. package/src/routes/activity.ts +220 -0
  168. package/src/routes/credentials.ts +266 -0
  169. package/src/routes/mcp.ts +485 -0
  170. package/src/routes/oauth.ts +328 -0
  171. package/src/routes/shared.ts +330 -0
  172. package/src/routes/ui.ts +153 -0
  173. package/src/server.ts +66 -1703
  174. package/src/skills.ts +6 -5
  175. package/src/storage/file.ts +3 -1
  176. package/src/storage/memory.ts +3 -1
  177. package/src/toolkits.ts +2 -2
  178. package/src/types.ts +9 -2
  179. package/src/ui.ts +52 -1493
  180. package/src/version.ts +1 -1
@@ -0,0 +1,1121 @@
1
+ import {
2
+ filterUiConnectors,
3
+ type CredentialManagementCapability,
4
+ type UiData,
5
+ } from "./model.js";
6
+
7
+ type OperatorPage = "connections" | "credentials" | "activity";
8
+
9
+ interface BrowserAuth {
10
+ kind: string;
11
+ publishableKey?: string;
12
+ frontendApiUrl?: string;
13
+ signInUrl?: string;
14
+ signUpUrl?: string;
15
+ }
16
+
17
+ interface BrowserClerkSession {
18
+ id?: string;
19
+ getToken(): Promise<string | null>;
20
+ }
21
+
22
+ interface BrowserClerk {
23
+ user?: unknown;
24
+ session?: BrowserClerkSession | null;
25
+ load(options: {
26
+ signInUrl?: string;
27
+ signUpUrl?: string;
28
+ signInFallbackRedirectUrl: string;
29
+ signUpFallbackRedirectUrl: string;
30
+ afterSignOutUrl: string;
31
+ }): Promise<void>;
32
+ addListener(
33
+ listener: (resources: { session?: BrowserClerkSession | null }) => void,
34
+ ): void;
35
+ redirectToSignIn(options: {
36
+ signInFallbackRedirectUrl: string;
37
+ signUpFallbackRedirectUrl: string;
38
+ }): void;
39
+ signOut(options: { redirectUrl: string }): Promise<unknown>;
40
+ }
41
+
42
+ interface UiActivityActor {
43
+ kind?: string;
44
+ id?: string;
45
+ namespace?: string;
46
+ label?: string;
47
+ }
48
+
49
+ interface UiActivityEvent {
50
+ occurredAt: string;
51
+ actor?: UiActivityActor;
52
+ connectorId: string;
53
+ toolName: string;
54
+ address: string;
55
+ source: string;
56
+ outcome: string;
57
+ durationMs: number;
58
+ attempts: number;
59
+ errorCode?: string;
60
+ }
61
+
62
+ interface UiActivityResponse {
63
+ events?: UiActivityEvent[];
64
+ nextCursor?: string;
65
+ error?: string;
66
+ }
67
+
68
+ interface UiActionResponse {
69
+ ok?: boolean;
70
+ message?: string;
71
+ error?: string;
72
+ }
73
+
74
+ interface OperatorElement extends HTMLElement {
75
+ disabled: boolean;
76
+ value: string;
77
+ }
78
+
79
+ declare const AUTH: BrowserAuth;
80
+ declare const MCP_URL: string;
81
+ declare const INITIAL_PAGE: OperatorPage;
82
+ declare const TITLE_SUFFIX: string;
83
+ declare const PRODUCT_NAME: string;
84
+ declare const PRODUCT_OPERATOR_LABEL: string;
85
+ declare const Clerk: BrowserClerk;
86
+
87
+ declare global {
88
+ interface Window {
89
+ Clerk?: BrowserClerk;
90
+ }
91
+ }
92
+
93
+ const KEY = "connecta:token";
94
+ const $ = (id: string): OperatorElement => {
95
+ const element = document.getElementById(id);
96
+ if (!element) throw new Error(`Missing operator UI element #${id}`);
97
+ return element as OperatorElement;
98
+ };
99
+ const PAGE_META = {
100
+ connections: { path: "/", label: "Connections" },
101
+ credentials: { path: "/credentials", label: "Credentials" },
102
+ activity: { path: "/activity", label: "Activity" },
103
+ } satisfies Record<OperatorPage, { path: string; label: string }>;
104
+ let DATA: UiData | null = null;
105
+ let ACTIVITY: UiActivityEvent[] = [];
106
+ let ACTIVITY_CURSOR: string | null = null;
107
+ let ACTIVITY_LOADED = false;
108
+ let CURRENT_PAGE: OperatorPage = INITIAL_PAGE;
109
+ let SESSION_GENERATION = 0;
110
+ let ACTIVITY_GENERATION = 0;
111
+ let CLERK_SESSION_ID: string | null = null;
112
+ $("mcpUrl").textContent = MCP_URL;
113
+
114
+ function errorMessage(error: unknown, fallback: string): string {
115
+ return error instanceof Error && error.message ? error.message : fallback;
116
+ }
117
+
118
+ function closestElement<T extends Element>(
119
+ target: EventTarget | null,
120
+ selector: string,
121
+ ): T | null {
122
+ const candidate = target as { closest?: (value: string) => Element | null } | null;
123
+ return typeof candidate?.closest === "function"
124
+ ? candidate.closest(selector) as T | null
125
+ : null;
126
+ }
127
+
128
+ function esc(s: unknown): string {
129
+ return String(s == null ? "" : s).replace(/[&<>"]/g, (c) =>
130
+ ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c] ?? c);
131
+ }
132
+
133
+ // Only http/https may become a clickable href — mirrors the server-side gate
134
+ // so a hostile scheme (javascript:, data:) can never be linked. Defense in depth.
135
+ function safeHttp(u: string): string | null {
136
+ try {
137
+ const p = new URL(u).protocol;
138
+ return p === "http:" || p === "https:" ? u : null;
139
+ } catch { return null; }
140
+ }
141
+
142
+ function formatDate(value?: string): string {
143
+ if (!value) return "";
144
+ const date = new Date(value);
145
+ return Number.isNaN(date.valueOf()) ? "" : date.toLocaleString();
146
+ }
147
+
148
+ function setNotice(message: string, isError = false): void {
149
+ $("credentialNotice").textContent = message || "";
150
+ $("credentialNotice").classList.toggle("error-notice", Boolean(isError));
151
+ $("credentialNotice").setAttribute("role", isError ? "alert" : "status");
152
+ }
153
+
154
+ function setOauthNotice(message: string, isError = false): void {
155
+ $("oauthNotice").textContent = message || "";
156
+ $("oauthNotice").classList.toggle("error-notice", Boolean(isError));
157
+ $("oauthNotice").setAttribute("role", isError ? "alert" : "status");
158
+ }
159
+
160
+ async function sessionToken(): Promise<string | null | undefined> {
161
+ return AUTH.kind === "clerk"
162
+ ? await Clerk.session?.getToken()
163
+ : localStorage.getItem(KEY);
164
+ }
165
+
166
+ function clearActivityState(): void {
167
+ ACTIVITY_GENERATION += 1;
168
+ ACTIVITY = [];
169
+ ACTIVITY_CURSOR = null;
170
+ ACTIVITY_LOADED = false;
171
+ $("activityList").innerHTML = "";
172
+ $("activityList").setAttribute("aria-busy", "false");
173
+ $("activityNotice").textContent = "";
174
+ $("activityNotice").setAttribute("role", "status");
175
+ $("activitySummary").textContent = "Arguments and results are never stored.";
176
+ $("activitySearch").value = "";
177
+ $("refreshActivity").disabled = false;
178
+ $("moreActivity").disabled = false;
179
+ $("moreActivity").classList.add("hidden");
180
+ }
181
+
182
+ function clearIdentityState(): void {
183
+ SESSION_GENERATION += 1;
184
+ DATA = null;
185
+ clearActivityState();
186
+ $("list").innerHTML = "";
187
+ setOauthNotice("");
188
+ $("toolkitList").innerHTML = "";
189
+ $("filter").value = "";
190
+ $("credentialList").innerHTML = "";
191
+ $("credentialList").setAttribute("aria-busy", "false");
192
+ $("credentialNotice").textContent = "";
193
+ $("credentialNotice").setAttribute("role", "status");
194
+ $("credentialNotice").classList.remove("error-notice");
195
+ $("credentialUnavailable").textContent = "";
196
+ $("credentialUnavailable").classList.add("hidden");
197
+ $("credentialList").classList.add("hidden");
198
+ $("activityUnavailable").classList.add("hidden");
199
+ $("activityAvailable").classList.add("hidden");
200
+ $("credentialsNav").classList.add("hidden");
201
+ $("activityNav").classList.add("hidden");
202
+ $("serverInfo").textContent = PRODUCT_OPERATOR_LABEL;
203
+ }
204
+
205
+ function showGate(msg: string): void {
206
+ clearIdentityState();
207
+ $("app").classList.add("hidden");
208
+ $("appNav").classList.add("hidden");
209
+ $("gate").classList.remove("hidden");
210
+ $("err").textContent = msg || "";
211
+ if (AUTH.kind === "clerk") {
212
+ const signedIn = Boolean(window.Clerk && Clerk.user);
213
+ $("gateCopy").textContent = signedIn
214
+ ? "Signed in with Clerk, but this account cannot open deployment-wide operator pages."
215
+ : "Sign in with Clerk to open this operator page.";
216
+ $("signin").classList.toggle("hidden", signedIn);
217
+ $("gateSignout").classList.toggle("hidden", !signedIn);
218
+ } else {
219
+ $("gateCopy").textContent = "";
220
+ }
221
+ }
222
+
223
+ function pageForPath(path: string): OperatorPage {
224
+ if (path === "/credentials") return "credentials";
225
+ if (path === "/activity") return "activity";
226
+ return "connections";
227
+ }
228
+
229
+ function credentialUnavailableCopy(
230
+ capability?: CredentialManagementCapability,
231
+ ): string {
232
+ if (capability === "no_slots") {
233
+ return "No connectors declare operator-managed credential slots. Connector credentials remain configuration-as-code until a slot is declared.";
234
+ }
235
+ if (capability === "vault_not_configured") {
236
+ return "Credential storage is not configured. Set credentials.encryptionKey before managing connector credentials here.";
237
+ }
238
+ return "Credential management requires an eligible Clerk operator. Bearer-authenticated sessions can inspect connections but cannot manage stored credentials.";
239
+ }
240
+
241
+ function updateCapabilities(): void {
242
+ const credentialsAvailable =
243
+ DATA?.credentialManagement === "available";
244
+ $("credentialsNav").classList.toggle("hidden", !credentialsAvailable);
245
+ $("activityNav").classList.toggle("hidden", !DATA?.activityEnabled);
246
+ $("credentialUnavailable").classList.toggle("hidden", credentialsAvailable);
247
+ $("credentialList").classList.toggle("hidden", !credentialsAvailable);
248
+ $("credentialUnavailable").textContent = credentialsAvailable
249
+ ? ""
250
+ : credentialUnavailableCopy(DATA?.credentialManagement);
251
+ $("activityUnavailable").classList.toggle("hidden", Boolean(DATA?.activityEnabled));
252
+ $("activityAvailable").classList.toggle("hidden", !DATA?.activityEnabled);
253
+ }
254
+
255
+ function activatePage(
256
+ page: OperatorPage,
257
+ options?: { focus?: boolean },
258
+ ): void {
259
+ const next = PAGE_META[page] ? page : "connections";
260
+ CURRENT_PAGE = next;
261
+ for (const name of Object.keys(PAGE_META)) {
262
+ $(name + "View").classList.toggle("hidden", name !== next);
263
+ const link = $(name + "Nav");
264
+ if (name === next) link.setAttribute("aria-current", "page");
265
+ else link.removeAttribute("aria-current");
266
+ }
267
+ $("gateHeading").textContent = PAGE_META[next].label;
268
+ document.title = PAGE_META[next].label + " — " + TITLE_SUFFIX;
269
+ if (DATA) {
270
+ updateCapabilities();
271
+ if (next === "connections") renderConnections();
272
+ if (next === "credentials") renderCredentials();
273
+ if (next === "activity" && DATA.activityEnabled && !ACTIVITY_LOADED) {
274
+ loadActivity(true);
275
+ }
276
+ }
277
+ if (next !== "credentials") {
278
+ $("credentialList").innerHTML = "";
279
+ setNotice("");
280
+ }
281
+ // Focus what is actually on screen. While gated the page views are hidden, so
282
+ // focusing their heading is a silent no-op that drops focus to <body> and
283
+ // restarts the next Tab from the top of the document — the gate's own h1 is
284
+ // the visible heading, and activatePage has just relabelled it.
285
+ if (options?.focus) $(DATA ? next + "Heading" : "gateHeading").focus();
286
+ }
287
+
288
+ function navigateTo(page: OperatorPage, href: string): void {
289
+ history.pushState({ operatorPage: page }, "", href);
290
+ activatePage(page, { focus: true });
291
+ }
292
+
293
+ async function load(): Promise<void> {
294
+ const generation = SESSION_GENERATION;
295
+ let token;
296
+ try {
297
+ token = await sessionToken();
298
+ } catch (error) {
299
+ if (generation !== SESSION_GENERATION) return;
300
+ return showGate(
301
+ "Could not read the Clerk session: " +
302
+ errorMessage(error, "unknown error"),
303
+ );
304
+ }
305
+ if (generation !== SESSION_GENERATION) return;
306
+ if (!token) return showGate("");
307
+ let res;
308
+ try {
309
+ res = await fetch("/ui/data", { headers: { Authorization: "Bearer " + token } });
310
+ } catch (error) {
311
+ if (generation !== SESSION_GENERATION) return;
312
+ return showGate("Network error: " + errorMessage(error, "unknown error"));
313
+ }
314
+ if (generation !== SESSION_GENERATION) return;
315
+ if (res.status === 401 || res.status === 403) {
316
+ if (AUTH.kind === "clerk") {
317
+ return showGate(
318
+ res.status === 403
319
+ ? "This Clerk account is not allowed to access connecta."
320
+ : "Your Clerk session was not accepted. Sign out and try again."
321
+ );
322
+ }
323
+ localStorage.removeItem(KEY);
324
+ return showGate("Token rejected — enter a valid bearer token.");
325
+ }
326
+ if (!res.ok) return showGate("Error " + res.status);
327
+ let data: UiData;
328
+ try {
329
+ data = await res.json() as UiData;
330
+ } catch {
331
+ if (generation !== SESSION_GENERATION) return;
332
+ return showGate("Operator data could not be read.");
333
+ }
334
+ if (generation !== SESSION_GENERATION) return;
335
+ DATA = data;
336
+ $("gate").classList.add("hidden");
337
+ $("app").classList.remove("hidden");
338
+ $("appNav").classList.remove("hidden");
339
+ const si = data.serverInfo || {};
340
+ $("serverInfo").textContent =
341
+ (si.name || PRODUCT_NAME) + " v" + (data.connectaVersion || "?");
342
+ updateCapabilities();
343
+ activatePage(CURRENT_PAGE);
344
+ }
345
+
346
+ function actorLabel(actor?: UiActivityActor): string {
347
+ if (!actor || !actor.kind) return "unknown";
348
+ return actor.label
349
+ ? actor.kind + " · " + actor.label
350
+ : actor.id ? actor.kind + " · " + actor.id : actor.kind;
351
+ }
352
+
353
+ function renderActivity(): void {
354
+ const list = $("activityList");
355
+ list.innerHTML = "";
356
+ const query = $("activitySearch").value.trim().toLowerCase();
357
+ const visible = ACTIVITY.filter((event) => {
358
+ if (!query) return true;
359
+ const actor = event.actor || {};
360
+ return [
361
+ event.address,
362
+ event.connectorId,
363
+ event.toolName,
364
+ event.source,
365
+ event.outcome,
366
+ event.errorCode,
367
+ actor.kind,
368
+ actor.id,
369
+ actor.namespace,
370
+ actor.label,
371
+ ].some((value) => String(value || "").toLowerCase().includes(query));
372
+ });
373
+ const uniqueTools = new Set(ACTIVITY.map((event) => event.address)).size;
374
+ $("activitySummary").textContent = ACTIVITY.length
375
+ ? ACTIVITY.length + " loaded call" + (ACTIVITY.length === 1 ? "" : "s") +
376
+ " · " + uniqueTools + " tool" + (uniqueTools === 1 ? "" : "s") +
377
+ " · no arguments or results stored"
378
+ : "Arguments and results are never stored.";
379
+ if (visible.length === 0) {
380
+ list.innerHTML = '<div class="activity-empty">' +
381
+ (query ? "No loaded activity matches this search." :
382
+ "No connector tool calls recorded yet.") + "</div>";
383
+ }
384
+ for (const event of visible) {
385
+ const item = document.createElement("article");
386
+ const outcomeClass = [
387
+ "success",
388
+ "error",
389
+ "timeout",
390
+ "cancelled",
391
+ ].includes(event.outcome) ? event.outcome : "error";
392
+ item.className = "activity-item " + outcomeClass;
393
+ const retryCopy = event.attempts > 1
394
+ ? " · " + esc(event.attempts) + " attempts"
395
+ : "";
396
+ const errorCopy = event.errorCode ? " · " + esc(event.errorCode) : "";
397
+ const actorId = event.actor?.id
398
+ ? (event.actor.namespace
399
+ ? event.actor.namespace + " · " + event.actor.id
400
+ : event.actor.id)
401
+ : "";
402
+ const stableActorId = actorId &&
403
+ (event.actor?.label || event.actor?.namespace)
404
+ ? '<div class="activity-actor-id mono">' + esc(actorId) + "</div>"
405
+ : "";
406
+ item.innerHTML =
407
+ '<div class="activity-stamp"><span class="dot ' +
408
+ (outcomeClass === "success" ? "ok" : "") +
409
+ '" aria-hidden="true"></span><div><time class="activity-time" datetime="' +
410
+ esc(event.occurredAt) + '">' +
411
+ esc(formatDate(event.occurredAt)) +
412
+ '</time><div class="activity-actor">' + esc(actorLabel(event.actor)) +
413
+ "</div>" + stableActorId + "</div></div>" +
414
+ '<div><div class="activity-address">' + esc(event.address) +
415
+ '</div><div class="activity-detail">' + esc(event.source) + retryCopy +
416
+ errorCopy + '</div></div>' +
417
+ '<div><div class="activity-outcome">' + esc(event.outcome) +
418
+ '</div><div class="activity-detail">' + esc(event.durationMs) + ' ms</div></div>';
419
+ list.appendChild(item);
420
+ }
421
+ $("moreActivity").classList.toggle("hidden", !ACTIVITY_CURSOR);
422
+ }
423
+
424
+ async function loadActivity(reset: boolean): Promise<void> {
425
+ if (!DATA?.activityEnabled) return;
426
+ const sessionGeneration = SESSION_GENERATION;
427
+ if (reset) ACTIVITY_GENERATION += 1;
428
+ const activityGeneration = ACTIVITY_GENERATION;
429
+ const isCurrent = () =>
430
+ sessionGeneration === SESSION_GENERATION &&
431
+ activityGeneration === ACTIVITY_GENERATION;
432
+ $("activityNotice").textContent = "Loading activity…";
433
+ $("activityNotice").setAttribute("role", "status");
434
+ $("activityList").setAttribute("aria-busy", "true");
435
+ $("refreshActivity").disabled = true;
436
+ $("moreActivity").disabled = true;
437
+ try {
438
+ const token = await sessionToken();
439
+ if (!isCurrent()) return;
440
+ if (!token) return showGate("Your session has expired.");
441
+ const cursor = reset ? null : ACTIVITY_CURSOR;
442
+ const params = new URLSearchParams({ limit: "50" });
443
+ if (cursor) params.set("cursor", cursor);
444
+ const res = await fetch("/ui/activity?" + params, {
445
+ headers: { Authorization: "Bearer " + token },
446
+ });
447
+ if (!isCurrent()) return;
448
+ let payload: UiActivityResponse = {};
449
+ try {
450
+ payload = await res.json() as UiActivityResponse;
451
+ } catch {
452
+ // The status code below still owns the operator-facing error.
453
+ }
454
+ if (!isCurrent()) return;
455
+ if (res.status === 401) {
456
+ return showGate("Your session was not accepted. Sign in again.");
457
+ }
458
+ if (res.status === 403) {
459
+ clearActivityState();
460
+ $("activityNotice").setAttribute("role", "alert");
461
+ $("activityNotice").textContent =
462
+ "This identity may not read activity history.";
463
+ return;
464
+ }
465
+ if (!res.ok) {
466
+ throw new Error(
467
+ payload.error || "Activity could not be loaded (" + res.status + ")."
468
+ );
469
+ }
470
+ ACTIVITY = reset
471
+ ? (payload.events || [])
472
+ : ACTIVITY.concat(payload.events || []);
473
+ ACTIVITY_CURSOR = payload.nextCursor || null;
474
+ ACTIVITY_LOADED = true;
475
+ $("activityNotice").textContent = "";
476
+ renderActivity();
477
+ } catch (error) {
478
+ if (!isCurrent()) return;
479
+ $("activityNotice").setAttribute("role", "alert");
480
+ $("activityNotice").textContent = errorMessage(
481
+ error,
482
+ "Activity could not be loaded.",
483
+ );
484
+ } finally {
485
+ if (isCurrent()) {
486
+ $("activityList").setAttribute("aria-busy", "false");
487
+ $("refreshActivity").disabled = false;
488
+ $("moreActivity").disabled = false;
489
+ }
490
+ }
491
+ }
492
+
493
+ function toolkitMcpUrl(name: string): string {
494
+ const url = new URL(MCP_URL, window.location.href);
495
+ url.searchParams.set("toolkit", name);
496
+ return url.toString();
497
+ }
498
+
499
+ function renderToolkits(): void {
500
+ const data = DATA;
501
+ if (!data) return;
502
+ const list = $("toolkitList");
503
+ const toolkits = data.toolkits || [];
504
+ list.innerHTML = "";
505
+ if (!toolkits.length) {
506
+ list.innerHTML =
507
+ '<p class="empty">No toolkits are configured. Unscoped clients see the full connector registry.</p>';
508
+ return;
509
+ }
510
+ const connectors = new Map(
511
+ data.connectors.map((connector) => [connector.id, connector]),
512
+ );
513
+ for (const toolkit of toolkits) {
514
+ const el = document.createElement("article");
515
+ el.className = "toolkit-card";
516
+ const connectorCount = toolkit.connectors.length;
517
+ const toolCount = toolkit.toolCount || 0;
518
+ let body =
519
+ '<div class="toolkit-head"><div><div class="toolkit-name">' +
520
+ '<h3 class="mono">' + esc(toolkit.name) + "</h3>" +
521
+ '<span class="cap">configured view</span></div>';
522
+ body += '</div><div class="toolkit-state cap">' +
523
+ connectorCount + (connectorCount === 1 ? " connector" : " connectors") +
524
+ " · " + toolCount + (toolCount === 1 ? " loaded tool" : " loaded tools") +
525
+ "</div></div>";
526
+ body += '<ul class="toolkit-connectors" aria-label="Included connectors">';
527
+ for (const id of toolkit.connectors) {
528
+ const connector = connectors.get(id);
529
+ body += '<li class="toolkit-connector"><span>' +
530
+ esc(connector?.title || id) + '</span><code class="mono">' +
531
+ esc(id) + "</code></li>";
532
+ }
533
+ body += "</ul>";
534
+ body += '<div class="toolkit-rules meta">';
535
+ if (toolkit.includeTools.length) {
536
+ body += '<p>Per-connector allowlist: <span class="mono">' +
537
+ toolkit.includeTools.map(esc).join('</span>, <span class="mono">') +
538
+ "</span>. Connectors without an allowlist keep all tools.</p>";
539
+ }
540
+ if (toolkit.excludeTools.length) {
541
+ body += '<p>Hidden: <span class="mono">' +
542
+ toolkit.excludeTools.map(esc).join('</span>, <span class="mono">') +
543
+ "</span></p>";
544
+ }
545
+ if (!toolkit.includeTools.length && !toolkit.excludeTools.length) {
546
+ body += "<p>All tools on the included connectors are visible.</p>";
547
+ }
548
+ body += "</div>";
549
+ const endpoint = toolkitMcpUrl(toolkit.name);
550
+ body += '<div class="endpoint toolkit-endpoint"><div class="endpoint-row">' +
551
+ '<code class="mono">' + esc(endpoint) + "</code>" +
552
+ '<button class="linklike" type="button" data-toolkit-copy="' +
553
+ esc(toolkit.name) + '" aria-label="Copy endpoint for ' +
554
+ esc(toolkit.name) + '">Copy URL</button></div></div>';
555
+ el.innerHTML = body;
556
+ list.appendChild(el);
557
+ }
558
+ }
559
+
560
+ function renderConnections(): void {
561
+ const data = DATA;
562
+ if (!data) return;
563
+ const q = $("filter").value.trim().toLowerCase();
564
+ const list = $("list");
565
+ list.innerHTML = "";
566
+ for (const filtered of filterUiConnectors(data.connectors, q)) {
567
+ const c = filtered.connector;
568
+ const tools = filtered.tools;
569
+ const el = document.createElement("div");
570
+ el.className = "card";
571
+ const status = c.status === "ok"
572
+ ? "Connected"
573
+ : c.status === "auth_required"
574
+ ? "Authorization needed"
575
+ : "Unavailable";
576
+ let head = '<div class="connector-head"><div><div class="connector-title">' +
577
+ '<span class="dot ' + esc(c.status) + '" aria-hidden="true"></span>' +
578
+ '<h2>' + esc(c.title || c.id) + "</h2></div>";
579
+ if (c.description) {
580
+ head += '<p class="connector-description meta">' + esc(c.description) + "</p>";
581
+ }
582
+ const memberships = (data.toolkits || [])
583
+ .filter((toolkit) => toolkit.connectors.includes(c.id))
584
+ .map((toolkit) => toolkit.name);
585
+ if (memberships.length) {
586
+ head += '<div class="connector-toolkits meta"><span>Toolkits</span>' +
587
+ memberships.map((name) =>
588
+ '<span class="scope-label">' + esc(name) + "</span>"
589
+ ).join("") + "</div>";
590
+ }
591
+ head += '</div><div class="connector-state cap">' + esc(status) + " · " +
592
+ c.toolCount + (c.toolCount === 1 ? " tool" : " tools") +
593
+ '<br><span class="mono">' + esc(c.id) + "</span></div></div>";
594
+ if (c.message) {
595
+ head += '<p class="connector-message msg">' + esc(c.message) + "</p>";
596
+ }
597
+ if (c.credentialCheck) {
598
+ const check = c.credentialCheck;
599
+ const verdict = check.state === "ok"
600
+ ? "credential verified"
601
+ : check.state === "auth_required"
602
+ ? "credential needs authorization"
603
+ : "credential check failed";
604
+ head += '<p class="connector-check meta">Credential check: ' +
605
+ esc(verdict) + " · " + esc(formatDate(check.checkedAt)) +
606
+ (check.message && check.message !== c.message
607
+ ? " — " + esc(check.message)
608
+ : "") + "</p>";
609
+ }
610
+ if (c.authorizationUrl) {
611
+ const safe = safeHttp(c.authorizationUrl);
612
+ head += safe
613
+ ? '<p class="connector-auth"><a class="linklike" href="' + esc(safe) +
614
+ '" target="_blank" rel="noopener">Authorize connector →</a></p>'
615
+ : '<p class="connector-auth meta">Authorization URL: ' +
616
+ esc(c.authorizationUrl) + "</p>";
617
+ }
618
+ if (c.oauth && data.oauthManagement) {
619
+ const oauthName = c.title || c.id;
620
+ head += '<div class="credential-actions">';
621
+ head += '<button type="button" class="linklike danger" ' +
622
+ 'aria-label="Disconnect OAuth for ' + esc(oauthName) + '" ' +
623
+ 'data-oauth-action="disconnect" data-connector="' + esc(c.id) +
624
+ '">Disconnect OAuth</button>';
625
+ head += '<button type="button" class="linklike" ' +
626
+ 'aria-label="' + (c.status === "ok" ? "Reconnect OAuth for " :
627
+ "Restart authorization for ") + esc(oauthName) + '" ' +
628
+ 'data-oauth-action="reconnect" data-connector="' + esc(c.id) +
629
+ '">' + (c.status === "ok" ? "Reconnect OAuth" : "Restart authorization") +
630
+ "</button></div>";
631
+ }
632
+ if (c.credential) {
633
+ head += '<p class="connector-auth"><a class="linklike" href="/credentials" ' +
634
+ 'data-operator-page="credentials">Manage credential →</a></p>';
635
+ }
636
+ let body = "";
637
+ if (tools.length) {
638
+ body = "<details" + (q ? " open" : "") +
639
+ '><summary class="linklike">Show tools (' + tools.length + ")</summary>" +
640
+ '<div class="tool-list">';
641
+ for (const t of tools) {
642
+ body += '<div class="tool"><code>' + esc(t.address) + "</code>";
643
+ if (t.description) body += '<span class="td">' + esc(t.description) + "</span>";
644
+ body += "</div>";
645
+ }
646
+ body += "</div></details>";
647
+ }
648
+ el.innerHTML = head + body;
649
+ list.appendChild(el);
650
+ }
651
+ if (!list.children.length) {
652
+ list.innerHTML = '<p class="empty">' +
653
+ (q
654
+ ? "No connectors or tools match this filter."
655
+ : "No connectors are declared in this deployment.") +
656
+ "</p>";
657
+ }
658
+ renderToolkits();
659
+ }
660
+
661
+ async function oauthRequest(
662
+ connector: string,
663
+ method: "DELETE" | "POST",
664
+ generation: number,
665
+ ): Promise<UiActionResponse | null> {
666
+ const token = await sessionToken();
667
+ if (generation !== SESSION_GENERATION) {
668
+ throw new Error("The operator session changed.");
669
+ }
670
+ if (!token) throw new Error("Your Clerk session has expired.");
671
+ const res = await fetch("/ui/oauth/" + encodeURIComponent(connector), {
672
+ method,
673
+ headers: { Authorization: "Bearer " + token },
674
+ });
675
+ if (res.status === 204) return null;
676
+ let payload: UiActionResponse = {};
677
+ try {
678
+ payload = await res.json() as UiActionResponse;
679
+ } catch {
680
+ // The status code below still owns the operator-facing error.
681
+ }
682
+ if (!res.ok) throw new Error(payload.error || "Request failed (" + res.status + ").");
683
+ return payload;
684
+ }
685
+
686
+ $("list").onclick = async (event) => {
687
+ const button = closestElement<HTMLButtonElement>(
688
+ event.target,
689
+ "[data-oauth-action]",
690
+ );
691
+ if (!button) return;
692
+ const connector = button.dataset.connector;
693
+ const action = button.dataset.oauthAction;
694
+ if (!connector || (action !== "disconnect" && action !== "reconnect")) return;
695
+ const generation = SESSION_GENERATION;
696
+ const question = action === "disconnect"
697
+ ? "Disconnect OAuth for " + connector +
698
+ "? Stored credentials and any pending authorization will be removed."
699
+ : "Restart OAuth for " + connector +
700
+ "? Stored credentials and any pending authorization will be replaced.";
701
+ if (!window.confirm(question)) return;
702
+
703
+ setOauthNotice("");
704
+ const buttons = [...document.querySelectorAll<HTMLButtonElement>(
705
+ '[data-connector="' + CSS.escape(connector) + '"]'
706
+ )];
707
+ buttons.forEach((item) => { item.disabled = true; });
708
+ try {
709
+ const result = await oauthRequest(
710
+ connector,
711
+ action === "disconnect" ? "DELETE" : "POST",
712
+ generation,
713
+ );
714
+ if (generation !== SESSION_GENERATION) return;
715
+ await load();
716
+ if (generation !== SESSION_GENERATION) return;
717
+ setOauthNotice(
718
+ action === "disconnect"
719
+ ? "OAuth disconnected. Restart authorization when you are ready to reconnect."
720
+ : result?.message ||
721
+ "Authorization restarted. Open the authorization link to reconnect.",
722
+ );
723
+ $("oauthNotice").focus();
724
+ } catch (error) {
725
+ if (generation !== SESSION_GENERATION) return;
726
+ // A reset can publish its durable epoch before best-effort physical cleanup
727
+ // reports failure. Refresh so stale tools/health/actions never survive that
728
+ // partial success, while preserving the original error for the operator.
729
+ try {
730
+ await load();
731
+ } catch {
732
+ // The mutation error is the actionable one; load() already owns its gate.
733
+ }
734
+ if (generation !== SESSION_GENERATION) return;
735
+ setOauthNotice(errorMessage(error, "OAuth action failed."), true);
736
+ $("oauthNotice").focus();
737
+ } finally {
738
+ if (generation === SESSION_GENERATION) {
739
+ buttons.forEach((item) => { item.disabled = false; });
740
+ }
741
+ }
742
+ };
743
+
744
+ function renderCredentials(): void {
745
+ const data = DATA;
746
+ if (!data) return;
747
+ const list = $("credentialList");
748
+ list.innerHTML = "";
749
+ if (data.credentialManagement !== "available") return;
750
+ for (const c of data.connectors) {
751
+ const cred = c.credential;
752
+ if (!cred) continue;
753
+ const configured = Boolean(cred.configured);
754
+ const removable = configured || Boolean(cred.removable);
755
+ const state = configured
756
+ ? cred.fields?.length
757
+ ? "configured"
758
+ : "configured · ••••" + esc(cred.lastFour || "")
759
+ : "not configured";
760
+ const updated = configured && cred.updatedAt
761
+ ? " · updated " + esc(formatDate(cred.updatedAt))
762
+ : "";
763
+ const el = document.createElement("section");
764
+ el.className = "credential-card";
765
+ el.id = "credential-" + c.id;
766
+ el.setAttribute("aria-labelledby", "credential-title-" + c.id);
767
+ let body = '<div class="credential-head"><div class="connector-title">' +
768
+ '<span class="dot ' + (configured ? "ok" : "auth_required") +
769
+ '" aria-hidden="true"></span><h2 id="credential-title-' + esc(c.id) + '">' +
770
+ esc(c.title || c.id) + '</h2></div><span class="credential-state">' +
771
+ state + updated + "</span></div>";
772
+ body += '<p class="mono">' + esc(c.id) + " · " + esc(cred.label) + "</p>";
773
+ if (cred.description) {
774
+ body += '<p class="credential-copy meta">' + esc(cred.description) + "</p>";
775
+ }
776
+ if (cred.fields?.length) {
777
+ body += '<div class="credential-field-summary">';
778
+ for (const field of cred.fields) {
779
+ const fieldState = field.configured
780
+ ? "configured · ••••" + esc(field.lastFour || "") +
781
+ (field.updatedAt ? " · updated " + esc(formatDate(field.updatedAt)) : "")
782
+ : "not configured";
783
+ body += '<div><span>' + esc(field.label) +
784
+ '</span><span class="meta">' + fieldState + "</span></div>";
785
+ }
786
+ body += "</div>";
787
+ }
788
+ if (c.credentialCheck) {
789
+ const check = c.credentialCheck;
790
+ const verdict = check.state === "ok"
791
+ ? "healthy"
792
+ : check.state === "auth_required"
793
+ ? "needs authorization"
794
+ : "check failed";
795
+ body += '<p class="connector-check meta">Liveness: ' + esc(verdict) +
796
+ " · " + esc(formatDate(check.checkedAt)) +
797
+ (check.message ? " — " + esc(check.message) : "") + "</p>";
798
+ }
799
+ if (cred.error) body += '<div class="msg">' + esc(cred.error) + "</div>";
800
+ // Leftover stored fields are not an error — the credential still works, so
801
+ // this stays muted copy rather than the msg block an actual failure earns.
802
+ if (cred.notice) {
803
+ body += '<p class="credential-copy meta">' + esc(cred.notice) + "</p>";
804
+ }
805
+ body += '<div class="credential-actions">';
806
+ body += '<button class="linklike" type="button" data-credential-action="edit" data-connector="' +
807
+ esc(c.id) + '">' + (removable ? "Replace" : "Add credential") + "</button>";
808
+ if (configured && cred.testable) {
809
+ body += '<button class="linklike" type="button" data-credential-action="test" data-connector="' +
810
+ esc(c.id) + '">Test</button>';
811
+ }
812
+ if (removable) {
813
+ body += '<button type="button" class="linklike danger" data-credential-action="remove" data-connector="' +
814
+ esc(c.id) + '">Remove</button>';
815
+ }
816
+ body += "</div>";
817
+ body += '<div class="credential-form hidden" data-credential-form="' +
818
+ esc(c.id) + '">';
819
+ if (cred.fields && cred.fields.length) {
820
+ body += '<div class="credential-fields">';
821
+ for (const [index, field] of cred.fields.entries()) {
822
+ const inputId = "credential-input-" + c.id + "-" + index;
823
+ body += '<div class="credential-field"><label for="' + esc(inputId) + '">' +
824
+ esc(field.label) + '</label><input id="' + esc(inputId) + '" type="' +
825
+ esc(field.inputType || "password") + '" data-credential-field="' +
826
+ esc(field.name) + '" placeholder="' + esc(field.placeholder || field.label) +
827
+ '" autocomplete="' +
828
+ (field.inputType === "password" ? "new-password" : "off") +
829
+ '" autocapitalize="none" spellcheck="false"></div>';
830
+ }
831
+ body += "</div>";
832
+ } else {
833
+ const inputId = "credential-input-" + c.id;
834
+ body += '<label class="visually-hidden" for="' + esc(inputId) + '">' +
835
+ esc(cred.label) + '</label><input id="' + esc(inputId) +
836
+ '" type="password" data-credential-input="' +
837
+ esc(c.id) + '" aria-label="' + esc(cred.label) + '" placeholder="' +
838
+ esc(cred.placeholder || "Paste credential") +
839
+ '" autocomplete="new-password" autocapitalize="none" spellcheck="false">';
840
+ }
841
+ body += '<button class="linklike" type="button" data-credential-action="save" data-connector="' +
842
+ esc(c.id) + '">Save</button><button class="linklike" type="button" data-credential-action="cancel" data-connector="' +
843
+ esc(c.id) + '">Cancel</button></div>';
844
+ el.innerHTML = body;
845
+ list.appendChild(el);
846
+ }
847
+ }
848
+
849
+ async function credentialRequest(
850
+ connector: string,
851
+ method: "DELETE" | "POST" | "PUT",
852
+ action: "" | "test",
853
+ body: { value: string } | { values: Record<string, string> } | null,
854
+ generation: number,
855
+ ): Promise<UiActionResponse | null> {
856
+ const token = await sessionToken();
857
+ if (generation !== SESSION_GENERATION) {
858
+ throw new Error("The operator session changed.");
859
+ }
860
+ if (!token) throw new Error("Your Clerk session has expired.");
861
+ const suffix = action ? "/" + action : "";
862
+ const res = await fetch(
863
+ "/ui/credentials/" + encodeURIComponent(connector) + suffix,
864
+ {
865
+ method,
866
+ headers: {
867
+ Authorization: "Bearer " + token,
868
+ ...(body ? { "Content-Type": "application/json" } : {}),
869
+ },
870
+ ...(body ? { body: JSON.stringify(body) } : {}),
871
+ },
872
+ );
873
+ if (res.status === 204) return null;
874
+ let payload: UiActionResponse = {};
875
+ try {
876
+ payload = await res.json() as UiActionResponse;
877
+ } catch {
878
+ // The status code below still owns the operator-facing error.
879
+ }
880
+ if (!res.ok) throw new Error(payload.error || "Request failed (" + res.status + ").");
881
+ return payload;
882
+ }
883
+
884
+ function credentialForm(connector: string): HTMLElement {
885
+ const form = document.querySelector<HTMLElement>(
886
+ '[data-credential-form="' + CSS.escape(connector) + '"]',
887
+ );
888
+ if (!form) throw new Error("Credential form is unavailable.");
889
+ return form;
890
+ }
891
+
892
+ $("credentialList").onclick = async (event) => {
893
+ const button = closestElement<HTMLButtonElement>(
894
+ event.target,
895
+ "[data-credential-action]",
896
+ );
897
+ if (!button) return;
898
+ const connector = button.dataset.connector;
899
+ const action = button.dataset.credentialAction;
900
+ if (!connector || !action) return;
901
+ const form = credentialForm(connector);
902
+ const generation = SESSION_GENERATION;
903
+
904
+ if (action === "edit") {
905
+ form.classList.remove("hidden");
906
+ form.querySelector("input")?.focus();
907
+ return;
908
+ }
909
+ if (action === "cancel") {
910
+ form.querySelectorAll("input").forEach((input) => { input.value = ""; });
911
+ form.classList.add("hidden");
912
+ document.querySelector<HTMLButtonElement>(
913
+ '[data-credential-action="edit"][data-connector="' +
914
+ CSS.escape(connector) + '"]'
915
+ )?.focus();
916
+ return;
917
+ }
918
+ if (action === "remove" && !window.confirm(
919
+ "Remove this credential? The connector will stop authenticating until a replacement is added."
920
+ )) return;
921
+
922
+ setNotice("");
923
+ $("credentialList").setAttribute("aria-busy", "true");
924
+ const buttons = [...document.querySelectorAll<HTMLButtonElement>(
925
+ '[data-connector="' + CSS.escape(connector) + '"]'
926
+ )];
927
+ buttons.forEach((item) => { item.disabled = true; });
928
+ try {
929
+ if (action === "save") {
930
+ const fieldInputs = [
931
+ ...form.querySelectorAll<HTMLInputElement>("[data-credential-field]"),
932
+ ];
933
+ if (fieldInputs.length) {
934
+ const values: Record<string, string> = {};
935
+ for (const input of fieldInputs) {
936
+ const value = input.value.trim();
937
+ if (!value) throw new Error("Complete every credential field before saving.");
938
+ const field = input.dataset.credentialField;
939
+ if (!field) throw new Error("Credential field is unnamed.");
940
+ values[field] = value;
941
+ }
942
+ await credentialRequest(connector, "PUT", "", { values }, generation);
943
+ } else {
944
+ const input = form.querySelector<HTMLInputElement>(
945
+ "[data-credential-input]",
946
+ );
947
+ if (!input) throw new Error("Credential input is unavailable.");
948
+ const value = input.value.trim();
949
+ if (!value) throw new Error("Paste a credential before saving.");
950
+ await credentialRequest(connector, "PUT", "", { value }, generation);
951
+ }
952
+ if (generation !== SESSION_GENERATION) return;
953
+ form.querySelectorAll<HTMLInputElement>("input")
954
+ .forEach((input) => { input.value = ""; });
955
+ setNotice("Credential saved.");
956
+ await load();
957
+ if (generation !== SESSION_GENERATION) return;
958
+ $("credentialNotice").focus();
959
+ } else if (action === "remove") {
960
+ await credentialRequest(connector, "DELETE", "", null, generation);
961
+ if (generation !== SESSION_GENERATION) return;
962
+ setNotice("Credential removed.");
963
+ await load();
964
+ if (generation !== SESSION_GENERATION) return;
965
+ $("credentialNotice").focus();
966
+ } else if (action === "test") {
967
+ const result = await credentialRequest(
968
+ connector,
969
+ "POST",
970
+ "test",
971
+ null,
972
+ generation,
973
+ );
974
+ if (generation !== SESSION_GENERATION) return;
975
+ setNotice(
976
+ result?.message ||
977
+ (result?.ok ? "Credential is valid." : "Credential test failed."),
978
+ !result?.ok,
979
+ );
980
+ }
981
+ } catch (error) {
982
+ if (generation !== SESSION_GENERATION) return;
983
+ setNotice(errorMessage(error, "Credential action failed."), true);
984
+ } finally {
985
+ if (generation === SESSION_GENERATION) {
986
+ $("credentialList").setAttribute("aria-busy", "false");
987
+ buttons.forEach((item) => { item.disabled = false; });
988
+ }
989
+ }
990
+ };
991
+
992
+ $("save").onclick = async () => {
993
+ const v = $("token").value.trim();
994
+ if (!v) return;
995
+ clearIdentityState();
996
+ localStorage.setItem(KEY, v);
997
+ $("token").value = "";
998
+ await load();
999
+ if (DATA) $(CURRENT_PAGE + "Heading").focus();
1000
+ };
1001
+ $("change").onclick = () => {
1002
+ localStorage.removeItem(KEY);
1003
+ showGate("");
1004
+ $("token").focus();
1005
+ };
1006
+ $("copyMcpUrl").onclick = async () => {
1007
+ const button = $("copyMcpUrl");
1008
+ try {
1009
+ await navigator.clipboard.writeText(MCP_URL);
1010
+ button.textContent = "Copied";
1011
+ } catch {
1012
+ button.textContent = "Copy failed";
1013
+ }
1014
+ window.setTimeout(() => { button.textContent = "Copy URL"; }, 1600);
1015
+ };
1016
+ $("toolkitList").onclick = async (event) => {
1017
+ const button = closestElement<HTMLButtonElement>(
1018
+ event.target,
1019
+ "[data-toolkit-copy]",
1020
+ );
1021
+ if (!button) return;
1022
+ const toolkit = button.dataset.toolkitCopy;
1023
+ if (!toolkit) return;
1024
+ try {
1025
+ await navigator.clipboard.writeText(
1026
+ toolkitMcpUrl(toolkit),
1027
+ );
1028
+ button.textContent = "Copied";
1029
+ } catch {
1030
+ button.textContent = "Copy failed";
1031
+ }
1032
+ window.setTimeout(() => { button.textContent = "Copy URL"; }, 1600);
1033
+ };
1034
+ $("signin").onclick = () => Clerk.redirectToSignIn({
1035
+ signInFallbackRedirectUrl: window.location.href,
1036
+ signUpFallbackRedirectUrl: window.location.href,
1037
+ });
1038
+ function signOut(): Promise<unknown> {
1039
+ clearIdentityState();
1040
+ return Clerk.signOut({ redirectUrl: window.location.href });
1041
+ }
1042
+ $("gateSignout").onclick = signOut;
1043
+ $("signout").onclick = signOut;
1044
+ $("filter").oninput = () => { if (DATA) renderConnections(); };
1045
+ $("refreshActivity").onclick = () => loadActivity(true);
1046
+ $("moreActivity").onclick = () => loadActivity(false);
1047
+ $("activitySearch").oninput = () => renderActivity();
1048
+ document.addEventListener("click", (event) => {
1049
+ const link = closestElement<HTMLAnchorElement>(
1050
+ event.target,
1051
+ "a[data-operator-page]",
1052
+ );
1053
+ if (
1054
+ !link ||
1055
+ event.defaultPrevented ||
1056
+ event.button !== 0 ||
1057
+ event.metaKey ||
1058
+ event.ctrlKey ||
1059
+ event.shiftKey ||
1060
+ event.altKey
1061
+ ) return;
1062
+ const target = new URL(link.href, window.location.href);
1063
+ if (target.origin !== window.location.origin) return;
1064
+ const page = link.dataset.operatorPage;
1065
+ if (
1066
+ page !== "connections" &&
1067
+ page !== "credentials" &&
1068
+ page !== "activity"
1069
+ ) return;
1070
+ event.preventDefault();
1071
+ navigateTo(page, target.pathname + target.search + target.hash);
1072
+ });
1073
+ window.addEventListener("popstate", () => {
1074
+ activatePage(pageForPath(window.location.pathname), { focus: true });
1075
+ });
1076
+
1077
+ async function init(): Promise<void> {
1078
+ if (AUTH.kind === "clerk") {
1079
+ $("clerkGate").classList.remove("hidden");
1080
+ $("signout").classList.remove("hidden");
1081
+ try {
1082
+ if (!window.Clerk) {
1083
+ return showGate("Clerk could not load. Check your network and try again.");
1084
+ }
1085
+ await Clerk.load({
1086
+ ...(AUTH.signInUrl ? { signInUrl: AUTH.signInUrl } : {}),
1087
+ ...(AUTH.signUpUrl ? { signUpUrl: AUTH.signUpUrl } : {}),
1088
+ signInFallbackRedirectUrl: window.location.href,
1089
+ signUpFallbackRedirectUrl: window.location.href,
1090
+ afterSignOutUrl: window.location.href,
1091
+ });
1092
+ CLERK_SESSION_ID = Clerk.session?.id ?? null;
1093
+ Clerk.addListener((resources) => {
1094
+ const nextSessionId = resources.session?.id ?? null;
1095
+ if (nextSessionId === CLERK_SESSION_ID) return;
1096
+ CLERK_SESSION_ID = nextSessionId;
1097
+ // Clerk has already updated its public session before notifying
1098
+ // listeners. Clear synchronously so stale identity-scoped data cannot
1099
+ // be repainted while the replacement identity is being fetched.
1100
+ showGate("");
1101
+ void load();
1102
+ });
1103
+ } catch (error) {
1104
+ return showGate(
1105
+ "Clerk could not initialize: " +
1106
+ errorMessage(error, "unknown error"),
1107
+ );
1108
+ }
1109
+ } else {
1110
+ $("tokenGate").classList.remove("hidden");
1111
+ $("change").classList.remove("hidden");
1112
+ }
1113
+ activatePage(pageForPath(window.location.pathname));
1114
+ await load();
1115
+ }
1116
+
1117
+ if (AUTH.kind === "clerk") {
1118
+ window.addEventListener("load", init);
1119
+ } else {
1120
+ init();
1121
+ }