@tangle-network/agent-app 0.50.31 → 0.50.33

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 (67) hide show
  1. package/dist/VaultPane-RHLY4DR5.js +7 -0
  2. package/dist/agent-enrollment/application.d.ts +25 -5
  3. package/dist/agent-enrollment/drizzle.d.ts +63 -0
  4. package/dist/agent-enrollment/drizzle.js +160 -0
  5. package/dist/agent-enrollment/drizzle.js.map +1 -0
  6. package/dist/agent-enrollment/index.d.ts +1 -1
  7. package/dist/agent-enrollment/index.js +5 -199
  8. package/dist/agent-enrollment/index.js.map +1 -1
  9. package/dist/app-oauth/index.d.ts +101 -0
  10. package/dist/app-oauth/index.js +231 -0
  11. package/dist/app-oauth/index.js.map +1 -0
  12. package/dist/assistant/index.js +1 -1
  13. package/dist/chat-routes/index.js +4 -4
  14. package/dist/{chunk-LDCR7MRU.js → chunk-2PDKWV2S.js} +2 -2
  15. package/dist/{chunk-2ZNU55YJ.js → chunk-3IATFW4U.js} +5 -5
  16. package/dist/chunk-3IATFW4U.js.map +1 -0
  17. package/dist/chunk-C3JSO2CB.js +232 -0
  18. package/dist/chunk-C3JSO2CB.js.map +1 -0
  19. package/dist/{chunk-CNI46COH.js → chunk-CBRYWGUO.js} +2 -2
  20. package/dist/{chunk-CNI46COH.js.map → chunk-CBRYWGUO.js.map} +1 -1
  21. package/dist/{chunk-BATKJP3P.js → chunk-E4AY62T2.js} +24 -7
  22. package/dist/chunk-E4AY62T2.js.map +1 -0
  23. package/dist/{chunk-5KFRCVAO.js → chunk-IYLPQKAH.js} +2 -2
  24. package/dist/{chunk-5TOV7EDF.js → chunk-PF3AZD5G.js} +4 -4
  25. package/dist/{chunk-ACFM2GFL.js → chunk-SYIV74NB.js} +1 -1
  26. package/dist/design-canvas-react/index.js +4 -4
  27. package/dist/design-canvas-react/lazy.js +1 -1
  28. package/dist/hosted-agent/react/SharedLineAppNotice.d.ts +16 -0
  29. package/dist/hosted-agent/react/index.d.ts +1 -0
  30. package/dist/hosted-agent/react/index.js +46 -1
  31. package/dist/hosted-agent/react/index.js.map +1 -1
  32. package/dist/hosted-agent/react/lines.css +92 -2
  33. package/dist/integrations-react/callback.d.ts +6 -0
  34. package/dist/integrations-react/client.d.ts +34 -0
  35. package/dist/integrations-react/index.d.ts +6 -0
  36. package/dist/integrations-react/index.js +830 -0
  37. package/dist/integrations-react/index.js.map +1 -0
  38. package/dist/integrations-react/panel.d.ts +22 -0
  39. package/dist/integrations-react/popup.d.ts +19 -0
  40. package/dist/integrations-react/projection.d.ts +25 -0
  41. package/dist/integrations-react/use-hub-integrations.d.ts +102 -0
  42. package/dist/preset-cloudflare/index.js +2 -2
  43. package/dist/sandbox/index.js +4 -4
  44. package/dist/studio-react/index.js +91 -56
  45. package/dist/studio-react/index.js.map +1 -1
  46. package/dist/teams-react/index.js +3 -3
  47. package/dist/theme/tokens.css +3 -1
  48. package/dist/tools/index.js +4 -4
  49. package/dist/vault/index.js +1 -1
  50. package/dist/vault/lazy.js +1 -1
  51. package/dist/web-react/index.js +4 -4
  52. package/dist/web-react/sandbox-terminal.d.ts +2 -0
  53. package/dist/web-react/terminal.js +1 -1
  54. package/dist/work-product/index.js +2 -2
  55. package/dist/workspace-react/companion.d.ts +31 -0
  56. package/dist/workspace-react/index.d.ts +1 -1
  57. package/dist/workspace-react/index.js +140 -2
  58. package/dist/workspace-react/index.js.map +1 -1
  59. package/package.json +35 -5
  60. package/dist/VaultPane-OTUP5AEX.js +0 -7
  61. package/dist/chunk-2ZNU55YJ.js.map +0 -1
  62. package/dist/chunk-BATKJP3P.js.map +0 -1
  63. /package/dist/{VaultPane-OTUP5AEX.js.map → VaultPane-RHLY4DR5.js.map} +0 -0
  64. /package/dist/{chunk-LDCR7MRU.js.map → chunk-2PDKWV2S.js.map} +0 -0
  65. /package/dist/{chunk-5KFRCVAO.js.map → chunk-IYLPQKAH.js.map} +0 -0
  66. /package/dist/{chunk-5TOV7EDF.js.map → chunk-PF3AZD5G.js.map} +0 -0
  67. /package/dist/{chunk-ACFM2GFL.js.map → chunk-SYIV74NB.js.map} +0 -0
@@ -0,0 +1,830 @@
1
+ import {
2
+ confirmWrite,
3
+ useAsyncResource,
4
+ useConfirmedMutation
5
+ } from "../chunk-Q3ZHNN5X.js";
6
+
7
+ // src/integrations-react/callback.tsx
8
+ import { useEffect, useState } from "react";
9
+
10
+ // src/integrations-react/popup.ts
11
+ var HUB_CONNECT_CHANNEL = "tangle:hub-connect";
12
+ var HUB_CONNECTED_MESSAGE_TYPE = "tangle:hub-connected";
13
+ var HUB_CONNECT_FAILED_MESSAGE_TYPE = "tangle:hub-connect-failed";
14
+ var POPUP_TIMEOUT_MS = 5 * 60 * 1e3;
15
+ var PRE_REDIRECT_TIMEOUT_MS = 3e4;
16
+ var POLL_INTERVAL_MS = 2500;
17
+ var POPUP_FEATURES = "popup=yes,width=520,height=680";
18
+ function localAppUrl(path) {
19
+ if (!path.startsWith("/") || path.startsWith("//")) return null;
20
+ try {
21
+ const origin = typeof window === "undefined" ? "https://local.invalid" : window.location.origin;
22
+ const url = new URL(path, origin);
23
+ return url.origin === origin && !url.username && !url.password ? url : null;
24
+ } catch {
25
+ return null;
26
+ }
27
+ }
28
+ function updatedConnection(providerId, before, after) {
29
+ const previous = new Map(before.filter((connection) => connection.providerId === providerId).map((connection) => [connection.id, connection]));
30
+ return after.some((connection) => {
31
+ if (connection.providerId !== providerId || connection.status !== "active" || connection.health === "unhealthy") return false;
32
+ const old = previous.get(connection.id);
33
+ return !old || old.updatedAt !== connection.updatedAt || old.status !== connection.status;
34
+ });
35
+ }
36
+ function closePopup(popup) {
37
+ try {
38
+ if (!popup.closed) popup.close();
39
+ } catch {
40
+ }
41
+ }
42
+ function withAbort(promise, signal) {
43
+ return new Promise((resolve, reject) => {
44
+ if (signal.aborted) {
45
+ reject(new DOMException("Aborted", "AbortError"));
46
+ return;
47
+ }
48
+ const onAbort = () => reject(new DOMException("Aborted", "AbortError"));
49
+ signal.addEventListener("abort", onAbort, { once: true });
50
+ promise.then((value) => {
51
+ signal.removeEventListener("abort", onAbort);
52
+ resolve(value);
53
+ }, (error) => {
54
+ signal.removeEventListener("abort", onAbort);
55
+ reject(error);
56
+ });
57
+ });
58
+ }
59
+ function waitForConnection(input) {
60
+ return new Promise((resolve) => {
61
+ let settled = false;
62
+ let checking = false;
63
+ let pollId;
64
+ let timeoutId;
65
+ let channel;
66
+ const finish = (result) => {
67
+ if (settled) return;
68
+ settled = true;
69
+ if (pollId !== void 0) window.clearTimeout(pollId);
70
+ if (timeoutId !== void 0) window.clearTimeout(timeoutId);
71
+ input.signal.removeEventListener("abort", onAbort);
72
+ channel?.close();
73
+ closePopup(input.popup);
74
+ resolve(result);
75
+ };
76
+ const onAbort = () => finish("cancelled");
77
+ const check = async () => {
78
+ if (settled || checking) return;
79
+ checking = true;
80
+ if (!input.isCurrent() || input.signal.aborted) {
81
+ finish("cancelled");
82
+ return;
83
+ }
84
+ try {
85
+ const after = await input.client.connections(input.identity, input.signal);
86
+ if (input.isCurrent() && updatedConnection(input.providerId, input.before, after)) {
87
+ finish("connected");
88
+ return;
89
+ }
90
+ } catch {
91
+ }
92
+ checking = false;
93
+ if (!settled) pollId = window.setTimeout(check, POLL_INTERVAL_MS);
94
+ };
95
+ if (input.signal.aborted) {
96
+ finish("cancelled");
97
+ return;
98
+ }
99
+ input.signal.addEventListener("abort", onAbort, { once: true });
100
+ try {
101
+ const candidate = new BroadcastChannel(HUB_CONNECT_CHANNEL);
102
+ candidate.onmessage = (event) => {
103
+ const message = event.data;
104
+ if (!message || message.provider !== input.providerId || message.nonce !== input.nonce || message.context !== input.contextToken) return;
105
+ if (message.type === HUB_CONNECT_FAILED_MESSAGE_TYPE) finish("cancelled");
106
+ if (message.type === HUB_CONNECTED_MESSAGE_TYPE) {
107
+ if (pollId !== void 0) window.clearTimeout(pollId);
108
+ void check();
109
+ }
110
+ };
111
+ channel = candidate;
112
+ } catch {
113
+ }
114
+ pollId = window.setTimeout(check, POLL_INTERVAL_MS);
115
+ timeoutId = window.setTimeout(() => finish("unverified"), POPUP_TIMEOUT_MS);
116
+ });
117
+ }
118
+ async function connectWithPopup(input) {
119
+ const callback = localAppUrl(input.callbackPath);
120
+ if (!callback) throw new TypeError("Callback path must be local.");
121
+ const popup = window.open("", "_blank", POPUP_FEATURES);
122
+ if (!popup) return "blocked";
123
+ try {
124
+ popup.opener = null;
125
+ } catch {
126
+ }
127
+ const nonce = crypto.randomUUID();
128
+ const contextToken = crypto.randomUUID();
129
+ callback.searchParams.set("provider", input.providerId);
130
+ callback.searchParams.set("nonce", nonce);
131
+ callback.searchParams.set("context", contextToken);
132
+ const timeout = new AbortController();
133
+ const onAbort = () => timeout.abort();
134
+ input.signal.addEventListener("abort", onAbort, { once: true });
135
+ const preRedirectId = window.setTimeout(() => timeout.abort(), PRE_REDIRECT_TIMEOUT_MS);
136
+ try {
137
+ if (!input.isCurrent()) return "cancelled";
138
+ const start = await withAbort(input.client.startOAuth(input.identity, input.providerId, {
139
+ returnUrl: callback.href,
140
+ ...input.connectionParameters === void 0 ? {} : { connectionParameters: input.connectionParameters }
141
+ }, timeout.signal), timeout.signal);
142
+ if (!input.isCurrent() || input.signal.aborted) return "cancelled";
143
+ let redirect;
144
+ try {
145
+ redirect = new URL(start.redirectUrl);
146
+ } catch {
147
+ return "unavailable";
148
+ }
149
+ if (redirect.protocol !== "https:" || redirect.username || redirect.password) return "unavailable";
150
+ window.clearTimeout(preRedirectId);
151
+ const waitController = new AbortController();
152
+ const abortWait = () => waitController.abort();
153
+ input.signal.addEventListener("abort", abortWait, { once: true });
154
+ if (input.signal.aborted) abortWait();
155
+ const waiting = waitForConnection({ ...input, popup, nonce, contextToken, signal: waitController.signal });
156
+ try {
157
+ popup.location.href = redirect.href;
158
+ return await waiting;
159
+ } catch {
160
+ waitController.abort();
161
+ await waiting;
162
+ return "unavailable";
163
+ } finally {
164
+ input.signal.removeEventListener("abort", abortWait);
165
+ }
166
+ } catch {
167
+ return input.signal.aborted || timeout.signal.aborted ? "cancelled" : "unavailable";
168
+ } finally {
169
+ window.clearTimeout(preRedirectId);
170
+ input.signal.removeEventListener("abort", onAbort);
171
+ closePopup(popup);
172
+ }
173
+ }
174
+
175
+ // src/integrations-react/callback.tsx
176
+ import { jsx, jsxs } from "react/jsx-runtime";
177
+ function HubConnectCallbackPage({ returnHref }) {
178
+ const [phase, setPhase] = useState("checking");
179
+ const [reason, setReason] = useState("");
180
+ useEffect(() => {
181
+ const params = new URLSearchParams(window.location.search);
182
+ const provider = params.get("provider");
183
+ const nonce = params.get("nonce");
184
+ const context = params.get("context");
185
+ if (!provider || !nonce || !context) {
186
+ setReason("This connection callback is incomplete.");
187
+ setPhase("failed");
188
+ return;
189
+ }
190
+ const failure = params.get("error_description") || params.get("error");
191
+ try {
192
+ const channel = new BroadcastChannel(HUB_CONNECT_CHANNEL);
193
+ channel.postMessage({ type: failure ? HUB_CONNECT_FAILED_MESSAGE_TYPE : HUB_CONNECTED_MESSAGE_TYPE, provider, nonce, context });
194
+ channel.close();
195
+ } catch {
196
+ }
197
+ if (failure) {
198
+ setReason(failure.slice(0, 200));
199
+ setPhase("failed");
200
+ return;
201
+ }
202
+ window.close();
203
+ const timer = window.setTimeout(() => setPhase("returned"), 150);
204
+ return () => window.clearTimeout(timer);
205
+ }, []);
206
+ const destination = localAppUrl(returnHref);
207
+ const localReturn = destination ? `${destination.pathname}${destination.search}${destination.hash}` : "/";
208
+ return /* @__PURE__ */ jsxs("main", { "aria-live": "polite", style: { maxWidth: 560, margin: "20vh auto", padding: 24, textAlign: "center" }, children: [
209
+ phase === "checking" ? /* @__PURE__ */ jsx("p", { children: "Checking your connection\u2026" }) : phase === "returned" ? /* @__PURE__ */ jsx("p", { children: "Return to the app to check your connection. You can close this window." }) : /* @__PURE__ */ jsxs("p", { children: [
210
+ "Could not complete the connection. ",
211
+ reason
212
+ ] }),
213
+ /* @__PURE__ */ jsx("a", { href: localReturn, children: "Return to integrations" })
214
+ ] });
215
+ }
216
+
217
+ // src/integrations-react/client.ts
218
+ function object(value) {
219
+ if (value === null || typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid Hub settings response.");
220
+ return value;
221
+ }
222
+ function array(value) {
223
+ if (!Array.isArray(value)) throw new Error("Invalid Hub settings response.");
224
+ return value;
225
+ }
226
+ function namedArray(value, key) {
227
+ const rows = array(object(value)[key]);
228
+ if (rows.some((row) => row === null || typeof row !== "object" || Array.isArray(row))) throw new Error("Invalid Hub settings response.");
229
+ return rows;
230
+ }
231
+ function namedObject(value, key) {
232
+ return object(object(value)[key]);
233
+ }
234
+ function segment(value) {
235
+ if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(value)) throw new TypeError("Invalid Hub settings identifier.");
236
+ return encodeURIComponent(value);
237
+ }
238
+ function createHubIntegrationsClient(request, basePath = "/api/hub/settings") {
239
+ if (!/^\/(?:[A-Za-z0-9_-]+\/)*[A-Za-z0-9_-]+$/.test(basePath)) throw new TypeError("Invalid Hub settings basePath.");
240
+ async function call(identity, path, method, signal, body) {
241
+ if (![identity.userId, identity.sessionId, identity.workspaceId].every((part) => typeof part === "string" && part.trim())) {
242
+ throw new TypeError("Hub settings identity is required.");
243
+ }
244
+ const response = await request({
245
+ identity,
246
+ path: `${basePath}${path}`,
247
+ init: { method, signal, ...body === void 0 ? {} : { headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) } }
248
+ });
249
+ if (!response.ok) {
250
+ let code;
251
+ try {
252
+ const error = object(await response.json());
253
+ if (typeof error.code === "string") code = error.code;
254
+ } catch {
255
+ }
256
+ throw new Error(`Hub settings request failed (${response.status}${code ? `, ${code}` : ""}).`);
257
+ }
258
+ return response.json();
259
+ }
260
+ return {
261
+ async providers(identity, signal) {
262
+ return namedArray(await call(identity, "/providers", "GET", signal), "providers");
263
+ },
264
+ async connections(identity, signal) {
265
+ return namedArray(await call(identity, "/connections", "GET", signal), "connections");
266
+ },
267
+ async startOAuth(identity, providerId, input, signal) {
268
+ const response = object(await call(identity, `/connections/${segment(providerId)}/start`, "POST", signal, input));
269
+ if (typeof response.redirectUrl !== "string") throw new Error("Invalid Hub OAuth response.");
270
+ return response;
271
+ },
272
+ async connectApiKey(identity, providerId, apiKey, metadata, signal) {
273
+ return namedObject(await call(identity, `/connections/${segment(providerId)}/connect-key`, "POST", signal, { apiKey, ...metadata === void 0 ? {} : { metadata } }), "connection");
274
+ },
275
+ async revoke(identity, connectionId, signal) {
276
+ return namedObject(await call(identity, `/connections/${segment(connectionId)}`, "DELETE", signal), "connection");
277
+ },
278
+ async health(identity, connectionId, signal) {
279
+ const response = object(await call(identity, `/connections/${segment(connectionId)}/health`, "POST", signal));
280
+ object(response.connection);
281
+ object(response.health);
282
+ return response;
283
+ },
284
+ async actions(identity, providerId, limit, signal) {
285
+ if (!Number.isInteger(limit) || limit < 1 || limit > 200) throw new TypeError("Hub action limit must be 1\u2013200.");
286
+ const search = new URLSearchParams({ query: "", limit: String(limit) });
287
+ return namedArray(await call(identity, `/providers/${segment(providerId)}/actions?${search}`, "GET", signal), "tools");
288
+ },
289
+ async policies(identity, connectionId, signal) {
290
+ const search = new URLSearchParams({ connectionId });
291
+ return namedArray(await call(identity, `/policies?${search}`, "GET", signal), "policies");
292
+ },
293
+ async setPolicy(identity, connectionId, actionPath, decision, signal) {
294
+ return namedObject(await call(identity, "/policies", "PUT", signal, { connectionId, actionPath, decision }), "policy");
295
+ },
296
+ async resetPolicy(identity, connectionId, actionPath, signal) {
297
+ const response = object(await call(identity, "/policies", "DELETE", signal, { connectionId, actionPath }));
298
+ if (response.connectionId !== connectionId || response.actionPath !== actionPath || typeof response.deleted !== "boolean") {
299
+ throw new Error("Invalid Hub policy reset response.");
300
+ }
301
+ }
302
+ };
303
+ }
304
+
305
+ // src/integrations-react/panel.tsx
306
+ import {
307
+ ApiKeyConnectDialog,
308
+ IntegrationConnectionDetail,
309
+ IntegrationsCatalog,
310
+ OAuthConnectionParameterDialog
311
+ } from "@tangle-network/sandbox-ui/integrations";
312
+ import { Button } from "@tangle-network/ui/primitives";
313
+ import { useEffect as useEffect3, useMemo as useMemo2, useRef as useRef2, useState as useState3 } from "react";
314
+
315
+ // src/integrations-react/projection.ts
316
+ var ACTION_LIMIT = 200;
317
+ function contextKey(identity) {
318
+ return JSON.stringify([identity.userId, identity.sessionId, identity.workspaceId]);
319
+ }
320
+ function displayProvider(provider) {
321
+ return { providerId: provider.providerId, title: provider.title, category: provider.category };
322
+ }
323
+ function catalogRows(providers, connections, selectedIds, can, hasUnsupportedConnect = false) {
324
+ return providers.map((provider) => {
325
+ const accounts = connections.filter((connection) => connection.providerId === provider.providerId);
326
+ return {
327
+ ...displayProvider(provider),
328
+ kind: "provider",
329
+ authKind: provider.authKind,
330
+ selectedConnectionId: accounts.some((account) => account.id === selectedIds[provider.providerId]) ? selectedIds[provider.providerId] ?? null : null,
331
+ canConnect: provider.authKind === "oauth2" ? provider.configured && can({ operation: "oauth.start", providerId: provider.providerId }) : provider.authKind === "api_key" ? provider.configured && can({ operation: "api-key.connect", providerId: provider.providerId }) : hasUnsupportedConnect,
332
+ connections: accounts.map((connection) => ({
333
+ id: connection.id,
334
+ accountDisplay: connection.accountDisplay ?? connection.displayName,
335
+ statusLabel: connection.status === "active" ? "Connected" : connection.status.replaceAll("_", " "),
336
+ statusTone: connection.status === "active" && connection.health !== "unhealthy" ? "success" : "warning",
337
+ detail: connection.providerAccountId ?? void 0,
338
+ capabilities: {
339
+ manage: can({ operation: "policies.list", connectionId: connection.id }),
340
+ disconnect: can({ operation: "connection.revoke", connectionId: connection.id }),
341
+ test: can({ operation: "connection.health", connectionId: connection.id }),
342
+ editPermissions: can({ operation: "policies.list", connectionId: connection.id }),
343
+ resetPermissions: can({ operation: "policies.list", connectionId: connection.id })
344
+ }
345
+ }))
346
+ };
347
+ });
348
+ }
349
+ var OPTIONS = [
350
+ { value: "allow", label: "Allow" },
351
+ { value: "ask", label: "Ask" },
352
+ { value: "deny", label: "Deny" }
353
+ ];
354
+ function permissionDetails(tools, policies, connectionId, can) {
355
+ const overrides = new Map(policies.filter((policy) => policy.connectionId === connectionId).map((policy) => [policy.actionPath, policy.decision]));
356
+ const groups = [
357
+ { id: "writes", title: "Write and unknown actions", rows: [] },
358
+ { id: "reads", title: "Read actions", collapsed: true, rows: [] }
359
+ ];
360
+ const writes = [];
361
+ const reads = [];
362
+ for (const tool of tools) {
363
+ const override = overrides.get(tool.path);
364
+ const row = {
365
+ actionPath: tool.path,
366
+ title: tool.title ?? tool.path,
367
+ riskLabel: tool.risk ?? "unknown",
368
+ riskTone: tool.risk === "destructive" ? "error" : tool.risk === "write" || tool.risk === void 0 ? "warning" : "neutral",
369
+ decision: override ?? null,
370
+ decisionOptions: OPTIONS,
371
+ sourceLabel: override ? "Stored override" : "No stored override",
372
+ canReset: override !== void 0 && can({ operation: "policy.reset", connectionId, actionPath: tool.path }),
373
+ disabled: !can({ operation: "policy.set", connectionId, actionPath: tool.path })
374
+ };
375
+ if (tool.risk === "read") reads.push(row);
376
+ else writes.push(row);
377
+ }
378
+ writes.sort((a, b) => a.title.localeCompare(b.title));
379
+ reads.sort((a, b) => a.title.localeCompare(b.title));
380
+ groups[0] = { ...groups[0], rows: writes };
381
+ groups[1] = { ...groups[1], rows: reads };
382
+ return { permissionGroups: groups };
383
+ }
384
+
385
+ // src/integrations-react/use-hub-integrations.ts
386
+ import { useCallback, useEffect as useEffect2, useMemo, useRef, useState as useState2 } from "react";
387
+ function initialSelection(scope) {
388
+ if (typeof window === "undefined") return { scope, providerId: null, connectionId: null };
389
+ const query = new URL(window.location.href).searchParams;
390
+ return { scope, providerId: query.get("integration"), connectionId: query.get("connection") };
391
+ }
392
+ function updateUrl(providerId, connectionId) {
393
+ if (typeof window === "undefined") return;
394
+ const url = new URL(window.location.href);
395
+ if (providerId) url.searchParams.set("integration", providerId);
396
+ else url.searchParams.delete("integration");
397
+ if (connectionId) url.searchParams.set("connection", connectionId);
398
+ else url.searchParams.delete("connection");
399
+ window.history.pushState(window.history.state, "", url);
400
+ }
401
+ function useHubIntegrations({ identity, client, can, callbackPath, onUnsupportedConnect }) {
402
+ const scope = contextKey(identity);
403
+ const activeScope = useRef(scope);
404
+ activeScope.current = scope;
405
+ const [selection, setSelection] = useState2(() => initialSelection(scope));
406
+ const visibleSelection = selection.scope === scope ? selection : { scope, providerId: null, connectionId: null };
407
+ const [dialog, setDialog] = useState2(null);
408
+ const visibleDialog = dialog?.scope === scope ? dialog : null;
409
+ const [connectStatus, setConnectStatus] = useState2({ scope, status: "idle" });
410
+ const [writeScope, setWriteScope] = useState2(scope);
411
+ const pendingPopup = useRef(null);
412
+ useEffect2(() => {
413
+ const onPop = () => setSelection(initialSelection(scope));
414
+ window.addEventListener("popstate", onPop);
415
+ return () => window.removeEventListener("popstate", onPop);
416
+ }, [scope]);
417
+ const providers = useAsyncResource({ load: ({ signal }) => client.providers(identity, signal), deps: [client, scope], isEmpty: () => false });
418
+ const connections = useAsyncResource({ load: ({ signal }) => client.connections(identity, signal), deps: [client, scope], isEmpty: () => false });
419
+ const providerList = providers.status === "ready" ? providers.value : [];
420
+ const connectionList = connections.status === "ready" ? connections.value : [];
421
+ const provider = providerList.find((item) => item.providerId === visibleSelection.providerId) ?? null;
422
+ const connection = connectionList.find((item) => item.id === visibleSelection.connectionId && item.providerId === provider?.providerId) ?? null;
423
+ const canReadPolicies = connection !== null && can({ operation: "policies.list", connectionId: connection.id });
424
+ const detail = useAsyncResource({
425
+ enabled: canReadPolicies && connection?.status === "active",
426
+ deps: [client, scope, provider?.providerId, connection?.id, canReadPolicies],
427
+ isEmpty: () => false,
428
+ load: async ({ signal }) => {
429
+ if (!provider || !connection) throw new Error("Choose a connection.");
430
+ const [tools, policies] = await Promise.all([
431
+ client.actions(identity, provider.providerId, ACTION_LIMIT, signal),
432
+ client.policies(identity, connection.id, signal)
433
+ ]);
434
+ if (tools.some((tool) => !tool.path.startsWith(`${provider.providerId}.`)) || policies.some((policy) => policy.connectionId !== connection.id)) {
435
+ throw new Error("Hub settings response changed connection or provider.");
436
+ }
437
+ return { tools, policies, truncated: tools.length >= ACTION_LIMIT };
438
+ }
439
+ });
440
+ const write = useConfirmedMutation({
441
+ concurrency: "reject",
442
+ mutate: async (input, { signal }) => {
443
+ if (input.scope !== activeScope.current) throw new Error("Integration context changed. Retry in the current workspace.");
444
+ const origin = input.identity;
445
+ const receipt = (reconciliation, message) => confirmWrite({ scope: input.scope, kind: input.kind, reconciliation, message });
446
+ if (input.kind === "api-key") {
447
+ if (!can({ operation: "api-key.connect", providerId: input.providerId })) throw new Error("Connection setup is unavailable.");
448
+ const created = await client.connectApiKey(origin, input.providerId, input.apiKey, input.metadata, signal);
449
+ if (created.providerId !== input.providerId || created.status !== "active") throw new Error("Hub did not confirm the requested connection.");
450
+ try {
451
+ const current = await client.connections(origin, signal);
452
+ return current.some((item) => item.id === created.id && item.status === "active") ? receipt("verified", "Connection saved and verified.") : receipt("refresh-failed", "Connection saved; current account state could not be confirmed.");
453
+ } catch {
454
+ return receipt("refresh-failed", "Connection saved; refresh failed.");
455
+ }
456
+ }
457
+ if (input.kind === "revoke") {
458
+ if (!can({ operation: "connection.revoke", connectionId: input.connectionId })) throw new Error("Disconnect is unavailable.");
459
+ await client.revoke(origin, input.connectionId, signal);
460
+ try {
461
+ const current = await client.connections(origin, signal);
462
+ return current.some((item) => item.id === input.connectionId && item.status === "active") ? receipt("refresh-failed", "Disconnected, but the current account state disagrees.") : receipt("verified", "Connection disconnected and verified.");
463
+ } catch {
464
+ return receipt("refresh-failed", "Disconnected; refresh failed.");
465
+ }
466
+ }
467
+ if (input.kind === "health") {
468
+ if (!can({ operation: "connection.health", connectionId: input.connectionId })) throw new Error("Connection test is unavailable.");
469
+ const result = await client.health(origin, input.connectionId, signal);
470
+ if (result.connection.id !== input.connectionId) throw new Error("Hub returned another connection.");
471
+ return receipt("verified", `Connection test: ${result.health.status.replaceAll("_", " ")}.`);
472
+ }
473
+ if (!can({ operation: input.kind === "set" ? "policy.set" : "policy.reset", connectionId: input.connectionId, actionPath: input.actionPath })) {
474
+ throw new Error("Permission editing is unavailable.");
475
+ }
476
+ if (input.kind === "set") {
477
+ const stored = await client.setPolicy(origin, input.connectionId, input.actionPath, input.decision, signal);
478
+ if (stored.connectionId !== input.connectionId || stored.actionPath !== input.actionPath || stored.decision !== input.decision) {
479
+ throw new Error("Hub did not confirm the requested permission.");
480
+ }
481
+ } else await client.resetPolicy(origin, input.connectionId, input.actionPath, signal);
482
+ try {
483
+ const current = await client.policies(origin, input.connectionId, signal);
484
+ const override = current.find((policy) => policy.actionPath === input.actionPath);
485
+ const matches = input.kind === "set" ? override?.decision === input.decision : override === void 0;
486
+ return matches ? receipt("verified", "Permission saved and verified.") : receipt("refresh-failed", "Permission write was accepted; current policy state disagrees.");
487
+ } catch {
488
+ return receipt("refresh-failed", "Permission write was accepted; refresh failed.");
489
+ }
490
+ },
491
+ onSucceeded: (value) => {
492
+ if (value.scope === activeScope.current) {
493
+ connections.retry();
494
+ detail.retry();
495
+ }
496
+ }
497
+ });
498
+ useEffect2(() => {
499
+ pendingPopup.current?.abort();
500
+ pendingPopup.current = null;
501
+ setDialog(null);
502
+ setConnectStatus({ scope, status: "idle" });
503
+ setWriteScope(scope);
504
+ write.reset();
505
+ return () => {
506
+ pendingPopup.current?.abort();
507
+ pendingPopup.current = null;
508
+ };
509
+ }, [scope, client, write.reset]);
510
+ const selectProvider = useCallback((providerId) => {
511
+ const next = { scope, providerId, connectionId: null };
512
+ setSelection(next);
513
+ updateUrl(providerId, null);
514
+ }, [scope]);
515
+ const selectConnection = useCallback((providerId, connectionId) => {
516
+ if (connectionId && !connectionList.some((item) => item.id === connectionId && item.providerId === providerId)) return;
517
+ setSelection({ scope, providerId, connectionId });
518
+ updateUrl(providerId, connectionId);
519
+ }, [scope, connectionList]);
520
+ const startOAuth = useCallback(async (target, connectionParameters) => {
521
+ if (!can({ operation: "oauth.start", providerId: target.providerId })) return "unavailable";
522
+ if (connections.status !== "ready") {
523
+ setConnectStatus({ scope, status: "failed", message: "Load connections before connecting." });
524
+ return "unavailable";
525
+ }
526
+ pendingPopup.current?.abort();
527
+ const controller = new AbortController();
528
+ pendingPopup.current = controller;
529
+ setConnectStatus({ scope, status: "pending", providerId: target.providerId });
530
+ const result = await connectWithPopup({
531
+ client,
532
+ identity,
533
+ providerId: target.providerId,
534
+ before: connections.value,
535
+ callbackPath,
536
+ connectionParameters,
537
+ signal: controller.signal,
538
+ isCurrent: () => activeScope.current === scope && !controller.signal.aborted
539
+ });
540
+ if (pendingPopup.current !== controller || activeScope.current !== scope) return result;
541
+ pendingPopup.current = null;
542
+ if (result === "connected") {
543
+ connections.retry();
544
+ setDialog(null);
545
+ setConnectStatus({ scope, status: "connected", message: "Connection verified." });
546
+ } else setConnectStatus({ scope, status: "failed", message: result === "blocked" ? "Allow the popup and try again." : result === "unverified" ? "Could not verify a new connection. Refresh and try again." : result === "cancelled" ? "Connection was cancelled." : "This connection flow is unavailable." });
547
+ return result;
548
+ }, [can, connections, client, identity, callbackPath, scope]);
549
+ const beginConnect = useCallback((target) => {
550
+ if (target.authKind !== "api_key" && target.authKind !== "oauth2") {
551
+ if (onUnsupportedConnect) onUnsupportedConnect(target);
552
+ else setConnectStatus({ scope, status: "failed", message: "This provider needs an app-specific connection flow." });
553
+ return;
554
+ }
555
+ if (!target.configured) {
556
+ setConnectStatus({ scope, status: "failed", message: "This provider is not configured for connection." });
557
+ return;
558
+ }
559
+ if (target.authKind === "api_key") {
560
+ if (can({ operation: "api-key.connect", providerId: target.providerId })) setDialog({ scope, kind: "api-key", provider: target });
561
+ else setConnectStatus({ scope, status: "failed", message: "Connection setup is unavailable." });
562
+ return;
563
+ }
564
+ if (target.authKind === "oauth2") {
565
+ if (!can({ operation: "oauth.start", providerId: target.providerId })) {
566
+ setConnectStatus({ scope, status: "failed", message: "Connection setup is unavailable." });
567
+ return;
568
+ }
569
+ if (target.connectionParameters?.length) setDialog({ scope, kind: "oauth", provider: target });
570
+ else void startOAuth(target);
571
+ return;
572
+ }
573
+ }, [can, onUnsupportedConnect, scope, startOAuth]);
574
+ const cancelConnect = useCallback(() => {
575
+ pendingPopup.current?.abort();
576
+ pendingPopup.current = null;
577
+ setDialog(null);
578
+ setConnectStatus({ scope, status: "failed", message: "Connection was cancelled." });
579
+ }, [scope]);
580
+ const rows = useMemo(
581
+ () => catalogRows(providerList, connectionList, visibleSelection.providerId && visibleSelection.connectionId ? { [visibleSelection.providerId]: visibleSelection.connectionId } : {}, can, !!onUnsupportedConnect),
582
+ [providerList, connectionList, visibleSelection.providerId, visibleSelection.connectionId, can, onUnsupportedConnect]
583
+ );
584
+ const details = detail.status === "ready" && connection ? permissionDetails(detail.value.tools, detail.value.policies, connection.id, can) : void 0;
585
+ return {
586
+ providers,
587
+ connections,
588
+ detail,
589
+ rows,
590
+ provider,
591
+ connection,
592
+ dialog: visibleDialog,
593
+ setDialog,
594
+ connectStatus: connectStatus.scope === scope ? connectStatus : { scope, status: "idle", providerId: void 0 },
595
+ selection: visibleSelection,
596
+ selectProvider,
597
+ selectConnection,
598
+ beginConnect,
599
+ startOAuth,
600
+ cancelConnect,
601
+ write,
602
+ writeState: writeScope === scope ? write.state : { status: "idle" },
603
+ details,
604
+ refresh: () => {
605
+ providers.retry();
606
+ connections.retry();
607
+ detail.retry();
608
+ },
609
+ submitApiKey: (providerId, apiKey, metadata) => {
610
+ setWriteScope(scope);
611
+ return write.run({ kind: "api-key", identity, scope, providerId, apiKey, metadata });
612
+ },
613
+ revoke: (connectionId) => {
614
+ setWriteScope(scope);
615
+ return write.run({ kind: "revoke", identity, scope, connectionId });
616
+ },
617
+ test: (connectionId) => {
618
+ setWriteScope(scope);
619
+ return write.run({ kind: "health", identity, scope, connectionId });
620
+ },
621
+ setDecision: (connectionId, actionPath, decision) => {
622
+ setWriteScope(scope);
623
+ return write.run({ kind: "set", identity, scope, connectionId, actionPath, decision });
624
+ },
625
+ resetDecision: (connectionId, actionPath) => {
626
+ setWriteScope(scope);
627
+ return write.run({ kind: "reset", identity, scope, connectionId, actionPath });
628
+ }
629
+ };
630
+ }
631
+
632
+ // src/integrations-react/panel.tsx
633
+ import { Fragment, jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
634
+ function catalogHref() {
635
+ if (typeof window === "undefined") return "/";
636
+ const url = new URL(window.location.href);
637
+ url.searchParams.delete("integration");
638
+ url.searchParams.delete("connection");
639
+ return `${url.pathname}${url.search}${url.hash}`;
640
+ }
641
+ function HubIntegrationsPanel(props) {
642
+ const hub = useHubIntegrations(props);
643
+ const scope = contextKey(props.identity);
644
+ const activeScope = useRef2(scope);
645
+ activeScope.current = scope;
646
+ const activeDialog = useRef2(hub.dialog);
647
+ activeDialog.current = hub.dialog;
648
+ const [query, setQuery] = useState3("");
649
+ const [category, setCategory] = useState3("");
650
+ const [sort, setSort] = useState3("featured");
651
+ const [keyInput, setKeyInput] = useState3({ scope, value: "" });
652
+ const apiKey = keyInput.scope === scope ? keyInput.value : "";
653
+ const setApiKey = (value) => setKeyInput({ scope, value });
654
+ const [metadataInput, setMetadataInput] = useState3({ scope, value: void 0 });
655
+ const metadata = metadataInput.scope === scope ? metadataInput.value : void 0;
656
+ const setMetadata = (value) => setMetadataInput({ scope, value });
657
+ const [parameterInput, setParameterInput] = useState3({ scope, values: {} });
658
+ const parameters = parameterInput.scope === scope ? parameterInput.values : {};
659
+ const setParameters = (values) => setParameterInput({ scope, values });
660
+ useEffect3(() => {
661
+ setApiKey("");
662
+ setMetadata(void 0);
663
+ setParameters({});
664
+ }, [scope]);
665
+ const pending = hub.writeState.status === "pending" || hub.connectStatus.status === "pending";
666
+ const error = hub.providers.status === "error" ? hub.providers.message : hub.connections.status === "error" ? hub.connections.message : null;
667
+ const mutationError = hub.writeState.status === "failed" ? hub.writeState.message : null;
668
+ const writeMessage = hub.writeState.status === "succeeded" ? hub.writeState.value.message : null;
669
+ const writeWarning = hub.writeState.status === "succeeded" && hub.writeState.value.reconciliation === "refresh-failed";
670
+ const selectedRow = hub.rows.find((row) => row.providerId === hub.provider?.providerId);
671
+ const detailError = hub.detail.status === "error" ? hub.detail.message : hub.detail.status === "ready" && hub.detail.value.truncated ? `Showing at most ${hub.detail.value.tools.length} actions. The provider catalog may be incomplete.` : null;
672
+ const detailsByConnectionId = useMemo2(() => hub.connection ? {
673
+ [hub.connection.id]: {
674
+ ...hub.details,
675
+ loading: hub.detail.status === "loading",
676
+ busy: pending,
677
+ error: detailError
678
+ }
679
+ } : {}, [hub.connection, hub.details, hub.detail.status, pending, detailError]);
680
+ const closeDialog = () => {
681
+ if (hub.connectStatus.status === "pending") hub.cancelConnect();
682
+ else hub.setDialog(null);
683
+ setApiKey("");
684
+ setMetadata(void 0);
685
+ setParameters({});
686
+ };
687
+ return /* @__PURE__ */ jsxs2("section", { className: props.className, children: [
688
+ hub.connectStatus.status === "pending" ? /* @__PURE__ */ jsxs2("div", { role: "status", className: "mb-4 flex flex-wrap items-center gap-3", children: [
689
+ /* @__PURE__ */ jsx2("span", { children: "Finish connecting in the popup." }),
690
+ /* @__PURE__ */ jsx2(Button, { type: "button", variant: "outline", onClick: hub.cancelConnect, children: "Cancel connection" })
691
+ ] }) : null,
692
+ hub.writeState.status === "pending" ? /* @__PURE__ */ jsx2("p", { role: "status", children: "Saving Hub settings\u2026" }) : null,
693
+ mutationError ? /* @__PURE__ */ jsx2("p", { role: "alert", children: mutationError }) : null,
694
+ writeMessage ? /* @__PURE__ */ jsx2("p", { role: writeWarning ? "alert" : "status", children: writeMessage }) : null,
695
+ hub.connectStatus.message && hub.provider ? /* @__PURE__ */ jsx2("p", { role: hub.connectStatus.status === "failed" ? "alert" : "status", children: hub.connectStatus.message }) : null,
696
+ hub.provider ? /* @__PURE__ */ jsxs2(Fragment, { children: [
697
+ selectedRow?.canConnect ? /* @__PURE__ */ jsx2("div", { className: "mb-4 flex justify-end", children: /* @__PURE__ */ jsx2(
698
+ Button,
699
+ {
700
+ type: "button",
701
+ variant: "outline",
702
+ disabled: pending,
703
+ onClick: () => hub.beginConnect(hub.provider),
704
+ children: "Connect another account"
705
+ }
706
+ ) }) : null,
707
+ /* @__PURE__ */ jsx2(
708
+ IntegrationConnectionDetail,
709
+ {
710
+ provider: displayProvider(hub.provider),
711
+ connections: selectedRow?.connections ?? [],
712
+ selectedConnectionId: hub.connection?.id ?? null,
713
+ onSelectConnection: (connectionId) => hub.selectConnection(hub.provider.providerId, connectionId),
714
+ detailsByConnectionId,
715
+ loading: hub.connections.status === "loading" || hub.detail.status === "loading",
716
+ error: detailError,
717
+ backHref: catalogHref(),
718
+ onRetry: () => hub.refresh(),
719
+ onTestConnection: (connectionId) => {
720
+ void hub.test(connectionId);
721
+ },
722
+ onDisconnect: (connectionId) => {
723
+ void hub.revoke(connectionId);
724
+ },
725
+ onDecisionChange: (connectionId, actionPath, decision) => {
726
+ if (decision !== "allow" && decision !== "ask" && decision !== "deny") return;
727
+ void hub.setDecision(connectionId, actionPath, decision);
728
+ },
729
+ onResetDecision: (connectionId, actionPath) => {
730
+ void hub.resetDecision(connectionId, actionPath);
731
+ }
732
+ }
733
+ )
734
+ ] }) : /* @__PURE__ */ jsx2(
735
+ IntegrationsCatalog,
736
+ {
737
+ title: props.title ?? "Integrations",
738
+ rows: hub.rows,
739
+ query,
740
+ onQueryChange: setQuery,
741
+ categoryFilter: category,
742
+ onCategoryFilterChange: setCategory,
743
+ sort,
744
+ onSortChange: setSort,
745
+ onSelectConnection: (providerId, connectionId) => hub.selectConnection(providerId, connectionId),
746
+ onConnect: (row) => {
747
+ const provider = hub.providers.status === "ready" ? hub.providers.value.find((item) => item.providerId === row.providerId) : null;
748
+ if (provider) hub.beginConnect(provider);
749
+ },
750
+ onManage: (connection, row) => hub.selectConnection(row.providerId, connection.id),
751
+ onDisconnect: (connection) => {
752
+ void hub.revoke(connection.id);
753
+ },
754
+ onRequestIntegration: props.onRequestIntegration,
755
+ onRetry: () => hub.refresh(),
756
+ loading: hub.providers.status === "loading" || hub.connections.status === "loading",
757
+ error,
758
+ actionError: mutationError,
759
+ connectError: hub.connectStatus.status === "failed" ? hub.connectStatus.message : null,
760
+ busyProviderId: hub.connectStatus.status === "pending" ? hub.connectStatus.providerId ?? null : null,
761
+ reserveConnectionContext: true
762
+ }
763
+ ),
764
+ hub.dialog?.kind === "api-key" ? /* @__PURE__ */ jsx2(
765
+ ApiKeyConnectDialog,
766
+ {
767
+ open: true,
768
+ onOpenChange: (open) => {
769
+ if (!open) closeDialog();
770
+ },
771
+ providerId: hub.dialog.provider.providerId,
772
+ title: hub.dialog.provider.title,
773
+ description: hub.dialog.provider.authHint,
774
+ value: apiKey,
775
+ onValueChange: setApiKey,
776
+ busy: pending,
777
+ error: mutationError,
778
+ canSubmit: apiKey.trim().length > 0 && !pending,
779
+ onSubmit: () => {
780
+ const secret = apiKey;
781
+ const target = hub.dialog?.provider.providerId;
782
+ const submittedDialog = hub.dialog;
783
+ setApiKey("");
784
+ if (target) void hub.submitApiKey(target, secret, metadata).then((result) => {
785
+ if (result.succeeded && activeScope.current === scope && activeDialog.current === submittedDialog) {
786
+ hub.setDialog(null);
787
+ setMetadata(void 0);
788
+ }
789
+ });
790
+ },
791
+ children: props.renderApiKeyMetadata?.({ provider: hub.dialog.provider, value: metadata, onChange: setMetadata })
792
+ }
793
+ ) : null,
794
+ hub.dialog?.kind === "oauth" ? /* @__PURE__ */ jsx2(
795
+ OAuthConnectionParameterDialog,
796
+ {
797
+ open: true,
798
+ onOpenChange: (open) => {
799
+ if (!open) closeDialog();
800
+ },
801
+ providerId: hub.dialog.provider.providerId,
802
+ title: hub.dialog.provider.title,
803
+ parameters: hub.dialog.provider.connectionParameters ?? [],
804
+ values: parameters,
805
+ onValueChange: (key, value) => setParameters({ ...parameters, [key]: value }),
806
+ busy: pending,
807
+ error: hub.connectStatus.status === "failed" ? hub.connectStatus.message : null,
808
+ canSubmit: !pending && (hub.dialog.provider.connectionParameters ?? []).every((field) => !field.required || !!parameters[field.key]?.trim()),
809
+ onSubmit: () => {
810
+ const target = hub.dialog?.provider;
811
+ const submittedDialog = hub.dialog;
812
+ if (target) void hub.startOAuth(target, parameters).then((result) => {
813
+ if (result === "connected" && activeScope.current === scope && activeDialog.current === submittedDialog) setParameters({});
814
+ });
815
+ }
816
+ }
817
+ ) : null
818
+ ] });
819
+ }
820
+ export {
821
+ HUB_CONNECTED_MESSAGE_TYPE,
822
+ HUB_CONNECT_CHANNEL,
823
+ HUB_CONNECT_FAILED_MESSAGE_TYPE,
824
+ HubConnectCallbackPage,
825
+ HubIntegrationsPanel,
826
+ POPUP_TIMEOUT_MS,
827
+ createHubIntegrationsClient,
828
+ useHubIntegrations
829
+ };
830
+ //# sourceMappingURL=index.js.map