@botdojo/chat-sdk 0.0.31 → 0.0.32

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.
package/lib/index.d.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  import React$1 from 'react';
2
- import { RPCConnection } from 'botdojo-rpc';
3
2
  import * as react_jsx_runtime from 'react/jsx-runtime';
4
3
 
5
4
  /**
@@ -889,6 +888,52 @@ interface FlowRequestRecord {
889
888
  }
890
889
  type FlowResponse = FlowRequestRecord;
891
890
 
891
+ declare class ConectionOptions {
892
+ timeout?: number;
893
+ maxDepth?: number;
894
+ }
895
+ declare class CallbackHandlerMethods {
896
+ source: any;
897
+ func: any;
898
+ }
899
+ declare class RPCMessage {
900
+ id: string;
901
+ source: string;
902
+ destination: string;
903
+ direction: "request" | "response";
904
+ functionName: string;
905
+ data: any;
906
+ sendOnlyIfThereIsAListener?: boolean;
907
+ host_id: string;
908
+ /** Origin of the PostMessage (for CORS validation) */
909
+ origin?: string;
910
+ static request(source: string, destination: string, functionName: string, data: any): RPCMessage;
911
+ static response(msg: RPCMessage, data: any): RPCMessage;
912
+ constructor(source: string, destination: string, direction: "request" | "response", functionName: string, data: any);
913
+ }
914
+ interface IRPC_Client {
915
+ clientId: string;
916
+ defaultDestinationId: string;
917
+ onMessage: (message: RPCMessage) => Promise<void>;
918
+ onConnectionStatusChange?: (status: 'connected' | 'disconnected' | 'reconnecting' | 'reconnect_failed', reason?: string) => void;
919
+ init(): Promise<void>;
920
+ close(): Promise<void>;
921
+ sendMessage(message: RPCMessage): Promise<any>;
922
+ }
923
+ declare class RPCConnection {
924
+ sender: IRPC_Client;
925
+ options: ConectionOptions;
926
+ callbacks: Map<string, CallbackHandlerMethods>;
927
+ onMessage: (msg: RPCMessage) => Promise<any>;
928
+ constructor(sender: IRPC_Client, options: ConectionOptions, onMessage?: (msg: RPCMessage) => Promise<any>);
929
+ log(msg: string, data?: any, data2?: any): void;
930
+ init(): Promise<void>;
931
+ close(): void;
932
+ sendRequestToHost(functionName: string, data: Array<any> | any): Promise<any>;
933
+ sendRequest(destinationId: string, functionName: string, data: Array<any> | any, timeoutMs?: number): Promise<any>;
934
+ incommingMessage(msg: RPCMessage): void;
935
+ }
936
+
892
937
  /**
893
938
  * Configuration class for handling flow request events
894
939
  */
@@ -1342,6 +1387,15 @@ interface BotDojoChatProps {
1342
1387
  * - Set to avoid collisions when embedding multiple agents
1343
1388
  */
1344
1389
  sessionKeyPrefix?: string;
1390
+ /**
1391
+ * Keep the channel the agent uses to call this page's tools (modelContext) across reloads of the tab
1392
+ * - Defaults to true when modelContext is passed: a run that is still going keeps reaching this
1393
+ * page's tools after a reload or navigation
1394
+ * - The SDK makes a random ID per widget and browser tab, kept in sessionStorage; a tab opened
1395
+ * from this one gets its own
1396
+ * - Set false for a new channel on every mount
1397
+ */
1398
+ keepToolChannelAcrossReloads?: boolean;
1345
1399
  /**
1346
1400
  * Override the welcome message shown in the chat widget (supports markdown)
1347
1401
  */
@@ -1459,45 +1513,6 @@ interface BotDojoChatProps {
1459
1513
  */
1460
1514
  onUiMessage?: (message: string, params: any, appId: string) => void;
1461
1515
  }
1462
- /**
1463
- * BotDojoChat - Single unified React component for embedding BotDojo chat
1464
- *
1465
- * This component provides a complete solution for embedding BotDojo chat with:
1466
- * - Multiple display modes (popup, side panel, inline)
1467
- * - Optional model context integration for tools and resources
1468
- * - Automatic connector lifecycle management
1469
- * - PostMessage-based communication (no WebSocket needed)
1470
- *
1471
- * @example
1472
- * Basic usage (no tools):
1473
- * ```tsx
1474
- * <BotDojoChat
1475
- * apiKey="YOUR_API_KEY"
1476
- * mode="chat-popup"
1477
- * accentColor="#4a3ed4"
1478
- * />
1479
- * ```
1480
- *
1481
- * @example
1482
- * With model context and tools:
1483
- * ```tsx
1484
- * <BotDojoChat
1485
- * apiKey="YOUR_API_KEY"
1486
- * mode="chat-popup"
1487
- * modelContext={{
1488
- * name: 'myapp',
1489
- * description: 'My application',
1490
- * tools: {
1491
- * get_data: {
1492
- * description: 'Get data',
1493
- * parameters: { type: 'object', properties: {} },
1494
- * execute: async () => ({ data: 'Hello!' })
1495
- * }
1496
- * }
1497
- * }}
1498
- * />
1499
- * ```
1500
- */
1501
1516
  declare const BotDojoChat: React$1.FC<BotDojoChatProps>;
1502
1517
 
1503
1518
  /**
package/lib/index.js CHANGED
@@ -2796,6 +2796,146 @@ function processStepUpdate(stepUpdate) {
2796
2796
  }
2797
2797
  return notifications;
2798
2798
  }
2799
+
2800
+ // src/tab-channel/index.ts
2801
+ var pageChannels = /* @__PURE__ */ new WeakMap();
2802
+ var OWNER_PROBE_MS = 150;
2803
+ function openChannel(host, id) {
2804
+ try {
2805
+ return host.BroadcastChannel && new host.BroadcastChannel(`aries:channel:${id}`);
2806
+ } catch {
2807
+ }
2808
+ }
2809
+ function hasLiveOwner(host, channel) {
2810
+ return new Promise((resolve) => {
2811
+ const finish = (owned) => {
2812
+ host.clearTimeout(timeout);
2813
+ channel.onmessage = null;
2814
+ resolve(owned);
2815
+ };
2816
+ const timeout = host.setTimeout(() => finish(false), OWNER_PROBE_MS);
2817
+ channel.onmessage = (event) => {
2818
+ if (event.data === "owner")
2819
+ finish(true);
2820
+ };
2821
+ try {
2822
+ channel.postMessage("probe");
2823
+ } catch {
2824
+ finish(false);
2825
+ }
2826
+ });
2827
+ }
2828
+ function watchForCopies(host, id, channel) {
2829
+ const listen = (owner2) => {
2830
+ owner2.onmessage = (event) => {
2831
+ if (event.data === "probe")
2832
+ owner2.postMessage("owner");
2833
+ };
2834
+ return owner2;
2835
+ };
2836
+ let owner = listen(channel);
2837
+ host.addEventListener("pagehide", () => {
2838
+ owner == null ? void 0 : owner.close();
2839
+ owner = void 0;
2840
+ });
2841
+ host.addEventListener("pageshow", (event) => {
2842
+ if (!event.persisted || owner)
2843
+ return;
2844
+ const restored = openChannel(host, id);
2845
+ if (restored)
2846
+ owner = listen(restored);
2847
+ });
2848
+ }
2849
+ function newChannelId(host) {
2850
+ if (host.crypto.randomUUID)
2851
+ return host.crypto.randomUUID();
2852
+ const bytes = host.crypto.getRandomValues(new Uint8Array(16));
2853
+ bytes[6] = bytes[6] & 15 | 64;
2854
+ bytes[8] = bytes[8] & 63 | 128;
2855
+ const hex = encodeHex(bytes);
2856
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
2857
+ }
2858
+ function encodeHex(data) {
2859
+ return Array.from(data, (byte) => byte.toString(16).padStart(2, "0")).join("");
2860
+ }
2861
+ function createTabChannel(host, key) {
2862
+ let storage;
2863
+ let storedId;
2864
+ try {
2865
+ storage = host.sessionStorage;
2866
+ storedId = storage.getItem(key);
2867
+ } catch {
2868
+ return newChannelId(host);
2869
+ }
2870
+ const adopt = (id2, channel2) => {
2871
+ if (id2 !== storedId) {
2872
+ try {
2873
+ storage.setItem(key, id2);
2874
+ } catch {
2875
+ channel2 == null ? void 0 : channel2.close();
2876
+ return id2;
2877
+ }
2878
+ }
2879
+ if (channel2)
2880
+ watchForCopies(host, id2, channel2);
2881
+ return id2;
2882
+ };
2883
+ const id = storedId || newChannelId(host);
2884
+ const channel = openChannel(host, id);
2885
+ if (!storedId || !channel)
2886
+ return adopt(id, channel);
2887
+ return hasLiveOwner(host, channel).then((owned) => {
2888
+ if (!owned)
2889
+ return adopt(id, channel);
2890
+ channel.close();
2891
+ const next = newChannelId(host);
2892
+ return adopt(next, openChannel(host, next));
2893
+ });
2894
+ }
2895
+ function getTabChannelId(host, key) {
2896
+ let channels = pageChannels.get(host);
2897
+ if (!channels) {
2898
+ channels = /* @__PURE__ */ new Map();
2899
+ pageChannels.set(host, channels);
2900
+ }
2901
+ const existing = channels.get(key);
2902
+ if (existing)
2903
+ return existing;
2904
+ const channel = createTabChannel(host, key);
2905
+ channels.set(key, channel);
2906
+ return channel;
2907
+ }
2908
+ async function getEmbedTabChannelId(host, options) {
2909
+ const { embedOrigin, embedKey, instanceKey } = options;
2910
+ let keyDigest;
2911
+ if (embedKey) {
2912
+ try {
2913
+ const bytes = await host.crypto.subtle.digest("SHA-256", new TextEncoder().encode(embedKey));
2914
+ keyDigest = encodeHex(new Uint8Array(bytes));
2915
+ } catch {
2916
+ return newChannelId(host);
2917
+ }
2918
+ }
2919
+ return getTabChannelId(host, `botdojo:tab-channel:${JSON.stringify([embedOrigin, keyDigest, instanceKey])}`);
2920
+ }
2921
+ var widgetPositions = /* @__PURE__ */ new WeakMap();
2922
+ function useWidgetPosition() {
2923
+ const [position, setPosition] = useState(null);
2924
+ useEffect(() => {
2925
+ var _a;
2926
+ const used = (_a = widgetPositions.get(window)) != null ? _a : /* @__PURE__ */ new Set();
2927
+ widgetPositions.set(window, used);
2928
+ let next = 0;
2929
+ while (used.has(next))
2930
+ next++;
2931
+ used.add(next);
2932
+ setPosition(next);
2933
+ return () => {
2934
+ used.delete(next);
2935
+ };
2936
+ }, []);
2937
+ return position;
2938
+ }
2799
2939
  var BotDojoChat = ({
2800
2940
  apiKey,
2801
2941
  mode = "chat-popup",
@@ -2817,6 +2957,7 @@ var BotDojoChat = ({
2817
2957
  newSession = false,
2818
2958
  sessionId,
2819
2959
  sessionKeyPrefix,
2960
+ keepToolChannelAcrossReloads,
2820
2961
  welcomeMessage,
2821
2962
  autoFocus,
2822
2963
  allowMicrophone = false,
@@ -2973,6 +3114,28 @@ var BotDojoChat = ({
2973
3114
  }
2974
3115
  return "https://embed.botdojo.com";
2975
3116
  }, [baseUrl]);
3117
+ const keepToolChannel = keepToolChannelAcrossReloads !== false && hasModelContextContent;
3118
+ const widgetPosition = useWidgetPosition();
3119
+ const [keptChannelId, setKeptChannelId] = useState(null);
3120
+ useEffect(() => {
3121
+ if (!keepToolChannel || !iframeApiKey || keptChannelId || widgetPosition === null && !sessionKeyPrefix)
3122
+ return;
3123
+ let active = true;
3124
+ void getEmbedTabChannelId(window, {
3125
+ embedOrigin: getBaseUrl2().replace(/\/+$/, ""),
3126
+ embedKey: iframeApiKey,
3127
+ // Widgets sharing an embed key are told apart by sessionKeyPrefix, else by their place on the page.
3128
+ instanceKey: sessionKeyPrefix != null ? sessionKeyPrefix : `widget-${widgetPosition}`
3129
+ }).then((id) => {
3130
+ if (active)
3131
+ setKeptChannelId(id);
3132
+ });
3133
+ return () => {
3134
+ active = false;
3135
+ };
3136
+ }, [keepToolChannel, iframeApiKey, keptChannelId, getBaseUrl2, sessionKeyPrefix, widgetPosition]);
3137
+ const toolChannelId = keepToolChannel ? keptChannelId : null;
3138
+ const toolChannelReady = !keepToolChannel || !!keptChannelId;
2976
3139
  const hasEventCallbacks = !!(onReady || onError || onMessageStart || onMessageComplete || onStepUpdate || onToken || onSessionCreated || onSessionHydrated || onRequestAborted);
2977
3140
  const effectiveAutoFocus = autoFocus != null ? autoFocus : mode !== "inline";
2978
3141
  console.log("[BotDojoChat] hasEventCallbacks:", hasEventCallbacks, {
@@ -2981,7 +3144,7 @@ var BotDojoChat = ({
2981
3144
  onMessageStart: !!onMessageStart
2982
3145
  });
2983
3146
  const initialIframeUrlRef = useRef(null);
2984
- if (iframeApiKey && !initialIframeUrlRef.current) {
3147
+ if (iframeApiKey && toolChannelReady && !initialIframeUrlRef.current) {
2985
3148
  try {
2986
3149
  const base = `${getBaseUrl2()}/embed/chat?key=${encodeURIComponent(iframeApiKey)}`;
2987
3150
  const url = new URL(base);
@@ -3018,6 +3181,10 @@ var BotDojoChat = ({
3018
3181
  }
3019
3182
  url.searchParams.set("transport", "postmessage");
3020
3183
  url.searchParams.set("transport-mode", "iframe");
3184
+ if (toolChannelId)
3185
+ url.searchParams.set("external-ui-channel-id", toolChannelId);
3186
+ else
3187
+ url.searchParams.set("keep-tool-channel", "false");
3021
3188
  if (hasEventCallbacks) {
3022
3189
  url.searchParams.set("forward-events", "true");
3023
3190
  console.log("[BotDojoChat] Added forward-events=true to iframe URL");
@@ -3026,13 +3193,13 @@ var BotDojoChat = ({
3026
3193
  console.log("[BotDojoChat] iframeUrl (set once):", initialIframeUrlRef.current);
3027
3194
  } catch (error) {
3028
3195
  console.warn("[BotDojoChat] Error building iframe URL:", error);
3029
- initialIframeUrlRef.current = `${getBaseUrl2()}/embed/chat?key=${encodeURIComponent(iframeApiKey)}`;
3196
+ initialIframeUrlRef.current = `${getBaseUrl2()}/embed/chat?key=${encodeURIComponent(iframeApiKey)}${toolChannelId ? `&external-ui-channel-id=${encodeURIComponent(toolChannelId)}` : "&keep-tool-channel=false"}`;
3030
3197
  }
3031
3198
  }
3032
3199
  const iframeUrl = initialIframeUrlRef.current;
3033
3200
  const connectorInitializedRef = useRef(false);
3034
3201
  useEffect(() => {
3035
- if (connectorInitializedRef.current || !needsConnector || !apiKey) {
3202
+ if (connectorInitializedRef.current || !needsConnector || !apiKey || !toolChannelReady) {
3036
3203
  return;
3037
3204
  }
3038
3205
  let mounted = true;
@@ -3048,6 +3215,7 @@ var BotDojoChat = ({
3048
3215
  projectId: "embedded",
3049
3216
  flowId: "embedded",
3050
3217
  modelContext: modelContext2,
3218
+ ...toolChannelId ? { external_ui_channel_id: toolChannelId } : {},
3051
3219
  // Don't pass toolCalls - tools will be registered from modelContext with canvas metadata preserved
3052
3220
  transport: "postmessage"
3053
3221
  // CORS is extracted from modelContext.cors by the connector
@@ -3084,7 +3252,7 @@ var BotDojoChat = ({
3084
3252
  return () => {
3085
3253
  mounted = false;
3086
3254
  };
3087
- }, [needsConnector, apiKey]);
3255
+ }, [needsConnector, apiKey, toolChannelReady]);
3088
3256
  useEffect(() => {
3089
3257
  return () => {
3090
3258
  if (!connectorInitializedRef.current)
@@ -4354,7 +4522,7 @@ var BotDojoChat = ({
4354
4522
  );
4355
4523
  };
4356
4524
  const renderIframe = () => {
4357
- if (!iframeApiKey) {
4525
+ if (!iframeUrl) {
4358
4526
  return null;
4359
4527
  }
4360
4528
  if ((mode === "chat-popup" || mode === "side-panel" || mode === "side-push") && !isOpen && !iframeLoaded) {