@copilotkit/react-core 1.57.0 → 1.57.1

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 (82) hide show
  1. package/dist/{copilotkit-DFaI4j2r.d.mts → copilotkit-BN4I_y1n.d.mts} +64 -8
  2. package/dist/copilotkit-BN4I_y1n.d.mts.map +1 -0
  3. package/dist/{copilotkit-DGbvw8n2.cjs → copilotkit-C3k13WZn.cjs} +572 -435
  4. package/dist/copilotkit-C3k13WZn.cjs.map +1 -0
  5. package/dist/{copilotkit-CPe2-340.mjs → copilotkit-DjxXMYHG.mjs} +571 -440
  6. package/dist/copilotkit-DjxXMYHG.mjs.map +1 -0
  7. package/dist/{copilotkit-Dg4r4Gi_.d.cts → copilotkit-sQWiKtxA.d.cts} +64 -8
  8. package/dist/copilotkit-sQWiKtxA.d.cts.map +1 -0
  9. package/dist/index.cjs +2 -5
  10. package/dist/index.cjs.map +1 -1
  11. package/dist/index.d.cts +1 -1
  12. package/dist/index.d.mts +1 -1
  13. package/dist/index.mjs +2 -5
  14. package/dist/index.mjs.map +1 -1
  15. package/dist/index.umd.js +449 -502
  16. package/dist/index.umd.js.map +1 -1
  17. package/dist/v2/context.cjs +135 -0
  18. package/dist/v2/context.cjs.map +1 -0
  19. package/dist/v2/context.d.cts +148 -0
  20. package/dist/v2/context.d.cts.map +1 -0
  21. package/dist/v2/context.d.mts +148 -0
  22. package/dist/v2/context.d.mts.map +1 -0
  23. package/dist/v2/context.mjs +129 -0
  24. package/dist/v2/context.mjs.map +1 -0
  25. package/dist/v2/headless.cjs +1043 -0
  26. package/dist/v2/headless.cjs.map +1 -0
  27. package/dist/v2/headless.d.cts +605 -0
  28. package/dist/v2/headless.d.cts.map +1 -0
  29. package/dist/v2/headless.d.mts +512 -0
  30. package/dist/v2/headless.d.mts.map +1 -0
  31. package/dist/v2/headless.mjs +997 -0
  32. package/dist/v2/headless.mjs.map +1 -0
  33. package/dist/v2/index.cjs +2 -1
  34. package/dist/v2/index.css +1 -1
  35. package/dist/v2/index.d.cts +2 -2
  36. package/dist/v2/index.d.mts +2 -2
  37. package/dist/v2/index.mjs +2 -2
  38. package/dist/v2/index.umd.js +584 -441
  39. package/dist/v2/index.umd.js.map +1 -1
  40. package/package.json +14 -6
  41. package/src/hooks/__tests__/use-copilot-chat-internal-connect.test.tsx +5 -6
  42. package/src/hooks/use-copilot-chat_internal.ts +0 -1
  43. package/src/v2/components/chat/CopilotChat.tsx +2 -1
  44. package/src/v2/components/chat/CopilotChatMessageView.tsx +24 -9
  45. package/src/v2/components/chat/CopilotChatView.tsx +2 -2
  46. package/src/v2/components/chat/__tests__/CopilotChat.welcomeGate.test.tsx +1 -3
  47. package/src/v2/components/chat/__tests__/CopilotChatActivityRendering.e2e.test.tsx +29 -25
  48. package/src/v2/components/chat/__tests__/MCPAppsUiMessage.e2e.test.tsx +5 -60
  49. package/src/v2/components/index.ts +1 -0
  50. package/src/v2/components/intelligence-indicator/IntelligenceIndicator.tsx +286 -0
  51. package/src/v2/components/intelligence-indicator/__tests__/IntelligenceIndicator.e2e.test.tsx +464 -0
  52. package/src/v2/components/intelligence-indicator/index.ts +2 -0
  53. package/src/v2/context.ts +62 -0
  54. package/src/v2/headless.ts +42 -0
  55. package/src/v2/hooks/__tests__/standard-schema.test.tsx +2 -2
  56. package/src/v2/hooks/__tests__/use-agent-context.test.tsx +3 -3
  57. package/src/v2/hooks/__tests__/use-agent-stability.test.tsx +3 -3
  58. package/src/v2/hooks/__tests__/use-agent-throttle.test.tsx +85 -85
  59. package/src/v2/hooks/__tests__/use-interrupt.test.tsx +2 -2
  60. package/src/v2/hooks/__tests__/use-render-tool.test.tsx +2 -2
  61. package/src/v2/hooks/__tests__/use-threads.test.tsx +2 -2
  62. package/src/v2/hooks/__tests__/zod-regression.test.tsx +2 -2
  63. package/src/v2/hooks/use-agent-context.tsx +1 -1
  64. package/src/v2/hooks/use-agent.tsx +9 -118
  65. package/src/v2/hooks/use-configure-suggestions.tsx +1 -1
  66. package/src/v2/hooks/use-frontend-tool.tsx +2 -2
  67. package/src/v2/hooks/use-human-in-the-loop.tsx +1 -1
  68. package/src/v2/hooks/use-interrupt.tsx +1 -1
  69. package/src/v2/hooks/use-render-activity-message.tsx +3 -11
  70. package/src/v2/hooks/use-render-custom-messages.tsx +1 -6
  71. package/src/v2/hooks/use-render-tool-call.tsx +1 -1
  72. package/src/v2/hooks/use-render-tool.tsx +2 -2
  73. package/src/v2/hooks/use-suggestions.tsx +1 -1
  74. package/src/v2/hooks/use-threads.tsx +1 -1
  75. package/src/v2/providers/CopilotKitProvider.tsx +19 -59
  76. package/src/v2/styles/globals.css +118 -0
  77. package/tsdown.config.ts +75 -0
  78. package/dist/copilotkit-CPe2-340.mjs.map +0 -1
  79. package/dist/copilotkit-DFaI4j2r.d.mts.map +0 -1
  80. package/dist/copilotkit-DGbvw8n2.cjs.map +0 -1
  81. package/dist/copilotkit-Dg4r4Gi_.d.cts.map +0 -1
  82. package/src/v2/hooks/__tests__/use-agent-thread-isolation.test.tsx +0 -333
package/dist/index.umd.js CHANGED
@@ -203,6 +203,206 @@ react_markdown = __toESM(react_markdown);
203
203
  return (0, react.useContext)(CopilotChatConfiguration);
204
204
  };
205
205
 
206
+ //#endregion
207
+ //#region src/v2/lib/react-core.ts
208
+ var CopilotKitCoreReact = class extends _copilotkit_core.CopilotKitCore {
209
+ constructor(config) {
210
+ var _config$renderToolCal, _config$renderCustomM, _config$renderActivit;
211
+ super(config);
212
+ this._renderToolCalls = [];
213
+ this._hookRenderToolCalls = /* @__PURE__ */ new Map();
214
+ this._cachedMergedRenderToolCalls = null;
215
+ this._renderCustomMessages = [];
216
+ this._renderActivityMessages = [];
217
+ this._interruptElement = null;
218
+ this._renderToolCalls = (_config$renderToolCal = config.renderToolCalls) !== null && _config$renderToolCal !== void 0 ? _config$renderToolCal : [];
219
+ this._renderCustomMessages = (_config$renderCustomM = config.renderCustomMessages) !== null && _config$renderCustomM !== void 0 ? _config$renderCustomM : [];
220
+ this._renderActivityMessages = (_config$renderActivit = config.renderActivityMessages) !== null && _config$renderActivit !== void 0 ? _config$renderActivit : [];
221
+ }
222
+ get renderCustomMessages() {
223
+ return this._renderCustomMessages;
224
+ }
225
+ get renderActivityMessages() {
226
+ return this._renderActivityMessages;
227
+ }
228
+ get renderToolCalls() {
229
+ if (this._hookRenderToolCalls.size === 0) return this._renderToolCalls;
230
+ if (this._cachedMergedRenderToolCalls) return this._cachedMergedRenderToolCalls;
231
+ const merged = /* @__PURE__ */ new Map();
232
+ for (const rc of this._renderToolCalls) {
233
+ var _rc$agentId;
234
+ merged.set(`${(_rc$agentId = rc.agentId) !== null && _rc$agentId !== void 0 ? _rc$agentId : ""}:${rc.name}`, rc);
235
+ }
236
+ for (const [key, rc] of this._hookRenderToolCalls) merged.set(key, rc);
237
+ this._cachedMergedRenderToolCalls = Array.from(merged.values());
238
+ return this._cachedMergedRenderToolCalls;
239
+ }
240
+ setRenderActivityMessages(renderers) {
241
+ this._renderActivityMessages = renderers;
242
+ }
243
+ setRenderCustomMessages(renderers) {
244
+ this._renderCustomMessages = renderers;
245
+ }
246
+ setRenderToolCalls(renderToolCalls) {
247
+ this._renderToolCalls = renderToolCalls;
248
+ this._cachedMergedRenderToolCalls = null;
249
+ this._notifyRenderToolCallsChanged();
250
+ }
251
+ addHookRenderToolCall(entry) {
252
+ var _entry$agentId;
253
+ const key = `${(_entry$agentId = entry.agentId) !== null && _entry$agentId !== void 0 ? _entry$agentId : ""}:${entry.name}`;
254
+ this._hookRenderToolCalls.set(key, entry);
255
+ this._cachedMergedRenderToolCalls = null;
256
+ this._notifyRenderToolCallsChanged();
257
+ }
258
+ removeHookRenderToolCall(name, agentId) {
259
+ const key = `${agentId !== null && agentId !== void 0 ? agentId : ""}:${name}`;
260
+ if (this._hookRenderToolCalls.delete(key)) {
261
+ this._cachedMergedRenderToolCalls = null;
262
+ this._notifyRenderToolCallsChanged();
263
+ }
264
+ }
265
+ _notifyRenderToolCallsChanged() {
266
+ this.notifySubscribers((subscriber) => {
267
+ const reactSubscriber = subscriber;
268
+ if (reactSubscriber.onRenderToolCallsChanged) reactSubscriber.onRenderToolCallsChanged({
269
+ copilotkit: this,
270
+ renderToolCalls: this.renderToolCalls
271
+ });
272
+ }, "Subscriber onRenderToolCallsChanged error:");
273
+ }
274
+ get interruptElement() {
275
+ return this._interruptElement;
276
+ }
277
+ setInterruptElement(element) {
278
+ this._interruptElement = element;
279
+ this.notifySubscribers((subscriber) => {
280
+ var _reactSubscriber$onIn;
281
+ const reactSubscriber = subscriber;
282
+ (_reactSubscriber$onIn = reactSubscriber.onInterruptElementChanged) === null || _reactSubscriber$onIn === void 0 || _reactSubscriber$onIn.call(reactSubscriber, {
283
+ copilotkit: this,
284
+ interruptElement: this._interruptElement
285
+ });
286
+ }, "Subscriber onInterruptElementChanged error:");
287
+ }
288
+ subscribe(subscriber) {
289
+ return super.subscribe(subscriber);
290
+ }
291
+ /**
292
+ * Wait for pending React state updates before the follow-up agent run.
293
+ *
294
+ * When a frontend tool handler calls setState(), React 18 batches the update
295
+ * and schedules a commit via its internal scheduler (MessageChannel). The
296
+ * useAgentContext hook registers context via useLayoutEffect, which runs
297
+ * synchronously after React commits that batch.
298
+ *
299
+ * Awaiting a zero-delay timeout yields to the macrotask queue. React's
300
+ * MessageChannel task runs first, committing the pending state and running
301
+ * useLayoutEffect (which updates the context store). The follow-up runAgent
302
+ * call then reads fresh context.
303
+ */
304
+ async waitForPendingFrameworkUpdates() {
305
+ await new Promise((resolve) => setTimeout(resolve, 0));
306
+ }
307
+ };
308
+
309
+ //#endregion
310
+ //#region src/v2/context.ts
311
+ const CopilotKitContext = (0, react.createContext)(null);
312
+ const useCopilotKit = () => {
313
+ const context = (0, react.useContext)(CopilotKitContext);
314
+ const [, forceUpdate] = (0, react.useReducer)((x) => x + 1, 0);
315
+ if (!context) throw new Error("useCopilotKit must be used within CopilotKitProvider");
316
+ (0, react.useEffect)(() => {
317
+ const subscription = context.copilotkit.subscribe({ onRuntimeConnectionStatusChanged: () => {
318
+ forceUpdate();
319
+ } });
320
+ return () => {
321
+ subscription.unsubscribe();
322
+ };
323
+ }, []);
324
+ return context;
325
+ };
326
+ const LicenseContext = (0, react.createContext)({
327
+ status: null,
328
+ license: null,
329
+ checkFeature: () => true,
330
+ getLimit: () => null
331
+ });
332
+
333
+ //#endregion
334
+ //#region src/v2/hooks/use-render-tool-call.tsx
335
+ /**
336
+ * Memoized component that renders a single tool call.
337
+ * This prevents unnecessary re-renders when parent components update
338
+ * but the tool call data hasn't changed.
339
+ */
340
+ const ToolCallRenderer = react.default.memo(function ToolCallRenderer({ toolCall, toolMessage, RenderComponent, isExecuting }) {
341
+ const args = (0, react.useMemo)(() => (0, _copilotkit_shared.partialJSONParse)(toolCall.function.arguments), [toolCall.function.arguments]);
342
+ const toolName = toolCall.function.name;
343
+ if (toolMessage) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(RenderComponent, {
344
+ name: toolName,
345
+ toolCallId: toolCall.id,
346
+ args,
347
+ status: _copilotkit_core.ToolCallStatus.Complete,
348
+ result: toolMessage.content
349
+ });
350
+ else if (isExecuting) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(RenderComponent, {
351
+ name: toolName,
352
+ toolCallId: toolCall.id,
353
+ args,
354
+ status: _copilotkit_core.ToolCallStatus.Executing,
355
+ result: void 0
356
+ });
357
+ else return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(RenderComponent, {
358
+ name: toolName,
359
+ toolCallId: toolCall.id,
360
+ args,
361
+ status: _copilotkit_core.ToolCallStatus.InProgress,
362
+ result: void 0
363
+ });
364
+ }, (prevProps, nextProps) => {
365
+ var _prevProps$toolMessag, _nextProps$toolMessag;
366
+ if (prevProps.toolCall.id !== nextProps.toolCall.id) return false;
367
+ if (prevProps.toolCall.function.name !== nextProps.toolCall.function.name) return false;
368
+ if (prevProps.toolCall.function.arguments !== nextProps.toolCall.function.arguments) return false;
369
+ if (((_prevProps$toolMessag = prevProps.toolMessage) === null || _prevProps$toolMessag === void 0 ? void 0 : _prevProps$toolMessag.content) !== ((_nextProps$toolMessag = nextProps.toolMessage) === null || _nextProps$toolMessag === void 0 ? void 0 : _nextProps$toolMessag.content)) return false;
370
+ if (prevProps.isExecuting !== nextProps.isExecuting) return false;
371
+ if (prevProps.RenderComponent !== nextProps.RenderComponent) return false;
372
+ return true;
373
+ });
374
+ /**
375
+ * Hook that returns a function to render tool calls based on the render functions
376
+ * defined in CopilotKitProvider.
377
+ *
378
+ * @returns A function that takes a tool call and optional tool message and returns the rendered component
379
+ */
380
+ function useRenderToolCall$1() {
381
+ var _config$agentId;
382
+ const { copilotkit, executingToolCallIds } = useCopilotKit();
383
+ const config = useCopilotChatConfiguration();
384
+ const agentId = (_config$agentId = config === null || config === void 0 ? void 0 : config.agentId) !== null && _config$agentId !== void 0 ? _config$agentId : _copilotkit_shared.DEFAULT_AGENT_ID;
385
+ const renderToolCalls = (0, react.useSyncExternalStore)((callback) => {
386
+ return copilotkit.subscribe({ onRenderToolCallsChanged: callback }).unsubscribe;
387
+ }, () => copilotkit.renderToolCalls, () => copilotkit.renderToolCalls);
388
+ return (0, react.useCallback)(({ toolCall, toolMessage }) => {
389
+ const exactMatches = renderToolCalls.filter((rc) => rc.name === toolCall.function.name);
390
+ const renderConfig = exactMatches.find((rc) => rc.agentId === agentId) || exactMatches.find((rc) => !rc.agentId) || exactMatches[0] || renderToolCalls.find((rc) => rc.name === "*");
391
+ if (!renderConfig) return null;
392
+ const RenderComponent = renderConfig.render;
393
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ToolCallRenderer, {
394
+ toolCall,
395
+ toolMessage,
396
+ RenderComponent,
397
+ isExecuting: executingToolCallIds.has(toolCall.id)
398
+ }, toolCall.id);
399
+ }, [
400
+ renderToolCalls,
401
+ executingToolCallIds,
402
+ agentId
403
+ ]);
404
+ }
405
+
206
406
  //#endregion
207
407
  //#region src/v2/components/CopilotKitInspector.tsx
208
408
  const CopilotKitInspector = ({ core, ...rest }) => {
@@ -1835,109 +2035,6 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
1835
2035
  return null;
1836
2036
  }
1837
2037
 
1838
- //#endregion
1839
- //#region src/v2/lib/react-core.ts
1840
- var CopilotKitCoreReact = class extends _copilotkit_core.CopilotKitCore {
1841
- constructor(config) {
1842
- var _config$renderToolCal, _config$renderCustomM, _config$renderActivit;
1843
- super(config);
1844
- this._renderToolCalls = [];
1845
- this._hookRenderToolCalls = /* @__PURE__ */ new Map();
1846
- this._cachedMergedRenderToolCalls = null;
1847
- this._renderCustomMessages = [];
1848
- this._renderActivityMessages = [];
1849
- this._interruptElement = null;
1850
- this._renderToolCalls = (_config$renderToolCal = config.renderToolCalls) !== null && _config$renderToolCal !== void 0 ? _config$renderToolCal : [];
1851
- this._renderCustomMessages = (_config$renderCustomM = config.renderCustomMessages) !== null && _config$renderCustomM !== void 0 ? _config$renderCustomM : [];
1852
- this._renderActivityMessages = (_config$renderActivit = config.renderActivityMessages) !== null && _config$renderActivit !== void 0 ? _config$renderActivit : [];
1853
- }
1854
- get renderCustomMessages() {
1855
- return this._renderCustomMessages;
1856
- }
1857
- get renderActivityMessages() {
1858
- return this._renderActivityMessages;
1859
- }
1860
- get renderToolCalls() {
1861
- if (this._hookRenderToolCalls.size === 0) return this._renderToolCalls;
1862
- if (this._cachedMergedRenderToolCalls) return this._cachedMergedRenderToolCalls;
1863
- const merged = /* @__PURE__ */ new Map();
1864
- for (const rc of this._renderToolCalls) {
1865
- var _rc$agentId;
1866
- merged.set(`${(_rc$agentId = rc.agentId) !== null && _rc$agentId !== void 0 ? _rc$agentId : ""}:${rc.name}`, rc);
1867
- }
1868
- for (const [key, rc] of this._hookRenderToolCalls) merged.set(key, rc);
1869
- this._cachedMergedRenderToolCalls = Array.from(merged.values());
1870
- return this._cachedMergedRenderToolCalls;
1871
- }
1872
- setRenderActivityMessages(renderers) {
1873
- this._renderActivityMessages = renderers;
1874
- }
1875
- setRenderCustomMessages(renderers) {
1876
- this._renderCustomMessages = renderers;
1877
- }
1878
- setRenderToolCalls(renderToolCalls) {
1879
- this._renderToolCalls = renderToolCalls;
1880
- this._cachedMergedRenderToolCalls = null;
1881
- this._notifyRenderToolCallsChanged();
1882
- }
1883
- addHookRenderToolCall(entry) {
1884
- var _entry$agentId;
1885
- const key = `${(_entry$agentId = entry.agentId) !== null && _entry$agentId !== void 0 ? _entry$agentId : ""}:${entry.name}`;
1886
- this._hookRenderToolCalls.set(key, entry);
1887
- this._cachedMergedRenderToolCalls = null;
1888
- this._notifyRenderToolCallsChanged();
1889
- }
1890
- removeHookRenderToolCall(name, agentId) {
1891
- const key = `${agentId !== null && agentId !== void 0 ? agentId : ""}:${name}`;
1892
- if (this._hookRenderToolCalls.delete(key)) {
1893
- this._cachedMergedRenderToolCalls = null;
1894
- this._notifyRenderToolCallsChanged();
1895
- }
1896
- }
1897
- _notifyRenderToolCallsChanged() {
1898
- this.notifySubscribers((subscriber) => {
1899
- const reactSubscriber = subscriber;
1900
- if (reactSubscriber.onRenderToolCallsChanged) reactSubscriber.onRenderToolCallsChanged({
1901
- copilotkit: this,
1902
- renderToolCalls: this.renderToolCalls
1903
- });
1904
- }, "Subscriber onRenderToolCallsChanged error:");
1905
- }
1906
- get interruptElement() {
1907
- return this._interruptElement;
1908
- }
1909
- setInterruptElement(element) {
1910
- this._interruptElement = element;
1911
- this.notifySubscribers((subscriber) => {
1912
- var _reactSubscriber$onIn;
1913
- const reactSubscriber = subscriber;
1914
- (_reactSubscriber$onIn = reactSubscriber.onInterruptElementChanged) === null || _reactSubscriber$onIn === void 0 || _reactSubscriber$onIn.call(reactSubscriber, {
1915
- copilotkit: this,
1916
- interruptElement: this._interruptElement
1917
- });
1918
- }, "Subscriber onInterruptElementChanged error:");
1919
- }
1920
- subscribe(subscriber) {
1921
- return super.subscribe(subscriber);
1922
- }
1923
- /**
1924
- * Wait for pending React state updates before the follow-up agent run.
1925
- *
1926
- * When a frontend tool handler calls setState(), React 18 batches the update
1927
- * and schedules a commit via its internal scheduler (MessageChannel). The
1928
- * useAgentContext hook registers context via useLayoutEffect, which runs
1929
- * synchronously after React commits that batch.
1930
- *
1931
- * Awaiting a zero-delay timeout yields to the macrotask queue. React's
1932
- * MessageChannel task runs first, committing the pending state and running
1933
- * useLayoutEffect (which updates the context store). The follow-up runAgent
1934
- * call then reads fresh context.
1935
- */
1936
- async waitForPendingFrameworkUpdates() {
1937
- await new Promise((resolve) => setTimeout(resolve, 0));
1938
- }
1939
- };
1940
-
1941
2038
  //#endregion
1942
2039
  //#region src/v2/providers/CopilotKitProvider.tsx
1943
2040
  const HEADER_NAME = "X-CopilotCloud-Public-Api-Key";
@@ -1953,11 +2050,6 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
1953
2050
  - Minimal transitions (150ms) for hover/focus states only. No decorative animations.
1954
2051
  - Keep the UI focused and dense — avoid excessive padding. Use compact spacing (8–12px gaps, 10–14px padding in controls).`;
1955
2052
  const GENERATE_SANDBOXED_UI_DESCRIPTION = "Generate sandboxed UI. IMPORTANT: The generated code runs in a sandboxed iframe WITHOUT same-origin access. Do NOT use localStorage, sessionStorage, document.cookie, IndexedDB, or fetch/XMLHttpRequest to same-origin URLs. To communicate with the host application, use Websandbox.connection.remote.<functionName>(args) which returns a Promise.\n\nYou CAN use external libraries from CDNs by including <script> or <link> tags in the HTML <head> (e.g., Chart.js, D3, Three.js, x-data-spreadsheet, etc.). CDN resources load normally inside the sandbox.\n\nPARAMETER ORDER IS CRITICAL — generate parameters in exactly this order:\n1. initialHeight + placeholderMessages (shown to user while generating)\n2. css (all styles FIRST — the user sees a placeholder until CSS is complete)\n3. html (streams in live — the user watches the UI build as HTML is generated)\n4. jsFunctions (reusable helper functions)\n5. jsExpressions (applied one-by-one — the user sees each expression take effect)";
1956
- const CopilotKitContext = (0, react.createContext)({
1957
- copilotkit: null,
1958
- executingToolCallIds: /* @__PURE__ */ new Set()
1959
- });
1960
- const LicenseContext = (0, react.createContext)((0, _copilotkit_shared.createLicenseContextValue)(null));
1961
2053
  function useStableArrayProp(prop, warningMessage, isMeaningfulChange) {
1962
2054
  const empty = (0, react.useMemo)(() => [], []);
1963
2055
  const value = prop !== null && prop !== void 0 ? prop : empty;
@@ -2167,399 +2259,145 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
2167
2259
  next.add(toolCallId);
2168
2260
  return next;
2169
2261
  });
2170
- },
2171
- onToolExecutionEnd: ({ toolCallId }) => {
2172
- setExecutingToolCallIds((prev) => {
2173
- if (!prev.has(toolCallId)) return prev;
2174
- const next = new Set(prev);
2175
- next.delete(toolCallId);
2176
- return next;
2177
- });
2178
- }
2179
- });
2180
- return () => {
2181
- subscription.unsubscribe();
2182
- };
2183
- }, [copilotkit]);
2184
- const onErrorRef = (0, react.useRef)(onError);
2185
- (0, react.useEffect)(() => {
2186
- onErrorRef.current = onError;
2187
- }, [onError]);
2188
- (0, react.useEffect)(() => {
2189
- if (!onErrorRef.current) return;
2190
- const subscription = copilotkit.subscribe({ onError: (event) => {
2191
- var _onErrorRef$current;
2192
- (_onErrorRef$current = onErrorRef.current) === null || _onErrorRef$current === void 0 || _onErrorRef$current.call(onErrorRef, {
2193
- error: event.error,
2194
- code: event.code,
2195
- context: event.context
2196
- });
2197
- } });
2198
- return () => {
2199
- subscription.unsubscribe();
2200
- };
2201
- }, [copilotkit]);
2202
- (0, react.useEffect)(() => {
2203
- copilotkit.setRuntimeUrl(chatApiEndpoint);
2204
- copilotkit.setRuntimeTransport(useSingleEndpoint === true ? "single" : useSingleEndpoint === false ? "rest" : "auto");
2205
- copilotkit.setHeaders(mergedHeaders);
2206
- copilotkit.setCredentials(credentials);
2207
- copilotkit.setProperties(properties);
2208
- copilotkit.setAgents__unsafe_dev_only(mergedAgents);
2209
- copilotkit.setDebug(debug);
2210
- }, [
2211
- copilotkit,
2212
- chatApiEndpoint,
2213
- mergedHeaders,
2214
- credentials,
2215
- properties,
2216
- mergedAgents,
2217
- useSingleEndpoint,
2218
- debug
2219
- ]);
2220
- const didMountRef = (0, react.useRef)(false);
2221
- (0, react.useEffect)(() => {
2222
- if (!didMountRef.current) return;
2223
- copilotkit.setTools(allTools);
2224
- }, [copilotkit, allTools]);
2225
- (0, react.useEffect)(() => {
2226
- if (!didMountRef.current) return;
2227
- copilotkit.setRenderToolCalls(allRenderToolCalls);
2228
- }, [copilotkit, allRenderToolCalls]);
2229
- (0, react.useEffect)(() => {
2230
- if (!didMountRef.current) return;
2231
- copilotkit.setRenderActivityMessages(allActivityRenderers);
2232
- }, [copilotkit, allActivityRenderers]);
2233
- (0, react.useEffect)(() => {
2234
- if (!didMountRef.current) return;
2235
- copilotkit.setRenderCustomMessages(renderCustomMessagesList);
2236
- }, [copilotkit, renderCustomMessagesList]);
2237
- (0, react.useEffect)(() => {
2238
- didMountRef.current = true;
2239
- }, []);
2240
- (0, react.useEffect)(() => {
2241
- copilotkit.setDefaultThrottleMs(defaultThrottleMs);
2242
- }, [copilotkit, defaultThrottleMs]);
2243
- const designSkill = (_openGenerativeUI$des = openGenerativeUI === null || openGenerativeUI === void 0 ? void 0 : openGenerativeUI.designSkill) !== null && _openGenerativeUI$des !== void 0 ? _openGenerativeUI$des : DEFAULT_DESIGN_SKILL;
2244
- (0, react.useLayoutEffect)(() => {
2245
- if (!copilotkit || !openGenUIActive) return;
2246
- const id = copilotkit.addContext({
2247
- description: "Design guidelines for the generateSandboxedUi tool. Follow these when building UI.",
2248
- value: designSkill
2249
- });
2250
- return () => {
2251
- copilotkit.removeContext(id);
2252
- };
2253
- }, [
2254
- copilotkit,
2255
- designSkill,
2256
- openGenUIActive
2257
- ]);
2258
- const sandboxFunctionsDescriptors = (0, react.useMemo)(() => {
2259
- if (sandboxFunctionsList.length === 0) return null;
2260
- return JSON.stringify(sandboxFunctionsList.map((fn) => ({
2261
- name: fn.name,
2262
- description: fn.description,
2263
- parameters: (0, _copilotkit_shared.schemaToJsonSchema)(fn.parameters, { zodToJsonSchema: zod_to_json_schema.zodToJsonSchema })
2264
- })));
2265
- }, [sandboxFunctionsList]);
2266
- (0, react.useLayoutEffect)(() => {
2267
- if (!copilotkit || !sandboxFunctionsDescriptors || !openGenUIActive) return;
2268
- const id = copilotkit.addContext({
2269
- description: "Sandbox functions available in generated sandboxed UI code. Call via: await Websandbox.connection.remote.<functionName>(args)",
2270
- value: sandboxFunctionsDescriptors
2271
- });
2272
- return () => {
2273
- copilotkit.removeContext(id);
2274
- };
2275
- }, [
2276
- copilotkit,
2277
- sandboxFunctionsDescriptors,
2278
- openGenUIActive
2279
- ]);
2280
- const contextValue = (0, react.useMemo)(() => ({
2281
- copilotkit,
2282
- executingToolCallIds
2283
- }), [copilotkit, executingToolCallIds]);
2284
- const licenseContextValue = (0, react.useMemo)(() => (0, _copilotkit_shared.createLicenseContextValue)(null), []);
2285
- return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SandboxFunctionsContext.Provider, {
2286
- value: sandboxFunctionsList,
2287
- children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotKitContext.Provider, {
2288
- value: contextValue,
2289
- children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(LicenseContext.Provider, {
2290
- value: licenseContextValue,
2291
- children: [
2292
- runtimeA2UIEnabled && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(A2UIBuiltInToolCallRenderer, {}),
2293
- runtimeA2UIEnabled && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(A2UICatalogContext, {
2294
- catalog: a2ui === null || a2ui === void 0 ? void 0 : a2ui.catalog,
2295
- includeSchema: a2ui === null || a2ui === void 0 ? void 0 : a2ui.includeSchema
2296
- }),
2297
- children,
2298
- shouldRenderInspector ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotKitInspector, {
2299
- core: copilotkit,
2300
- defaultAnchor: inspectorDefaultAnchor
2301
- }) : null,
2302
- runtimeLicenseStatus === "none" && !resolvedPublicKey && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(LicenseWarningBanner, { type: "no_license" }),
2303
- runtimeLicenseStatus === "expired" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(LicenseWarningBanner, { type: "expired" }),
2304
- runtimeLicenseStatus === "invalid" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(LicenseWarningBanner, { type: "invalid" }),
2305
- runtimeLicenseStatus === "expiring" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(LicenseWarningBanner, { type: "expiring" })
2306
- ]
2307
- })
2308
- })
2309
- });
2310
- };
2311
- const useCopilotKit = () => {
2312
- const context = (0, react.useContext)(CopilotKitContext);
2313
- const [, forceUpdate] = (0, react.useReducer)((x) => x + 1, 0);
2314
- if (!context) throw new Error("useCopilotKit must be used within CopilotKitProvider");
2315
- (0, react.useEffect)(() => {
2316
- const subscription = context.copilotkit.subscribe({ onRuntimeConnectionStatusChanged: () => {
2317
- forceUpdate();
2318
- } });
2319
- return () => {
2320
- subscription.unsubscribe();
2321
- };
2322
- }, []);
2323
- return context;
2324
- };
2325
-
2326
- //#endregion
2327
- //#region src/v2/hooks/use-render-tool-call.tsx
2328
- /**
2329
- * Memoized component that renders a single tool call.
2330
- * This prevents unnecessary re-renders when parent components update
2331
- * but the tool call data hasn't changed.
2332
- */
2333
- const ToolCallRenderer = react.default.memo(function ToolCallRenderer({ toolCall, toolMessage, RenderComponent, isExecuting }) {
2334
- const args = (0, react.useMemo)(() => (0, _copilotkit_shared.partialJSONParse)(toolCall.function.arguments), [toolCall.function.arguments]);
2335
- const toolName = toolCall.function.name;
2336
- if (toolMessage) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(RenderComponent, {
2337
- name: toolName,
2338
- toolCallId: toolCall.id,
2339
- args,
2340
- status: _copilotkit_core.ToolCallStatus.Complete,
2341
- result: toolMessage.content
2342
- });
2343
- else if (isExecuting) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(RenderComponent, {
2344
- name: toolName,
2345
- toolCallId: toolCall.id,
2346
- args,
2347
- status: _copilotkit_core.ToolCallStatus.Executing,
2348
- result: void 0
2349
- });
2350
- else return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(RenderComponent, {
2351
- name: toolName,
2352
- toolCallId: toolCall.id,
2353
- args,
2354
- status: _copilotkit_core.ToolCallStatus.InProgress,
2355
- result: void 0
2356
- });
2357
- }, (prevProps, nextProps) => {
2358
- var _prevProps$toolMessag, _nextProps$toolMessag;
2359
- if (prevProps.toolCall.id !== nextProps.toolCall.id) return false;
2360
- if (prevProps.toolCall.function.name !== nextProps.toolCall.function.name) return false;
2361
- if (prevProps.toolCall.function.arguments !== nextProps.toolCall.function.arguments) return false;
2362
- if (((_prevProps$toolMessag = prevProps.toolMessage) === null || _prevProps$toolMessag === void 0 ? void 0 : _prevProps$toolMessag.content) !== ((_nextProps$toolMessag = nextProps.toolMessage) === null || _nextProps$toolMessag === void 0 ? void 0 : _nextProps$toolMessag.content)) return false;
2363
- if (prevProps.isExecuting !== nextProps.isExecuting) return false;
2364
- if (prevProps.RenderComponent !== nextProps.RenderComponent) return false;
2365
- return true;
2366
- });
2367
- /**
2368
- * Hook that returns a function to render tool calls based on the render functions
2369
- * defined in CopilotKitProvider.
2370
- *
2371
- * @returns A function that takes a tool call and optional tool message and returns the rendered component
2372
- */
2373
- function useRenderToolCall$1() {
2374
- var _config$agentId;
2375
- const { copilotkit, executingToolCallIds } = useCopilotKit();
2376
- const config = useCopilotChatConfiguration();
2377
- const agentId = (_config$agentId = config === null || config === void 0 ? void 0 : config.agentId) !== null && _config$agentId !== void 0 ? _config$agentId : _copilotkit_shared.DEFAULT_AGENT_ID;
2378
- const renderToolCalls = (0, react.useSyncExternalStore)((callback) => {
2379
- return copilotkit.subscribe({ onRenderToolCallsChanged: callback }).unsubscribe;
2380
- }, () => copilotkit.renderToolCalls, () => copilotkit.renderToolCalls);
2381
- return (0, react.useCallback)(({ toolCall, toolMessage }) => {
2382
- const exactMatches = renderToolCalls.filter((rc) => rc.name === toolCall.function.name);
2383
- const renderConfig = exactMatches.find((rc) => rc.agentId === agentId) || exactMatches.find((rc) => !rc.agentId) || exactMatches[0] || renderToolCalls.find((rc) => rc.name === "*");
2384
- if (!renderConfig) return null;
2385
- const RenderComponent = renderConfig.render;
2386
- return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ToolCallRenderer, {
2387
- toolCall,
2388
- toolMessage,
2389
- RenderComponent,
2390
- isExecuting: executingToolCallIds.has(toolCall.id)
2391
- }, toolCall.id);
2392
- }, [
2393
- renderToolCalls,
2394
- executingToolCallIds,
2395
- agentId
2396
- ]);
2397
- }
2398
-
2399
- //#endregion
2400
- //#region src/v2/hooks/use-agent.tsx
2401
- let UseAgentUpdate = /* @__PURE__ */ function(UseAgentUpdate) {
2402
- UseAgentUpdate["OnMessagesChanged"] = "OnMessagesChanged";
2403
- UseAgentUpdate["OnStateChanged"] = "OnStateChanged";
2404
- UseAgentUpdate["OnRunStatusChanged"] = "OnRunStatusChanged";
2405
- return UseAgentUpdate;
2406
- }({});
2407
- const ALL_UPDATES = [
2408
- UseAgentUpdate.OnMessagesChanged,
2409
- UseAgentUpdate.OnStateChanged,
2410
- UseAgentUpdate.OnRunStatusChanged
2411
- ];
2412
- /**
2413
- * Clone a registry agent for per-thread isolation.
2414
- * Copies agent configuration (transport, headers, etc.) but resets conversation
2415
- * state (messages, threadId, state) so each thread starts fresh.
2416
- */
2417
- function cloneForThread(source, threadId, headers) {
2418
- const clone = source.clone();
2419
- if (clone === source) throw new Error(`useAgent: ${source.constructor.name}.clone() returned the same instance. clone() must return a new, independent object.`);
2420
- clone.threadId = threadId;
2421
- clone.setMessages([]);
2422
- clone.setState({});
2423
- if (clone instanceof _ag_ui_client.HttpAgent) clone.headers = { ...headers };
2424
- return clone;
2425
- }
2426
- /**
2427
- * Module-level WeakMap: registryAgent → (threadId → clone).
2428
- * Shared across all useAgent() calls so that every component using the same
2429
- * (agentId, threadId) pair receives the same agent instance. Using WeakMap
2430
- * ensures the clone map is garbage-collected when the registry agent is
2431
- * replaced (e.g. after reconnect or hot-reload).
2432
- */
2433
- const globalThreadCloneMap = /* @__PURE__ */ new WeakMap();
2434
- /**
2435
- * Look up an existing per-thread clone without creating one.
2436
- * Returns undefined when no clone has been created yet for this pair.
2437
- */
2438
- function getThreadClone(registryAgent, threadId) {
2439
- var _globalThreadCloneMap;
2440
- if (!registryAgent || !threadId) return void 0;
2441
- return (_globalThreadCloneMap = globalThreadCloneMap.get(registryAgent)) === null || _globalThreadCloneMap === void 0 ? void 0 : _globalThreadCloneMap.get(threadId);
2442
- }
2443
- function getOrCreateThreadClone(existing, threadId, headers) {
2444
- let byThread = globalThreadCloneMap.get(existing);
2445
- if (!byThread) {
2446
- byThread = /* @__PURE__ */ new Map();
2447
- globalThreadCloneMap.set(existing, byThread);
2448
- }
2449
- const cached = byThread.get(threadId);
2450
- if (cached) return cached;
2451
- const clone = cloneForThread(existing, threadId, headers);
2452
- byThread.set(threadId, clone);
2453
- return clone;
2454
- }
2455
- function useAgent({ agentId, threadId, updates, throttleMs } = {}) {
2456
- var _agentId, _threadId;
2457
- (_agentId = agentId) !== null && _agentId !== void 0 || (agentId = _copilotkit_shared.DEFAULT_AGENT_ID);
2458
- const { copilotkit } = useCopilotKit();
2459
- const providerThrottleMs = copilotkit.defaultThrottleMs;
2460
- const chatConfig = useCopilotChatConfiguration();
2461
- (_threadId = threadId) !== null && _threadId !== void 0 || (threadId = chatConfig === null || chatConfig === void 0 ? void 0 : chatConfig.threadId);
2462
- const [, forceUpdate] = (0, react.useReducer)((x) => x + 1, 0);
2463
- const updateFlags = (0, react.useMemo)(() => updates !== null && updates !== void 0 ? updates : ALL_UPDATES, [JSON.stringify(updates)]);
2464
- const provisionalAgentCache = (0, react.useRef)(/* @__PURE__ */ new Map());
2465
- const agent = (0, react.useMemo)(() => {
2466
- var _copilotkit$agents;
2467
- const cacheKey = threadId ? `${agentId}:${threadId}` : agentId;
2468
- const existing = copilotkit.getAgent(agentId);
2469
- if (existing) {
2470
- provisionalAgentCache.current.delete(cacheKey);
2471
- provisionalAgentCache.current.delete(agentId);
2472
- if (!threadId) return existing;
2473
- return getOrCreateThreadClone(existing, threadId, copilotkit.headers);
2474
- }
2475
- const isRuntimeConfigured = copilotkit.runtimeUrl !== void 0;
2476
- const status = copilotkit.runtimeConnectionStatus;
2477
- if (isRuntimeConfigured && (status === _copilotkit_core.CopilotKitCoreRuntimeConnectionStatus.Disconnected || status === _copilotkit_core.CopilotKitCoreRuntimeConnectionStatus.Connecting)) {
2478
- const cached = provisionalAgentCache.current.get(cacheKey);
2479
- if (cached) {
2480
- cached.headers = { ...copilotkit.headers };
2481
- return cached;
2482
- }
2483
- const provisional = new _copilotkit_core.ProxiedCopilotRuntimeAgent({
2484
- runtimeUrl: copilotkit.runtimeUrl,
2485
- agentId,
2486
- transport: copilotkit.runtimeTransport,
2487
- runtimeMode: "pending"
2488
- });
2489
- provisional.headers = { ...copilotkit.headers };
2490
- if (threadId) provisional.threadId = threadId;
2491
- provisionalAgentCache.current.set(cacheKey, provisional);
2492
- return provisional;
2493
- }
2494
- if (isRuntimeConfigured && status === _copilotkit_core.CopilotKitCoreRuntimeConnectionStatus.Error) {
2495
- const cached = provisionalAgentCache.current.get(cacheKey);
2496
- if (cached) {
2497
- cached.headers = { ...copilotkit.headers };
2498
- return cached;
2499
- }
2500
- const provisional = new _copilotkit_core.ProxiedCopilotRuntimeAgent({
2501
- runtimeUrl: copilotkit.runtimeUrl,
2502
- agentId,
2503
- transport: copilotkit.runtimeTransport,
2504
- runtimeMode: "pending"
2505
- });
2506
- provisional.headers = { ...copilotkit.headers };
2507
- if (threadId) provisional.threadId = threadId;
2508
- provisionalAgentCache.current.set(cacheKey, provisional);
2509
- return provisional;
2510
- }
2511
- const knownAgents = Object.keys((_copilotkit$agents = copilotkit.agents) !== null && _copilotkit$agents !== void 0 ? _copilotkit$agents : {});
2512
- const runtimePart = isRuntimeConfigured ? `runtimeUrl=${copilotkit.runtimeUrl}` : "no runtimeUrl";
2513
- throw new Error(`useAgent: Agent '${agentId}' not found after runtime sync (${runtimePart}). ` + (knownAgents.length ? `Known agents: [${knownAgents.join(", ")}]` : "No agents registered.") + " Verify your runtime /info and/or agents__unsafe_dev_only.");
2514
- }, [
2515
- agentId,
2516
- threadId,
2517
- copilotkit.agents,
2518
- copilotkit.runtimeConnectionStatus,
2519
- copilotkit.runtimeUrl,
2520
- copilotkit.runtimeTransport,
2521
- JSON.stringify(copilotkit.headers)
2522
- ]);
2523
- (0, react.useEffect)(() => {
2524
- if (updateFlags.length === 0) return;
2525
- let active = true;
2526
- const handlers = {};
2527
- let batchScheduled = false;
2528
- const batchedForceUpdate = () => {
2529
- if (!active) return;
2530
- if (!batchScheduled) {
2531
- batchScheduled = true;
2532
- queueMicrotask(() => {
2533
- batchScheduled = false;
2534
- if (active) forceUpdate();
2535
- });
2262
+ },
2263
+ onToolExecutionEnd: ({ toolCallId }) => {
2264
+ setExecutingToolCallIds((prev) => {
2265
+ if (!prev.has(toolCallId)) return prev;
2266
+ const next = new Set(prev);
2267
+ next.delete(toolCallId);
2268
+ return next;
2269
+ });
2536
2270
  }
2271
+ });
2272
+ return () => {
2273
+ subscription.unsubscribe();
2537
2274
  };
2538
- if (updateFlags.includes(UseAgentUpdate.OnMessagesChanged)) handlers.onMessagesChanged = forceUpdate;
2539
- if (updateFlags.includes(UseAgentUpdate.OnStateChanged)) handlers.onStateChanged = batchedForceUpdate;
2540
- if (updateFlags.includes(UseAgentUpdate.OnRunStatusChanged)) {
2541
- handlers.onRunInitialized = batchedForceUpdate;
2542
- handlers.onRunFinalized = batchedForceUpdate;
2543
- handlers.onRunFailed = batchedForceUpdate;
2544
- handlers.onRunErrorEvent = batchedForceUpdate;
2545
- }
2546
- const subscription = copilotkit.subscribeToAgentWithOptions(agent, handlers, { throttleMs });
2275
+ }, [copilotkit]);
2276
+ const onErrorRef = (0, react.useRef)(onError);
2277
+ (0, react.useEffect)(() => {
2278
+ onErrorRef.current = onError;
2279
+ }, [onError]);
2280
+ (0, react.useEffect)(() => {
2281
+ const subscription = copilotkit.subscribe({ onError: (event) => {
2282
+ if (onErrorRef.current) onErrorRef.current(event);
2283
+ else {
2284
+ var _event$context;
2285
+ console.error(`[CopilotKit] Error (${event.code}):`, event.error, (_event$context = event.context) !== null && _event$context !== void 0 ? _event$context : {});
2286
+ }
2287
+ } });
2547
2288
  return () => {
2548
- active = false;
2549
2289
  subscription.unsubscribe();
2550
2290
  };
2291
+ }, [copilotkit]);
2292
+ (0, react.useEffect)(() => {
2293
+ copilotkit.setRuntimeUrl(chatApiEndpoint);
2294
+ copilotkit.setRuntimeTransport(useSingleEndpoint === true ? "single" : useSingleEndpoint === false ? "rest" : "auto");
2295
+ copilotkit.setHeaders(mergedHeaders);
2296
+ copilotkit.setCredentials(credentials);
2297
+ copilotkit.setProperties(properties);
2298
+ copilotkit.setAgents__unsafe_dev_only(mergedAgents);
2299
+ copilotkit.setDebug(debug);
2551
2300
  }, [
2552
- agent,
2553
- forceUpdate,
2554
- throttleMs,
2555
- providerThrottleMs,
2556
- updateFlags
2301
+ copilotkit,
2302
+ chatApiEndpoint,
2303
+ mergedHeaders,
2304
+ credentials,
2305
+ properties,
2306
+ mergedAgents,
2307
+ useSingleEndpoint,
2308
+ debug
2557
2309
  ]);
2310
+ const didMountRef = (0, react.useRef)(false);
2558
2311
  (0, react.useEffect)(() => {
2559
- if (agent instanceof _ag_ui_client.HttpAgent) agent.headers = { ...copilotkit.headers };
2560
- }, [agent, JSON.stringify(copilotkit.headers)]);
2561
- return { agent };
2562
- }
2312
+ if (!didMountRef.current) return;
2313
+ copilotkit.setTools(allTools);
2314
+ }, [copilotkit, allTools]);
2315
+ (0, react.useEffect)(() => {
2316
+ if (!didMountRef.current) return;
2317
+ copilotkit.setRenderToolCalls(allRenderToolCalls);
2318
+ }, [copilotkit, allRenderToolCalls]);
2319
+ (0, react.useEffect)(() => {
2320
+ if (!didMountRef.current) return;
2321
+ copilotkit.setRenderActivityMessages(allActivityRenderers);
2322
+ }, [copilotkit, allActivityRenderers]);
2323
+ (0, react.useEffect)(() => {
2324
+ if (!didMountRef.current) return;
2325
+ copilotkit.setRenderCustomMessages(renderCustomMessagesList);
2326
+ }, [copilotkit, renderCustomMessagesList]);
2327
+ (0, react.useEffect)(() => {
2328
+ didMountRef.current = true;
2329
+ }, []);
2330
+ (0, react.useEffect)(() => {
2331
+ copilotkit.setDefaultThrottleMs(defaultThrottleMs);
2332
+ }, [copilotkit, defaultThrottleMs]);
2333
+ const designSkill = (_openGenerativeUI$des = openGenerativeUI === null || openGenerativeUI === void 0 ? void 0 : openGenerativeUI.designSkill) !== null && _openGenerativeUI$des !== void 0 ? _openGenerativeUI$des : DEFAULT_DESIGN_SKILL;
2334
+ (0, react.useLayoutEffect)(() => {
2335
+ if (!copilotkit || !openGenUIActive) return;
2336
+ const id = copilotkit.addContext({
2337
+ description: "Design guidelines for the generateSandboxedUi tool. Follow these when building UI.",
2338
+ value: designSkill
2339
+ });
2340
+ return () => {
2341
+ copilotkit.removeContext(id);
2342
+ };
2343
+ }, [
2344
+ copilotkit,
2345
+ designSkill,
2346
+ openGenUIActive
2347
+ ]);
2348
+ const sandboxFunctionsDescriptors = (0, react.useMemo)(() => {
2349
+ if (sandboxFunctionsList.length === 0) return null;
2350
+ return JSON.stringify(sandboxFunctionsList.map((fn) => ({
2351
+ name: fn.name,
2352
+ description: fn.description,
2353
+ parameters: (0, _copilotkit_shared.schemaToJsonSchema)(fn.parameters, { zodToJsonSchema: zod_to_json_schema.zodToJsonSchema })
2354
+ })));
2355
+ }, [sandboxFunctionsList]);
2356
+ (0, react.useLayoutEffect)(() => {
2357
+ if (!copilotkit || !sandboxFunctionsDescriptors || !openGenUIActive) return;
2358
+ const id = copilotkit.addContext({
2359
+ description: "Sandbox functions available in generated sandboxed UI code. Call via: await Websandbox.connection.remote.<functionName>(args)",
2360
+ value: sandboxFunctionsDescriptors
2361
+ });
2362
+ return () => {
2363
+ copilotkit.removeContext(id);
2364
+ };
2365
+ }, [
2366
+ copilotkit,
2367
+ sandboxFunctionsDescriptors,
2368
+ openGenUIActive
2369
+ ]);
2370
+ const contextValue = (0, react.useMemo)(() => ({
2371
+ copilotkit,
2372
+ executingToolCallIds
2373
+ }), [copilotkit, executingToolCallIds]);
2374
+ const licenseContextValue = (0, react.useMemo)(() => (0, _copilotkit_shared.createLicenseContextValue)(null), []);
2375
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SandboxFunctionsContext.Provider, {
2376
+ value: sandboxFunctionsList,
2377
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotKitContext.Provider, {
2378
+ value: contextValue,
2379
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(LicenseContext.Provider, {
2380
+ value: licenseContextValue,
2381
+ children: [
2382
+ runtimeA2UIEnabled && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(A2UIBuiltInToolCallRenderer, {}),
2383
+ runtimeA2UIEnabled && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(A2UICatalogContext, {
2384
+ catalog: a2ui === null || a2ui === void 0 ? void 0 : a2ui.catalog,
2385
+ includeSchema: a2ui === null || a2ui === void 0 ? void 0 : a2ui.includeSchema
2386
+ }),
2387
+ children,
2388
+ shouldRenderInspector ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotKitInspector, {
2389
+ core: copilotkit,
2390
+ defaultAnchor: inspectorDefaultAnchor
2391
+ }) : null,
2392
+ runtimeLicenseStatus === "none" && !resolvedPublicKey && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(LicenseWarningBanner, { type: "no_license" }),
2393
+ runtimeLicenseStatus === "expired" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(LicenseWarningBanner, { type: "expired" }),
2394
+ runtimeLicenseStatus === "invalid" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(LicenseWarningBanner, { type: "invalid" }),
2395
+ runtimeLicenseStatus === "expiring" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(LicenseWarningBanner, { type: "expiring" })
2396
+ ]
2397
+ })
2398
+ })
2399
+ });
2400
+ };
2563
2401
 
2564
2402
  //#endregion
2565
2403
  //#region src/v2/hooks/use-render-custom-messages.tsx
@@ -2574,13 +2412,12 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
2574
2412
  return aHasAgent ? -1 : 1;
2575
2413
  });
2576
2414
  return function(params) {
2577
- var _copilotkit$getRunIdF, _getThreadClone;
2415
+ var _copilotkit$getRunIdF;
2578
2416
  if (!customMessageRenderers.length) return null;
2579
2417
  const { message, position } = params;
2580
2418
  const resolvedRunId = (_copilotkit$getRunIdF = copilotkit.getRunIdForMessage(agentId, threadId, message.id)) !== null && _copilotkit$getRunIdF !== void 0 ? _copilotkit$getRunIdF : copilotkit.getRunIdsForThread(agentId, threadId).slice(-1)[0];
2581
2419
  const runId = resolvedRunId !== null && resolvedRunId !== void 0 ? resolvedRunId : `missing-run-id:${message.id}`;
2582
- const registryAgent = copilotkit.getAgent(agentId);
2583
- const agent = (_getThreadClone = getThreadClone(registryAgent, threadId)) !== null && _getThreadClone !== void 0 ? _getThreadClone : registryAgent;
2420
+ const agent = copilotkit.getAgent(agentId);
2584
2421
  if (!agent) return null;
2585
2422
  const messagesIdsInRun = resolvedRunId ? agent.messages.filter((msg) => copilotkit.getRunIdForMessage(agentId, threadId, msg.id) === resolvedRunId).map((msg) => msg.id) : [message.id];
2586
2423
  const rawMessageIndex = agent.messages.findIndex((msg) => msg.id === message.id);
@@ -2637,8 +2474,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
2637
2474
  tool.name,
2638
2475
  tool.available,
2639
2476
  copilotkit,
2640
- extraDeps.length,
2641
- ...extraDeps
2477
+ JSON.stringify(extraDeps)
2642
2478
  ]);
2643
2479
  }
2644
2480
 
@@ -2708,6 +2544,120 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
2708
2544
  ]);
2709
2545
  }
2710
2546
 
2547
+ //#endregion
2548
+ //#region src/v2/hooks/use-agent.tsx
2549
+ let UseAgentUpdate = /* @__PURE__ */ function(UseAgentUpdate) {
2550
+ UseAgentUpdate["OnMessagesChanged"] = "OnMessagesChanged";
2551
+ UseAgentUpdate["OnStateChanged"] = "OnStateChanged";
2552
+ UseAgentUpdate["OnRunStatusChanged"] = "OnRunStatusChanged";
2553
+ return UseAgentUpdate;
2554
+ }({});
2555
+ const ALL_UPDATES = [
2556
+ UseAgentUpdate.OnMessagesChanged,
2557
+ UseAgentUpdate.OnStateChanged,
2558
+ UseAgentUpdate.OnRunStatusChanged
2559
+ ];
2560
+ function useAgent({ agentId, updates, throttleMs } = {}) {
2561
+ var _agentId;
2562
+ (_agentId = agentId) !== null && _agentId !== void 0 || (agentId = _copilotkit_shared.DEFAULT_AGENT_ID);
2563
+ const { copilotkit } = useCopilotKit();
2564
+ const providerThrottleMs = copilotkit.defaultThrottleMs;
2565
+ const [, forceUpdate] = (0, react.useReducer)((x) => x + 1, 0);
2566
+ const updateFlags = (0, react.useMemo)(() => updates !== null && updates !== void 0 ? updates : ALL_UPDATES, [JSON.stringify(updates)]);
2567
+ const provisionalAgentCache = (0, react.useRef)(/* @__PURE__ */ new Map());
2568
+ const agent = (0, react.useMemo)(() => {
2569
+ var _copilotkit$agents;
2570
+ const existing = copilotkit.getAgent(agentId);
2571
+ if (existing) {
2572
+ provisionalAgentCache.current.delete(agentId);
2573
+ return existing;
2574
+ }
2575
+ const isRuntimeConfigured = copilotkit.runtimeUrl !== void 0;
2576
+ const status = copilotkit.runtimeConnectionStatus;
2577
+ if (isRuntimeConfigured && (status === _copilotkit_core.CopilotKitCoreRuntimeConnectionStatus.Disconnected || status === _copilotkit_core.CopilotKitCoreRuntimeConnectionStatus.Connecting)) {
2578
+ const cached = provisionalAgentCache.current.get(agentId);
2579
+ if (cached) {
2580
+ cached.headers = { ...copilotkit.headers };
2581
+ return cached;
2582
+ }
2583
+ const provisional = new _copilotkit_core.ProxiedCopilotRuntimeAgent({
2584
+ runtimeUrl: copilotkit.runtimeUrl,
2585
+ agentId,
2586
+ transport: copilotkit.runtimeTransport,
2587
+ runtimeMode: "pending"
2588
+ });
2589
+ provisional.headers = { ...copilotkit.headers };
2590
+ provisionalAgentCache.current.set(agentId, provisional);
2591
+ return provisional;
2592
+ }
2593
+ if (isRuntimeConfigured && status === _copilotkit_core.CopilotKitCoreRuntimeConnectionStatus.Error) {
2594
+ const cached = provisionalAgentCache.current.get(agentId);
2595
+ if (cached) {
2596
+ cached.headers = { ...copilotkit.headers };
2597
+ return cached;
2598
+ }
2599
+ const provisional = new _copilotkit_core.ProxiedCopilotRuntimeAgent({
2600
+ runtimeUrl: copilotkit.runtimeUrl,
2601
+ agentId,
2602
+ transport: copilotkit.runtimeTransport,
2603
+ runtimeMode: "pending"
2604
+ });
2605
+ provisional.headers = { ...copilotkit.headers };
2606
+ provisionalAgentCache.current.set(agentId, provisional);
2607
+ return provisional;
2608
+ }
2609
+ const knownAgents = Object.keys((_copilotkit$agents = copilotkit.agents) !== null && _copilotkit$agents !== void 0 ? _copilotkit$agents : {});
2610
+ const runtimePart = isRuntimeConfigured ? `runtimeUrl=${copilotkit.runtimeUrl}` : "no runtimeUrl";
2611
+ throw new Error(`useAgent: Agent '${agentId}' not found after runtime sync (${runtimePart}). ` + (knownAgents.length ? `Known agents: [${knownAgents.join(", ")}]` : "No agents registered.") + " Verify your runtime /info and/or agents__unsafe_dev_only.");
2612
+ }, [
2613
+ agentId,
2614
+ copilotkit.agents,
2615
+ copilotkit.runtimeConnectionStatus,
2616
+ copilotkit.runtimeUrl,
2617
+ copilotkit.runtimeTransport,
2618
+ JSON.stringify(copilotkit.headers)
2619
+ ]);
2620
+ (0, react.useEffect)(() => {
2621
+ if (updateFlags.length === 0) return;
2622
+ let active = true;
2623
+ const handlers = {};
2624
+ let batchScheduled = false;
2625
+ const batchedForceUpdate = () => {
2626
+ if (!active) return;
2627
+ if (!batchScheduled) {
2628
+ batchScheduled = true;
2629
+ queueMicrotask(() => {
2630
+ batchScheduled = false;
2631
+ if (active) forceUpdate();
2632
+ });
2633
+ }
2634
+ };
2635
+ if (updateFlags.includes(UseAgentUpdate.OnMessagesChanged)) handlers.onMessagesChanged = batchedForceUpdate;
2636
+ if (updateFlags.includes(UseAgentUpdate.OnStateChanged)) handlers.onStateChanged = batchedForceUpdate;
2637
+ if (updateFlags.includes(UseAgentUpdate.OnRunStatusChanged)) {
2638
+ handlers.onRunInitialized = batchedForceUpdate;
2639
+ handlers.onRunFinalized = batchedForceUpdate;
2640
+ handlers.onRunFailed = batchedForceUpdate;
2641
+ handlers.onRunErrorEvent = batchedForceUpdate;
2642
+ }
2643
+ const subscription = copilotkit.subscribeToAgentWithOptions(agent, handlers, { throttleMs });
2644
+ return () => {
2645
+ active = false;
2646
+ subscription.unsubscribe();
2647
+ };
2648
+ }, [
2649
+ agent,
2650
+ forceUpdate,
2651
+ throttleMs,
2652
+ providerThrottleMs,
2653
+ updateFlags
2654
+ ]);
2655
+ (0, react.useEffect)(() => {
2656
+ if (agent instanceof _ag_ui_client.HttpAgent) agent.headers = { ...copilotkit.headers };
2657
+ }, [agent, JSON.stringify(copilotkit.headers)]);
2658
+ return { agent };
2659
+ }
2660
+
2711
2661
  //#endregion
2712
2662
  //#region src/v2/hooks/use-suggestions.tsx
2713
2663
  function useSuggestions({ agentId } = {}) {
@@ -5299,10 +5249,7 @@ window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-
5299
5249
  const existingConfig = useCopilotChatConfiguration();
5300
5250
  const [agentAvailable, setAgentAvailable] = (0, react.useState)(false);
5301
5251
  const resolvedAgentId = (_existingConfig$agent = existingConfig === null || existingConfig === void 0 ? void 0 : existingConfig.agentId) !== null && _existingConfig$agent !== void 0 ? _existingConfig$agent : "default";
5302
- const { agent } = useAgent({
5303
- agentId: resolvedAgentId,
5304
- threadId: existingConfig === null || existingConfig === void 0 ? void 0 : existingConfig.threadId
5305
- });
5252
+ const { agent } = useAgent({ agentId: resolvedAgentId });
5306
5253
  const lastConnectedAgentRef = (0, react.useRef)(null);
5307
5254
  (0, react.useEffect)(() => {
5308
5255
  let detached = false;