@yourgpt/copilot-sdk 0.1.0 → 1.0.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.
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var chunk2ZCWVAAK_cjs = require('./chunk-2ZCWVAAK.cjs');
3
+ var chunk42YQ4ATO_cjs = require('./chunk-42YQ4ATO.cjs');
4
4
  var react = require('react');
5
5
  var jsxRuntime = require('react/jsx-runtime');
6
6
  var z = require('zod');
@@ -844,7 +844,7 @@ var AbstractAgentLoop = class {
844
844
  this._isProcessing = false;
845
845
  // Registered tools
846
846
  this.registeredTools = /* @__PURE__ */ new Map();
847
- // Pending approvals
847
+ // Pending approvals - resolve with approval result including extraData
848
848
  this.pendingApprovals = /* @__PURE__ */ new Map();
849
849
  this.config = config;
850
850
  this.callbacks = callbacks;
@@ -990,15 +990,18 @@ var AbstractAgentLoop = class {
990
990
  });
991
991
  return errorResult;
992
992
  }
993
+ let approvalData;
993
994
  if (tool.needsApproval && !this.config.autoApprove) {
994
- typeof tool.approvalMessage === "function" ? tool.approvalMessage(toolCall.args) : tool.approvalMessage;
995
+ const approvalMessage = typeof tool.approvalMessage === "function" ? tool.approvalMessage(toolCall.args) : tool.approvalMessage;
995
996
  execution.approvalStatus = "required";
997
+ execution.approvalMessage = approvalMessage;
996
998
  this.updateToolExecution(toolCall.id, {
997
- approvalStatus: "required"
999
+ approvalStatus: "required",
1000
+ approvalMessage
998
1001
  });
999
1002
  this.callbacks.onApprovalRequired?.(execution);
1000
- const approved = await this.waitForApproval(toolCall.id, execution);
1001
- if (!approved) {
1003
+ const approvalResult = await this.waitForApproval(toolCall.id, execution);
1004
+ if (!approvalResult.approved) {
1002
1005
  const rejectedResult = {
1003
1006
  toolCallId: toolCall.id,
1004
1007
  success: false,
@@ -1012,9 +1015,7 @@ var AbstractAgentLoop = class {
1012
1015
  });
1013
1016
  return rejectedResult;
1014
1017
  }
1015
- this.updateToolExecution(toolCall.id, {
1016
- approvalStatus: "approved"
1017
- });
1018
+ approvalData = approvalResult.extraData;
1018
1019
  }
1019
1020
  this.updateToolExecution(toolCall.id, { status: "executing" });
1020
1021
  try {
@@ -1022,7 +1023,8 @@ var AbstractAgentLoop = class {
1022
1023
  throw new Error(`Tool "${toolCall.name}" has no handler`);
1023
1024
  }
1024
1025
  const result = await tool.handler(toolCall.args, {
1025
- data: { toolCallId: toolCall.id }
1026
+ data: { toolCallId: toolCall.id },
1027
+ approvalData
1026
1028
  });
1027
1029
  this.updateToolExecution(toolCall.id, {
1028
1030
  status: "completed",
@@ -1056,6 +1058,7 @@ var AbstractAgentLoop = class {
1056
1058
  }
1057
1059
  /**
1058
1060
  * Wait for user approval
1061
+ * Returns approval result with optional extraData from user's action
1059
1062
  */
1060
1063
  waitForApproval(executionId, execution) {
1061
1064
  return new Promise((resolve) => {
@@ -1066,13 +1069,17 @@ var AbstractAgentLoop = class {
1066
1069
  // Actions (implements AgentLoopActions)
1067
1070
  // ============================================
1068
1071
  /**
1069
- * Approve a tool execution
1072
+ * Approve a tool execution with optional extra data
1070
1073
  */
1071
- approveToolExecution(executionId, _permissionLevel) {
1074
+ approveToolExecution(executionId, extraData, _permissionLevel) {
1072
1075
  const pending = this.pendingApprovals.get(executionId);
1073
1076
  if (pending) {
1074
- pending.resolve(true);
1077
+ pending.resolve({ approved: true, extraData });
1075
1078
  this.pendingApprovals.delete(executionId);
1079
+ this.updateToolExecution(executionId, {
1080
+ approvalStatus: "approved",
1081
+ approvalData: extraData
1082
+ });
1076
1083
  }
1077
1084
  }
1078
1085
  /**
@@ -1086,7 +1093,7 @@ var AbstractAgentLoop = class {
1086
1093
  error: reason
1087
1094
  });
1088
1095
  }
1089
- pending.resolve(false);
1096
+ pending.resolve({ approved: false });
1090
1097
  this.pendingApprovals.delete(executionId);
1091
1098
  }
1092
1099
  }
@@ -1130,8 +1137,8 @@ var AbstractAgentLoop = class {
1130
1137
  * Dispose of resources
1131
1138
  */
1132
1139
  dispose() {
1133
- for (const [id, pending] of this.pendingApprovals) {
1134
- pending.resolve(false);
1140
+ for (const [_id, pending] of this.pendingApprovals) {
1141
+ pending.resolve({ approved: false });
1135
1142
  }
1136
1143
  this.pendingApprovals.clear();
1137
1144
  this.registeredTools.clear();
@@ -1321,10 +1328,10 @@ var ChatWithTools = class {
1321
1328
  // Tool Approval
1322
1329
  // ============================================
1323
1330
  /**
1324
- * Approve a tool execution
1331
+ * Approve a tool execution with optional extra data
1325
1332
  */
1326
- approveToolExecution(id, permissionLevel) {
1327
- this.agentLoop.approveToolExecution(id, permissionLevel);
1333
+ approveToolExecution(id, extraData, permissionLevel) {
1334
+ this.agentLoop.approveToolExecution(id, extraData, permissionLevel);
1328
1335
  }
1329
1336
  /**
1330
1337
  * Reject a tool execution
@@ -1667,8 +1674,8 @@ function CopilotProvider({
1667
1674
  chatRef.current?.unregisterTool(name);
1668
1675
  }, []);
1669
1676
  const approveToolExecution = react.useCallback(
1670
- (id, permissionLevel) => {
1671
- chatRef.current?.approveToolExecution(id, permissionLevel);
1677
+ (id, extraData, permissionLevel) => {
1678
+ chatRef.current?.approveToolExecution(id, extraData, permissionLevel);
1672
1679
  },
1673
1680
  []
1674
1681
  );
@@ -1735,6 +1742,9 @@ function CopilotProvider({
1735
1742
  const clearMessages = react.useCallback(() => {
1736
1743
  chatRef.current?.clearMessages();
1737
1744
  }, []);
1745
+ const setMessages = react.useCallback((messages2) => {
1746
+ chatRef.current?.setMessages(messages2);
1747
+ }, []);
1738
1748
  const regenerate = react.useCallback(async (messageId) => {
1739
1749
  await chatRef.current?.regenerate(messageId);
1740
1750
  }, []);
@@ -1776,6 +1786,7 @@ function CopilotProvider({
1776
1786
  sendMessage,
1777
1787
  stop,
1778
1788
  clearMessages,
1789
+ setMessages,
1779
1790
  regenerate,
1780
1791
  // Tool execution
1781
1792
  registerTool,
@@ -1805,6 +1816,7 @@ function CopilotProvider({
1805
1816
  sendMessage,
1806
1817
  stop,
1807
1818
  clearMessages,
1819
+ setMessages,
1808
1820
  regenerate,
1809
1821
  registerTool,
1810
1822
  unregisterTool,
@@ -1918,17 +1930,17 @@ function useAITools(options = {}) {
1918
1930
  const rememberedConsentRef = react.useRef(/* @__PURE__ */ new Set());
1919
1931
  react.useEffect(() => {
1920
1932
  if (!autoStart || !isEnabled) return;
1921
- if (consoleCapture && !chunk2ZCWVAAK_cjs.isConsoleCaptureActive()) {
1922
- chunk2ZCWVAAK_cjs.startConsoleCapture(consoleOptions);
1933
+ if (consoleCapture && !chunk42YQ4ATO_cjs.isConsoleCaptureActive()) {
1934
+ chunk42YQ4ATO_cjs.startConsoleCapture(consoleOptions);
1923
1935
  setActiveCaptures((prev) => ({ ...prev, console: true }));
1924
1936
  }
1925
- if (network && !chunk2ZCWVAAK_cjs.isNetworkCaptureActive()) {
1926
- chunk2ZCWVAAK_cjs.startNetworkCapture(networkOptions);
1937
+ if (network && !chunk42YQ4ATO_cjs.isNetworkCaptureActive()) {
1938
+ chunk42YQ4ATO_cjs.startNetworkCapture(networkOptions);
1927
1939
  setActiveCaptures((prev) => ({ ...prev, network: true }));
1928
1940
  }
1929
1941
  return () => {
1930
- chunk2ZCWVAAK_cjs.stopConsoleCapture();
1931
- chunk2ZCWVAAK_cjs.stopNetworkCapture();
1942
+ chunk42YQ4ATO_cjs.stopConsoleCapture();
1943
+ chunk42YQ4ATO_cjs.stopNetworkCapture();
1932
1944
  };
1933
1945
  }, [
1934
1946
  autoStart,
@@ -1943,12 +1955,12 @@ function useAITools(options = {}) {
1943
1955
  if (!screenshot) {
1944
1956
  throw new Error("Screenshot capture is not enabled");
1945
1957
  }
1946
- if (!chunk2ZCWVAAK_cjs.isScreenshotSupported()) {
1958
+ if (!chunk42YQ4ATO_cjs.isScreenshotSupported()) {
1947
1959
  throw new Error(
1948
1960
  "Screenshot capture is not supported in this environment"
1949
1961
  );
1950
1962
  }
1951
- return chunk2ZCWVAAK_cjs.captureScreenshot({ ...screenshotOptions, ...opts });
1963
+ return chunk42YQ4ATO_cjs.captureScreenshot({ ...screenshotOptions, ...opts });
1952
1964
  },
1953
1965
  [screenshot, screenshotOptions]
1954
1966
  );
@@ -1957,7 +1969,7 @@ function useAITools(options = {}) {
1957
1969
  if (!consoleCapture) {
1958
1970
  return { logs: [], totalCaptured: 0 };
1959
1971
  }
1960
- return chunk2ZCWVAAK_cjs.getConsoleLogs({ ...consoleOptions, ...opts });
1972
+ return chunk42YQ4ATO_cjs.getConsoleLogs({ ...consoleOptions, ...opts });
1961
1973
  },
1962
1974
  [consoleCapture, consoleOptions]
1963
1975
  );
@@ -1966,7 +1978,7 @@ function useAITools(options = {}) {
1966
1978
  if (!network) {
1967
1979
  return { requests: [], totalCaptured: 0 };
1968
1980
  }
1969
- return chunk2ZCWVAAK_cjs.getNetworkRequests({ ...networkOptions, ...opts });
1981
+ return chunk42YQ4ATO_cjs.getNetworkRequests({ ...networkOptions, ...opts });
1970
1982
  },
1971
1983
  [network, networkOptions]
1972
1984
  );
@@ -2059,23 +2071,23 @@ function useAITools(options = {}) {
2059
2071
  ]
2060
2072
  );
2061
2073
  const startCapturing = react.useCallback(() => {
2062
- if (consoleCapture && !chunk2ZCWVAAK_cjs.isConsoleCaptureActive()) {
2063
- chunk2ZCWVAAK_cjs.startConsoleCapture(consoleOptions);
2074
+ if (consoleCapture && !chunk42YQ4ATO_cjs.isConsoleCaptureActive()) {
2075
+ chunk42YQ4ATO_cjs.startConsoleCapture(consoleOptions);
2064
2076
  setActiveCaptures((prev) => ({ ...prev, console: true }));
2065
2077
  }
2066
- if (network && !chunk2ZCWVAAK_cjs.isNetworkCaptureActive()) {
2067
- chunk2ZCWVAAK_cjs.startNetworkCapture(networkOptions);
2078
+ if (network && !chunk42YQ4ATO_cjs.isNetworkCaptureActive()) {
2079
+ chunk42YQ4ATO_cjs.startNetworkCapture(networkOptions);
2068
2080
  setActiveCaptures((prev) => ({ ...prev, network: true }));
2069
2081
  }
2070
2082
  }, [consoleCapture, network, consoleOptions, networkOptions]);
2071
2083
  const stopCapturing = react.useCallback(() => {
2072
- chunk2ZCWVAAK_cjs.stopConsoleCapture();
2073
- chunk2ZCWVAAK_cjs.stopNetworkCapture();
2084
+ chunk42YQ4ATO_cjs.stopConsoleCapture();
2085
+ chunk42YQ4ATO_cjs.stopNetworkCapture();
2074
2086
  setActiveCaptures({ console: false, network: false });
2075
2087
  }, []);
2076
2088
  const clearCaptured = react.useCallback(() => {
2077
- chunk2ZCWVAAK_cjs.clearConsoleLogs();
2078
- chunk2ZCWVAAK_cjs.clearNetworkRequests();
2089
+ chunk42YQ4ATO_cjs.clearConsoleLogs();
2090
+ chunk42YQ4ATO_cjs.clearNetworkRequests();
2079
2091
  }, []);
2080
2092
  const formatForAI = react.useCallback((context) => {
2081
2093
  const parts = [];
@@ -2085,16 +2097,16 @@ function useAITools(options = {}) {
2085
2097
  );
2086
2098
  }
2087
2099
  if (context.consoleLogs && context.consoleLogs.logs.length > 0) {
2088
- parts.push(chunk2ZCWVAAK_cjs.formatLogsForAI(context.consoleLogs.logs));
2100
+ parts.push(chunk42YQ4ATO_cjs.formatLogsForAI(context.consoleLogs.logs));
2089
2101
  }
2090
2102
  if (context.networkRequests && context.networkRequests.requests.length > 0) {
2091
- parts.push(chunk2ZCWVAAK_cjs.formatRequestsForAI(context.networkRequests.requests));
2103
+ parts.push(chunk42YQ4ATO_cjs.formatRequestsForAI(context.networkRequests.requests));
2092
2104
  }
2093
2105
  return parts.length > 0 ? parts.join("\n\n---\n\n") : "No context captured.";
2094
2106
  }, []);
2095
2107
  const detectIntentFn = react.useCallback(
2096
2108
  (message) => {
2097
- const result = chunk2ZCWVAAK_cjs.detectIntent(message);
2109
+ const result = chunk42YQ4ATO_cjs.detectIntent(message);
2098
2110
  result.suggestedTools = result.suggestedTools.filter((tool) => {
2099
2111
  if (tool === "screenshot") return screenshot;
2100
2112
  if (tool === "console") return consoleCapture;
@@ -2218,7 +2230,7 @@ function convertZodSchema(schema, _toolName) {
2218
2230
  }
2219
2231
  } catch {
2220
2232
  }
2221
- return chunk2ZCWVAAK_cjs.zodObjectToInputSchema(schema);
2233
+ return chunk42YQ4ATO_cjs.zodObjectToInputSchema(schema);
2222
2234
  }
2223
2235
  function useToolWithSchema(config, dependencies = []) {
2224
2236
  const { registerTool, unregisterTool } = useCopilotContext();
@@ -2516,7 +2528,7 @@ function useAgent(options) {
2516
2528
  if (!response.ok) {
2517
2529
  throw new Error(`Agent error: ${response.status}`);
2518
2530
  }
2519
- for await (const event of chunk2ZCWVAAK_cjs.streamSSE(response)) {
2531
+ for await (const event of chunk42YQ4ATO_cjs.streamSSE(response)) {
2520
2532
  handleAgentEvent(event);
2521
2533
  }
2522
2534
  } catch (err) {
@@ -2869,6 +2881,425 @@ function useDevLogger() {
2869
2881
  ]);
2870
2882
  }
2871
2883
 
2884
+ // src/react/internal/ReactThreadManagerState.ts
2885
+ var ReactThreadManagerState = class {
2886
+ constructor(initialThreads) {
2887
+ this._threads = [];
2888
+ this._currentThreadId = null;
2889
+ this._currentThread = null;
2890
+ this._loadStatus = "idle";
2891
+ this._error = void 0;
2892
+ // Callbacks for React subscriptions (useSyncExternalStore)
2893
+ this.subscribers = /* @__PURE__ */ new Set();
2894
+ // ============================================
2895
+ // Subscription (for useSyncExternalStore)
2896
+ // ============================================
2897
+ /**
2898
+ * Subscribe to state changes.
2899
+ * Returns an unsubscribe function.
2900
+ *
2901
+ * @example
2902
+ * ```tsx
2903
+ * const threads = useSyncExternalStore(
2904
+ * state.subscribe,
2905
+ * () => state.threads
2906
+ * );
2907
+ * ```
2908
+ */
2909
+ this.subscribe = (callback) => {
2910
+ this.subscribers.add(callback);
2911
+ return () => {
2912
+ this.subscribers.delete(callback);
2913
+ };
2914
+ };
2915
+ if (initialThreads) {
2916
+ this._threads = initialThreads;
2917
+ }
2918
+ }
2919
+ // ============================================
2920
+ // Getters
2921
+ // ============================================
2922
+ get threads() {
2923
+ return this._threads;
2924
+ }
2925
+ get currentThreadId() {
2926
+ return this._currentThreadId;
2927
+ }
2928
+ get currentThread() {
2929
+ return this._currentThread;
2930
+ }
2931
+ get loadStatus() {
2932
+ return this._loadStatus;
2933
+ }
2934
+ get error() {
2935
+ return this._error;
2936
+ }
2937
+ // ============================================
2938
+ // Setters (trigger reactivity)
2939
+ // ============================================
2940
+ set threads(value) {
2941
+ this._threads = value;
2942
+ this.notify();
2943
+ }
2944
+ // ============================================
2945
+ // Mutations
2946
+ // ============================================
2947
+ setThreads(threads) {
2948
+ this._threads = threads;
2949
+ this.notify();
2950
+ }
2951
+ setCurrentThread(thread) {
2952
+ this._currentThread = thread;
2953
+ this._currentThreadId = thread?.id ?? null;
2954
+ this.notify();
2955
+ }
2956
+ setCurrentThreadId(id) {
2957
+ this._currentThreadId = id;
2958
+ this.notify();
2959
+ }
2960
+ addThread(thread) {
2961
+ this._threads = [thread, ...this._threads];
2962
+ this.notify();
2963
+ }
2964
+ updateThread(id, updates) {
2965
+ this._threads = this._threads.map(
2966
+ (t) => t.id === id ? { ...t, ...updates } : t
2967
+ );
2968
+ if (updates.updatedAt) {
2969
+ this._threads = [...this._threads].sort(
2970
+ (a, b) => b.updatedAt.getTime() - a.updatedAt.getTime()
2971
+ );
2972
+ }
2973
+ if (this._currentThread?.id === id) {
2974
+ this._currentThread = { ...this._currentThread, ...updates };
2975
+ }
2976
+ this.notify();
2977
+ }
2978
+ removeThread(id) {
2979
+ this._threads = this._threads.filter((t) => t.id !== id);
2980
+ if (this._currentThreadId === id) {
2981
+ this._currentThreadId = null;
2982
+ this._currentThread = null;
2983
+ }
2984
+ this.notify();
2985
+ }
2986
+ setLoadStatus(status) {
2987
+ this._loadStatus = status;
2988
+ this.notify();
2989
+ }
2990
+ setError(error) {
2991
+ this._error = error;
2992
+ this.notify();
2993
+ }
2994
+ // ============================================
2995
+ // Snapshots (for useSyncExternalStore)
2996
+ // ============================================
2997
+ getThreadsSnapshot() {
2998
+ return this._threads;
2999
+ }
3000
+ getCurrentThreadSnapshot() {
3001
+ return this._currentThread;
3002
+ }
3003
+ getLoadStatusSnapshot() {
3004
+ return this._loadStatus;
3005
+ }
3006
+ getErrorSnapshot() {
3007
+ return this._error;
3008
+ }
3009
+ // ============================================
3010
+ // Private Methods
3011
+ // ============================================
3012
+ notify() {
3013
+ this.subscribers.forEach((cb) => cb());
3014
+ }
3015
+ /**
3016
+ * Cleanup subscriptions
3017
+ */
3018
+ dispose() {
3019
+ this.subscribers.clear();
3020
+ }
3021
+ };
3022
+ function createReactThreadManagerState(initialThreads) {
3023
+ return new ReactThreadManagerState(initialThreads);
3024
+ }
3025
+
3026
+ // src/react/internal/ReactThreadManager.ts
3027
+ var _ReactThreadManager = class _ReactThreadManager extends chunk42YQ4ATO_cjs.ThreadManager {
3028
+ constructor(config = {}, callbacks = {}) {
3029
+ const reactState = new ReactThreadManagerState();
3030
+ super({ ...config, state: reactState }, callbacks);
3031
+ // ============================================
3032
+ // Subscription Methods (for useSyncExternalStore)
3033
+ // ============================================
3034
+ /**
3035
+ * Subscribe to state changes
3036
+ * Use with useSyncExternalStore
3037
+ */
3038
+ this.subscribe = (callback) => {
3039
+ return this.state.subscribe(callback);
3040
+ };
3041
+ // ============================================
3042
+ // Snapshot Getters (for useSyncExternalStore)
3043
+ // ============================================
3044
+ /**
3045
+ * Get threads snapshot
3046
+ */
3047
+ this.getThreadsSnapshot = () => {
3048
+ return this.state.getThreadsSnapshot();
3049
+ };
3050
+ /**
3051
+ * Get current thread snapshot
3052
+ */
3053
+ this.getCurrentThreadSnapshot = () => {
3054
+ return this.state.getCurrentThreadSnapshot();
3055
+ };
3056
+ /**
3057
+ * Get current thread ID snapshot
3058
+ */
3059
+ this.getCurrentThreadIdSnapshot = () => {
3060
+ return this.state.currentThreadId;
3061
+ };
3062
+ /**
3063
+ * Get load status snapshot
3064
+ */
3065
+ this.getLoadStatusSnapshot = () => {
3066
+ return this.state.getLoadStatusSnapshot();
3067
+ };
3068
+ /**
3069
+ * Get error snapshot
3070
+ */
3071
+ this.getErrorSnapshot = () => {
3072
+ return this.state.getErrorSnapshot();
3073
+ };
3074
+ /**
3075
+ * Get isLoading snapshot
3076
+ */
3077
+ this.getIsLoadingSnapshot = () => {
3078
+ return this.state.getLoadStatusSnapshot() === "loading";
3079
+ };
3080
+ /**
3081
+ * Get threads snapshot for server (always empty for hydration consistency)
3082
+ */
3083
+ this.getThreadsServerSnapshot = () => {
3084
+ return _ReactThreadManager.EMPTY_THREADS;
3085
+ };
3086
+ /**
3087
+ * Get current thread snapshot for server (always null)
3088
+ */
3089
+ this.getCurrentThreadServerSnapshot = () => {
3090
+ return null;
3091
+ };
3092
+ /**
3093
+ * Get current thread ID snapshot for server (always null)
3094
+ */
3095
+ this.getCurrentThreadIdServerSnapshot = () => {
3096
+ return null;
3097
+ };
3098
+ /**
3099
+ * Get load status snapshot for server (always "idle")
3100
+ */
3101
+ this.getLoadStatusServerSnapshot = () => {
3102
+ return _ReactThreadManager.IDLE_STATUS;
3103
+ };
3104
+ /**
3105
+ * Get error snapshot for server (always undefined)
3106
+ */
3107
+ this.getErrorServerSnapshot = () => {
3108
+ return void 0;
3109
+ };
3110
+ /**
3111
+ * Get isLoading snapshot for server (always false)
3112
+ */
3113
+ this.getIsLoadingServerSnapshot = () => {
3114
+ return false;
3115
+ };
3116
+ }
3117
+ // ============================================
3118
+ // Cleanup
3119
+ // ============================================
3120
+ /**
3121
+ * Dispose of the manager
3122
+ */
3123
+ async dispose() {
3124
+ this.state.dispose();
3125
+ await super.dispose();
3126
+ }
3127
+ };
3128
+ // ============================================
3129
+ // Server Snapshots (for SSR - stable cached values)
3130
+ // ============================================
3131
+ // Cached values for server snapshots (must be stable references)
3132
+ _ReactThreadManager.EMPTY_THREADS = [];
3133
+ _ReactThreadManager.IDLE_STATUS = "idle";
3134
+ var ReactThreadManager = _ReactThreadManager;
3135
+ function createReactThreadManager(config, callbacks) {
3136
+ return new ReactThreadManager(config, callbacks);
3137
+ }
3138
+
3139
+ // src/react/hooks/useThreadManager.ts
3140
+ var defaultManager = null;
3141
+ function getDefaultManager() {
3142
+ if (!defaultManager) {
3143
+ defaultManager = createReactThreadManager();
3144
+ }
3145
+ return defaultManager;
3146
+ }
3147
+ var internalManager = null;
3148
+ function getInternalManager(config) {
3149
+ if (!internalManager) {
3150
+ internalManager = createReactThreadManager(
3151
+ {
3152
+ adapter: config.adapter,
3153
+ saveDebounce: config.saveDebounce,
3154
+ autoLoad: config.autoLoad,
3155
+ autoRestoreLastThread: config.autoRestoreLastThread
3156
+ },
3157
+ config.callbacks
3158
+ );
3159
+ }
3160
+ return internalManager;
3161
+ }
3162
+ function useThreadManager(config) {
3163
+ const manager = react.useMemo(() => {
3164
+ if (!config) {
3165
+ return getDefaultManager();
3166
+ }
3167
+ if (!config.adapter) {
3168
+ return getInternalManager(config);
3169
+ }
3170
+ console.log("[useThreadManager] Creating new manager with custom adapter");
3171
+ return createReactThreadManager(
3172
+ {
3173
+ adapter: config.adapter,
3174
+ saveDebounce: config.saveDebounce,
3175
+ autoLoad: config.autoLoad,
3176
+ autoRestoreLastThread: config.autoRestoreLastThread
3177
+ },
3178
+ config.callbacks
3179
+ );
3180
+ }, [
3181
+ config?.adapter,
3182
+ config?.saveDebounce,
3183
+ config?.autoLoad,
3184
+ config?.autoRestoreLastThread
3185
+ // Note: callbacks are intentionally not in deps to avoid recreating manager
3186
+ ]);
3187
+ const threads = react.useSyncExternalStore(
3188
+ manager.subscribe,
3189
+ manager.getThreadsSnapshot,
3190
+ manager.getThreadsServerSnapshot
3191
+ // SSR - always empty array
3192
+ );
3193
+ const currentThread = react.useSyncExternalStore(
3194
+ manager.subscribe,
3195
+ manager.getCurrentThreadSnapshot,
3196
+ manager.getCurrentThreadServerSnapshot
3197
+ // SSR - always null
3198
+ );
3199
+ const currentThreadId = react.useSyncExternalStore(
3200
+ manager.subscribe,
3201
+ manager.getCurrentThreadIdSnapshot,
3202
+ manager.getCurrentThreadIdServerSnapshot
3203
+ // SSR - always null
3204
+ );
3205
+ const loadStatus = react.useSyncExternalStore(
3206
+ manager.subscribe,
3207
+ manager.getLoadStatusSnapshot,
3208
+ manager.getLoadStatusServerSnapshot
3209
+ // SSR - always "idle"
3210
+ );
3211
+ const error = react.useSyncExternalStore(
3212
+ manager.subscribe,
3213
+ manager.getErrorSnapshot,
3214
+ manager.getErrorServerSnapshot
3215
+ // SSR - always undefined
3216
+ );
3217
+ const isLoading = react.useSyncExternalStore(
3218
+ manager.subscribe,
3219
+ manager.getIsLoadingSnapshot,
3220
+ manager.getIsLoadingServerSnapshot
3221
+ // SSR - always false
3222
+ );
3223
+ react.useEffect(() => {
3224
+ return () => {
3225
+ if (config?.adapter && manager !== defaultManager && manager !== internalManager) {
3226
+ manager.dispose();
3227
+ }
3228
+ };
3229
+ }, [manager, config]);
3230
+ react.useEffect(() => {
3231
+ const handleBeforeUnload = () => {
3232
+ if (manager.hasPendingChanges) {
3233
+ manager.saveNow().catch(() => {
3234
+ });
3235
+ }
3236
+ };
3237
+ if (typeof window !== "undefined") {
3238
+ window.addEventListener("beforeunload", handleBeforeUnload);
3239
+ return () => {
3240
+ window.removeEventListener("beforeunload", handleBeforeUnload);
3241
+ };
3242
+ }
3243
+ }, [manager]);
3244
+ const createThread = react.useCallback(
3245
+ (options) => manager.createThread(options),
3246
+ [manager]
3247
+ );
3248
+ const switchThread = react.useCallback(
3249
+ (id) => manager.switchThread(id),
3250
+ [manager]
3251
+ );
3252
+ const updateCurrentThread = react.useCallback(
3253
+ (updates) => manager.updateCurrentThread(updates),
3254
+ [manager]
3255
+ );
3256
+ const deleteThread = react.useCallback(
3257
+ (id) => manager.deleteThread(id),
3258
+ [manager]
3259
+ );
3260
+ const clearCurrentThread = react.useCallback(
3261
+ () => manager.clearCurrentThread(),
3262
+ [manager]
3263
+ );
3264
+ const refreshThreads = react.useCallback(() => manager.loadThreads(), [manager]);
3265
+ const saveNow = react.useCallback(() => manager.saveNow(), [manager]);
3266
+ const clearAllThreads = react.useCallback(
3267
+ () => manager.clearAllThreads(),
3268
+ [manager]
3269
+ );
3270
+ const messages = react.useMemo(
3271
+ () => currentThread?.messages ?? [],
3272
+ [currentThread]
3273
+ );
3274
+ const setMessages = react.useCallback(
3275
+ (newMessages) => updateCurrentThread({ messages: newMessages }),
3276
+ [updateCurrentThread]
3277
+ );
3278
+ const hasPendingChanges = manager.hasPendingChanges;
3279
+ return {
3280
+ // State
3281
+ threads,
3282
+ currentThread,
3283
+ currentThreadId,
3284
+ isLoading,
3285
+ loadStatus,
3286
+ error,
3287
+ // Actions
3288
+ createThread,
3289
+ switchThread,
3290
+ updateCurrentThread,
3291
+ deleteThread,
3292
+ clearCurrentThread,
3293
+ refreshThreads,
3294
+ saveNow,
3295
+ clearAllThreads,
3296
+ // Utilities
3297
+ messages,
3298
+ setMessages,
3299
+ hasPendingChanges
3300
+ };
3301
+ }
3302
+
2872
3303
  // src/react/utils/permission-storage.ts
2873
3304
  var DEFAULT_KEY_PREFIX = "yourgpt-permissions";
2874
3305
  function createPermissionStorage(config) {
@@ -3122,9 +3553,13 @@ exports.AbstractChat = AbstractChat;
3122
3553
  exports.CopilotProvider = CopilotProvider;
3123
3554
  exports.ReactChat = ReactChat;
3124
3555
  exports.ReactChatState = ReactChatState;
3556
+ exports.ReactThreadManager = ReactThreadManager;
3557
+ exports.ReactThreadManagerState = ReactThreadManagerState;
3125
3558
  exports.createPermissionStorage = createPermissionStorage;
3126
3559
  exports.createReactChat = createReactChat;
3127
3560
  exports.createReactChatState = createReactChatState;
3561
+ exports.createReactThreadManager = createReactThreadManager;
3562
+ exports.createReactThreadManagerState = createReactThreadManagerState;
3128
3563
  exports.createSessionPermissionCache = createSessionPermissionCache;
3129
3564
  exports.formatKnowledgeResultsForAI = formatKnowledgeResultsForAI;
3130
3565
  exports.initialAgentLoopState = initialAgentLoopState;
@@ -3143,10 +3578,11 @@ exports.useFeatureSupport = useFeatureSupport;
3143
3578
  exports.useKnowledgeBase = useKnowledgeBase;
3144
3579
  exports.useSuggestions = useSuggestions;
3145
3580
  exports.useSupportedMediaTypes = useSupportedMediaTypes;
3581
+ exports.useThreadManager = useThreadManager;
3146
3582
  exports.useTool = useTool;
3147
3583
  exports.useToolExecutor = useToolExecutor;
3148
3584
  exports.useToolWithSchema = useToolWithSchema;
3149
3585
  exports.useTools = useTools;
3150
3586
  exports.useToolsWithSchema = useToolsWithSchema;
3151
- //# sourceMappingURL=chunk-W6KQT7YZ.cjs.map
3152
- //# sourceMappingURL=chunk-W6KQT7YZ.cjs.map
3587
+ //# sourceMappingURL=chunk-BN75ZW24.cjs.map
3588
+ //# sourceMappingURL=chunk-BN75ZW24.cjs.map