@zackbart/connecta 0.10.5 → 0.11.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 (93) hide show
  1. package/AGENTS.md +8 -6
  2. package/CHANGELOG.md +150 -0
  3. package/README.md +5 -4
  4. package/bin/connecta.mjs +0 -7
  5. package/dist/activity.d.ts +11 -1
  6. package/dist/activity.d.ts.map +1 -1
  7. package/dist/activity.js +44 -3
  8. package/dist/activity.js.map +1 -1
  9. package/dist/catalog-service.d.ts +24 -0
  10. package/dist/catalog-service.d.ts.map +1 -1
  11. package/dist/catalog-service.js +68 -9
  12. package/dist/catalog-service.js.map +1 -1
  13. package/dist/connectors/api.d.ts +2 -2
  14. package/dist/connectors/remote-mcp.d.ts +1 -1
  15. package/dist/errors.d.ts +49 -4
  16. package/dist/errors.d.ts.map +1 -1
  17. package/dist/errors.js +68 -1
  18. package/dist/errors.js.map +1 -1
  19. package/dist/execute.d.ts +73 -3
  20. package/dist/execute.d.ts.map +1 -1
  21. package/dist/execute.js +161 -29
  22. package/dist/execute.js.map +1 -1
  23. package/dist/index.d.ts +28 -30
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +29 -37
  26. package/dist/index.js.map +1 -1
  27. package/dist/invocation.d.ts +9 -2
  28. package/dist/invocation.d.ts.map +1 -1
  29. package/dist/invocation.js +61 -31
  30. package/dist/invocation.js.map +1 -1
  31. package/dist/meta-tools.d.ts +24 -59
  32. package/dist/meta-tools.d.ts.map +1 -1
  33. package/dist/meta-tools.js +107 -359
  34. package/dist/meta-tools.js.map +1 -1
  35. package/dist/operator-ui/generated.d.ts +1 -1
  36. package/dist/operator-ui/generated.d.ts.map +1 -1
  37. package/dist/operator-ui/generated.js +1 -1
  38. package/dist/operator-ui/generated.js.map +1 -1
  39. package/dist/registry.d.ts +12 -10
  40. package/dist/registry.d.ts.map +1 -1
  41. package/dist/registry.js +8 -17
  42. package/dist/registry.js.map +1 -1
  43. package/dist/routes/mcp.d.ts.map +1 -1
  44. package/dist/routes/mcp.js +19 -21
  45. package/dist/routes/mcp.js.map +1 -1
  46. package/dist/routes/shared.d.ts +9 -11
  47. package/dist/routes/shared.d.ts.map +1 -1
  48. package/dist/routes/shared.js.map +1 -1
  49. package/dist/server.js +5 -4
  50. package/dist/server.js.map +1 -1
  51. package/dist/skills.d.ts +8 -18
  52. package/dist/skills.d.ts.map +1 -1
  53. package/dist/skills.js +13 -60
  54. package/dist/skills.js.map +1 -1
  55. package/dist/types.d.ts +6 -20
  56. package/dist/types.d.ts.map +1 -1
  57. package/dist/version.d.ts +1 -1
  58. package/dist/version.js +1 -1
  59. package/documentation/code-first-exploration.md +16 -16
  60. package/documentation/code-mode.md +137 -63
  61. package/documentation/connectors.md +1 -1
  62. package/documentation/meta-tools.md +96 -33
  63. package/documentation/rich-output-design.md +212 -0
  64. package/ethos.md +17 -19
  65. package/examples/node/README.md +1 -2
  66. package/examples/node/src/index.ts +1 -3
  67. package/examples/worker/README.md +19 -16
  68. package/examples/worker/src/d1-activity-row.ts +40 -0
  69. package/examples/worker/src/d1-activity.ts +3 -2
  70. package/examples/worker/src/index.ts +6 -14
  71. package/examples/worker/wrangler.jsonc +3 -6
  72. package/package.json +1 -1
  73. package/src/activity.ts +69 -3
  74. package/src/catalog-service.ts +113 -20
  75. package/src/connectors/api.ts +2 -2
  76. package/src/connectors/remote-mcp.ts +1 -1
  77. package/src/errors.ts +104 -3
  78. package/src/execute.ts +237 -37
  79. package/src/index.ts +60 -67
  80. package/src/invocation.ts +61 -19
  81. package/src/meta-tools.ts +136 -482
  82. package/src/operator-ui/browser.ts +10 -2
  83. package/src/operator-ui/generated.ts +1 -1
  84. package/src/registry.ts +7 -35
  85. package/src/routes/mcp.ts +19 -21
  86. package/src/routes/shared.ts +8 -11
  87. package/src/server.ts +7 -7
  88. package/src/skills.ts +11 -74
  89. package/src/types.ts +6 -21
  90. package/src/version.ts +1 -1
  91. package/templates/node/README.md +2 -1
  92. package/templates/node/package.json +1 -1
  93. package/templates/node/src/index.ts +1 -1
@@ -58,6 +58,7 @@ interface UiActivityEvent {
58
58
  durationMs: number;
59
59
  attempts: number;
60
60
  errorCode?: string;
61
+ friction?: string;
61
62
  }
62
63
 
63
64
  interface UiActivityResponse {
@@ -425,6 +426,7 @@ function renderActivity(): void {
425
426
  event.source,
426
427
  event.outcome,
427
428
  event.errorCode,
429
+ event.friction,
428
430
  actor.kind,
429
431
  actor.id,
430
432
  actor.namespace,
@@ -454,7 +456,13 @@ function renderActivity(): void {
454
456
  const retryCopy = event.attempts > 1
455
457
  ? " · " + esc(event.attempts) + " attempts"
456
458
  : "";
457
- const errorCopy = event.errorCode ? " · " + esc(event.errorCode) : "";
459
+ const frictionCopy = event.friction ? " · " + esc(event.friction) : "";
460
+ // The friction class and the code coincide for auth_required and
461
+ // result_too_large. Printing "· auth_required · auth_required" says nothing
462
+ // twice, so the coarse class stands in for both when they agree.
463
+ const errorCopy = event.errorCode && event.errorCode !== event.friction
464
+ ? " · " + esc(event.errorCode)
465
+ : "";
458
466
  const actorId = event.actor?.id
459
467
  ? (event.actor.namespace
460
468
  ? event.actor.namespace + " · " + event.actor.id
@@ -474,7 +482,7 @@ function renderActivity(): void {
474
482
  "</div>" + stableActorId + "</div></div>" +
475
483
  '<div><div class="activity-address">' + esc(event.address) +
476
484
  '</div><div class="activity-detail">' + esc(event.source) + retryCopy +
477
- errorCopy + '</div></div>' +
485
+ frictionCopy + errorCopy + '</div></div>' +
478
486
  '<div><div class="activity-outcome">' + esc(event.outcome) +
479
487
  '</div><div class="activity-detail">' + esc(event.durationMs) + ' ms</div></div>';
480
488
  list.appendChild(item);
@@ -1,4 +1,4 @@
1
1
  // Generated by scripts/build-operator-ui.mjs. Do not edit.
2
2
  // Source: src/operator-ui/browser.ts and src/operator-ui/browser.css.
3
3
  export const OPERATOR_UI_CSS = "/* src/operator-ui/browser.css */\n:root {\n color-scheme: light;\n --ink: #000;\n --paper: #fff;\n --rule: #ccc;\n --muted: #666;\n --trace: #f5f5f5;\n --shell: 70rem;\n --pad: 1rem;\n --gap: 1.5rem;\n --sans:\n \"Helvetica Neue\",\n Helvetica,\n Arial,\n sans-serif;\n --mono:\n ui-monospace,\n \"SF Mono\",\n Menlo,\n Monaco,\n \"Cascadia Code\",\n Consolas,\n monospace;\n}\n* {\n border-radius: 0;\n box-sizing: border-box;\n}\nhtml {\n background: var(--paper);\n color: var(--ink);\n font-family: var(--sans);\n font-size: 16px;\n line-height: 1.5;\n -webkit-font-smoothing: antialiased;\n text-rendering: optimizeLegibility;\n}\nbody {\n margin: 0;\n min-height: 100vh;\n}\n::selection {\n background: var(--ink);\n color: var(--paper);\n}\n:is(h1, h2, h3, p, ul, ol) {\n margin: 0;\n padding: 0;\n}\n:is(h1, h2, h3) {\n font-size: inherit;\n font-weight: 400;\n}\n:is(ul, ol) {\n list-style: none;\n}\na {\n color: inherit;\n}\nbutton,\ninput {\n font: inherit;\n}\nbutton {\n background: none;\n border: 0;\n color: inherit;\n cursor: pointer;\n margin: 0;\n padding: 0;\n text-align: left;\n}\nbutton:disabled {\n cursor: wait;\n opacity: .5;\n}\ninput {\n background: var(--paper);\n border: 1px solid var(--rule);\n color: var(--ink);\n min-height: 2rem;\n padding: .2rem .5rem;\n}\ninput:focus-visible {\n outline-offset: -1px;\n}\n:is(a, button, input, summary):focus-visible {\n outline: 1px solid var(--ink);\n}\n:is(a, button, summary):focus-visible {\n outline-offset: 2px;\n}\n.skip-link {\n background: var(--paper);\n left: var(--pad);\n padding: .5rem;\n position: fixed;\n top: -4rem;\n z-index: 10;\n}\n.skip-link:focus {\n top: var(--pad);\n}\n.shell {\n margin: 0 auto;\n max-width: var(--shell);\n padding-left: var(--pad);\n padding-right: var(--pad);\n}\n.pgrid {\n column-gap: var(--gap);\n display: grid;\n grid-template-columns: repeat(3, minmax(0, 1fr));\n row-gap: 1rem;\n}\n.pcap {\n grid-column: 1;\n}\n.pbody {\n grid-column: 2 / -1;\n min-width: 0;\n}\n.cap,\n.meta {\n color: var(--muted);\n font-size: .9em;\n}\n.mono {\n font-family: var(--mono);\n font-size: .78rem;\n}\n.hidden {\n display: none !important;\n}\n.visually-hidden {\n clip: rect(0 0 0 0);\n clip-path: inset(50%);\n height: 1px;\n overflow: hidden;\n position: absolute;\n white-space: nowrap;\n width: 1px;\n}\n.masthead {\n align-items: start;\n padding-bottom: var(--pad);\n padding-top: var(--pad);\n}\n.brand {\n font-weight: 500;\n grid-column: 1;\n text-decoration: none;\n}\n.mast-nav {\n display: flex;\n gap: var(--gap);\n grid-column: 2 / -1;\n justify-content: space-between;\n min-width: 0;\n}\n.mast-actions {\n display: flex;\n gap: var(--gap);\n justify-content: flex-end;\n min-width: 0;\n}\n.page-nav,\n.session-actions {\n display: flex;\n flex-wrap: wrap;\n gap: .5rem var(--gap);\n}\n.mast-actions :is(a, button) {\n align-items: center;\n display: inline-flex;\n min-height: 2rem;\n}\n.navlink,\n.linklike {\n text-decoration: underline;\n text-decoration-thickness: 1.5px;\n text-underline-offset: .22em;\n}\n.navlink {\n text-decoration-color: transparent;\n}\n.navlink:hover,\n.navlink:focus-visible,\n.navlink[aria-current=page] {\n text-decoration-color: currentColor;\n}\n.linklike {\n text-decoration-color: currentColor;\n}\n.linklike:hover,\n.linklike:focus-visible {\n text-decoration-color: transparent;\n}\n.page {\n padding-bottom: 5rem;\n}\n.lead {\n margin-top: 6rem;\n}\n.section,\n.section + .section {\n margin-top: 3rem;\n}\n.lead-copy,\n.body-copy {\n max-width: 34em;\n}\n.lead-copy > * + *,\n.body-copy > * + * {\n margin-top: 1.5rem;\n}\n.row,\n.actions {\n align-items: center;\n display: flex;\n flex-wrap: wrap;\n gap: var(--gap);\n}\n.row input {\n flex: 1;\n min-width: 12rem;\n}\n.gate-actions {\n margin-top: 1.5rem;\n}\n#err {\n margin-top: 1.5rem;\n text-decoration: underline;\n}\n.endpoint {\n border-bottom: 1px solid var(--rule);\n border-top: 1px solid var(--rule);\n}\n.endpoint-row {\n align-items: baseline;\n display: flex;\n gap: var(--gap);\n min-width: 0;\n padding: .75rem 0;\n}\n.endpoint-row code {\n flex: 1;\n min-width: 0;\n overflow-x: auto;\n white-space: nowrap;\n}\n.endpoint-row button {\n flex: none;\n}\n.connector-tools {\n border-bottom: 1px solid var(--rule);\n}\n.toolbar {\n margin-bottom: 1.5rem;\n}\n.toolbar input {\n flex-basis: 18rem;\n}\n#notice {\n margin-bottom: .75rem;\n}\n#notice:empty {\n display: none;\n}\n#notice:not(:empty) {\n text-decoration: underline;\n}\n#oauthNotice {\n margin-bottom: .75rem;\n}\n#oauthNotice:empty {\n display: none;\n}\n.error-notice,\n.msg {\n text-decoration: underline;\n}\n.card,\n.credential-card,\n.activity-item {\n padding-left: 1.25rem;\n position: relative;\n}\n.card::before,\n.credential-card::before,\n.activity-item::before {\n background: var(--rule);\n bottom: 0;\n content: \"\";\n left: .25rem;\n position: absolute;\n top: 0;\n width: 1px;\n}\n.card {\n border-top: 1px solid var(--rule);\n padding-bottom: .75rem;\n padding-top: .75rem;\n}\n.connector-head {\n display: grid;\n gap: var(--gap);\n grid-template-columns: minmax(0, 2fr) minmax(10rem, 1fr);\n}\n.connector-title {\n align-items: baseline;\n display: flex;\n gap: .5rem;\n}\n.connector-title .dot,\n.activity-stamp .dot {\n margin-left: -1.25rem;\n}\n.activity-stamp {\n align-items: baseline;\n display: flex;\n gap: .75rem;\n}\n.card h2 {\n overflow-wrap: anywhere;\n}\n.connector-state {\n text-align: right;\n}\n.dot {\n background: var(--paper);\n border: 1px solid var(--ink);\n display: inline-block;\n flex: none;\n height: .5rem;\n width: .5rem;\n z-index: 1;\n}\n.dot.ok {\n background: var(--ink);\n}\n.dot.auth_required {\n background:\n linear-gradient(\n 90deg,\n var(--ink) 50%,\n var(--paper) 50%);\n}\n.connector-description {\n margin-top: .25rem;\n max-width: 40rem;\n}\n.connector-message,\n.connector-auth {\n margin-top: .75rem;\n}\n.credential-ledger {\n border-bottom: 1px solid var(--rule);\n}\n.credential-card {\n border-top: 1px solid var(--rule);\n padding-bottom: .75rem;\n padding-top: .75rem;\n}\n.credential-head {\n align-items: baseline;\n display: flex;\n flex-wrap: wrap;\n gap: .25rem var(--gap);\n justify-content: space-between;\n}\n.credential-copy {\n margin-top: .25rem;\n max-width: 40rem;\n}\n.credential-field-summary {\n border-top: 1px solid var(--rule);\n margin-top: .75rem;\n}\n.credential-field-summary > div {\n border-bottom: 1px solid var(--rule);\n display: flex;\n flex-wrap: wrap;\n gap: .25rem var(--gap);\n justify-content: space-between;\n padding: .5rem 0;\n}\n.credential-actions {\n display: flex;\n flex-wrap: wrap;\n gap: var(--gap);\n margin-top: .75rem;\n}\n.credential-actions button,\n.credential-form button,\n.activity-controls button,\n.activity-more {\n align-items: center;\n display: inline-flex;\n min-height: 2.75rem;\n}\n.credential-form {\n align-items: center;\n display: flex;\n flex-wrap: wrap;\n gap: .75rem var(--gap);\n margin-top: .75rem;\n}\n.credential-form > input {\n flex: 1 1 18rem;\n}\n.credential-fields {\n display: grid;\n flex: 1 1 100%;\n gap: .75rem;\n}\n.credential-field {\n align-items: center;\n display: grid;\n gap: var(--gap);\n grid-template-columns: minmax(9rem, 12rem) 1fr;\n}\n.credential-field input {\n min-width: 0;\n width: 100%;\n}\n.danger {\n text-decoration-style: double;\n}\n.token-create {\n border-bottom: 1px solid var(--rule);\n border-top: 1px solid var(--rule);\n padding: .75rem 0;\n}\n.token-create > label {\n display: block;\n margin-bottom: .5rem;\n}\n.token-create input {\n flex: 1 1 18rem;\n}\n.token-create button,\n.token-card button,\n.token-reveal button {\n align-items: center;\n display: inline-flex;\n min-height: 2.75rem;\n}\n.token-reveal {\n background: var(--ink);\n color: var(--paper);\n margin-top: 1.5rem;\n padding: 1rem 1.25rem;\n}\n.token-reveal .meta,\n.token-reveal .cap {\n color: #bbb;\n}\n.token-reveal-head,\n.token-card-head {\n align-items: baseline;\n display: flex;\n flex-wrap: wrap;\n gap: .25rem var(--gap);\n justify-content: space-between;\n}\n.token-secret {\n border-bottom: 1px solid #555;\n border-top: 1px solid #555;\n margin-top: .75rem;\n}\n.token-secret code {\n color: var(--paper);\n user-select: all;\n}\n.token-ledger {\n border-bottom: 1px solid var(--rule);\n margin-top: 1.5rem;\n}\n.token-card {\n border-top: 1px solid var(--rule);\n padding: .75rem 0 .75rem 1.25rem;\n position: relative;\n}\n.token-card::before {\n background: var(--ink);\n bottom: 0;\n content: \"\";\n left: .25rem;\n position: absolute;\n top: 0;\n width: 1px;\n}\n.token-card.revoked {\n color: var(--muted);\n}\n.token-card.revoked::before {\n background: var(--rule);\n}\ndetails {\n margin-top: .75rem;\n}\nsummary {\n cursor: pointer;\n list-style: none;\n width: max-content;\n}\nsummary::-webkit-details-marker {\n display: none;\n}\n.tool-list {\n border-bottom: 1px solid var(--rule);\n margin-top: .5rem;\n}\n.tool {\n border-top: 1px solid var(--rule);\n display: grid;\n gap: .25rem var(--gap);\n grid-template-columns: minmax(12rem, 1fr) minmax(0, 2fr);\n padding: .5rem 0;\n}\n.tool code {\n font-family: var(--mono);\n font-size: .78rem;\n overflow-wrap: anywhere;\n}\n.tool .td {\n color: var(--muted);\n font-size: .9em;\n}\n.empty {\n border-top: 1px solid var(--rule);\n padding: .75rem 0;\n}\n.activity-copy {\n margin-bottom: 1.5rem;\n}\n.activity-controls {\n margin-bottom: 1.5rem;\n}\n.activity-controls input {\n flex: 1 1 18rem;\n}\n#activityNotice {\n margin-bottom: .75rem;\n}\n.activity-ledger {\n border-bottom: 1px solid var(--rule);\n}\n.activity-item {\n border-top: 1px solid var(--rule);\n display: grid;\n gap: .25rem var(--gap);\n grid-template-columns: minmax(9rem, .85fr) minmax(12rem, 1.4fr) minmax(8rem, .9fr);\n padding-bottom: .75rem;\n padding-top: .75rem;\n}\n.activity-time,\n.activity-actor,\n.activity-detail {\n color: var(--muted);\n font-size: .82rem;\n}\n.activity-actor-id {\n color: var(--muted);\n margin-top: .1rem;\n}\n.activity-address {\n font-family: var(--mono);\n font-size: .78rem;\n overflow-wrap: anywhere;\n}\n.activity-outcome {\n font-size: .9em;\n}\n.activity-item.error .activity-outcome,\n.activity-item.timeout .activity-outcome,\n.activity-item.cancelled .activity-outcome {\n text-decoration: underline;\n}\n.activity-empty {\n border-top: 1px solid var(--rule);\n padding: .75rem 0;\n}\n.activity-more {\n margin-top: .75rem;\n}\n.unavailable {\n background: var(--trace);\n border-bottom: 1px solid var(--rule);\n border-top: 1px solid var(--rule);\n padding: .75rem;\n}\n@media (prefers-reduced-motion: reduce) {\n html:focus-within {\n scroll-behavior: auto;\n }\n}\n@media (max-width: 36.99rem) {\n .pgrid {\n grid-template-columns: repeat(2, minmax(0, 1fr));\n }\n .pcap,\n .pbody {\n grid-column: 1 / -1;\n }\n .masthead .brand {\n grid-column: 1;\n }\n .mast-nav {\n grid-column: 1 / -1;\n grid-row: 2;\n justify-content: flex-start;\n }\n .product {\n display: none;\n }\n .mast-actions {\n align-items: flex-start;\n flex-direction: column;\n font-size: .875rem;\n gap: .25rem;\n }\n .lead {\n margin-top: 4rem;\n }\n .section,\n .section + .section {\n margin-top: 2.5rem;\n }\n .connector-head,\n .tool,\n .activity-item {\n grid-template-columns: 1fr;\n }\n .connector-state {\n text-align: left;\n }\n .credential-field {\n align-items: start;\n grid-template-columns: 1fr;\n gap: .25rem;\n }\n input {\n min-height: 2.75rem;\n }\n}\n";
4
- export const OPERATOR_UI_SCRIPT = "\"use strict\";\n(() => {\n // src/operator-ui/model.ts\n function filterUiConnectors(connectors, query) {\n const q = query.trim().toLowerCase();\n const filtered = [];\n for (const connector of connectors) {\n const connectorText = [\n connector.id,\n connector.title,\n connector.description,\n connector.status\n ].join(\" \").toLowerCase();\n const connectorMatches = Boolean(q && connectorText.includes(q));\n const tools = connector.tools.filter(\n (tool) => !q || connectorMatches || `${tool.name} ${tool.description ?? \"\"}`.toLowerCase().includes(q)\n );\n if (q && tools.length === 0 && !connectorMatches) continue;\n filtered.push({ connector, tools });\n }\n return filtered;\n }\n\n // src/operator-ui/browser.ts\n var KEY = \"connecta:token\";\n var $ = (id) => {\n const element = document.getElementById(id);\n if (!element) throw new Error(`Missing operator UI element #${id}`);\n return element;\n };\n var PAGE_META = {\n connections: { path: \"/\", label: \"Connections\" },\n credentials: { path: \"/credentials\", label: \"Credentials\" },\n tokens: { path: \"/tokens\", label: \"Access tokens\" },\n activity: { path: \"/activity\", label: \"Activity\" }\n };\n var DATA = null;\n var ACTIVITY = [];\n var ACTIVITY_CURSOR = null;\n var ACTIVITY_LOADED = false;\n var ACCESS_TOKENS = [];\n var ACCESS_TOKENS_LOADED = false;\n var CURRENT_PAGE = INITIAL_PAGE;\n var SESSION_GENERATION = 0;\n var ACTIVITY_GENERATION = 0;\n var CLERK_SESSION_ID = null;\n $(\"mcpUrl\").textContent = MCP_URL;\n function errorMessage(error, fallback) {\n return error instanceof Error && error.message ? error.message : fallback;\n }\n function closestElement(target, selector) {\n const candidate = target;\n return typeof candidate?.closest === \"function\" ? candidate.closest(selector) : null;\n }\n function esc(s) {\n return String(s == null ? \"\" : s).replace(/[&<>\"]/g, (c) => ({ \"&\": \"&amp;\", \"<\": \"&lt;\", \">\": \"&gt;\", '\"': \"&quot;\" })[c] ?? c);\n }\n function safeHttp(u) {\n try {\n const p = new URL(u).protocol;\n return p === \"http:\" || p === \"https:\" ? u : null;\n } catch {\n return null;\n }\n }\n function formatDate(value) {\n if (!value) return \"\";\n const date = new Date(value);\n return Number.isNaN(date.valueOf()) ? \"\" : date.toLocaleString();\n }\n function setNotice(message, isError = false) {\n $(\"credentialNotice\").textContent = message || \"\";\n $(\"credentialNotice\").classList.toggle(\"error-notice\", Boolean(isError));\n $(\"credentialNotice\").setAttribute(\"role\", isError ? \"alert\" : \"status\");\n }\n function setOauthNotice(message, isError = false) {\n $(\"oauthNotice\").textContent = message || \"\";\n $(\"oauthNotice\").classList.toggle(\"error-notice\", Boolean(isError));\n $(\"oauthNotice\").setAttribute(\"role\", isError ? \"alert\" : \"status\");\n }\n async function sessionToken() {\n return AUTH.kind === \"clerk\" ? await Clerk.session?.getToken() : localStorage.getItem(KEY);\n }\n function clearActivityState() {\n ACTIVITY_GENERATION += 1;\n ACTIVITY = [];\n ACTIVITY_CURSOR = null;\n ACTIVITY_LOADED = false;\n $(\"activityList\").innerHTML = \"\";\n $(\"activityList\").setAttribute(\"aria-busy\", \"false\");\n $(\"activityNotice\").textContent = \"\";\n $(\"activityNotice\").setAttribute(\"role\", \"status\");\n $(\"activitySummary\").textContent = \"Arguments and results are never stored.\";\n $(\"activitySearch\").value = \"\";\n $(\"refreshActivity\").disabled = false;\n $(\"moreActivity\").disabled = false;\n $(\"moreActivity\").classList.add(\"hidden\");\n }\n function clearIdentityState() {\n SESSION_GENERATION += 1;\n DATA = null;\n clearActivityState();\n $(\"list\").innerHTML = \"\";\n setOauthNotice(\"\");\n $(\"filter\").value = \"\";\n $(\"credentialList\").innerHTML = \"\";\n $(\"credentialList\").setAttribute(\"aria-busy\", \"false\");\n $(\"credentialNotice\").textContent = \"\";\n $(\"credentialNotice\").setAttribute(\"role\", \"status\");\n $(\"credentialNotice\").classList.remove(\"error-notice\");\n $(\"credentialUnavailable\").textContent = \"\";\n $(\"credentialUnavailable\").classList.add(\"hidden\");\n $(\"credentialList\").classList.add(\"hidden\");\n ACCESS_TOKENS = [];\n ACCESS_TOKENS_LOADED = false;\n $(\"tokenList\").innerHTML = \"\";\n $(\"tokenList\").setAttribute(\"aria-busy\", \"false\");\n $(\"tokenNotice\").textContent = \"\";\n clearCreatedAccessToken();\n $(\"tokenName\").value = \"\";\n $(\"tokenUnavailable\").textContent = \"\";\n $(\"tokenUnavailable\").classList.add(\"hidden\");\n $(\"tokenAvailable\").classList.add(\"hidden\");\n $(\"activityUnavailable\").classList.add(\"hidden\");\n $(\"activityAvailable\").classList.add(\"hidden\");\n $(\"credentialsNav\").classList.add(\"hidden\");\n $(\"tokensNav\").classList.add(\"hidden\");\n $(\"activityNav\").classList.add(\"hidden\");\n $(\"serverInfo\").textContent = PRODUCT_OPERATOR_LABEL;\n }\n function showGate(msg) {\n clearIdentityState();\n $(\"app\").classList.add(\"hidden\");\n $(\"appNav\").classList.add(\"hidden\");\n $(\"gate\").classList.remove(\"hidden\");\n $(\"err\").textContent = msg || \"\";\n if (AUTH.kind === \"clerk\") {\n const signedIn = Boolean(window.Clerk && Clerk.user);\n $(\"gateCopy\").textContent = signedIn ? \"Signed in with Clerk, but this account cannot open deployment-wide operator pages.\" : \"Sign in with Clerk to open this operator page.\";\n $(\"signin\").classList.toggle(\"hidden\", signedIn);\n $(\"gateSignout\").classList.toggle(\"hidden\", !signedIn);\n } else {\n $(\"gateCopy\").textContent = \"\";\n }\n }\n function pageForPath(path) {\n if (path === \"/credentials\") return \"credentials\";\n if (path === \"/tokens\") return \"tokens\";\n if (path === \"/activity\") return \"activity\";\n return \"connections\";\n }\n function credentialUnavailableCopy(capability) {\n if (capability === \"no_slots\") {\n return \"No connectors declare operator-managed credential slots. Connector credentials remain configuration-as-code until a slot is declared.\";\n }\n if (capability === \"vault_not_configured\") {\n return \"Credential storage is not configured. Set credentials.encryptionKey before managing connector credentials here.\";\n }\n return \"Credential management requires an eligible Clerk operator. Bearer-authenticated sessions can inspect connections but cannot manage stored credentials.\";\n }\n function accessTokenUnavailableCopy(capability) {\n if (capability === \"not_configured\") {\n return \"Access tokens are not configured for this deployment. Add accessTokens to the deployment configuration to enable them.\";\n }\n return \"Access token management requires an eligible Clerk operator. A Bearer token can connect to MCP, but it cannot create or revoke other tokens.\";\n }\n function setTokenNotice(message, error = false) {\n $(\"tokenNotice\").textContent = message;\n $(\"tokenNotice\").setAttribute(\"role\", error ? \"alert\" : \"status\");\n }\n function clearCreatedAccessToken() {\n $(\"createdToken\").textContent = \"\";\n $(\"tokenReveal\").classList.add(\"hidden\");\n $(\"tokenCreateForm\").classList.remove(\"hidden\");\n }\n function updateCapabilities() {\n const credentialsAvailable = DATA?.credentialManagement === \"available\";\n $(\"credentialsNav\").classList.toggle(\"hidden\", !credentialsAvailable);\n const tokensAvailable = DATA?.accessTokenManagement === \"available\";\n $(\"tokensNav\").classList.toggle(\"hidden\", !tokensAvailable);\n $(\"activityNav\").classList.toggle(\"hidden\", !DATA?.activityEnabled);\n $(\"credentialUnavailable\").classList.toggle(\"hidden\", credentialsAvailable);\n $(\"credentialList\").classList.toggle(\"hidden\", !credentialsAvailable);\n $(\"credentialUnavailable\").textContent = credentialsAvailable ? \"\" : credentialUnavailableCopy(DATA?.credentialManagement);\n $(\"tokenUnavailable\").classList.toggle(\"hidden\", Boolean(tokensAvailable));\n $(\"tokenAvailable\").classList.toggle(\"hidden\", !tokensAvailable);\n $(\"tokenUnavailable\").textContent = tokensAvailable ? \"\" : accessTokenUnavailableCopy(DATA?.accessTokenManagement);\n $(\"activityUnavailable\").classList.toggle(\"hidden\", Boolean(DATA?.activityEnabled));\n $(\"activityAvailable\").classList.toggle(\"hidden\", !DATA?.activityEnabled);\n }\n function activatePage(page, options) {\n const next = PAGE_META[page] ? page : \"connections\";\n CURRENT_PAGE = next;\n for (const name of Object.keys(PAGE_META)) {\n $(name + \"View\").classList.toggle(\"hidden\", name !== next);\n const link = $(name + \"Nav\");\n if (name === next) link.setAttribute(\"aria-current\", \"page\");\n else link.removeAttribute(\"aria-current\");\n }\n $(\"gateHeading\").textContent = PAGE_META[next].label;\n document.title = PAGE_META[next].label + \" — \" + TITLE_SUFFIX;\n if (DATA) {\n updateCapabilities();\n if (next === \"connections\") renderConnections();\n if (next === \"credentials\") renderCredentials();\n if (next === \"tokens\" && DATA.accessTokenManagement === \"available\" && !ACCESS_TOKENS_LOADED) {\n void loadAccessTokens();\n }\n if (next === \"activity\" && DATA.activityEnabled && !ACTIVITY_LOADED) {\n loadActivity(true);\n }\n }\n if (next !== \"credentials\") {\n $(\"credentialList\").innerHTML = \"\";\n setNotice(\"\");\n }\n if (next !== \"tokens\") clearCreatedAccessToken();\n if (options?.focus) $(DATA ? next + \"Heading\" : \"gateHeading\").focus();\n }\n function navigateTo(page, href) {\n history.pushState({ operatorPage: page }, \"\", href);\n activatePage(page, { focus: true });\n }\n async function load() {\n const generation = SESSION_GENERATION;\n let token;\n try {\n token = await sessionToken();\n } catch (error) {\n if (generation !== SESSION_GENERATION) return;\n return showGate(\n \"Could not read the Clerk session: \" + errorMessage(error, \"unknown error\")\n );\n }\n if (generation !== SESSION_GENERATION) return;\n if (!token) return showGate(\"\");\n let res;\n try {\n res = await fetch(\"/ui/data\", { headers: { Authorization: \"Bearer \" + token } });\n } catch (error) {\n if (generation !== SESSION_GENERATION) return;\n return showGate(\"Network error: \" + errorMessage(error, \"unknown error\"));\n }\n if (generation !== SESSION_GENERATION) return;\n if (res.status === 401 || res.status === 403) {\n if (AUTH.kind === \"clerk\") {\n return showGate(\n res.status === 403 ? \"This Clerk account is not allowed to access connecta.\" : \"Your Clerk session was not accepted. Sign out and try again.\"\n );\n }\n localStorage.removeItem(KEY);\n return showGate(\"Token rejected — enter a valid bearer token.\");\n }\n if (!res.ok) return showGate(\"Error \" + res.status);\n let data;\n try {\n data = await res.json();\n } catch {\n if (generation !== SESSION_GENERATION) return;\n return showGate(\"Operator data could not be read.\");\n }\n if (generation !== SESSION_GENERATION) return;\n DATA = data;\n $(\"gate\").classList.add(\"hidden\");\n $(\"app\").classList.remove(\"hidden\");\n $(\"appNav\").classList.remove(\"hidden\");\n const si = data.serverInfo || {};\n $(\"serverInfo\").textContent = (si.name || PRODUCT_NAME) + \" v\" + (data.connectaVersion || \"?\");\n updateCapabilities();\n activatePage(CURRENT_PAGE);\n }\n function actorLabel(actor) {\n if (!actor || !actor.kind) return \"unknown\";\n return actor.label ? actor.kind + \" · \" + actor.label : actor.id ? actor.kind + \" · \" + actor.id : actor.kind;\n }\n function renderActivity() {\n const list = $(\"activityList\");\n list.innerHTML = \"\";\n const query = $(\"activitySearch\").value.trim().toLowerCase();\n const visible = ACTIVITY.filter((event) => {\n if (!query) return true;\n const actor = event.actor || {};\n return [\n event.address,\n event.connectorId,\n event.toolName,\n event.source,\n event.outcome,\n event.errorCode,\n actor.kind,\n actor.id,\n actor.namespace,\n actor.label\n ].some((value) => String(value || \"\").toLowerCase().includes(query));\n });\n const uniqueTools = new Set(ACTIVITY.map((event) => event.address)).size;\n $(\"activitySummary\").textContent = ACTIVITY.length ? ACTIVITY.length + \" loaded call\" + (ACTIVITY.length === 1 ? \"\" : \"s\") + \" · \" + uniqueTools + \" tool\" + (uniqueTools === 1 ? \"\" : \"s\") + \" · no arguments or results stored\" : \"Arguments and results are never stored.\";\n if (visible.length === 0) {\n list.innerHTML = '<div class=\"activity-empty\">' + (query ? \"No loaded activity matches this search.\" : \"No connector tool calls recorded yet.\") + \"</div>\";\n }\n for (const event of visible) {\n const item = document.createElement(\"article\");\n const outcomeClass = [\n \"success\",\n \"error\",\n \"timeout\",\n \"cancelled\"\n ].includes(event.outcome) ? event.outcome : \"error\";\n item.className = \"activity-item \" + outcomeClass;\n const retryCopy = event.attempts > 1 ? \" · \" + esc(event.attempts) + \" attempts\" : \"\";\n const errorCopy = event.errorCode ? \" · \" + esc(event.errorCode) : \"\";\n const actorId = event.actor?.id ? event.actor.namespace ? event.actor.namespace + \" · \" + event.actor.id : event.actor.id : \"\";\n const stableActorId = actorId && (event.actor?.label || event.actor?.namespace) ? '<div class=\"activity-actor-id mono\">' + esc(actorId) + \"</div>\" : \"\";\n item.innerHTML = '<div class=\"activity-stamp\"><span class=\"dot ' + (outcomeClass === \"success\" ? \"ok\" : \"\") + '\" aria-hidden=\"true\"></span><div><time class=\"activity-time\" datetime=\"' + esc(event.occurredAt) + '\">' + esc(formatDate(event.occurredAt)) + '</time><div class=\"activity-actor\">' + esc(actorLabel(event.actor)) + \"</div>\" + stableActorId + '</div></div><div><div class=\"activity-address\">' + esc(event.address) + '</div><div class=\"activity-detail\">' + esc(event.source) + retryCopy + errorCopy + '</div></div><div><div class=\"activity-outcome\">' + esc(event.outcome) + '</div><div class=\"activity-detail\">' + esc(event.durationMs) + \" ms</div></div>\";\n list.appendChild(item);\n }\n $(\"moreActivity\").classList.toggle(\"hidden\", !ACTIVITY_CURSOR);\n }\n async function loadActivity(reset) {\n if (!DATA?.activityEnabled) return;\n const sessionGeneration = SESSION_GENERATION;\n if (reset) ACTIVITY_GENERATION += 1;\n const activityGeneration = ACTIVITY_GENERATION;\n const isCurrent = () => sessionGeneration === SESSION_GENERATION && activityGeneration === ACTIVITY_GENERATION;\n $(\"activityNotice\").textContent = \"Loading activity…\";\n $(\"activityNotice\").setAttribute(\"role\", \"status\");\n $(\"activityList\").setAttribute(\"aria-busy\", \"true\");\n $(\"refreshActivity\").disabled = true;\n $(\"moreActivity\").disabled = true;\n try {\n const token = await sessionToken();\n if (!isCurrent()) return;\n if (!token) return showGate(\"Your session has expired.\");\n const cursor = reset ? null : ACTIVITY_CURSOR;\n const params = new URLSearchParams({ limit: \"50\" });\n if (cursor) params.set(\"cursor\", cursor);\n const res = await fetch(\"/ui/activity?\" + params, {\n headers: { Authorization: \"Bearer \" + token }\n });\n if (!isCurrent()) return;\n let payload = {};\n try {\n payload = await res.json();\n } catch {\n }\n if (!isCurrent()) return;\n if (res.status === 401) {\n return showGate(\"Your session was not accepted. Sign in again.\");\n }\n if (res.status === 403) {\n clearActivityState();\n $(\"activityNotice\").setAttribute(\"role\", \"alert\");\n $(\"activityNotice\").textContent = \"This identity may not read activity history.\";\n return;\n }\n if (!res.ok) {\n throw new Error(\n payload.error || \"Activity could not be loaded (\" + res.status + \").\"\n );\n }\n ACTIVITY = reset ? payload.events || [] : ACTIVITY.concat(payload.events || []);\n ACTIVITY_CURSOR = payload.nextCursor || null;\n ACTIVITY_LOADED = true;\n $(\"activityNotice\").textContent = \"\";\n renderActivity();\n } catch (error) {\n if (!isCurrent()) return;\n $(\"activityNotice\").setAttribute(\"role\", \"alert\");\n $(\"activityNotice\").textContent = errorMessage(\n error,\n \"Activity could not be loaded.\"\n );\n } finally {\n if (isCurrent()) {\n $(\"activityList\").setAttribute(\"aria-busy\", \"false\");\n $(\"refreshActivity\").disabled = false;\n $(\"moreActivity\").disabled = false;\n }\n }\n }\n function renderConnections() {\n const data = DATA;\n if (!data) return;\n const q = $(\"filter\").value.trim().toLowerCase();\n const list = $(\"list\");\n list.innerHTML = \"\";\n for (const filtered of filterUiConnectors(data.connectors, q)) {\n const c = filtered.connector;\n const tools = filtered.tools;\n const el = document.createElement(\"div\");\n el.className = \"card\";\n const status = c.status === \"ok\" ? \"Connected\" : c.status === \"auth_required\" ? \"Authorization needed\" : \"Unavailable\";\n let head = '<div class=\"connector-head\"><div><div class=\"connector-title\"><span class=\"dot ' + esc(c.status) + '\" aria-hidden=\"true\"></span><h2>' + esc(c.title || c.id) + \"</h2></div>\";\n if (c.description) {\n head += '<p class=\"connector-description meta\">' + esc(c.description) + \"</p>\";\n }\n head += '</div><div class=\"connector-state cap\">' + esc(status) + \" · \" + c.toolCount + (c.toolCount === 1 ? \" tool\" : \" tools\") + '<br><span class=\"mono\">' + esc(c.id) + \"</span></div></div>\";\n if (c.message) {\n head += '<p class=\"connector-message msg\">' + esc(c.message) + \"</p>\";\n }\n if (c.authorizationUrl) {\n const safe = safeHttp(c.authorizationUrl);\n head += safe ? '<p class=\"connector-auth\"><a class=\"linklike\" href=\"' + esc(safe) + '\" target=\"_blank\" rel=\"noopener\">Authorize connector →</a></p>' : '<p class=\"connector-auth meta\">Authorization URL: ' + esc(c.authorizationUrl) + \"</p>\";\n }\n if (c.oauth && data.oauthManagement) {\n const oauthName = c.title || c.id;\n head += '<div class=\"credential-actions\">';\n head += '<button type=\"button\" class=\"linklike danger\" aria-label=\"Disconnect OAuth for ' + esc(oauthName) + '\" data-oauth-action=\"disconnect\" data-connector=\"' + esc(c.id) + '\">Disconnect OAuth</button>';\n head += '<button type=\"button\" class=\"linklike\" aria-label=\"' + (c.status === \"ok\" ? \"Reconnect OAuth for \" : \"Restart authorization for \") + esc(oauthName) + '\" data-oauth-action=\"reconnect\" data-connector=\"' + esc(c.id) + '\">' + (c.status === \"ok\" ? \"Reconnect OAuth\" : \"Restart authorization\") + \"</button></div>\";\n }\n if (c.credential) {\n head += '<p class=\"connector-auth\"><a class=\"linklike\" href=\"/credentials\" data-operator-page=\"credentials\">Manage credential →</a></p>';\n }\n let body = \"\";\n if (tools.length) {\n body = \"<details\" + (q ? \" open\" : \"\") + '><summary class=\"linklike\">Show tools (' + tools.length + ')</summary><div class=\"tool-list\">';\n for (const t of tools) {\n body += '<div class=\"tool\"><code>' + esc(t.address) + \"</code>\";\n if (t.description) body += '<span class=\"td\">' + esc(t.description) + \"</span>\";\n body += \"</div>\";\n }\n body += \"</div></details>\";\n }\n el.innerHTML = head + body;\n list.appendChild(el);\n }\n if (!list.children.length) {\n list.innerHTML = '<p class=\"empty\">' + (q ? \"No connectors or tools match this filter.\" : \"No connectors are declared in this deployment.\") + \"</p>\";\n }\n }\n async function operatorRequest(path, method, generation, body) {\n const token = await sessionToken();\n if (generation !== SESSION_GENERATION) {\n throw new Error(\"The operator session changed.\");\n }\n if (!token) throw new Error(\"Your Clerk session has expired.\");\n const res = await fetch(path, {\n method,\n headers: {\n Authorization: \"Bearer \" + token,\n ...body ? { \"Content-Type\": \"application/json\" } : {}\n },\n ...body ? { body: JSON.stringify(body) } : {}\n });\n if (res.status === 204) return null;\n let payload = {};\n try {\n payload = await res.json();\n } catch {\n }\n if (!res.ok) throw new Error(payload.error || \"Request failed (\" + res.status + \").\");\n return payload;\n }\n function renderAccessTokens() {\n const list = $(\"tokenList\");\n list.innerHTML = \"\";\n if (!ACCESS_TOKENS.length) {\n list.innerHTML = '<p class=\"empty\">No access tokens yet. Name the first MCP client above.</p>';\n return;\n }\n for (const token of ACCESS_TOKENS) {\n const revoked = Boolean(token.revokedAt);\n const item = document.createElement(\"section\");\n item.className = \"token-card\" + (revoked ? \" revoked\" : \"\");\n item.setAttribute(\"aria-labelledby\", \"access-token-\" + token.id);\n item.innerHTML = '<div class=\"token-card-head\"><div><h2 id=\"access-token-' + esc(token.id) + '\">' + esc(token.name) + '</h2><p class=\"mono\">' + esc(token.tokenPrefix) + '…</p></div><div class=\"cap\">' + (revoked ? \"Revoked \" + esc(formatDate(token.revokedAt)) : \"Created \" + esc(formatDate(token.createdAt))) + '</div></div><div class=\"credential-actions\"><button class=\"linklike\" type=\"button\" data-token-action=\"rename\" data-token-id=\"' + esc(token.id) + '\">Rename</button>' + (revoked ? \"\" : '<button class=\"linklike danger\" type=\"button\" data-token-action=\"revoke\" data-token-id=\"' + esc(token.id) + '\">Revoke</button>') + '</div><form class=\"credential-form hidden\" data-token-form=\"' + esc(token.id) + '\"><label class=\"visually-hidden\" for=\"token-name-' + esc(token.id) + '\">Token name</label><input id=\"token-name-' + esc(token.id) + '\" type=\"text\" maxlength=\"80\" value=\"' + esc(token.name) + '\" autocomplete=\"off\"><button class=\"linklike\" type=\"submit\" data-token-action=\"save-name\" data-token-id=\"' + esc(token.id) + '\">Save name</button><button class=\"linklike\" type=\"button\" data-token-action=\"cancel-name\" data-token-id=\"' + esc(token.id) + '\">Cancel</button></form>';\n list.appendChild(item);\n }\n }\n async function loadAccessTokens() {\n const generation = SESSION_GENERATION;\n $(\"tokenList\").setAttribute(\"aria-busy\", \"true\");\n setTokenNotice(\"Loading access tokens…\");\n try {\n const payload = await operatorRequest(\n \"/ui/access-tokens\",\n \"GET\",\n generation\n );\n if (generation !== SESSION_GENERATION) return;\n ACCESS_TOKENS = payload?.accessTokens || [];\n ACCESS_TOKENS_LOADED = true;\n setTokenNotice(\"\");\n renderAccessTokens();\n } catch (error) {\n if (generation !== SESSION_GENERATION) return;\n setTokenNotice(errorMessage(\n error,\n \"Access tokens could not be loaded.\"\n ), true);\n } finally {\n if (generation === SESSION_GENERATION) {\n $(\"tokenList\").setAttribute(\"aria-busy\", \"false\");\n }\n }\n }\n $(\"tokenCreateForm\").onsubmit = async (event) => {\n event.preventDefault();\n const name = $(\"tokenName\").value.trim();\n if (!name) {\n setTokenNotice(\"Name the MCP client before creating a token.\", true);\n return;\n }\n const generation = SESSION_GENERATION;\n $(\"createToken\").disabled = true;\n setTokenNotice(\"\");\n try {\n const payload = await operatorRequest(\n \"/ui/access-tokens\",\n \"POST\",\n generation,\n { name }\n );\n if (generation !== SESSION_GENERATION) return;\n if (!payload?.token || !payload.accessToken) {\n throw new Error(\"The created token was not returned.\");\n }\n ACCESS_TOKENS = [\n payload.accessToken,\n ...ACCESS_TOKENS.filter((token) => token.id !== payload.accessToken.id)\n ];\n ACCESS_TOKENS_LOADED = true;\n $(\"tokenName\").value = \"\";\n $(\"createdToken\").textContent = payload.token;\n $(\"tokenCreateForm\").classList.add(\"hidden\");\n $(\"tokenReveal\").classList.remove(\"hidden\");\n setTokenNotice(\"Access token created.\");\n renderAccessTokens();\n $(\"tokenRevealHeading\").focus();\n } catch (error) {\n if (generation !== SESSION_GENERATION) return;\n setTokenNotice(errorMessage(\n error,\n \"Access token could not be created.\"\n ), true);\n $(\"tokenNotice\").focus();\n } finally {\n if (generation === SESSION_GENERATION) $(\"createToken\").disabled = false;\n }\n };\n $(\"copyCreatedToken\").onclick = async () => {\n const button = $(\"copyCreatedToken\");\n const token = $(\"createdToken\").textContent || \"\";\n try {\n await navigator.clipboard.writeText(token);\n button.textContent = \"Copied\";\n } catch {\n button.textContent = \"Copy failed\";\n }\n window.setTimeout(() => {\n button.textContent = \"Copy token\";\n }, 1600);\n };\n $(\"dismissCreatedToken\").onclick = () => {\n clearCreatedAccessToken();\n $(\"tokenName\").focus();\n };\n $(\"tokenList\").onclick = async (event) => {\n const button = closestElement(\n event.target,\n \"[data-token-action]\"\n );\n if (!button) return;\n const id = button.dataset.tokenId;\n const action = button.dataset.tokenAction;\n if (!id || !action) return;\n const form = document.querySelector(\n '[data-token-form=\"' + CSS.escape(id) + '\"]'\n );\n if (!form) return;\n if (action === \"rename\") {\n form.classList.remove(\"hidden\");\n form.querySelector(\"input\")?.focus();\n return;\n }\n if (action === \"cancel-name\") {\n const current = ACCESS_TOKENS.find((token) => token.id === id);\n const input = form.querySelector(\"input\");\n if (input && current) input.value = current.name;\n form.classList.add(\"hidden\");\n return;\n }\n if (action !== \"revoke\") return;\n const named = ACCESS_TOKENS.find((token) => token.id === id);\n if (!window.confirm(\n \"Revoke \" + (named?.name || \"this access token\") + \"? Its MCP client will immediately lose access.\"\n )) return;\n const generation = SESSION_GENERATION;\n try {\n const payload = await operatorRequest(\n \"/ui/access-tokens/\" + encodeURIComponent(id),\n \"DELETE\",\n generation\n );\n if (generation !== SESSION_GENERATION) return;\n if (payload?.accessToken) {\n ACCESS_TOKENS = ACCESS_TOKENS.map((token) => token.id === id ? payload.accessToken : token);\n }\n setTokenNotice(\"Access token revoked.\");\n renderAccessTokens();\n $(\"tokenNotice\").focus();\n } catch (error) {\n if (generation !== SESSION_GENERATION) return;\n setTokenNotice(errorMessage(\n error,\n \"Access token could not be revoked.\"\n ), true);\n }\n };\n $(\"tokenList\").onsubmit = async (event) => {\n event.preventDefault();\n const form = closestElement(event.target, \"[data-token-form]\");\n if (!form) return;\n const id = form.dataset.tokenForm;\n const name = form.querySelector(\"input\")?.value.trim();\n if (!id || !name) return;\n const generation = SESSION_GENERATION;\n try {\n const payload = await operatorRequest(\n \"/ui/access-tokens/\" + encodeURIComponent(id),\n \"PUT\",\n generation,\n { name }\n );\n if (generation !== SESSION_GENERATION) return;\n if (payload?.accessToken) {\n ACCESS_TOKENS = ACCESS_TOKENS.map((token) => token.id === id ? payload.accessToken : token);\n }\n setTokenNotice(\"Access token renamed.\");\n renderAccessTokens();\n $(\"tokenNotice\").focus();\n } catch (error) {\n if (generation !== SESSION_GENERATION) return;\n setTokenNotice(errorMessage(\n error,\n \"Access token could not be renamed.\"\n ), true);\n }\n };\n $(\"list\").onclick = async (event) => {\n const button = closestElement(\n event.target,\n \"[data-oauth-action]\"\n );\n if (!button) return;\n const connector = button.dataset.connector;\n const action = button.dataset.oauthAction;\n if (!connector || action !== \"disconnect\" && action !== \"reconnect\") return;\n const generation = SESSION_GENERATION;\n const question = action === \"disconnect\" ? \"Disconnect OAuth for \" + connector + \"? Stored credentials and any pending authorization will be removed.\" : \"Restart OAuth for \" + connector + \"? Stored credentials and any pending authorization will be replaced.\";\n if (!window.confirm(question)) return;\n setOauthNotice(\"\");\n const buttons = [...document.querySelectorAll(\n '[data-connector=\"' + CSS.escape(connector) + '\"]'\n )];\n buttons.forEach((item) => {\n item.disabled = true;\n });\n try {\n const result = await operatorRequest(\n \"/ui/oauth/\" + encodeURIComponent(connector),\n action === \"disconnect\" ? \"DELETE\" : \"POST\",\n generation\n );\n if (generation !== SESSION_GENERATION) return;\n await load();\n if (generation !== SESSION_GENERATION) return;\n setOauthNotice(\n action === \"disconnect\" ? \"OAuth disconnected. Restart authorization when you are ready to reconnect.\" : result?.message || \"Authorization restarted. Open the authorization link to reconnect.\"\n );\n $(\"oauthNotice\").focus();\n } catch (error) {\n if (generation !== SESSION_GENERATION) return;\n try {\n await load();\n } catch {\n }\n if (generation !== SESSION_GENERATION) return;\n setOauthNotice(errorMessage(error, \"OAuth action failed.\"), true);\n $(\"oauthNotice\").focus();\n } finally {\n if (generation === SESSION_GENERATION) {\n buttons.forEach((item) => {\n item.disabled = false;\n });\n }\n }\n };\n function renderCredentials() {\n const data = DATA;\n if (!data) return;\n const list = $(\"credentialList\");\n list.innerHTML = \"\";\n if (data.credentialManagement !== \"available\") return;\n for (const c of data.connectors) {\n const cred = c.credential;\n if (!cred) continue;\n const configured = Boolean(cred.configured);\n const removable = configured || Boolean(cred.removable);\n const state = configured ? cred.fields?.length ? \"configured\" : \"configured · ••••\" + esc(cred.lastFour || \"\") : \"not configured\";\n const updated = configured && cred.updatedAt ? \" · updated \" + esc(formatDate(cred.updatedAt)) : \"\";\n const el = document.createElement(\"section\");\n el.className = \"credential-card\";\n el.id = \"credential-\" + c.id;\n el.setAttribute(\"aria-labelledby\", \"credential-title-\" + c.id);\n let body = '<div class=\"credential-head\"><div class=\"connector-title\"><span class=\"dot ' + (configured ? \"ok\" : \"auth_required\") + '\" aria-hidden=\"true\"></span><h2 id=\"credential-title-' + esc(c.id) + '\">' + esc(c.title || c.id) + '</h2></div><span class=\"credential-state\">' + state + updated + \"</span></div>\";\n body += '<p class=\"mono\">' + esc(c.id) + \" · \" + esc(cred.label) + \"</p>\";\n if (cred.description) {\n body += '<p class=\"credential-copy meta\">' + esc(cred.description) + \"</p>\";\n }\n if (cred.fields?.length) {\n body += '<div class=\"credential-field-summary\">';\n for (const field of cred.fields) {\n const fieldState = field.configured ? \"configured · ••••\" + esc(field.lastFour || \"\") + (field.updatedAt ? \" · updated \" + esc(formatDate(field.updatedAt)) : \"\") : \"not configured\";\n body += \"<div><span>\" + esc(field.label) + '</span><span class=\"meta\">' + fieldState + \"</span></div>\";\n }\n body += \"</div>\";\n }\n if (cred.error) body += '<div class=\"msg\">' + esc(cred.error) + \"</div>\";\n if (cred.notice) {\n body += '<p class=\"credential-copy meta\">' + esc(cred.notice) + \"</p>\";\n }\n body += '<div class=\"credential-actions\">';\n body += '<button class=\"linklike\" type=\"button\" data-credential-action=\"edit\" data-connector=\"' + esc(c.id) + '\">' + (removable ? \"Replace\" : \"Add credential\") + \"</button>\";\n if (configured && cred.testable) {\n body += '<button class=\"linklike\" type=\"button\" data-credential-action=\"test\" data-connector=\"' + esc(c.id) + '\">Test</button>';\n }\n if (removable) {\n body += '<button type=\"button\" class=\"linklike danger\" data-credential-action=\"remove\" data-connector=\"' + esc(c.id) + '\">Remove</button>';\n }\n body += \"</div>\";\n body += '<div class=\"credential-form hidden\" data-credential-form=\"' + esc(c.id) + '\">';\n if (cred.fields && cred.fields.length) {\n body += '<div class=\"credential-fields\">';\n for (const [index, field] of cred.fields.entries()) {\n const inputId = \"credential-input-\" + c.id + \"-\" + index;\n body += '<div class=\"credential-field\"><label for=\"' + esc(inputId) + '\">' + esc(field.label) + '</label><input id=\"' + esc(inputId) + '\" type=\"' + esc(field.inputType || \"password\") + '\" data-credential-field=\"' + esc(field.name) + '\" placeholder=\"' + esc(field.placeholder || field.label) + '\" autocomplete=\"' + (field.inputType === \"password\" ? \"new-password\" : \"off\") + '\" autocapitalize=\"none\" spellcheck=\"false\"></div>';\n }\n body += \"</div>\";\n } else {\n const inputId = \"credential-input-\" + c.id;\n body += '<label class=\"visually-hidden\" for=\"' + esc(inputId) + '\">' + esc(cred.label) + '</label><input id=\"' + esc(inputId) + '\" type=\"password\" data-credential-input=\"' + esc(c.id) + '\" aria-label=\"' + esc(cred.label) + '\" placeholder=\"' + esc(cred.placeholder || \"Paste credential\") + '\" autocomplete=\"new-password\" autocapitalize=\"none\" spellcheck=\"false\">';\n }\n body += '<button class=\"linklike\" type=\"button\" data-credential-action=\"save\" data-connector=\"' + esc(c.id) + '\">Save</button><button class=\"linklike\" type=\"button\" data-credential-action=\"cancel\" data-connector=\"' + esc(c.id) + '\">Cancel</button></div>';\n el.innerHTML = body;\n list.appendChild(el);\n }\n }\n async function credentialRequest(connector, method, action, body, generation) {\n const suffix = action ? \"/\" + action : \"\";\n return operatorRequest(\n \"/ui/credentials/\" + encodeURIComponent(connector) + suffix,\n method,\n generation,\n body ?? void 0\n );\n }\n function credentialForm(connector) {\n const form = document.querySelector(\n '[data-credential-form=\"' + CSS.escape(connector) + '\"]'\n );\n if (!form) throw new Error(\"Credential form is unavailable.\");\n return form;\n }\n $(\"credentialList\").onclick = async (event) => {\n const button = closestElement(\n event.target,\n \"[data-credential-action]\"\n );\n if (!button) return;\n const connector = button.dataset.connector;\n const action = button.dataset.credentialAction;\n if (!connector || !action) return;\n const form = credentialForm(connector);\n const generation = SESSION_GENERATION;\n if (action === \"edit\") {\n form.classList.remove(\"hidden\");\n form.querySelector(\"input\")?.focus();\n return;\n }\n if (action === \"cancel\") {\n form.querySelectorAll(\"input\").forEach((input) => {\n input.value = \"\";\n });\n form.classList.add(\"hidden\");\n document.querySelector(\n '[data-credential-action=\"edit\"][data-connector=\"' + CSS.escape(connector) + '\"]'\n )?.focus();\n return;\n }\n if (action === \"remove\" && !window.confirm(\n \"Remove this credential? The connector will stop authenticating until a replacement is added.\"\n )) return;\n setNotice(\"\");\n $(\"credentialList\").setAttribute(\"aria-busy\", \"true\");\n const buttons = [...document.querySelectorAll(\n '[data-connector=\"' + CSS.escape(connector) + '\"]'\n )];\n buttons.forEach((item) => {\n item.disabled = true;\n });\n try {\n if (action === \"save\") {\n const fieldInputs = [\n ...form.querySelectorAll(\"[data-credential-field]\")\n ];\n if (fieldInputs.length) {\n const values = {};\n for (const input of fieldInputs) {\n const value = input.value.trim();\n if (!value) throw new Error(\"Complete every credential field before saving.\");\n const field = input.dataset.credentialField;\n if (!field) throw new Error(\"Credential field is unnamed.\");\n values[field] = value;\n }\n await credentialRequest(connector, \"PUT\", \"\", { values }, generation);\n } else {\n const input = form.querySelector(\n \"[data-credential-input]\"\n );\n if (!input) throw new Error(\"Credential input is unavailable.\");\n const value = input.value.trim();\n if (!value) throw new Error(\"Paste a credential before saving.\");\n await credentialRequest(connector, \"PUT\", \"\", { value }, generation);\n }\n if (generation !== SESSION_GENERATION) return;\n form.querySelectorAll(\"input\").forEach((input) => {\n input.value = \"\";\n });\n setNotice(\"Credential saved.\");\n await load();\n if (generation !== SESSION_GENERATION) return;\n $(\"credentialNotice\").focus();\n } else if (action === \"remove\") {\n await credentialRequest(connector, \"DELETE\", \"\", null, generation);\n if (generation !== SESSION_GENERATION) return;\n setNotice(\"Credential removed.\");\n await load();\n if (generation !== SESSION_GENERATION) return;\n $(\"credentialNotice\").focus();\n } else if (action === \"test\") {\n const result = await credentialRequest(\n connector,\n \"POST\",\n \"test\",\n null,\n generation\n );\n if (generation !== SESSION_GENERATION) return;\n setNotice(\n result?.message || (result?.ok ? \"Credential is valid.\" : \"Credential test failed.\"),\n !result?.ok\n );\n }\n } catch (error) {\n if (generation !== SESSION_GENERATION) return;\n setNotice(errorMessage(error, \"Credential action failed.\"), true);\n } finally {\n if (generation === SESSION_GENERATION) {\n $(\"credentialList\").setAttribute(\"aria-busy\", \"false\");\n buttons.forEach((item) => {\n item.disabled = false;\n });\n }\n }\n };\n $(\"save\").onclick = async () => {\n const v = $(\"token\").value.trim();\n if (!v) return;\n clearIdentityState();\n localStorage.setItem(KEY, v);\n $(\"token\").value = \"\";\n await load();\n if (DATA) $(CURRENT_PAGE + \"Heading\").focus();\n };\n $(\"change\").onclick = () => {\n localStorage.removeItem(KEY);\n showGate(\"\");\n $(\"token\").focus();\n };\n $(\"copyMcpUrl\").onclick = async () => {\n const button = $(\"copyMcpUrl\");\n try {\n await navigator.clipboard.writeText(MCP_URL);\n button.textContent = \"Copied\";\n } catch {\n button.textContent = \"Copy failed\";\n }\n window.setTimeout(() => {\n button.textContent = \"Copy URL\";\n }, 1600);\n };\n $(\"signin\").onclick = () => Clerk.redirectToSignIn({\n signInFallbackRedirectUrl: window.location.href,\n signUpFallbackRedirectUrl: window.location.href\n });\n function signOut() {\n clearIdentityState();\n return Clerk.signOut({ redirectUrl: window.location.href });\n }\n $(\"gateSignout\").onclick = signOut;\n $(\"signout\").onclick = signOut;\n $(\"filter\").oninput = () => {\n if (DATA) renderConnections();\n };\n $(\"refreshActivity\").onclick = () => loadActivity(true);\n $(\"moreActivity\").onclick = () => loadActivity(false);\n $(\"activitySearch\").oninput = () => renderActivity();\n document.addEventListener(\"click\", (event) => {\n const link = closestElement(\n event.target,\n \"a[data-operator-page]\"\n );\n if (!link || event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;\n const target = new URL(link.href, window.location.href);\n if (target.origin !== window.location.origin) return;\n const page = link.dataset.operatorPage;\n if (page !== \"connections\" && page !== \"credentials\" && page !== \"tokens\" && page !== \"activity\") return;\n event.preventDefault();\n navigateTo(page, target.pathname + target.search + target.hash);\n });\n window.addEventListener(\"popstate\", () => {\n activatePage(pageForPath(window.location.pathname), { focus: true });\n });\n window.addEventListener(\"pagehide\", clearCreatedAccessToken);\n async function init() {\n if (AUTH.kind === \"clerk\") {\n $(\"clerkGate\").classList.remove(\"hidden\");\n $(\"signout\").classList.remove(\"hidden\");\n try {\n if (!window.Clerk) {\n return showGate(\"Clerk could not load. Check your network and try again.\");\n }\n await Clerk.load({\n ...AUTH.signInUrl ? { signInUrl: AUTH.signInUrl } : {},\n ...AUTH.signUpUrl ? { signUpUrl: AUTH.signUpUrl } : {},\n signInFallbackRedirectUrl: window.location.href,\n signUpFallbackRedirectUrl: window.location.href,\n afterSignOutUrl: window.location.href\n });\n CLERK_SESSION_ID = Clerk.session?.id ?? null;\n Clerk.addListener((resources) => {\n const nextSessionId = resources.session?.id ?? null;\n if (nextSessionId === CLERK_SESSION_ID) return;\n CLERK_SESSION_ID = nextSessionId;\n showGate(\"\");\n void load();\n });\n } catch (error) {\n return showGate(\n \"Clerk could not initialize: \" + errorMessage(error, \"unknown error\")\n );\n }\n } else {\n $(\"tokenGate\").classList.remove(\"hidden\");\n $(\"change\").classList.remove(\"hidden\");\n }\n activatePage(pageForPath(window.location.pathname));\n await load();\n }\n if (AUTH.kind === \"clerk\") {\n window.addEventListener(\"load\", init);\n } else {\n init();\n }\n})();\n";
4
+ export const OPERATOR_UI_SCRIPT = "\"use strict\";\n(() => {\n // src/operator-ui/model.ts\n function filterUiConnectors(connectors, query) {\n const q = query.trim().toLowerCase();\n const filtered = [];\n for (const connector of connectors) {\n const connectorText = [\n connector.id,\n connector.title,\n connector.description,\n connector.status\n ].join(\" \").toLowerCase();\n const connectorMatches = Boolean(q && connectorText.includes(q));\n const tools = connector.tools.filter(\n (tool) => !q || connectorMatches || `${tool.name} ${tool.description ?? \"\"}`.toLowerCase().includes(q)\n );\n if (q && tools.length === 0 && !connectorMatches) continue;\n filtered.push({ connector, tools });\n }\n return filtered;\n }\n\n // src/operator-ui/browser.ts\n var KEY = \"connecta:token\";\n var $ = (id) => {\n const element = document.getElementById(id);\n if (!element) throw new Error(`Missing operator UI element #${id}`);\n return element;\n };\n var PAGE_META = {\n connections: { path: \"/\", label: \"Connections\" },\n credentials: { path: \"/credentials\", label: \"Credentials\" },\n tokens: { path: \"/tokens\", label: \"Access tokens\" },\n activity: { path: \"/activity\", label: \"Activity\" }\n };\n var DATA = null;\n var ACTIVITY = [];\n var ACTIVITY_CURSOR = null;\n var ACTIVITY_LOADED = false;\n var ACCESS_TOKENS = [];\n var ACCESS_TOKENS_LOADED = false;\n var CURRENT_PAGE = INITIAL_PAGE;\n var SESSION_GENERATION = 0;\n var ACTIVITY_GENERATION = 0;\n var CLERK_SESSION_ID = null;\n $(\"mcpUrl\").textContent = MCP_URL;\n function errorMessage(error, fallback) {\n return error instanceof Error && error.message ? error.message : fallback;\n }\n function closestElement(target, selector) {\n const candidate = target;\n return typeof candidate?.closest === \"function\" ? candidate.closest(selector) : null;\n }\n function esc(s) {\n return String(s == null ? \"\" : s).replace(/[&<>\"]/g, (c) => ({ \"&\": \"&amp;\", \"<\": \"&lt;\", \">\": \"&gt;\", '\"': \"&quot;\" })[c] ?? c);\n }\n function safeHttp(u) {\n try {\n const p = new URL(u).protocol;\n return p === \"http:\" || p === \"https:\" ? u : null;\n } catch {\n return null;\n }\n }\n function formatDate(value) {\n if (!value) return \"\";\n const date = new Date(value);\n return Number.isNaN(date.valueOf()) ? \"\" : date.toLocaleString();\n }\n function setNotice(message, isError = false) {\n $(\"credentialNotice\").textContent = message || \"\";\n $(\"credentialNotice\").classList.toggle(\"error-notice\", Boolean(isError));\n $(\"credentialNotice\").setAttribute(\"role\", isError ? \"alert\" : \"status\");\n }\n function setOauthNotice(message, isError = false) {\n $(\"oauthNotice\").textContent = message || \"\";\n $(\"oauthNotice\").classList.toggle(\"error-notice\", Boolean(isError));\n $(\"oauthNotice\").setAttribute(\"role\", isError ? \"alert\" : \"status\");\n }\n async function sessionToken() {\n return AUTH.kind === \"clerk\" ? await Clerk.session?.getToken() : localStorage.getItem(KEY);\n }\n function clearActivityState() {\n ACTIVITY_GENERATION += 1;\n ACTIVITY = [];\n ACTIVITY_CURSOR = null;\n ACTIVITY_LOADED = false;\n $(\"activityList\").innerHTML = \"\";\n $(\"activityList\").setAttribute(\"aria-busy\", \"false\");\n $(\"activityNotice\").textContent = \"\";\n $(\"activityNotice\").setAttribute(\"role\", \"status\");\n $(\"activitySummary\").textContent = \"Arguments and results are never stored.\";\n $(\"activitySearch\").value = \"\";\n $(\"refreshActivity\").disabled = false;\n $(\"moreActivity\").disabled = false;\n $(\"moreActivity\").classList.add(\"hidden\");\n }\n function clearIdentityState() {\n SESSION_GENERATION += 1;\n DATA = null;\n clearActivityState();\n $(\"list\").innerHTML = \"\";\n setOauthNotice(\"\");\n $(\"filter\").value = \"\";\n $(\"credentialList\").innerHTML = \"\";\n $(\"credentialList\").setAttribute(\"aria-busy\", \"false\");\n $(\"credentialNotice\").textContent = \"\";\n $(\"credentialNotice\").setAttribute(\"role\", \"status\");\n $(\"credentialNotice\").classList.remove(\"error-notice\");\n $(\"credentialUnavailable\").textContent = \"\";\n $(\"credentialUnavailable\").classList.add(\"hidden\");\n $(\"credentialList\").classList.add(\"hidden\");\n ACCESS_TOKENS = [];\n ACCESS_TOKENS_LOADED = false;\n $(\"tokenList\").innerHTML = \"\";\n $(\"tokenList\").setAttribute(\"aria-busy\", \"false\");\n $(\"tokenNotice\").textContent = \"\";\n clearCreatedAccessToken();\n $(\"tokenName\").value = \"\";\n $(\"tokenUnavailable\").textContent = \"\";\n $(\"tokenUnavailable\").classList.add(\"hidden\");\n $(\"tokenAvailable\").classList.add(\"hidden\");\n $(\"activityUnavailable\").classList.add(\"hidden\");\n $(\"activityAvailable\").classList.add(\"hidden\");\n $(\"credentialsNav\").classList.add(\"hidden\");\n $(\"tokensNav\").classList.add(\"hidden\");\n $(\"activityNav\").classList.add(\"hidden\");\n $(\"serverInfo\").textContent = PRODUCT_OPERATOR_LABEL;\n }\n function showGate(msg) {\n clearIdentityState();\n $(\"app\").classList.add(\"hidden\");\n $(\"appNav\").classList.add(\"hidden\");\n $(\"gate\").classList.remove(\"hidden\");\n $(\"err\").textContent = msg || \"\";\n if (AUTH.kind === \"clerk\") {\n const signedIn = Boolean(window.Clerk && Clerk.user);\n $(\"gateCopy\").textContent = signedIn ? \"Signed in with Clerk, but this account cannot open deployment-wide operator pages.\" : \"Sign in with Clerk to open this operator page.\";\n $(\"signin\").classList.toggle(\"hidden\", signedIn);\n $(\"gateSignout\").classList.toggle(\"hidden\", !signedIn);\n } else {\n $(\"gateCopy\").textContent = \"\";\n }\n }\n function pageForPath(path) {\n if (path === \"/credentials\") return \"credentials\";\n if (path === \"/tokens\") return \"tokens\";\n if (path === \"/activity\") return \"activity\";\n return \"connections\";\n }\n function credentialUnavailableCopy(capability) {\n if (capability === \"no_slots\") {\n return \"No connectors declare operator-managed credential slots. Connector credentials remain configuration-as-code until a slot is declared.\";\n }\n if (capability === \"vault_not_configured\") {\n return \"Credential storage is not configured. Set credentials.encryptionKey before managing connector credentials here.\";\n }\n return \"Credential management requires an eligible Clerk operator. Bearer-authenticated sessions can inspect connections but cannot manage stored credentials.\";\n }\n function accessTokenUnavailableCopy(capability) {\n if (capability === \"not_configured\") {\n return \"Access tokens are not configured for this deployment. Add accessTokens to the deployment configuration to enable them.\";\n }\n return \"Access token management requires an eligible Clerk operator. A Bearer token can connect to MCP, but it cannot create or revoke other tokens.\";\n }\n function setTokenNotice(message, error = false) {\n $(\"tokenNotice\").textContent = message;\n $(\"tokenNotice\").setAttribute(\"role\", error ? \"alert\" : \"status\");\n }\n function clearCreatedAccessToken() {\n $(\"createdToken\").textContent = \"\";\n $(\"tokenReveal\").classList.add(\"hidden\");\n $(\"tokenCreateForm\").classList.remove(\"hidden\");\n }\n function updateCapabilities() {\n const credentialsAvailable = DATA?.credentialManagement === \"available\";\n $(\"credentialsNav\").classList.toggle(\"hidden\", !credentialsAvailable);\n const tokensAvailable = DATA?.accessTokenManagement === \"available\";\n $(\"tokensNav\").classList.toggle(\"hidden\", !tokensAvailable);\n $(\"activityNav\").classList.toggle(\"hidden\", !DATA?.activityEnabled);\n $(\"credentialUnavailable\").classList.toggle(\"hidden\", credentialsAvailable);\n $(\"credentialList\").classList.toggle(\"hidden\", !credentialsAvailable);\n $(\"credentialUnavailable\").textContent = credentialsAvailable ? \"\" : credentialUnavailableCopy(DATA?.credentialManagement);\n $(\"tokenUnavailable\").classList.toggle(\"hidden\", Boolean(tokensAvailable));\n $(\"tokenAvailable\").classList.toggle(\"hidden\", !tokensAvailable);\n $(\"tokenUnavailable\").textContent = tokensAvailable ? \"\" : accessTokenUnavailableCopy(DATA?.accessTokenManagement);\n $(\"activityUnavailable\").classList.toggle(\"hidden\", Boolean(DATA?.activityEnabled));\n $(\"activityAvailable\").classList.toggle(\"hidden\", !DATA?.activityEnabled);\n }\n function activatePage(page, options) {\n const next = PAGE_META[page] ? page : \"connections\";\n CURRENT_PAGE = next;\n for (const name of Object.keys(PAGE_META)) {\n $(name + \"View\").classList.toggle(\"hidden\", name !== next);\n const link = $(name + \"Nav\");\n if (name === next) link.setAttribute(\"aria-current\", \"page\");\n else link.removeAttribute(\"aria-current\");\n }\n $(\"gateHeading\").textContent = PAGE_META[next].label;\n document.title = PAGE_META[next].label + \" — \" + TITLE_SUFFIX;\n if (DATA) {\n updateCapabilities();\n if (next === \"connections\") renderConnections();\n if (next === \"credentials\") renderCredentials();\n if (next === \"tokens\" && DATA.accessTokenManagement === \"available\" && !ACCESS_TOKENS_LOADED) {\n void loadAccessTokens();\n }\n if (next === \"activity\" && DATA.activityEnabled && !ACTIVITY_LOADED) {\n loadActivity(true);\n }\n }\n if (next !== \"credentials\") {\n $(\"credentialList\").innerHTML = \"\";\n setNotice(\"\");\n }\n if (next !== \"tokens\") clearCreatedAccessToken();\n if (options?.focus) $(DATA ? next + \"Heading\" : \"gateHeading\").focus();\n }\n function navigateTo(page, href) {\n history.pushState({ operatorPage: page }, \"\", href);\n activatePage(page, { focus: true });\n }\n async function load() {\n const generation = SESSION_GENERATION;\n let token;\n try {\n token = await sessionToken();\n } catch (error) {\n if (generation !== SESSION_GENERATION) return;\n return showGate(\n \"Could not read the Clerk session: \" + errorMessage(error, \"unknown error\")\n );\n }\n if (generation !== SESSION_GENERATION) return;\n if (!token) return showGate(\"\");\n let res;\n try {\n res = await fetch(\"/ui/data\", { headers: { Authorization: \"Bearer \" + token } });\n } catch (error) {\n if (generation !== SESSION_GENERATION) return;\n return showGate(\"Network error: \" + errorMessage(error, \"unknown error\"));\n }\n if (generation !== SESSION_GENERATION) return;\n if (res.status === 401 || res.status === 403) {\n if (AUTH.kind === \"clerk\") {\n return showGate(\n res.status === 403 ? \"This Clerk account is not allowed to access connecta.\" : \"Your Clerk session was not accepted. Sign out and try again.\"\n );\n }\n localStorage.removeItem(KEY);\n return showGate(\"Token rejected — enter a valid bearer token.\");\n }\n if (!res.ok) return showGate(\"Error \" + res.status);\n let data;\n try {\n data = await res.json();\n } catch {\n if (generation !== SESSION_GENERATION) return;\n return showGate(\"Operator data could not be read.\");\n }\n if (generation !== SESSION_GENERATION) return;\n DATA = data;\n $(\"gate\").classList.add(\"hidden\");\n $(\"app\").classList.remove(\"hidden\");\n $(\"appNav\").classList.remove(\"hidden\");\n const si = data.serverInfo || {};\n $(\"serverInfo\").textContent = (si.name || PRODUCT_NAME) + \" v\" + (data.connectaVersion || \"?\");\n updateCapabilities();\n activatePage(CURRENT_PAGE);\n }\n function actorLabel(actor) {\n if (!actor || !actor.kind) return \"unknown\";\n return actor.label ? actor.kind + \" · \" + actor.label : actor.id ? actor.kind + \" · \" + actor.id : actor.kind;\n }\n function renderActivity() {\n const list = $(\"activityList\");\n list.innerHTML = \"\";\n const query = $(\"activitySearch\").value.trim().toLowerCase();\n const visible = ACTIVITY.filter((event) => {\n if (!query) return true;\n const actor = event.actor || {};\n return [\n event.address,\n event.connectorId,\n event.toolName,\n event.source,\n event.outcome,\n event.errorCode,\n event.friction,\n actor.kind,\n actor.id,\n actor.namespace,\n actor.label\n ].some((value) => String(value || \"\").toLowerCase().includes(query));\n });\n const uniqueTools = new Set(ACTIVITY.map((event) => event.address)).size;\n $(\"activitySummary\").textContent = ACTIVITY.length ? ACTIVITY.length + \" loaded call\" + (ACTIVITY.length === 1 ? \"\" : \"s\") + \" · \" + uniqueTools + \" tool\" + (uniqueTools === 1 ? \"\" : \"s\") + \" · no arguments or results stored\" : \"Arguments and results are never stored.\";\n if (visible.length === 0) {\n list.innerHTML = '<div class=\"activity-empty\">' + (query ? \"No loaded activity matches this search.\" : \"No connector tool calls recorded yet.\") + \"</div>\";\n }\n for (const event of visible) {\n const item = document.createElement(\"article\");\n const outcomeClass = [\n \"success\",\n \"error\",\n \"timeout\",\n \"cancelled\"\n ].includes(event.outcome) ? event.outcome : \"error\";\n item.className = \"activity-item \" + outcomeClass;\n const retryCopy = event.attempts > 1 ? \" · \" + esc(event.attempts) + \" attempts\" : \"\";\n const frictionCopy = event.friction ? \" · \" + esc(event.friction) : \"\";\n const errorCopy = event.errorCode && event.errorCode !== event.friction ? \" · \" + esc(event.errorCode) : \"\";\n const actorId = event.actor?.id ? event.actor.namespace ? event.actor.namespace + \" · \" + event.actor.id : event.actor.id : \"\";\n const stableActorId = actorId && (event.actor?.label || event.actor?.namespace) ? '<div class=\"activity-actor-id mono\">' + esc(actorId) + \"</div>\" : \"\";\n item.innerHTML = '<div class=\"activity-stamp\"><span class=\"dot ' + (outcomeClass === \"success\" ? \"ok\" : \"\") + '\" aria-hidden=\"true\"></span><div><time class=\"activity-time\" datetime=\"' + esc(event.occurredAt) + '\">' + esc(formatDate(event.occurredAt)) + '</time><div class=\"activity-actor\">' + esc(actorLabel(event.actor)) + \"</div>\" + stableActorId + '</div></div><div><div class=\"activity-address\">' + esc(event.address) + '</div><div class=\"activity-detail\">' + esc(event.source) + retryCopy + frictionCopy + errorCopy + '</div></div><div><div class=\"activity-outcome\">' + esc(event.outcome) + '</div><div class=\"activity-detail\">' + esc(event.durationMs) + \" ms</div></div>\";\n list.appendChild(item);\n }\n $(\"moreActivity\").classList.toggle(\"hidden\", !ACTIVITY_CURSOR);\n }\n async function loadActivity(reset) {\n if (!DATA?.activityEnabled) return;\n const sessionGeneration = SESSION_GENERATION;\n if (reset) ACTIVITY_GENERATION += 1;\n const activityGeneration = ACTIVITY_GENERATION;\n const isCurrent = () => sessionGeneration === SESSION_GENERATION && activityGeneration === ACTIVITY_GENERATION;\n $(\"activityNotice\").textContent = \"Loading activity…\";\n $(\"activityNotice\").setAttribute(\"role\", \"status\");\n $(\"activityList\").setAttribute(\"aria-busy\", \"true\");\n $(\"refreshActivity\").disabled = true;\n $(\"moreActivity\").disabled = true;\n try {\n const token = await sessionToken();\n if (!isCurrent()) return;\n if (!token) return showGate(\"Your session has expired.\");\n const cursor = reset ? null : ACTIVITY_CURSOR;\n const params = new URLSearchParams({ limit: \"50\" });\n if (cursor) params.set(\"cursor\", cursor);\n const res = await fetch(\"/ui/activity?\" + params, {\n headers: { Authorization: \"Bearer \" + token }\n });\n if (!isCurrent()) return;\n let payload = {};\n try {\n payload = await res.json();\n } catch {\n }\n if (!isCurrent()) return;\n if (res.status === 401) {\n return showGate(\"Your session was not accepted. Sign in again.\");\n }\n if (res.status === 403) {\n clearActivityState();\n $(\"activityNotice\").setAttribute(\"role\", \"alert\");\n $(\"activityNotice\").textContent = \"This identity may not read activity history.\";\n return;\n }\n if (!res.ok) {\n throw new Error(\n payload.error || \"Activity could not be loaded (\" + res.status + \").\"\n );\n }\n ACTIVITY = reset ? payload.events || [] : ACTIVITY.concat(payload.events || []);\n ACTIVITY_CURSOR = payload.nextCursor || null;\n ACTIVITY_LOADED = true;\n $(\"activityNotice\").textContent = \"\";\n renderActivity();\n } catch (error) {\n if (!isCurrent()) return;\n $(\"activityNotice\").setAttribute(\"role\", \"alert\");\n $(\"activityNotice\").textContent = errorMessage(\n error,\n \"Activity could not be loaded.\"\n );\n } finally {\n if (isCurrent()) {\n $(\"activityList\").setAttribute(\"aria-busy\", \"false\");\n $(\"refreshActivity\").disabled = false;\n $(\"moreActivity\").disabled = false;\n }\n }\n }\n function renderConnections() {\n const data = DATA;\n if (!data) return;\n const q = $(\"filter\").value.trim().toLowerCase();\n const list = $(\"list\");\n list.innerHTML = \"\";\n for (const filtered of filterUiConnectors(data.connectors, q)) {\n const c = filtered.connector;\n const tools = filtered.tools;\n const el = document.createElement(\"div\");\n el.className = \"card\";\n const status = c.status === \"ok\" ? \"Connected\" : c.status === \"auth_required\" ? \"Authorization needed\" : \"Unavailable\";\n let head = '<div class=\"connector-head\"><div><div class=\"connector-title\"><span class=\"dot ' + esc(c.status) + '\" aria-hidden=\"true\"></span><h2>' + esc(c.title || c.id) + \"</h2></div>\";\n if (c.description) {\n head += '<p class=\"connector-description meta\">' + esc(c.description) + \"</p>\";\n }\n head += '</div><div class=\"connector-state cap\">' + esc(status) + \" · \" + c.toolCount + (c.toolCount === 1 ? \" tool\" : \" tools\") + '<br><span class=\"mono\">' + esc(c.id) + \"</span></div></div>\";\n if (c.message) {\n head += '<p class=\"connector-message msg\">' + esc(c.message) + \"</p>\";\n }\n if (c.authorizationUrl) {\n const safe = safeHttp(c.authorizationUrl);\n head += safe ? '<p class=\"connector-auth\"><a class=\"linklike\" href=\"' + esc(safe) + '\" target=\"_blank\" rel=\"noopener\">Authorize connector →</a></p>' : '<p class=\"connector-auth meta\">Authorization URL: ' + esc(c.authorizationUrl) + \"</p>\";\n }\n if (c.oauth && data.oauthManagement) {\n const oauthName = c.title || c.id;\n head += '<div class=\"credential-actions\">';\n head += '<button type=\"button\" class=\"linklike danger\" aria-label=\"Disconnect OAuth for ' + esc(oauthName) + '\" data-oauth-action=\"disconnect\" data-connector=\"' + esc(c.id) + '\">Disconnect OAuth</button>';\n head += '<button type=\"button\" class=\"linklike\" aria-label=\"' + (c.status === \"ok\" ? \"Reconnect OAuth for \" : \"Restart authorization for \") + esc(oauthName) + '\" data-oauth-action=\"reconnect\" data-connector=\"' + esc(c.id) + '\">' + (c.status === \"ok\" ? \"Reconnect OAuth\" : \"Restart authorization\") + \"</button></div>\";\n }\n if (c.credential) {\n head += '<p class=\"connector-auth\"><a class=\"linklike\" href=\"/credentials\" data-operator-page=\"credentials\">Manage credential →</a></p>';\n }\n let body = \"\";\n if (tools.length) {\n body = \"<details\" + (q ? \" open\" : \"\") + '><summary class=\"linklike\">Show tools (' + tools.length + ')</summary><div class=\"tool-list\">';\n for (const t of tools) {\n body += '<div class=\"tool\"><code>' + esc(t.address) + \"</code>\";\n if (t.description) body += '<span class=\"td\">' + esc(t.description) + \"</span>\";\n body += \"</div>\";\n }\n body += \"</div></details>\";\n }\n el.innerHTML = head + body;\n list.appendChild(el);\n }\n if (!list.children.length) {\n list.innerHTML = '<p class=\"empty\">' + (q ? \"No connectors or tools match this filter.\" : \"No connectors are declared in this deployment.\") + \"</p>\";\n }\n }\n async function operatorRequest(path, method, generation, body) {\n const token = await sessionToken();\n if (generation !== SESSION_GENERATION) {\n throw new Error(\"The operator session changed.\");\n }\n if (!token) throw new Error(\"Your Clerk session has expired.\");\n const res = await fetch(path, {\n method,\n headers: {\n Authorization: \"Bearer \" + token,\n ...body ? { \"Content-Type\": \"application/json\" } : {}\n },\n ...body ? { body: JSON.stringify(body) } : {}\n });\n if (res.status === 204) return null;\n let payload = {};\n try {\n payload = await res.json();\n } catch {\n }\n if (!res.ok) throw new Error(payload.error || \"Request failed (\" + res.status + \").\");\n return payload;\n }\n function renderAccessTokens() {\n const list = $(\"tokenList\");\n list.innerHTML = \"\";\n if (!ACCESS_TOKENS.length) {\n list.innerHTML = '<p class=\"empty\">No access tokens yet. Name the first MCP client above.</p>';\n return;\n }\n for (const token of ACCESS_TOKENS) {\n const revoked = Boolean(token.revokedAt);\n const item = document.createElement(\"section\");\n item.className = \"token-card\" + (revoked ? \" revoked\" : \"\");\n item.setAttribute(\"aria-labelledby\", \"access-token-\" + token.id);\n item.innerHTML = '<div class=\"token-card-head\"><div><h2 id=\"access-token-' + esc(token.id) + '\">' + esc(token.name) + '</h2><p class=\"mono\">' + esc(token.tokenPrefix) + '…</p></div><div class=\"cap\">' + (revoked ? \"Revoked \" + esc(formatDate(token.revokedAt)) : \"Created \" + esc(formatDate(token.createdAt))) + '</div></div><div class=\"credential-actions\"><button class=\"linklike\" type=\"button\" data-token-action=\"rename\" data-token-id=\"' + esc(token.id) + '\">Rename</button>' + (revoked ? \"\" : '<button class=\"linklike danger\" type=\"button\" data-token-action=\"revoke\" data-token-id=\"' + esc(token.id) + '\">Revoke</button>') + '</div><form class=\"credential-form hidden\" data-token-form=\"' + esc(token.id) + '\"><label class=\"visually-hidden\" for=\"token-name-' + esc(token.id) + '\">Token name</label><input id=\"token-name-' + esc(token.id) + '\" type=\"text\" maxlength=\"80\" value=\"' + esc(token.name) + '\" autocomplete=\"off\"><button class=\"linklike\" type=\"submit\" data-token-action=\"save-name\" data-token-id=\"' + esc(token.id) + '\">Save name</button><button class=\"linklike\" type=\"button\" data-token-action=\"cancel-name\" data-token-id=\"' + esc(token.id) + '\">Cancel</button></form>';\n list.appendChild(item);\n }\n }\n async function loadAccessTokens() {\n const generation = SESSION_GENERATION;\n $(\"tokenList\").setAttribute(\"aria-busy\", \"true\");\n setTokenNotice(\"Loading access tokens…\");\n try {\n const payload = await operatorRequest(\n \"/ui/access-tokens\",\n \"GET\",\n generation\n );\n if (generation !== SESSION_GENERATION) return;\n ACCESS_TOKENS = payload?.accessTokens || [];\n ACCESS_TOKENS_LOADED = true;\n setTokenNotice(\"\");\n renderAccessTokens();\n } catch (error) {\n if (generation !== SESSION_GENERATION) return;\n setTokenNotice(errorMessage(\n error,\n \"Access tokens could not be loaded.\"\n ), true);\n } finally {\n if (generation === SESSION_GENERATION) {\n $(\"tokenList\").setAttribute(\"aria-busy\", \"false\");\n }\n }\n }\n $(\"tokenCreateForm\").onsubmit = async (event) => {\n event.preventDefault();\n const name = $(\"tokenName\").value.trim();\n if (!name) {\n setTokenNotice(\"Name the MCP client before creating a token.\", true);\n return;\n }\n const generation = SESSION_GENERATION;\n $(\"createToken\").disabled = true;\n setTokenNotice(\"\");\n try {\n const payload = await operatorRequest(\n \"/ui/access-tokens\",\n \"POST\",\n generation,\n { name }\n );\n if (generation !== SESSION_GENERATION) return;\n if (!payload?.token || !payload.accessToken) {\n throw new Error(\"The created token was not returned.\");\n }\n ACCESS_TOKENS = [\n payload.accessToken,\n ...ACCESS_TOKENS.filter((token) => token.id !== payload.accessToken.id)\n ];\n ACCESS_TOKENS_LOADED = true;\n $(\"tokenName\").value = \"\";\n $(\"createdToken\").textContent = payload.token;\n $(\"tokenCreateForm\").classList.add(\"hidden\");\n $(\"tokenReveal\").classList.remove(\"hidden\");\n setTokenNotice(\"Access token created.\");\n renderAccessTokens();\n $(\"tokenRevealHeading\").focus();\n } catch (error) {\n if (generation !== SESSION_GENERATION) return;\n setTokenNotice(errorMessage(\n error,\n \"Access token could not be created.\"\n ), true);\n $(\"tokenNotice\").focus();\n } finally {\n if (generation === SESSION_GENERATION) $(\"createToken\").disabled = false;\n }\n };\n $(\"copyCreatedToken\").onclick = async () => {\n const button = $(\"copyCreatedToken\");\n const token = $(\"createdToken\").textContent || \"\";\n try {\n await navigator.clipboard.writeText(token);\n button.textContent = \"Copied\";\n } catch {\n button.textContent = \"Copy failed\";\n }\n window.setTimeout(() => {\n button.textContent = \"Copy token\";\n }, 1600);\n };\n $(\"dismissCreatedToken\").onclick = () => {\n clearCreatedAccessToken();\n $(\"tokenName\").focus();\n };\n $(\"tokenList\").onclick = async (event) => {\n const button = closestElement(\n event.target,\n \"[data-token-action]\"\n );\n if (!button) return;\n const id = button.dataset.tokenId;\n const action = button.dataset.tokenAction;\n if (!id || !action) return;\n const form = document.querySelector(\n '[data-token-form=\"' + CSS.escape(id) + '\"]'\n );\n if (!form) return;\n if (action === \"rename\") {\n form.classList.remove(\"hidden\");\n form.querySelector(\"input\")?.focus();\n return;\n }\n if (action === \"cancel-name\") {\n const current = ACCESS_TOKENS.find((token) => token.id === id);\n const input = form.querySelector(\"input\");\n if (input && current) input.value = current.name;\n form.classList.add(\"hidden\");\n return;\n }\n if (action !== \"revoke\") return;\n const named = ACCESS_TOKENS.find((token) => token.id === id);\n if (!window.confirm(\n \"Revoke \" + (named?.name || \"this access token\") + \"? Its MCP client will immediately lose access.\"\n )) return;\n const generation = SESSION_GENERATION;\n try {\n const payload = await operatorRequest(\n \"/ui/access-tokens/\" + encodeURIComponent(id),\n \"DELETE\",\n generation\n );\n if (generation !== SESSION_GENERATION) return;\n if (payload?.accessToken) {\n ACCESS_TOKENS = ACCESS_TOKENS.map((token) => token.id === id ? payload.accessToken : token);\n }\n setTokenNotice(\"Access token revoked.\");\n renderAccessTokens();\n $(\"tokenNotice\").focus();\n } catch (error) {\n if (generation !== SESSION_GENERATION) return;\n setTokenNotice(errorMessage(\n error,\n \"Access token could not be revoked.\"\n ), true);\n }\n };\n $(\"tokenList\").onsubmit = async (event) => {\n event.preventDefault();\n const form = closestElement(event.target, \"[data-token-form]\");\n if (!form) return;\n const id = form.dataset.tokenForm;\n const name = form.querySelector(\"input\")?.value.trim();\n if (!id || !name) return;\n const generation = SESSION_GENERATION;\n try {\n const payload = await operatorRequest(\n \"/ui/access-tokens/\" + encodeURIComponent(id),\n \"PUT\",\n generation,\n { name }\n );\n if (generation !== SESSION_GENERATION) return;\n if (payload?.accessToken) {\n ACCESS_TOKENS = ACCESS_TOKENS.map((token) => token.id === id ? payload.accessToken : token);\n }\n setTokenNotice(\"Access token renamed.\");\n renderAccessTokens();\n $(\"tokenNotice\").focus();\n } catch (error) {\n if (generation !== SESSION_GENERATION) return;\n setTokenNotice(errorMessage(\n error,\n \"Access token could not be renamed.\"\n ), true);\n }\n };\n $(\"list\").onclick = async (event) => {\n const button = closestElement(\n event.target,\n \"[data-oauth-action]\"\n );\n if (!button) return;\n const connector = button.dataset.connector;\n const action = button.dataset.oauthAction;\n if (!connector || action !== \"disconnect\" && action !== \"reconnect\") return;\n const generation = SESSION_GENERATION;\n const question = action === \"disconnect\" ? \"Disconnect OAuth for \" + connector + \"? Stored credentials and any pending authorization will be removed.\" : \"Restart OAuth for \" + connector + \"? Stored credentials and any pending authorization will be replaced.\";\n if (!window.confirm(question)) return;\n setOauthNotice(\"\");\n const buttons = [...document.querySelectorAll(\n '[data-connector=\"' + CSS.escape(connector) + '\"]'\n )];\n buttons.forEach((item) => {\n item.disabled = true;\n });\n try {\n const result = await operatorRequest(\n \"/ui/oauth/\" + encodeURIComponent(connector),\n action === \"disconnect\" ? \"DELETE\" : \"POST\",\n generation\n );\n if (generation !== SESSION_GENERATION) return;\n await load();\n if (generation !== SESSION_GENERATION) return;\n setOauthNotice(\n action === \"disconnect\" ? \"OAuth disconnected. Restart authorization when you are ready to reconnect.\" : result?.message || \"Authorization restarted. Open the authorization link to reconnect.\"\n );\n $(\"oauthNotice\").focus();\n } catch (error) {\n if (generation !== SESSION_GENERATION) return;\n try {\n await load();\n } catch {\n }\n if (generation !== SESSION_GENERATION) return;\n setOauthNotice(errorMessage(error, \"OAuth action failed.\"), true);\n $(\"oauthNotice\").focus();\n } finally {\n if (generation === SESSION_GENERATION) {\n buttons.forEach((item) => {\n item.disabled = false;\n });\n }\n }\n };\n function renderCredentials() {\n const data = DATA;\n if (!data) return;\n const list = $(\"credentialList\");\n list.innerHTML = \"\";\n if (data.credentialManagement !== \"available\") return;\n for (const c of data.connectors) {\n const cred = c.credential;\n if (!cred) continue;\n const configured = Boolean(cred.configured);\n const removable = configured || Boolean(cred.removable);\n const state = configured ? cred.fields?.length ? \"configured\" : \"configured · ••••\" + esc(cred.lastFour || \"\") : \"not configured\";\n const updated = configured && cred.updatedAt ? \" · updated \" + esc(formatDate(cred.updatedAt)) : \"\";\n const el = document.createElement(\"section\");\n el.className = \"credential-card\";\n el.id = \"credential-\" + c.id;\n el.setAttribute(\"aria-labelledby\", \"credential-title-\" + c.id);\n let body = '<div class=\"credential-head\"><div class=\"connector-title\"><span class=\"dot ' + (configured ? \"ok\" : \"auth_required\") + '\" aria-hidden=\"true\"></span><h2 id=\"credential-title-' + esc(c.id) + '\">' + esc(c.title || c.id) + '</h2></div><span class=\"credential-state\">' + state + updated + \"</span></div>\";\n body += '<p class=\"mono\">' + esc(c.id) + \" · \" + esc(cred.label) + \"</p>\";\n if (cred.description) {\n body += '<p class=\"credential-copy meta\">' + esc(cred.description) + \"</p>\";\n }\n if (cred.fields?.length) {\n body += '<div class=\"credential-field-summary\">';\n for (const field of cred.fields) {\n const fieldState = field.configured ? \"configured · ••••\" + esc(field.lastFour || \"\") + (field.updatedAt ? \" · updated \" + esc(formatDate(field.updatedAt)) : \"\") : \"not configured\";\n body += \"<div><span>\" + esc(field.label) + '</span><span class=\"meta\">' + fieldState + \"</span></div>\";\n }\n body += \"</div>\";\n }\n if (cred.error) body += '<div class=\"msg\">' + esc(cred.error) + \"</div>\";\n if (cred.notice) {\n body += '<p class=\"credential-copy meta\">' + esc(cred.notice) + \"</p>\";\n }\n body += '<div class=\"credential-actions\">';\n body += '<button class=\"linklike\" type=\"button\" data-credential-action=\"edit\" data-connector=\"' + esc(c.id) + '\">' + (removable ? \"Replace\" : \"Add credential\") + \"</button>\";\n if (configured && cred.testable) {\n body += '<button class=\"linklike\" type=\"button\" data-credential-action=\"test\" data-connector=\"' + esc(c.id) + '\">Test</button>';\n }\n if (removable) {\n body += '<button type=\"button\" class=\"linklike danger\" data-credential-action=\"remove\" data-connector=\"' + esc(c.id) + '\">Remove</button>';\n }\n body += \"</div>\";\n body += '<div class=\"credential-form hidden\" data-credential-form=\"' + esc(c.id) + '\">';\n if (cred.fields && cred.fields.length) {\n body += '<div class=\"credential-fields\">';\n for (const [index, field] of cred.fields.entries()) {\n const inputId = \"credential-input-\" + c.id + \"-\" + index;\n body += '<div class=\"credential-field\"><label for=\"' + esc(inputId) + '\">' + esc(field.label) + '</label><input id=\"' + esc(inputId) + '\" type=\"' + esc(field.inputType || \"password\") + '\" data-credential-field=\"' + esc(field.name) + '\" placeholder=\"' + esc(field.placeholder || field.label) + '\" autocomplete=\"' + (field.inputType === \"password\" ? \"new-password\" : \"off\") + '\" autocapitalize=\"none\" spellcheck=\"false\"></div>';\n }\n body += \"</div>\";\n } else {\n const inputId = \"credential-input-\" + c.id;\n body += '<label class=\"visually-hidden\" for=\"' + esc(inputId) + '\">' + esc(cred.label) + '</label><input id=\"' + esc(inputId) + '\" type=\"password\" data-credential-input=\"' + esc(c.id) + '\" aria-label=\"' + esc(cred.label) + '\" placeholder=\"' + esc(cred.placeholder || \"Paste credential\") + '\" autocomplete=\"new-password\" autocapitalize=\"none\" spellcheck=\"false\">';\n }\n body += '<button class=\"linklike\" type=\"button\" data-credential-action=\"save\" data-connector=\"' + esc(c.id) + '\">Save</button><button class=\"linklike\" type=\"button\" data-credential-action=\"cancel\" data-connector=\"' + esc(c.id) + '\">Cancel</button></div>';\n el.innerHTML = body;\n list.appendChild(el);\n }\n }\n async function credentialRequest(connector, method, action, body, generation) {\n const suffix = action ? \"/\" + action : \"\";\n return operatorRequest(\n \"/ui/credentials/\" + encodeURIComponent(connector) + suffix,\n method,\n generation,\n body ?? void 0\n );\n }\n function credentialForm(connector) {\n const form = document.querySelector(\n '[data-credential-form=\"' + CSS.escape(connector) + '\"]'\n );\n if (!form) throw new Error(\"Credential form is unavailable.\");\n return form;\n }\n $(\"credentialList\").onclick = async (event) => {\n const button = closestElement(\n event.target,\n \"[data-credential-action]\"\n );\n if (!button) return;\n const connector = button.dataset.connector;\n const action = button.dataset.credentialAction;\n if (!connector || !action) return;\n const form = credentialForm(connector);\n const generation = SESSION_GENERATION;\n if (action === \"edit\") {\n form.classList.remove(\"hidden\");\n form.querySelector(\"input\")?.focus();\n return;\n }\n if (action === \"cancel\") {\n form.querySelectorAll(\"input\").forEach((input) => {\n input.value = \"\";\n });\n form.classList.add(\"hidden\");\n document.querySelector(\n '[data-credential-action=\"edit\"][data-connector=\"' + CSS.escape(connector) + '\"]'\n )?.focus();\n return;\n }\n if (action === \"remove\" && !window.confirm(\n \"Remove this credential? The connector will stop authenticating until a replacement is added.\"\n )) return;\n setNotice(\"\");\n $(\"credentialList\").setAttribute(\"aria-busy\", \"true\");\n const buttons = [...document.querySelectorAll(\n '[data-connector=\"' + CSS.escape(connector) + '\"]'\n )];\n buttons.forEach((item) => {\n item.disabled = true;\n });\n try {\n if (action === \"save\") {\n const fieldInputs = [\n ...form.querySelectorAll(\"[data-credential-field]\")\n ];\n if (fieldInputs.length) {\n const values = {};\n for (const input of fieldInputs) {\n const value = input.value.trim();\n if (!value) throw new Error(\"Complete every credential field before saving.\");\n const field = input.dataset.credentialField;\n if (!field) throw new Error(\"Credential field is unnamed.\");\n values[field] = value;\n }\n await credentialRequest(connector, \"PUT\", \"\", { values }, generation);\n } else {\n const input = form.querySelector(\n \"[data-credential-input]\"\n );\n if (!input) throw new Error(\"Credential input is unavailable.\");\n const value = input.value.trim();\n if (!value) throw new Error(\"Paste a credential before saving.\");\n await credentialRequest(connector, \"PUT\", \"\", { value }, generation);\n }\n if (generation !== SESSION_GENERATION) return;\n form.querySelectorAll(\"input\").forEach((input) => {\n input.value = \"\";\n });\n setNotice(\"Credential saved.\");\n await load();\n if (generation !== SESSION_GENERATION) return;\n $(\"credentialNotice\").focus();\n } else if (action === \"remove\") {\n await credentialRequest(connector, \"DELETE\", \"\", null, generation);\n if (generation !== SESSION_GENERATION) return;\n setNotice(\"Credential removed.\");\n await load();\n if (generation !== SESSION_GENERATION) return;\n $(\"credentialNotice\").focus();\n } else if (action === \"test\") {\n const result = await credentialRequest(\n connector,\n \"POST\",\n \"test\",\n null,\n generation\n );\n if (generation !== SESSION_GENERATION) return;\n setNotice(\n result?.message || (result?.ok ? \"Credential is valid.\" : \"Credential test failed.\"),\n !result?.ok\n );\n }\n } catch (error) {\n if (generation !== SESSION_GENERATION) return;\n setNotice(errorMessage(error, \"Credential action failed.\"), true);\n } finally {\n if (generation === SESSION_GENERATION) {\n $(\"credentialList\").setAttribute(\"aria-busy\", \"false\");\n buttons.forEach((item) => {\n item.disabled = false;\n });\n }\n }\n };\n $(\"save\").onclick = async () => {\n const v = $(\"token\").value.trim();\n if (!v) return;\n clearIdentityState();\n localStorage.setItem(KEY, v);\n $(\"token\").value = \"\";\n await load();\n if (DATA) $(CURRENT_PAGE + \"Heading\").focus();\n };\n $(\"change\").onclick = () => {\n localStorage.removeItem(KEY);\n showGate(\"\");\n $(\"token\").focus();\n };\n $(\"copyMcpUrl\").onclick = async () => {\n const button = $(\"copyMcpUrl\");\n try {\n await navigator.clipboard.writeText(MCP_URL);\n button.textContent = \"Copied\";\n } catch {\n button.textContent = \"Copy failed\";\n }\n window.setTimeout(() => {\n button.textContent = \"Copy URL\";\n }, 1600);\n };\n $(\"signin\").onclick = () => Clerk.redirectToSignIn({\n signInFallbackRedirectUrl: window.location.href,\n signUpFallbackRedirectUrl: window.location.href\n });\n function signOut() {\n clearIdentityState();\n return Clerk.signOut({ redirectUrl: window.location.href });\n }\n $(\"gateSignout\").onclick = signOut;\n $(\"signout\").onclick = signOut;\n $(\"filter\").oninput = () => {\n if (DATA) renderConnections();\n };\n $(\"refreshActivity\").onclick = () => loadActivity(true);\n $(\"moreActivity\").onclick = () => loadActivity(false);\n $(\"activitySearch\").oninput = () => renderActivity();\n document.addEventListener(\"click\", (event) => {\n const link = closestElement(\n event.target,\n \"a[data-operator-page]\"\n );\n if (!link || event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;\n const target = new URL(link.href, window.location.href);\n if (target.origin !== window.location.origin) return;\n const page = link.dataset.operatorPage;\n if (page !== \"connections\" && page !== \"credentials\" && page !== \"tokens\" && page !== \"activity\") return;\n event.preventDefault();\n navigateTo(page, target.pathname + target.search + target.hash);\n });\n window.addEventListener(\"popstate\", () => {\n activatePage(pageForPath(window.location.pathname), { focus: true });\n });\n window.addEventListener(\"pagehide\", clearCreatedAccessToken);\n async function init() {\n if (AUTH.kind === \"clerk\") {\n $(\"clerkGate\").classList.remove(\"hidden\");\n $(\"signout\").classList.remove(\"hidden\");\n try {\n if (!window.Clerk) {\n return showGate(\"Clerk could not load. Check your network and try again.\");\n }\n await Clerk.load({\n ...AUTH.signInUrl ? { signInUrl: AUTH.signInUrl } : {},\n ...AUTH.signUpUrl ? { signUpUrl: AUTH.signUpUrl } : {},\n signInFallbackRedirectUrl: window.location.href,\n signUpFallbackRedirectUrl: window.location.href,\n afterSignOutUrl: window.location.href\n });\n CLERK_SESSION_ID = Clerk.session?.id ?? null;\n Clerk.addListener((resources) => {\n const nextSessionId = resources.session?.id ?? null;\n if (nextSessionId === CLERK_SESSION_ID) return;\n CLERK_SESSION_ID = nextSessionId;\n showGate(\"\");\n void load();\n });\n } catch (error) {\n return showGate(\n \"Clerk could not initialize: \" + errorMessage(error, \"unknown error\")\n );\n }\n } else {\n $(\"tokenGate\").classList.remove(\"hidden\");\n $(\"change\").classList.remove(\"hidden\");\n }\n activatePage(pageForPath(window.location.pathname));\n await load();\n }\n if (AUTH.kind === \"clerk\") {\n window.addEventListener(\"load\", init);\n } else {\n init();\n }\n})();\n";
package/src/registry.ts CHANGED
@@ -34,14 +34,15 @@ const DEFAULT_STALE_SECONDS = 3600;
34
34
  const CATALOG_CHUNK_TTL_GRACE_SECONDS = 300;
35
35
  const DEFAULT_MAX_RESULT_BYTES = 50_000;
36
36
  const encoder = new TextEncoder();
37
- /** Independent final-envelope boundary for `batch_call`. */
38
- const DEFAULT_MAX_BATCH_RESULT_BYTES = 100_000;
39
37
 
40
38
  /**
41
39
  * Split `"<connectorId>.<toolName>"` on the first dot. Connector ids contain
42
- * no dots, so a downstream tool name may.
40
+ * no dots, so a downstream tool name may. Exported because an address that
41
+ * resolves to nothing is still an address the invocation path has to record
42
+ * activity for — a connector id an agent invented is the most common address
43
+ * mistake, and the one an operator most needs to see.
43
44
  */
44
- function splitAddress(
45
+ export function splitAddress(
45
46
  address: string,
46
47
  ): { connectorId: string; toolName: string } | null {
47
48
  const dot = address.indexOf(".");
@@ -186,11 +187,6 @@ export interface RegistryOptions {
186
187
  * to the default 50_000.
187
188
  */
188
189
  maxResultBytes?: number;
189
- /**
190
- * Cap on the complete serialized batch_call envelope. Must be a whole number
191
- * of bytes >= 1; anything else warns and falls back to 100_000.
192
- */
193
- maxBatchResultBytes?: number;
194
190
  }
195
191
 
196
192
  function namespaced(storage: KVStorage, prefix: string): KVStorage {
@@ -222,8 +218,6 @@ export type ConnectorOperationOptions = Pick<
222
218
  export interface RegistryView {
223
219
  /** Deployment-wide result-size cap threaded to the meta-tools. */
224
220
  readonly maxResultBytes: number;
225
- /** Independent cap for the complete serialized batch_call envelope. */
226
- readonly maxBatchResultBytes: number;
227
221
  listConnectors(): Connector[];
228
222
  getConnector(id: string): Connector | undefined;
229
223
  resolveAddress(
@@ -299,8 +293,6 @@ export class Registry implements RegistryView {
299
293
  private readonly persistToolCatalog: boolean;
300
294
  /** Result-size guard cap threaded to the meta-tools. */
301
295
  readonly maxResultBytes: number;
302
- /** Final batch envelope cap threaded to the meta-tools. */
303
- readonly maxBatchResultBytes: number;
304
296
 
305
297
  constructor(
306
298
  connectors: Connector[],
@@ -315,10 +307,6 @@ export class Registry implements RegistryView {
315
307
  opts.maxResultBytes,
316
308
  DEFAULT_MAX_RESULT_BYTES,
317
309
  );
318
- this.maxBatchResultBytes = resolveMaxResultBytes(
319
- opts.maxBatchResultBytes,
320
- DEFAULT_MAX_BATCH_RESULT_BYTES,
321
- );
322
310
  for (const c of connectors) {
323
311
  if (!ID_RE.test(c.id)) {
324
312
  throw new Error(
@@ -337,11 +325,7 @@ export class Registry implements RegistryView {
337
325
  }
338
326
  }
339
327
  this.checkConventions(opts.logger);
340
- this.checkResultCaps(
341
- opts.logger,
342
- opts.maxResultBytes,
343
- opts.maxBatchResultBytes,
344
- );
328
+ this.checkResultCaps(opts.logger, opts.maxResultBytes);
345
329
  }
346
330
 
347
331
  /**
@@ -355,7 +339,6 @@ export class Registry implements RegistryView {
355
339
  private checkResultCaps(
356
340
  logger: Logger,
357
341
  configured: number | undefined,
358
- configuredBatch: number | undefined,
359
342
  ): void {
360
343
  if (configured !== undefined && !isValidMaxResultBytes(configured)) {
361
344
  logger.warn(
@@ -365,17 +348,6 @@ export class Registry implements RegistryView {
365
348
  `default ${DEFAULT_MAX_RESULT_BYTES} instead.`,
366
349
  );
367
350
  }
368
- if (
369
- configuredBatch !== undefined &&
370
- !isValidMaxResultBytes(configuredBatch)
371
- ) {
372
- logger.warn(
373
- `[connecta] calls.maxBatchResultBytes ${configuredBatch} is not a whole ` +
374
- `number of bytes >= ${MIN_MAX_RESULT_BYTES}: it would leave the final ` +
375
- "batch envelope unbounded or serve an unusable page. Using the " +
376
- `default ${DEFAULT_MAX_BATCH_RESULT_BYTES} instead.`,
377
- );
378
- }
379
351
  for (const c of this.connectors.values()) {
380
352
  if (
381
353
  c.maxResultBytes !== undefined &&
@@ -1056,7 +1028,7 @@ export class Registry implements RegistryView {
1056
1028
  }
1057
1029
  }
1058
1030
 
1059
- /** Best-effort connector status for list_connectors. */
1031
+ /** Best-effort connector status for the operator UI. */
1060
1032
  async statusFor(
1061
1033
  id: string,
1062
1034
  baseUrl: string,
package/src/routes/mcp.ts CHANGED
@@ -192,13 +192,9 @@ async function serveMcp(
192
192
  registry: RegistryView,
193
193
  runtimeContext?: RuntimeExecutionContext,
194
194
  ): Promise<Response> {
195
- // One deployment-wide value, read once here so the instructions, the
196
- // registered tools, and the guidance the `skills` tool serves cannot
197
- // disagree about which surface this deployment advertises.
198
- const surface = opts.surface ?? "classic";
199
195
  const createServer = (): McpServer => {
200
196
  const server = new McpServer(opts.serverInfo, {
201
- instructions: instructionsFor(surface),
197
+ instructions: instructionsFor(),
202
198
  cacheHints: {
203
199
  "tools/list": {
204
200
  ttlMs: 3_600_000,
@@ -223,7 +219,6 @@ async function serveMcp(
223
219
  : undefined;
224
220
  registerMetaTools(server, registry, {
225
221
  baseUrl,
226
- surface,
227
222
  ...(activity ? { activity } : {}),
228
223
  ...(opts.defaultToolTimeoutMs !== undefined
229
224
  ? { defaultToolTimeoutMs: opts.defaultToolTimeoutMs }
@@ -235,23 +230,26 @@ async function serveMcp(
235
230
  ? { discoveryConcurrency: opts.discoveryConcurrency }
236
231
  : {}),
237
232
  requestSignal: request.signal,
238
- ...(runtimeContext
239
- ? { defer: runtimeContext.waitUntil.bind(runtimeContext) }
233
+ });
234
+ registerExecuteTool(server, registry, {
235
+ baseUrl,
236
+ executor: opts.executor,
237
+ logger: opts.logger,
238
+ ...(activity ? { activity } : {}),
239
+ requestSignal: request.signal,
240
+ ...(opts.discoveryConcurrency !== undefined
241
+ ? { discoveryConcurrency: opts.discoveryConcurrency }
242
+ : {}),
243
+ ...(opts.probeTimeoutMs !== undefined
244
+ ? { probeTimeoutMs: opts.probeTimeoutMs }
245
+ : {}),
246
+ ...(opts.maxEmittedBytes !== undefined
247
+ ? { maxEmittedBytes: opts.maxEmittedBytes }
248
+ : {}),
249
+ ...(opts.maxEmittedBlocks !== undefined
250
+ ? { maxEmittedBlocks: opts.maxEmittedBlocks }
240
251
  : {}),
241
252
  });
242
- if (opts.executor) {
243
- registerExecuteTool(server, registry, {
244
- baseUrl,
245
- surface,
246
- executor: opts.executor,
247
- logger: opts.logger,
248
- ...(activity ? { activity } : {}),
249
- requestSignal: request.signal,
250
- ...(opts.discoveryConcurrency !== undefined
251
- ? { discoveryConcurrency: opts.discoveryConcurrency }
252
- : {}),
253
- });
254
- }
255
253
  return server;
256
254
  };
257
255
 
@@ -7,7 +7,6 @@ import type { AdmissionController } from "../executor-admission.js";
7
7
  import type { Registry } from "../registry.js";
8
8
  import type {
9
9
  ConnectaBranding,
10
- ConnectaSurface,
11
10
  Executor,
12
11
  InboundAuth,
13
12
  Logger,
@@ -26,20 +25,18 @@ export interface ServerOptions {
26
25
  activityReadGate?: ActivityReadGate;
27
26
  activityDeploymentId?: string;
28
27
  deploymentInfo?: Record<string, unknown>;
29
- /** Deadline for call_tool/batch_call calls that pass no timeoutMs. Off when unset. */
28
+ /** Deadline for call_tool/call_destructive_tool calls that pass no timeoutMs. Off when unset. */
30
29
  defaultToolTimeoutMs?: number;
31
- /** Per-connector deadline for the list/search/describe probe fan-out. Default 30_000. */
30
+ /** Per-connector deadline for the search/describe probe fan-out. Default 30_000. */
32
31
  probeTimeoutMs?: number;
33
32
  /** Maximum simultaneous connector discovery operations. Default 4. */
34
33
  discoveryConcurrency?: number;
35
- /** When set, the execute_code meta-tool is registered on top of the base surface. */
36
- executor?: Executor;
37
- /**
38
- * The advertised model-facing surface. createConnecta() always resolves it
39
- * from the executor; absent (a direct createFetchHandler() caller) is
40
- * classic, and `code-first` is only ever set alongside an `executor`.
41
- */
42
- surface?: ConnectaSurface;
34
+ /** Aggregate serialized-byte budget for connecta.emit per run. Default 4_000_000. */
35
+ maxEmittedBytes?: number;
36
+ /** Block-count budget for connecta.emit per run. Default 32. */
37
+ maxEmittedBlocks?: number;
38
+ /** Required sandbox backing the execute_code meta-tool. */
39
+ executor: Executor;
43
40
  /** Global FIFO boundary for all non-preflight `/mcp` requests. */
44
41
  requestAdmission: AdmissionController;
45
42
  /** Encrypted connector-credential storage backing the Credentials page. */
package/src/server.ts CHANGED
@@ -122,10 +122,12 @@ export function createFetchHandler(
122
122
  }
123
123
 
124
124
  if (path === "/health") {
125
- const codeAdmission =
126
- opts.executor && isAdmittingExecutor(opts.executor)
127
- ? opts.executor.admissionSnapshot?.()
128
- : undefined;
125
+ // The executor is required, so code admission always has a shape to
126
+ // report: either the executor's own pool or the fallback controller
127
+ // wrapped around it at construction.
128
+ const codeAdmission = isAdmittingExecutor(opts.executor)
129
+ ? opts.executor.admissionSnapshot?.()
130
+ : undefined;
129
131
  return Response.json({
130
132
  status: "ok",
131
133
  connectors: registry.listConnectors().length,
@@ -133,9 +135,7 @@ export function createFetchHandler(
133
135
  admission: {
134
136
  policy: "global-fifo",
135
137
  requests: opts.requestAdmission.snapshot(),
136
- code: opts.executor
137
- ? (codeAdmission ?? { managedByExecutor: true })
138
- : null,
138
+ code: codeAdmission ?? { managedByExecutor: true },
139
139
  downstreamCalls: {
140
140
  policy: "connector-partitioned-per-runtime",
141
141
  connectors: registry.callAdmissionSnapshot(),