@opengeni/react 3.3.2 → 3.7.0-canary.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 (79) hide show
  1. package/dist/artifacts.d.ts +1 -1
  2. package/dist/artifacts.js +241 -18
  3. package/dist/artifacts.js.map +1 -1
  4. package/dist/{browser-viewer-MKKFRRRV.js → browser-viewer-E5DDEFQ4.js} +3 -3
  5. package/dist/{chunk-2DZVYHVO.js → chunk-4JFUT22W.js} +39 -13
  6. package/dist/chunk-4JFUT22W.js.map +1 -0
  7. package/dist/{chunk-ELIYWBZR.js → chunk-BV5A4OTE.js} +4 -4
  8. package/dist/{chunk-3AGBGTRT.js → chunk-C6WDLHBA.js} +148 -26
  9. package/dist/chunk-C6WDLHBA.js.map +1 -0
  10. package/dist/{chunk-YG4QEQF5.js → chunk-DOK4KZF2.js} +7863 -7736
  11. package/dist/chunk-DOK4KZF2.js.map +1 -0
  12. package/dist/{chunk-JAQ5K7W6.js → chunk-FJBOU2TH.js} +167 -58
  13. package/dist/chunk-FJBOU2TH.js.map +1 -0
  14. package/dist/{chunk-XYRDDSXF.js → chunk-R55HFTT3.js} +80 -34
  15. package/dist/chunk-R55HFTT3.js.map +1 -0
  16. package/dist/{chunk-ZPBTI3TE.js → chunk-W2RGYBCV.js} +4 -4
  17. package/dist/{chunk-WSK7G5LE.js → chunk-W3OUAH6M.js} +80 -80
  18. package/dist/chunk-W3OUAH6M.js.map +1 -0
  19. package/dist/{chunk-X4A66EWZ.js → chunk-WMGF4Z7X.js} +41 -43
  20. package/dist/chunk-WMGF4Z7X.js.map +1 -0
  21. package/dist/client.d.ts +1 -1
  22. package/dist/components/artifacts/index.d.ts +1 -1
  23. package/dist/components/artifacts/published-html-artifact-frame.d.ts +45 -3
  24. package/dist/components/composer.d.ts +2 -0
  25. package/dist/components/session-chrome.d.ts +1 -1
  26. package/dist/composer.js +4 -4
  27. package/dist/{computer-viewer-FWEZISW4.js → computer-viewer-7TEZC6Y2.js} +3 -3
  28. package/dist/{fleet-decision-row-GGCAT4E4.js → fleet-decision-row-YZ3ZKWMM.js} +2 -1
  29. package/dist/fleet-decision-row-YZ3ZKWMM.js.map +1 -0
  30. package/dist/hooks/use-file-attachments.d.ts +8 -0
  31. package/dist/hooks/use-sandbox-files.d.ts +4 -1
  32. package/dist/hooks/use-session-events.d.ts +1 -1
  33. package/dist/hooks/use-workspace-edit.d.ts +4 -0
  34. package/dist/index.js +195 -141
  35. package/dist/index.js.map +1 -1
  36. package/dist/interaction.js +3 -3
  37. package/dist/model-policy.d.ts +2 -1
  38. package/dist/model-policy.js +1 -1
  39. package/dist/{queue-surface-implementation-BSKUWHRI.js → queue-surface-implementation-XL2A6PBM.js} +2 -2
  40. package/dist/realtime.js +2 -2
  41. package/dist/session-ui.js +6 -6
  42. package/dist/session.js +4 -4
  43. package/dist/timeline/registry.d.ts +2 -0
  44. package/dist/timeline/types.d.ts +3 -1
  45. package/package.json +2 -2
  46. package/src/artifacts.ts +3 -0
  47. package/src/client.ts +2 -1
  48. package/src/components/artifacts/index.ts +3 -0
  49. package/src/components/artifacts/published-html-artifact-frame.tsx +284 -4
  50. package/src/components/composer.tsx +103 -29
  51. package/src/components/message-timeline.tsx +48 -10
  52. package/src/components/model-policy-picker.tsx +37 -10
  53. package/src/components/sandbox-workspace.tsx +18 -7
  54. package/src/components/session-chrome.tsx +3 -3
  55. package/src/hooks/use-file-attachments.ts +62 -2
  56. package/src/hooks/use-sandbox-files.ts +68 -20
  57. package/src/hooks/use-session-events.ts +176 -21
  58. package/src/hooks/use-workspace-edit.ts +23 -5
  59. package/src/model-policy.ts +48 -53
  60. package/src/timeline/fleet-decision-projection.ts +2 -1
  61. package/src/timeline/fleet-decision-row.tsx +1 -0
  62. package/src/timeline/projection.ts +157 -8
  63. package/src/timeline/registry.ts +15 -3
  64. package/src/timeline/tool-renderers.tsx +117 -1
  65. package/src/timeline/types.ts +10 -1
  66. package/styles/compiled.css +5 -0
  67. package/dist/chunk-2DZVYHVO.js.map +0 -1
  68. package/dist/chunk-3AGBGTRT.js.map +0 -1
  69. package/dist/chunk-JAQ5K7W6.js.map +0 -1
  70. package/dist/chunk-WSK7G5LE.js.map +0 -1
  71. package/dist/chunk-X4A66EWZ.js.map +0 -1
  72. package/dist/chunk-XYRDDSXF.js.map +0 -1
  73. package/dist/chunk-YG4QEQF5.js.map +0 -1
  74. package/dist/fleet-decision-row-GGCAT4E4.js.map +0 -1
  75. /package/dist/{browser-viewer-MKKFRRRV.js.map → browser-viewer-E5DDEFQ4.js.map} +0 -0
  76. /package/dist/{chunk-ELIYWBZR.js.map → chunk-BV5A4OTE.js.map} +0 -0
  77. /package/dist/{chunk-ZPBTI3TE.js.map → chunk-W2RGYBCV.js.map} +0 -0
  78. /package/dist/{computer-viewer-FWEZISW4.js.map → computer-viewer-7TEZC6Y2.js.map} +0 -0
  79. /package/dist/{queue-surface-implementation-BSKUWHRI.js.map → queue-surface-implementation-XL2A6PBM.js.map} +0 -0
@@ -7,19 +7,20 @@ import {
7
7
  useBrowserSession,
8
8
  useBrowserSessions,
9
9
  useSiteAuthConnections
10
- } from "./chunk-ZPBTI3TE.js";
10
+ } from "./chunk-W2RGYBCV.js";
11
11
  import {
12
12
  ComputerViewer,
13
13
  useComputerFrameStream,
14
14
  useComputerSession,
15
15
  useComputerSessions
16
- } from "./chunk-ELIYWBZR.js";
16
+ } from "./chunk-BV5A4OTE.js";
17
17
  import {
18
18
  useInteractionInterventions,
19
19
  useInteractionInvalidation
20
20
  } from "./chunk-H5YGYNXS.js";
21
21
  import "./chunk-4MDLEHXL.js";
22
22
  import "./chunk-5YK2ZDIG.js";
23
+ import "./chunk-JVYQRRC4.js";
23
24
  import "./chunk-KZ73RL76.js";
24
25
  import {
25
26
  useEmbeddedBrowserInteraction,
@@ -27,7 +28,6 @@ import {
27
28
  useEmbeddedInteraction,
28
29
  useEmbeddedInterventions
29
30
  } from "./chunk-NEXLLTP4.js";
30
- import "./chunk-JVYQRRC4.js";
31
31
  import "./chunk-VTOREEXF.js";
32
32
  import "./chunk-22KP6LR5.js";
33
33
 
@@ -1,5 +1,6 @@
1
+ import { type ModelPickerBillingClass } from "@opengeni/sdk/model-picker-order";
1
2
  import type { ClientModel, ReasoningEffort, WorkspaceModelCatalogModel } from "@opengeni/sdk";
2
- export type PickerBillingClass = "opengeni_credits" | "external" | "codex_subscription" | "supergrok_subscription" | "byok";
3
+ export type PickerBillingClass = ModelPickerBillingClass;
3
4
  export type PickerModelRow<TCatalog extends ClientModel = WorkspaceModelCatalogModel> = {
4
5
  id: string;
5
6
  label: string;
@@ -15,7 +15,7 @@ import {
15
15
  projectPickerRows,
16
16
  runnableLatencyModesForModel,
17
17
  sortPickerRows
18
- } from "./chunk-X4A66EWZ.js";
18
+ } from "./chunk-WMGF4Z7X.js";
19
19
  export {
20
20
  advancedSourceSummary,
21
21
  availabilityReasonLabel,
@@ -3,7 +3,7 @@ import {
3
3
  QueueStoppingStatus,
4
4
  TimelineAnnotationsChip,
5
5
  requestQueueDraftEdit
6
- } from "./chunk-WSK7G5LE.js";
6
+ } from "./chunk-W3OUAH6M.js";
7
7
  import {
8
8
  usePortalTokenSource,
9
9
  usePortalTokenStyle
@@ -1047,4 +1047,4 @@ export {
1047
1047
  QueueSurface,
1048
1048
  queueComposerCheckoutEnabled
1049
1049
  };
1050
- //# sourceMappingURL=queue-surface-implementation-BSKUWHRI.js.map
1050
+ //# sourceMappingURL=queue-surface-implementation-XL2A6PBM.js.map
package/dist/realtime.js CHANGED
@@ -3,8 +3,7 @@ import {
3
3
  PickerAnimatedPage,
4
4
  PickerBackHeader,
5
5
  PickerNavRow
6
- } from "./chunk-2DZVYHVO.js";
7
- import "./chunk-X4A66EWZ.js";
6
+ } from "./chunk-4JFUT22W.js";
8
7
  import {
9
8
  usePortalTokenSource,
10
9
  usePortalTokenStyle
@@ -12,6 +11,7 @@ import {
12
11
  import {
13
12
  useEmbeddedRealtimeSession
14
13
  } from "./chunk-NEXLLTP4.js";
14
+ import "./chunk-WMGF4Z7X.js";
15
15
  import {
16
16
  cn
17
17
  } from "./chunk-22KP6LR5.js";
@@ -11,14 +11,14 @@ import {
11
11
  sessionChromeGoalPillLabel,
12
12
  sessionChromeGoalPillState,
13
13
  userMessageLikelyNeedsDisclosure
14
- } from "./chunk-YG4QEQF5.js";
15
- import {
16
- createOlderHistoryLoadReceipt
17
- } from "./chunk-JAQ5K7W6.js";
18
- import "./chunk-WSK7G5LE.js";
14
+ } from "./chunk-DOK4KZF2.js";
15
+ import "./chunk-W3OUAH6M.js";
16
+ import "./chunk-JVYQRRC4.js";
19
17
  import "./chunk-7EAFGICR.js";
20
18
  import "./chunk-VZTQ73XT.js";
21
- import "./chunk-JVYQRRC4.js";
19
+ import {
20
+ createOlderHistoryLoadReceipt
21
+ } from "./chunk-FJBOU2TH.js";
22
22
  import "./chunk-VTOREEXF.js";
23
23
  import "./chunk-22KP6LR5.js";
24
24
  export {
package/dist/session.js CHANGED
@@ -17,7 +17,7 @@ import {
17
17
  useSessionLineage,
18
18
  useSessionMcpApprovalPolicy,
19
19
  useTurnQueue
20
- } from "./chunk-3AGBGTRT.js";
20
+ } from "./chunk-C6WDLHBA.js";
21
21
  import {
22
22
  FILE_ONLY_MESSAGE_TEXT,
23
23
  composeSendInput,
@@ -25,6 +25,8 @@ import {
25
25
  shouldSubmitOnKey,
26
26
  useComposer
27
27
  } from "./chunk-IOLVN74D.js";
28
+ import "./chunk-KZ73RL76.js";
29
+ import "./chunk-NEXLLTP4.js";
28
30
  import {
29
31
  buildTimeline,
30
32
  createOlderHistoryLoadReceipt,
@@ -35,9 +37,7 @@ import {
35
37
  projectPendingHumanInputRequests,
36
38
  sessionStatusFromEvents,
37
39
  toolDisplayName
38
- } from "./chunk-JAQ5K7W6.js";
39
- import "./chunk-KZ73RL76.js";
40
- import "./chunk-NEXLLTP4.js";
40
+ } from "./chunk-FJBOU2TH.js";
41
41
  import "./chunk-VTOREEXF.js";
42
42
  export {
43
43
  FILE_ONLY_MESSAGE_TEXT,
@@ -22,6 +22,8 @@ export type ToolRegistryEntry = {
22
22
  match: "name";
23
23
  name: string;
24
24
  render: ToolRenderer;
25
+ /** Disable untrusted `<server>__${name}` leaf matching for identity-sensitive renderers. */
26
+ matchPrefixedLeaf?: boolean | undefined;
25
27
  };
26
28
  export type ToolRegistry = {
27
29
  /** Resolve the renderer for a call (never null — falls back to generic). */
@@ -228,7 +228,7 @@ export type FleetDecisionItem = {
228
228
  policyVersion: "adaptive-shadow-v1";
229
229
  actualOutcome: "selected" | "waiting" | "none";
230
230
  actualCandidateKey: string | null;
231
- actualReason: "lease_reused" | "pin" | "rotation" | "active" | "all_capped" | "none";
231
+ actualReason: "lease_reused" | "pin" | "rotation" | "active" | "all_capped" | "allocator_disabled" | "none";
232
232
  shadowOutcome: "selected" | "paced" | "none";
233
233
  shadowCandidateKey: string | null;
234
234
  shadowReason: "fenced_in_flight" | "fenced_candidate_missing" | "admission_paced" | "no_eligible_candidate" | "overlay_isolated_empty" | "best_score" | "affinity_best" | "hysteresis_hold";
@@ -332,6 +332,8 @@ export type AuthNeededItem = {
332
332
  providerDomain: string;
333
333
  /** The lapsed connection to reconnect, when the row survived. */
334
334
  connectionId: string | null;
335
+ /** Host-owned bindings must never be routed into OpenGeni's native reconnect flow. */
336
+ authoritySource?: ToolAuthNeededPayload["authoritySource"] | null | undefined;
335
337
  reason: ToolAuthNeededPayload["reason"] | null;
336
338
  /** Scopes the provider now needs; may inform the copy, never shown as a raw label. */
337
339
  scopes: string[];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opengeni/react",
3
- "version": "3.3.2",
3
+ "version": "3.7.0-canary.0",
4
4
  "description": "React hooks and styled components for OpenGeni: live session streaming, chat composer, message timeline, session status, and fleet views — token-themed (CSS variables), dark-first, built on Tailwind v4 + Radix + Motion.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -120,7 +120,7 @@
120
120
  "@dnd-kit/utilities": "3.2.2",
121
121
  "@fontsource-variable/noto-sans-arabic": "5.2.10",
122
122
  "@fontsource-variable/noto-sans-jp": "5.2.10",
123
- "@opengeni/sdk": "^3.3.2",
123
+ "@opengeni/sdk": "^3.7.0-canary.0",
124
124
  "clsx": "^2.1.1",
125
125
  "dequal": "2.0.3",
126
126
  "lucide-react": "^1.8.0",
package/src/artifacts.ts CHANGED
@@ -18,6 +18,8 @@ export {
18
18
  PresentationProjectionEditor,
19
19
  PublishedHtmlArtifactFrame,
20
20
  PUBLISHED_HTML_ARTIFACT_IFRAME_SANDBOX,
21
+ openGeniSiteBridgePortFromBootstrap,
22
+ publishedHtmlArtifactDocument,
21
23
  SpreadsheetArtifactSurface,
22
24
  SpreadsheetGrid,
23
25
  SpreadsheetProjectionGrid,
@@ -62,6 +64,7 @@ export {
62
64
  type PresentationProjectionConnector,
63
65
  type PresentationProjectionEditorProps,
64
66
  type PublishedHtmlArtifactFrameProps,
67
+ type PublishedHtmlArtifactToolBridge,
65
68
  type PresentationProjectionElementMetadata,
66
69
  type PresentationProjectionElement,
67
70
  type PresentationProjectionFill,
package/src/client.ts CHANGED
@@ -246,7 +246,8 @@ export type EmbeddedSessionLineageClientLike = EmbeddedSessionEventClientLike &
246
246
  Pick<OpenGeniClient, "getSessionLineage">;
247
247
 
248
248
  /** Exact client surface required by {@link useFileAttachments}. */
249
- export type EmbeddedFileAttachmentClientLike = Pick<OpenGeniClient, "uploadFile">;
249
+ export type EmbeddedFileAttachmentClientLike = Pick<OpenGeniClient, "uploadFile"> &
250
+ Partial<Pick<OpenGeniClient, "createFileDownloadUrl">>;
250
251
 
251
252
  /** Exact client surface required by structured human-input hooks. */
252
253
  export type EmbeddedHumanInputSessionClientLike = EmbeddedSessionEventClientLike &
@@ -6,7 +6,10 @@ export {
6
6
  export {
7
7
  PUBLISHED_HTML_ARTIFACT_IFRAME_SANDBOX,
8
8
  PublishedHtmlArtifactFrame,
9
+ openGeniSiteBridgePortFromBootstrap,
10
+ publishedHtmlArtifactDocument,
9
11
  type PublishedHtmlArtifactFrameProps,
12
+ type PublishedHtmlArtifactToolBridge,
10
13
  } from "./published-html-artifact-frame";
11
14
  export {
12
15
  SpreadsheetArtifactSurface,
@@ -1,4 +1,21 @@
1
- import type { CSSProperties } from "react";
1
+ import {
2
+ OPENGENI_SITE_BRIDGE_BOOTSTRAP_GLOBAL,
3
+ OPENGENI_SITE_BRIDGE_READY,
4
+ OPENGENI_SITE_BRIDGE_RESPONSE,
5
+ OPENGENI_SITE_BRIDGE_VERSION,
6
+ isOpenGeniSiteBridgeCancelMessage,
7
+ isOpenGeniSiteBridgeConnectMessage,
8
+ isOpenGeniSiteBridgeRequestMessage,
9
+ sanitizeOpenGeniSiteToolCallRequest,
10
+ type OpenGeniSiteBridgeResponseMessage,
11
+ type OpenGeniSiteToolCatalog,
12
+ } from "@opengeni/sdk/site";
13
+ import type {
14
+ ToolGatewayCallRequest,
15
+ ToolGatewayCallResponse,
16
+ ToolGatewayDeclarationsResponse,
17
+ } from "@opengeni/sdk";
18
+ import { useEffect, useRef, type CSSProperties } from "react";
2
19
 
3
20
  export const PUBLISHED_HTML_ARTIFACT_IFRAME_SANDBOX = [
4
21
  "allow-downloads",
@@ -17,22 +34,285 @@ export type PublishedHtmlArtifactFrameProps = {
17
34
  title: string;
18
35
  className?: string;
19
36
  style?: CSSProperties;
37
+ toolBridge?: PublishedHtmlArtifactToolBridge;
20
38
  };
21
39
 
40
+ export type PublishedHtmlArtifactToolBridge = {
41
+ catalog: (options: { signal: AbortSignal }) => Promise<OpenGeniSiteToolCatalog>;
42
+ call: (
43
+ request: ToolGatewayCallRequest,
44
+ options: { signal: AbortSignal },
45
+ ) => Promise<ToolGatewayCallResponse>;
46
+ declarations?: (options: { signal: AbortSignal }) => Promise<ToolGatewayDeclarationsResponse>;
47
+ };
48
+
49
+ const SITE_BRIDGE_BOOTSTRAP_SCRIPT = `<script>(()=>{const key=${JSON.stringify(
50
+ OPENGENI_SITE_BRIDGE_BOOTSTRAP_GLOBAL,
51
+ )};const parentWindow=window.parent;if(parentWindow===window)return;window.addEventListener("message",event=>{const data=event.data;if(event.source!==parentWindow||!data||data.type!==${JSON.stringify(
52
+ OPENGENI_SITE_BRIDGE_READY,
53
+ )}||data.version!==${OPENGENI_SITE_BRIDGE_VERSION}||event.ports.length!==1)return;const port=event.ports[0];const previous=window[key]?.port;if(previous&&previous!==port)previous.close();Object.defineProperty(window,key,{configurable:true,value:{port}});port.start();});})();</script>`;
54
+
55
+ export function publishedHtmlArtifactDocument(html: string, toolBridgeEnabled: boolean): string {
56
+ if (!toolBridgeEnabled) return html;
57
+ const doctypeEnd = leadingDoctypeEnd(html);
58
+ if (doctypeEnd >= 0) {
59
+ return `${html.slice(0, doctypeEnd + 1)}${SITE_BRIDGE_BOOTSTRAP_SCRIPT}${html.slice(doctypeEnd + 1)}`;
60
+ }
61
+ return `${SITE_BRIDGE_BOOTSTRAP_SCRIPT}${html}`;
62
+ }
63
+
64
+ function leadingDoctypeEnd(html: string): number {
65
+ const lower = html.toLowerCase();
66
+ let cursor = html.charCodeAt(0) === 0xfeff ? 1 : 0;
67
+ while (cursor < html.length) {
68
+ while (/\s/.test(html[cursor] ?? "")) cursor += 1;
69
+ if (!html.startsWith("<!--", cursor)) break;
70
+ const commentEnd = html.indexOf("-->", cursor + 4);
71
+ if (commentEnd < 0) return -1;
72
+ cursor = commentEnd + 3;
73
+ }
74
+ if (!lower.startsWith("<!doctype", cursor)) return -1;
75
+ return html.indexOf(">", cursor + 9);
76
+ }
77
+
22
78
  /**
23
79
  * Render exact published HTML in an opaque-origin iframe. Artifact scripts,
24
- * external resources, forms, popups, and downloads work without granting
25
- * parent-origin authority, shared cookies/storage, or top-level navigation.
80
+ * external resources, forms, popups, downloads, and the host-filtered tool
81
+ * bridge work without granting parent-origin authority, shared cookies/storage,
82
+ * or top-level navigation.
26
83
  */
27
84
  export function PublishedHtmlArtifactFrame(props: PublishedHtmlArtifactFrameProps) {
85
+ const frameRef = useRef<HTMLIFrameElement | null>(null);
86
+ const bridgeRef = useRef(props.toolBridge);
87
+ const onFrameLoadRef = useRef<() => void>(() => undefined);
88
+ const frameLoadPendingRef = useRef(false);
89
+ const toolBridgeEnabled = props.toolBridge !== undefined;
90
+ useEffect(() => {
91
+ bridgeRef.current = props.toolBridge;
92
+ }, [props.toolBridge]);
93
+ useEffect(() => {
94
+ if (!toolBridgeEnabled || typeof window === "undefined") return;
95
+ const requests = new SiteBridgeRequestRegistry();
96
+ const attachToolPort = (data: unknown, ports: readonly MessagePort[]) => {
97
+ const port = openGeniSiteBridgePortFromBootstrap(data, ports);
98
+ if (!port) return;
99
+ requests.replacePort(port);
100
+ port.addEventListener("message", (portEvent: MessageEvent<unknown>) => {
101
+ const message = portEvent.data;
102
+ if (isOpenGeniSiteBridgeCancelMessage(message)) {
103
+ requests.cancel(port, message.requestId);
104
+ return;
105
+ }
106
+ if (!isOpenGeniSiteBridgeRequestMessage(message)) return;
107
+ const controller = requests.start(port, message.requestId);
108
+ if (!controller) {
109
+ port.postMessage({
110
+ type: OPENGENI_SITE_BRIDGE_RESPONSE,
111
+ version: OPENGENI_SITE_BRIDGE_VERSION,
112
+ requestId: message.requestId,
113
+ ok: false,
114
+ error: {
115
+ code: "duplicate_request_id",
116
+ message: "A Site tool request with this id is already running",
117
+ retryable: false,
118
+ },
119
+ } satisfies OpenGeniSiteBridgeResponseMessage);
120
+ return;
121
+ }
122
+ void handleSiteBridgeRequest(bridgeRef.current, message, controller.signal)
123
+ .then((value) => {
124
+ if (!controller.signal.aborted) {
125
+ port.postMessage({
126
+ type: OPENGENI_SITE_BRIDGE_RESPONSE,
127
+ version: OPENGENI_SITE_BRIDGE_VERSION,
128
+ requestId: message.requestId,
129
+ ok: true,
130
+ value,
131
+ } satisfies OpenGeniSiteBridgeResponseMessage);
132
+ }
133
+ })
134
+ .catch((error) => {
135
+ if (!controller.signal.aborted) {
136
+ port.postMessage({
137
+ type: OPENGENI_SITE_BRIDGE_RESPONSE,
138
+ version: OPENGENI_SITE_BRIDGE_VERSION,
139
+ requestId: message.requestId,
140
+ ok: false,
141
+ error: siteBridgeError(error),
142
+ } satisfies OpenGeniSiteBridgeResponseMessage);
143
+ }
144
+ })
145
+ .finally(() => requests.complete(port, message.requestId, controller));
146
+ });
147
+ port.addEventListener("messageerror", () => requests.closePort(port));
148
+ port.start();
149
+ port.postMessage({
150
+ type: OPENGENI_SITE_BRIDGE_READY,
151
+ version: OPENGENI_SITE_BRIDGE_VERSION,
152
+ });
153
+ };
154
+ const documentLease = new SiteBridgeDocumentLease(attachToolPort, () => requests.closeAll());
155
+ const onFrameLoad = () => {
156
+ frameLoadPendingRef.current = false;
157
+ const frameWindow = frameRef.current?.contentWindow ?? null;
158
+ if (!frameWindow) return;
159
+ documentLease.load(frameWindow);
160
+ };
161
+ onFrameLoadRef.current = onFrameLoad;
162
+ if (frameLoadPendingRef.current) {
163
+ frameLoadPendingRef.current = false;
164
+ onFrameLoad();
165
+ }
166
+ return () => {
167
+ onFrameLoadRef.current = () => undefined;
168
+ documentLease.close();
169
+ };
170
+ }, [props.html, toolBridgeEnabled]);
28
171
  return (
29
172
  <iframe
173
+ ref={frameRef}
30
174
  title={props.title}
31
175
  sandbox={PUBLISHED_HTML_ARTIFACT_IFRAME_SANDBOX}
32
176
  referrerPolicy="no-referrer"
33
- srcDoc={props.html}
177
+ srcDoc={publishedHtmlArtifactDocument(props.html, toolBridgeEnabled)}
178
+ onLoad={() => {
179
+ frameLoadPendingRef.current = true;
180
+ onFrameLoadRef.current();
181
+ }}
34
182
  className={props.className}
35
183
  style={props.style}
36
184
  />
37
185
  );
38
186
  }
187
+
188
+ export class SiteBridgeRequestRegistry {
189
+ private readonly controllersByPort = new Map<MessagePort, Map<string, AbortController>>();
190
+
191
+ replacePort(port: MessagePort): void {
192
+ this.closeAll();
193
+ this.controllersByPort.set(port, new Map());
194
+ }
195
+
196
+ start(port: MessagePort, requestId: string): AbortController | null {
197
+ const controllers = this.controllersByPort.get(port);
198
+ if (!controllers || controllers.has(requestId)) return null;
199
+ const controller = new AbortController();
200
+ controllers.set(requestId, controller);
201
+ return controller;
202
+ }
203
+
204
+ cancel(port: MessagePort, requestId: string): void {
205
+ const controllers = this.controllersByPort.get(port);
206
+ const controller = controllers?.get(requestId);
207
+ if (!controller) return;
208
+ controller.abort(new Error("Site tool request cancelled"));
209
+ controllers!.delete(requestId);
210
+ }
211
+
212
+ complete(port: MessagePort, requestId: string, controller: AbortController): void {
213
+ const controllers = this.controllersByPort.get(port);
214
+ if (controllers?.get(requestId) === controller) controllers.delete(requestId);
215
+ }
216
+
217
+ closePort(port: MessagePort): void {
218
+ const controllers = this.controllersByPort.get(port);
219
+ if (!controllers) return;
220
+ for (const controller of controllers.values()) {
221
+ controller.abort(new Error("Site tool bridge port closed"));
222
+ }
223
+ controllers.clear();
224
+ this.controllersByPort.delete(port);
225
+ port.close();
226
+ }
227
+
228
+ closeAll(): void {
229
+ for (const port of [...this.controllersByPort.keys()]) this.closePort(port);
230
+ }
231
+ }
232
+
233
+ export class SiteBridgeDocumentLease {
234
+ private loaded = false;
235
+ private bootstrapPort: MessagePort | null = null;
236
+
237
+ constructor(
238
+ private readonly attachToolPort: (data: unknown, ports: readonly MessagePort[]) => void,
239
+ private readonly closeActivePorts: () => void,
240
+ private readonly createMessageChannel: () => MessageChannel = () => new MessageChannel(),
241
+ ) {}
242
+
243
+ load(frameWindow: Pick<Window, "postMessage">): boolean {
244
+ if (this.loaded) {
245
+ this.close();
246
+ return false;
247
+ }
248
+ this.loaded = true;
249
+ const channel = this.createMessageChannel();
250
+ this.bootstrapPort = channel.port1;
251
+ channel.port1.addEventListener("message", (event: MessageEvent<unknown>) => {
252
+ this.attachToolPort(event.data, event.ports);
253
+ });
254
+ channel.port1.start();
255
+ frameWindow.postMessage(
256
+ {
257
+ type: OPENGENI_SITE_BRIDGE_READY,
258
+ version: OPENGENI_SITE_BRIDGE_VERSION,
259
+ },
260
+ "*",
261
+ [channel.port2],
262
+ );
263
+ return true;
264
+ }
265
+
266
+ close(): void {
267
+ this.bootstrapPort?.close();
268
+ this.bootstrapPort = null;
269
+ this.closeActivePorts();
270
+ }
271
+ }
272
+
273
+ export function openGeniSiteBridgePortFromBootstrap(
274
+ data: unknown,
275
+ ports: readonly MessagePort[],
276
+ ): MessagePort | null {
277
+ if (!isOpenGeniSiteBridgeConnectMessage(data)) return null;
278
+ return ports.length === 1 ? ports[0]! : null;
279
+ }
280
+
281
+ async function handleSiteBridgeRequest(
282
+ bridge: PublishedHtmlArtifactToolBridge | undefined,
283
+ message: Parameters<typeof isOpenGeniSiteBridgeRequestMessage>[0] & {
284
+ method: "catalog" | "call" | "declarations";
285
+ requestId: string;
286
+ payload?: ToolGatewayCallRequest;
287
+ },
288
+ signal: AbortSignal,
289
+ ): Promise<OpenGeniSiteToolCatalog | ToolGatewayCallResponse | ToolGatewayDeclarationsResponse> {
290
+ if (!bridge) throw new Error("Site tool bridge is unavailable");
291
+ if (message.method === "catalog") return await bridge.catalog({ signal });
292
+ if (message.method === "declarations") {
293
+ if (!bridge.declarations) throw new Error("Site tool declarations are unavailable");
294
+ return await bridge.declarations({ signal });
295
+ }
296
+ return await bridge.call(sanitizeOpenGeniSiteToolCallRequest(message.payload!), { signal });
297
+ }
298
+
299
+ export function siteBridgeError(error: unknown): {
300
+ code: string;
301
+ message: string;
302
+ retryable: boolean;
303
+ outcomeUnknown: boolean;
304
+ } {
305
+ const candidate = error as {
306
+ code?: unknown;
307
+ message?: unknown;
308
+ retryable?: unknown;
309
+ outcomeUnknown?: unknown;
310
+ };
311
+ return {
312
+ code: typeof candidate?.code === "string" ? candidate.code : "site_tool_call_failed",
313
+ message:
314
+ typeof candidate?.message === "string" ? candidate.message : "Site tool request failed",
315
+ retryable: candidate?.retryable === true,
316
+ outcomeUnknown: candidate?.outcomeUnknown === true,
317
+ };
318
+ }