@copilotkit/react-core 2.0.0-rc.2 → 2.0.0-rc.21

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 (47) hide show
  1. package/dist/{MarkdownRendererContext-B4Us6mwL.d.cts → MarkdownRendererContext-Bsl28Gmn.d.mts} +17 -33
  2. package/dist/MarkdownRendererContext-Bsl28Gmn.d.mts.map +1 -0
  3. package/dist/{MarkdownRendererContext-CRKFzsEB.d.mts → MarkdownRendererContext-CBppkb5j.d.cts} +17 -33
  4. package/dist/MarkdownRendererContext-CBppkb5j.d.cts.map +1 -0
  5. package/dist/{MarkdownSurfaces-S4wfUl3J.cjs → MarkdownSurfaces-CGW92DCL.cjs} +244 -331
  6. package/dist/MarkdownSurfaces-CGW92DCL.cjs.map +1 -0
  7. package/dist/{MarkdownSurfaces-Bd--93O1.mjs → MarkdownSurfaces-DveOwhaW.mjs} +224 -312
  8. package/dist/MarkdownSurfaces-DveOwhaW.mjs.map +1 -0
  9. package/dist/context.cjs +62 -63
  10. package/dist/context.cjs.map +1 -1
  11. package/dist/context.d.cts +53 -109
  12. package/dist/context.d.cts.map +1 -1
  13. package/dist/context.d.mts +53 -109
  14. package/dist/context.d.mts.map +1 -1
  15. package/dist/context.mjs +63 -64
  16. package/dist/context.mjs.map +1 -1
  17. package/dist/generative-ui.cjs +570 -567
  18. package/dist/generative-ui.cjs.map +1 -1
  19. package/dist/generative-ui.d.cts +2137 -4178
  20. package/dist/generative-ui.d.cts.map +1 -1
  21. package/dist/generative-ui.d.mts +2137 -4178
  22. package/dist/generative-ui.d.mts.map +1 -1
  23. package/dist/generative-ui.mjs +75 -73
  24. package/dist/generative-ui.mjs.map +1 -1
  25. package/dist/headless.cjs +286 -1021
  26. package/dist/headless.cjs.map +1 -1
  27. package/dist/headless.d.cts +143 -277
  28. package/dist/headless.d.cts.map +1 -1
  29. package/dist/headless.d.mts +107 -216
  30. package/dist/headless.d.mts.map +1 -1
  31. package/dist/headless.mjs +280 -1021
  32. package/dist/headless.mjs.map +1 -1
  33. package/dist/index.cjs +3351 -5707
  34. package/dist/index.cjs.map +1 -1
  35. package/dist/index.d.cts +314 -808
  36. package/dist/index.d.cts.map +1 -1
  37. package/dist/index.d.mts +311 -805
  38. package/dist/index.d.mts.map +1 -1
  39. package/dist/index.mjs +1827 -5565
  40. package/dist/index.mjs.map +1 -1
  41. package/dist/index.umd.js +3571 -5978
  42. package/dist/index.umd.js.map +1 -1
  43. package/package.json +17 -18
  44. package/dist/MarkdownRendererContext-B4Us6mwL.d.cts.map +0 -1
  45. package/dist/MarkdownRendererContext-CRKFzsEB.d.mts.map +0 -1
  46. package/dist/MarkdownSurfaces-Bd--93O1.mjs.map +0 -1
  47. package/dist/MarkdownSurfaces-S4wfUl3J.cjs.map +0 -1
package/dist/headless.cjs CHANGED
@@ -29,23 +29,66 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
29
29
  let _copilotkit_react_core_context = require("@copilotkit/react-core/context");
30
30
  let react = require("react");
31
31
  react = __toESM(react);
32
- let _copilotkit_shared = require("@copilotkit/shared");
33
- let react_jsx_runtime = require("react/jsx-runtime");
34
32
  let _copilotkit_core = require("@copilotkit/core");
35
- let _ag_ui_client = require("@ag-ui/client");
36
- let zod = require("zod");
37
- let _ag_ui_core = require("@ag-ui/core");
33
+ let react_jsx_runtime = require("react/jsx-runtime");
34
+ let _copilotkit_shared = require("@copilotkit/shared");
35
+
36
+ //#region src/providers/use-owned-core.ts
37
+ /**
38
+ * @internal Create a core for the provider's lifetime and dispose it on
39
+ * unmount.
40
+ *
41
+ * The dispose waits one task. StrictMode (and Fast Refresh) unmount and
42
+ * remount effects in the same commit, so the remount cancels the pending
43
+ * dispose and the same core keeps working. When effects mount again after the
44
+ * core was really disposed (for example an `<Activity>` that was hidden and
45
+ * shown), the hook creates a new core and renders again: a disposed core is
46
+ * never reused.
47
+ *
48
+ * `ref` holds the current core. The provider owns it, so code that runs
49
+ * before the core exists can read `ref.current`.
50
+ *
51
+ * @example
52
+ * const coreRef = useRef<CopilotKitCoreReact | null>(null);
53
+ * const core = ɵuseOwnedCore(coreRef, () => new CopilotKitCoreReact(config));
54
+ */
55
+ function ɵuseOwnedCore(ref, create) {
56
+ const createRef = (0, react.useRef)(create);
57
+ createRef.current = create;
58
+ const pendingDispose = (0, react.useRef)(void 0);
59
+ const disposedRef = (0, react.useRef)(false);
60
+ const [, rerender] = (0, react.useReducer)((count) => count + 1, 0);
61
+ const current = ref.current ?? create();
62
+ ref.current = current;
63
+ (0, react.useEffect)(() => {
64
+ clearTimeout(pendingDispose.current);
65
+ pendingDispose.current = void 0;
66
+ let core = ref.current ?? createRef.current();
67
+ if (disposedRef.current) {
68
+ disposedRef.current = false;
69
+ core = createRef.current();
70
+ rerender();
71
+ }
72
+ ref.current = core;
73
+ return () => {
74
+ pendingDispose.current = setTimeout(() => {
75
+ pendingDispose.current = void 0;
76
+ disposedRef.current = true;
77
+ core.dispose();
78
+ }, 0);
79
+ };
80
+ }, [ref]);
81
+ return current;
82
+ }
38
83
 
84
+ //#endregion
39
85
  //#region src/lib/shallow-stable-ref.ts
40
86
  /**
41
- * Shallow equality comparison for objects.
87
+ * Shallow equality comparison for objects: same own keys, each holding the
88
+ * same value (`Object.is`). Core's `ɵshallowEqualRecord` holds the rule.
42
89
  */
43
90
  function shallowEqual(obj1, obj2) {
44
- const keys1 = Object.keys(obj1);
45
- const keys2 = Object.keys(obj2);
46
- if (keys1.length !== keys2.length) return false;
47
- for (const key of keys1) if (obj1[key] !== obj2[key]) return false;
48
- return true;
91
+ return (0, _copilotkit_core.ɵshallowEqualRecord)(obj1, obj2);
49
92
  }
50
93
  /**
51
94
  * Returns true only for plain JS objects (`{}`), excluding arrays, Dates,
@@ -79,241 +122,77 @@ function useShallowStableRef(value) {
79
122
 
80
123
  //#endregion
81
124
  //#region src/providers/CopilotChatConfigurationProvider.tsx
82
- const CopilotChatDefaultLabels = {
83
- chatInputPlaceholder: "Type a message...",
84
- chatInputToolbarStartTranscribeButtonLabel: "Transcribe",
85
- chatInputToolbarCancelTranscribeButtonLabel: "Cancel",
86
- chatInputToolbarFinishTranscribeButtonLabel: "Finish",
87
- chatInputToolbarAddButtonLabel: "Add attachments",
88
- chatInputToolbarToolsButtonLabel: "Tools",
89
- chatInputToolbarSendButtonLabel: "Send message",
90
- chatInputToolbarStopButtonLabel: "Stop",
91
- assistantMessageToolbarCopyCodeLabel: "Copy",
92
- assistantMessageToolbarCopyCodeCopiedLabel: "Copied",
93
- assistantMessageToolbarCopyMessageLabel: "Copy",
94
- assistantMessageToolbarInspectorLabel: "View in Inspector",
95
- assistantMessageToolbarInspectorDescription: "Open this message in the Inspector",
96
- assistantMessageToolbarInspectorLocalOnlyLabel: "Local only",
97
- assistantMessageToolbarInspectorLocalOnlyDescription: "Only visible on localhost or loopback hosts in development. Never shown in production.",
98
- assistantMessageToolbarInspectorTitle: "CopilotKit Inspector",
99
- assistantMessageToolbarInspectorHideLabel: "Hide this icon",
100
- assistantMessageToolbarInspectorHideDescription: "Until you reload this page",
101
- assistantMessageToolbarThumbsUpLabel: "Good response",
102
- assistantMessageToolbarThumbsDownLabel: "Bad response",
103
- assistantMessageFeedbackCommentPlaceholder: "Add a comment (optional)",
104
- assistantMessageFeedbackCommentSubmitLabel: "Send comment",
105
- assistantMessageToolbarReadAloudLabel: "Read aloud",
106
- assistantMessageToolbarRegenerateLabel: "Regenerate",
107
- userMessageToolbarCopyMessageLabel: "Copy",
108
- userMessageToolbarEditMessageLabel: "Edit",
109
- userMessageToolbarPreviousBranchLabel: "Previous branch",
110
- userMessageToolbarNextBranchLabel: "Next branch",
111
- chatDisclaimerText: "AI can make mistakes. Please verify important information.",
112
- chatToggleOpenLabel: "Open chat",
113
- chatToggleCloseLabel: "Close chat",
114
- chatScrollToBottomLabel: "Scroll to bottom",
115
- modalHeaderTitle: "CopilotKit Chat",
116
- welcomeMessageText: "How can I help you today?",
117
- reasoningMessageThinkingLabel: "Thinking…",
118
- chatInputSlashMenuLabel: "Slash commands",
119
- chatInputSlashMenuEmptyText: "No commands found",
120
- attachmentRemoveButtonLabel: "Remove attachment",
121
- attachmentPlayVideoButtonLabel: "Play video",
122
- attachmentPreviewCloseButtonLabel: "Close preview",
123
- modalHeaderCloseButtonLabel: "Close",
124
- modalHeaderThreadsButtonLabel: "Open threads",
125
- sidebarLabel: "Copilot chat sidebar"
126
- };
127
- /**
128
- * Mobile breakpoint below which the chat modal and the thread-list drawer are
129
- * mutually exclusive. At or above this width both surfaces may coexist. This
130
- * mirrors the `(max-width: 767px)` / `(min-width: 768px)` split already used by
131
- * CopilotChatInput and CopilotSidebarView.
132
- */
133
- const MOBILE_MAX_WIDTH_PX = 767;
134
- /**
135
- * Reports whether the current viewport is in the mobile range (`<768px`), where
136
- * the chat modal and drawer must not be open simultaneously. SSR-safe and
137
- * defensive against environments without `matchMedia` (treated as desktop, so
138
- * no mutual-exclusion constraint is applied).
139
- *
140
- * @returns `true` when the viewport is mobile-width, `false` otherwise.
141
- */
142
- function isMobileViewport() {
143
- if (typeof window === "undefined" || typeof window.matchMedia !== "function") return false;
144
- return window.matchMedia(`(max-width: ${MOBILE_MAX_WIDTH_PX}px)`).matches;
145
- }
146
125
  const CopilotChatConfiguration = (0, react.createContext)(null);
147
126
  const CopilotChatConfigurationProvider = ({ children, labels, agentId, threadId, hasExplicitThreadId, isModalDefaultOpen }) => {
148
127
  const parentConfig = (0, react.useContext)(CopilotChatConfiguration);
149
128
  const stableLabels = useShallowStableRef(labels);
150
129
  const mergedLabels = (0, react.useMemo)(() => ({
151
- ...CopilotChatDefaultLabels,
130
+ ..._copilotkit_core.CopilotChatDefaultLabels,
152
131
  ...parentConfig?.labels,
153
132
  ...stableLabels
154
133
  }), [stableLabels, parentConfig?.labels]);
155
134
  const providerAgentId = (0, _copilotkit_react_core_context.useDefaultAgentId)();
156
- const resolvedAgentId = agentId ?? parentConfig?.agentId ?? providerAgentId ?? _copilotkit_shared.DEFAULT_AGENT_ID;
157
- const threadIdPropIsAuthoritative = threadId !== void 0 && hasExplicitThreadId !== false;
158
- const isThreadIdControlled = threadIdPropIsAuthoritative;
159
- const [activeThreadOverride, setActiveThreadOverride] = (0, react.useState)(null);
160
- const resolvedThreadId = (0, react.useMemo)(() => {
161
- if (threadIdPropIsAuthoritative) return threadId;
162
- if (activeThreadOverride) return activeThreadOverride.threadId;
163
- if (parentConfig?.threadId) return parentConfig.threadId;
164
- if (threadId) return threadId;
165
- return (0, _copilotkit_shared.randomUUID)();
135
+ const options = {
136
+ agentId,
137
+ threadId,
138
+ hasExplicitThreadId,
139
+ isModalDefaultOpen,
140
+ providerAgentId
141
+ };
142
+ const parentStore = parentConfig?.ɵstore ?? null;
143
+ const [store] = (0, react.useState)(() => new _copilotkit_core.ɵChatConfigurationStore(options, parentStore));
144
+ store.ɵsetOptions(options);
145
+ const snapshot = (0, react.useSyncExternalStore)(store.subscribe, store.getSnapshot, store.getSnapshot);
146
+ (0, react.useEffect)(() => {
147
+ store.update({
148
+ agentId,
149
+ threadId,
150
+ hasExplicitThreadId,
151
+ isModalDefaultOpen,
152
+ providerAgentId
153
+ });
166
154
  }, [
167
- threadIdPropIsAuthoritative,
155
+ store,
156
+ agentId,
168
157
  threadId,
169
- parentConfig?.threadId,
170
- activeThreadOverride
158
+ hasExplicitThreadId,
159
+ isModalDefaultOpen,
160
+ providerAgentId
171
161
  ]);
172
162
  const copilotkit = (0, react.useContext)(_copilotkit_react_core_context.CopilotKitContext)?.copilotkit;
173
- const openThreadRef = (0, react.useRef)(null);
174
- const latestThreadIdRef = (0, react.useRef)(resolvedThreadId);
175
- latestThreadIdRef.current = resolvedThreadId;
176
163
  (0, react.useEffect)(() => {
177
164
  if (copilotkit === void 0) return;
178
- const registration = copilotkit.registerOpenThread({
179
- agentId: resolvedAgentId,
180
- threadId: latestThreadIdRef.current
181
- });
182
- openThreadRef.current = registration;
183
- return () => {
184
- registration.unregister();
185
- openThreadRef.current = null;
186
- };
187
- }, [copilotkit, resolvedAgentId]);
188
- (0, react.useEffect)(() => {
189
- openThreadRef.current?.update(resolvedThreadId);
190
- }, [resolvedThreadId]);
191
- const resolvedHasExplicitThreadId = (threadIdPropIsAuthoritative ? true : activeThreadOverride?.explicit ?? hasExplicitThreadId ?? false) || !!parentConfig?.hasExplicitThreadId;
192
- const [internalModalOpen, setInternalModalOpen] = (0, react.useState)(isModalDefaultOpen ?? true);
193
- const hasExplicitDefault = isModalDefaultOpen !== void 0;
194
- const setAndSync = (0, react.useCallback)((open) => {
195
- setInternalModalOpen(open);
196
- parentConfig?.setModalOpen(open);
197
- }, [parentConfig?.setModalOpen]);
198
- const isMounted = (0, react.useRef)(false);
199
- (0, react.useEffect)(() => {
200
- if (!hasExplicitDefault) return;
201
- if (!isMounted.current) {
202
- isMounted.current = true;
203
- return;
204
- }
205
- if (parentConfig?.isModalOpen === void 0) return;
206
- setInternalModalOpen(parentConfig.isModalOpen);
207
- }, [parentConfig?.isModalOpen, hasExplicitDefault]);
208
- const resolvedIsModalOpen = hasExplicitDefault ? internalModalOpen : parentConfig?.isModalOpen ?? internalModalOpen;
209
- const resolvedSetModalOpen = hasExplicitDefault ? setAndSync : parentConfig?.setModalOpen ?? setInternalModalOpen;
210
- const [ownDrawerOpen, setOwnDrawerOpen] = (0, react.useState)(false);
211
- const [ownDrawerCount, setOwnDrawerCount] = (0, react.useState)(0);
212
- const modalCloseRef = (0, react.useRef)(() => {});
213
- modalCloseRef.current = resolvedSetModalOpen;
214
- const registeredModalClosersRef = (0, react.useRef)([]);
215
- const ownRegisterModalCloser = (0, react.useCallback)((closeModal) => {
216
- registeredModalClosersRef.current.push(closeModal);
217
- return () => {
218
- registeredModalClosersRef.current = registeredModalClosersRef.current.filter((entry) => entry !== closeModal);
219
- };
220
- }, []);
221
- const ownSetDrawerOpen = (0, react.useCallback)((open) => {
222
- setOwnDrawerOpen(open);
223
- if (open && isMobileViewport()) {
224
- const registered = registeredModalClosersRef.current;
225
- (registered.length > 0 ? registered[registered.length - 1] : modalCloseRef.current)(false);
226
- }
227
- }, []);
228
- const ownRegisterDrawer = (0, react.useCallback)(() => {
229
- setOwnDrawerCount((count) => count + 1);
230
- return () => {
231
- setOwnDrawerCount((count) => Math.max(0, count - 1));
232
- };
233
- }, []);
234
- const resolvedDrawerOpen = parentConfig ? parentConfig.drawerOpen : ownDrawerOpen;
235
- const resolvedSetDrawerOpen = parentConfig ? parentConfig.setDrawerOpen : ownSetDrawerOpen;
236
- const resolvedDrawerRegistered = parentConfig ? parentConfig.drawerRegistered : ownDrawerCount > 0;
237
- const resolvedRegisterDrawer = parentConfig ? parentConfig.registerDrawer : ownRegisterDrawer;
238
- const resolvedRegisterModalCloser = parentConfig ? parentConfig.ɵregisterModalCloser : ownRegisterModalCloser;
239
- (0, react.useEffect)(() => {
240
- if (!hasExplicitDefault) return;
241
- return resolvedRegisterModalCloser(resolvedSetModalOpen);
242
- }, [
243
- hasExplicitDefault,
244
- resolvedRegisterModalCloser,
245
- resolvedSetModalOpen
246
- ]);
247
- const isThreadIdControlledRef = (0, react.useRef)(isThreadIdControlled);
248
- isThreadIdControlledRef.current = isThreadIdControlled;
249
- const ownSetActiveThreadId = (0, react.useCallback)((id, options) => {
250
- setActiveThreadOverride({
251
- threadId: id,
252
- explicit: options?.explicit ?? true
253
- });
254
- }, []);
255
- const ownStartNewThread = (0, react.useCallback)(() => {
256
- setActiveThreadOverride({
257
- threadId: (0, _copilotkit_shared.randomUUID)(),
258
- explicit: false
259
- });
260
- }, []);
261
- const parentSetActiveThreadId = parentConfig?.setActiveThreadId;
262
- const parentStartNewThread = parentConfig?.startNewThread;
263
- const resolvedSetActiveThreadId = (0, react.useCallback)((id, options) => {
264
- if (isThreadIdControlledRef.current) {
265
- console.warn("[CopilotKit] Ignoring setActiveThreadId(): threadId is controlled via the `threadId` prop on CopilotChatConfigurationProvider.");
266
- return;
267
- }
268
- if (parentSetActiveThreadId) {
269
- parentSetActiveThreadId(id, options);
270
- return;
271
- }
272
- ownSetActiveThreadId(id, options);
273
- }, [parentSetActiveThreadId, ownSetActiveThreadId]);
274
- const resolvedStartNewThread = (0, react.useCallback)(() => {
275
- if (isThreadIdControlledRef.current) {
276
- console.warn("[CopilotKit] Ignoring startNewThread(): threadId is controlled via the `threadId` prop on CopilotChatConfigurationProvider.");
277
- return;
278
- }
279
- if (parentStartNewThread) {
280
- parentStartNewThread();
281
- return;
282
- }
283
- ownStartNewThread();
284
- }, [parentStartNewThread, ownStartNewThread]);
285
- const setModalOpenWithDrawerExclusion = (0, react.useCallback)((open) => {
286
- if (open && isMobileViewport()) resolvedSetDrawerOpen(false);
287
- resolvedSetModalOpen(open);
288
- }, [resolvedSetModalOpen, resolvedSetDrawerOpen]);
165
+ return store.bindOpenThread(copilotkit);
166
+ }, [copilotkit, store]);
167
+ const ownsModal = isModalDefaultOpen !== void 0;
168
+ const isModalOpen = ownsModal || !parentConfig ? snapshot.isModalOpen : parentConfig.isModalOpen;
169
+ const setModalOpen = ownsModal || !parentConfig ? store.setModalOpen : parentConfig.setModalOpen;
170
+ const { agentId: resolvedAgentId, threadId: resolvedThreadId, hasExplicitThreadId: resolvedHasExplicitThreadId, drawerOpen, drawerRegistered } = snapshot;
289
171
  const configurationValue = (0, react.useMemo)(() => ({
290
172
  labels: mergedLabels,
291
173
  agentId: resolvedAgentId,
292
174
  threadId: resolvedThreadId,
293
175
  hasExplicitThreadId: resolvedHasExplicitThreadId,
294
- isModalOpen: resolvedIsModalOpen,
295
- setModalOpen: setModalOpenWithDrawerExclusion,
296
- drawerOpen: resolvedDrawerOpen,
297
- setDrawerOpen: resolvedSetDrawerOpen,
298
- drawerRegistered: resolvedDrawerRegistered,
299
- registerDrawer: resolvedRegisterDrawer,
300
- ɵregisterModalCloser: resolvedRegisterModalCloser,
301
- setActiveThreadId: resolvedSetActiveThreadId,
302
- startNewThread: resolvedStartNewThread
176
+ isModalOpen,
177
+ setModalOpen,
178
+ drawerOpen,
179
+ setDrawerOpen: store.setDrawerOpen,
180
+ drawerRegistered,
181
+ registerDrawer: store.registerDrawer,
182
+ ɵregisterModalCloser: store.registerModalCloser,
183
+ setActiveThreadId: store.setActiveThreadId,
184
+ startNewThread: store.startNewThread,
185
+ ɵstore: store
303
186
  }), [
304
187
  mergedLabels,
305
188
  resolvedAgentId,
306
189
  resolvedThreadId,
307
190
  resolvedHasExplicitThreadId,
308
- resolvedIsModalOpen,
309
- setModalOpenWithDrawerExclusion,
310
- resolvedDrawerOpen,
311
- resolvedSetDrawerOpen,
312
- resolvedDrawerRegistered,
313
- resolvedRegisterDrawer,
314
- resolvedRegisterModalCloser,
315
- resolvedSetActiveThreadId,
316
- resolvedStartNewThread
191
+ isModalOpen,
192
+ setModalOpen,
193
+ drawerOpen,
194
+ drawerRegistered,
195
+ store
317
196
  ]);
318
197
  return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotChatConfiguration.Provider, {
319
198
  value: configurationValue,
@@ -394,163 +273,57 @@ const ALL_UPDATES = [
394
273
  UseAgentUpdate.OnRunStatusChanged
395
274
  ];
396
275
  function useAgent({ agentId, threadId, runtimeAgentId, updates, throttleMs } = {}) {
397
- if (threadId != null && runtimeAgentId == null) throw new Error(`useAgent: \`threadId\` requires \`runtimeAgentId\`. A threadId is written onto a single agent, but an agent resolved by agentId alone is shared, so scoping a thread to it would clobber other useAgent callers. Pass a distinct local \`agentId\` and the runtime agent to route to, e.g. useAgent({ agentId: "chat-1", runtimeAgentId: "${agentId ?? "default"}", threadId }).`);
398
- if (runtimeAgentId != null && threadId == null) throw new Error(`useAgent: \`runtimeAgentId\` requires \`threadId\`. A proxied agent exists to scope a thread to a private instance; without a threadId it behaves like the shared agent while adding a registration and a local agentId to keep unique. Either pass the thread, e.g. useAgent({ agentId: "${agentId ?? "chat-1"}", runtimeAgentId: "${runtimeAgentId}", threadId }), or bind to the agent directly with useAgent({ agentId: "${runtimeAgentId}" }).`);
399
- if (runtimeAgentId != null && agentId == null) throw new Error(`useAgent: \`runtimeAgentId\` requires an explicit \`agentId\`. The proxied agent is registered under \`agentId\`, and the usual fallbacks (chat configuration, then "${_copilotkit_shared.DEFAULT_AGENT_ID}") name agents that already exist — registering over one throws or shadows it. Pick a local id for this hook, e.g. useAgent({ agentId: "chat-1", runtimeAgentId: "${runtimeAgentId}", threadId }).`);
276
+ (0, _copilotkit_core.ɵvalidateAgentBinding)({
277
+ agentId,
278
+ threadId,
279
+ runtimeAgentId
280
+ });
400
281
  const chatConfig = useCopilotChatConfiguration();
401
282
  const providerAgentId = (0, _copilotkit_react_core_context.useDefaultAgentId)();
402
- const resolvedAgentId = agentId ?? chatConfig?.agentId ?? providerAgentId ?? _copilotkit_shared.DEFAULT_AGENT_ID;
283
+ const resolvedAgentId = (0, _copilotkit_core.ɵresolveAgentId)({
284
+ agentId,
285
+ chatAgentId: chatConfig?.agentId,
286
+ providerAgentId
287
+ });
403
288
  const { copilotkit } = (0, _copilotkit_react_core_context.useCopilotKit)();
289
+ const resolver = (0, _copilotkit_core.ɵgetAgentResolver)(copilotkit);
290
+ const revision = (0, react.useSyncExternalStore)(resolver.subscribe, resolver.getSnapshot, resolver.getSnapshot);
404
291
  const providerThrottleMs = copilotkit.defaultThrottleMs;
405
292
  const [, forceUpdate] = (0, react.useReducer)((x) => x + 1, 0);
406
293
  const updateFlags = (0, react.useMemo)(() => updates ?? ALL_UPDATES, [JSON.stringify(updates)]);
407
- const provisionalAgentCache = (0, react.useRef)(/* @__PURE__ */ new Map());
408
- const [registeredProxyAgent, setRegisteredProxyAgent] = (0, react.useState)(null);
409
294
  (0, react.useEffect)(() => {
410
- if (runtimeAgentId == null) {
411
- setRegisteredProxyAgent(null);
412
- return;
413
- }
414
- const { agent: proxy, unregister } = copilotkit.registerProxiedAgent({
295
+ if (runtimeAgentId == null) return;
296
+ return resolver.bindProxy({
415
297
  agentId: resolvedAgentId,
416
298
  runtimeAgentId
417
299
  });
418
- provisionalAgentCache.current.delete(resolvedAgentId);
419
- setRegisteredProxyAgent(proxy);
420
- return () => {
421
- unregister();
422
- setRegisteredProxyAgent(null);
423
- };
424
300
  }, [
425
- copilotkit,
301
+ resolver,
426
302
  resolvedAgentId,
427
303
  runtimeAgentId
428
304
  ]);
429
- const { agent, isReady } = (0, react.useMemo)(() => {
430
- if (runtimeAgentId != null) {
431
- if (registeredProxyAgent) {
432
- provisionalAgentCache.current.delete(resolvedAgentId);
433
- return {
434
- agent: registeredProxyAgent,
435
- isReady: true
436
- };
437
- }
438
- const cached = provisionalAgentCache.current.get(resolvedAgentId);
439
- if (cached) {
440
- copilotkit.applyHeadersToAgent(cached);
441
- return {
442
- agent: cached,
443
- isReady: false
444
- };
445
- }
446
- const provisional = new _copilotkit_core.ProxiedCopilotRuntimeAgent({
447
- runtimeUrl: copilotkit.runtimeUrl,
448
- agentId: resolvedAgentId,
449
- runtimeAgentId,
450
- transport: copilotkit.runtimeTransport,
451
- runtimeMode: "pending"
452
- });
453
- copilotkit.applyHeadersToAgent(provisional);
454
- provisionalAgentCache.current.set(resolvedAgentId, provisional);
455
- return {
456
- agent: provisional,
457
- isReady: false
458
- };
459
- }
460
- const existing = copilotkit.getAgent(resolvedAgentId);
461
- if (existing) {
462
- provisionalAgentCache.current.delete(resolvedAgentId);
463
- return {
464
- agent: existing,
465
- isReady: true
466
- };
467
- }
468
- const isRuntimeConfigured = copilotkit.runtimeUrl !== void 0;
469
- const status = copilotkit.runtimeConnectionStatus;
470
- if (isRuntimeConfigured && (status === _copilotkit_core.CopilotKitCoreRuntimeConnectionStatus.Disconnected || status === _copilotkit_core.CopilotKitCoreRuntimeConnectionStatus.Connecting)) {
471
- const cached = provisionalAgentCache.current.get(resolvedAgentId);
472
- if (cached) return {
473
- agent: cached,
474
- isReady: false
475
- };
476
- const provisional = new _copilotkit_core.ProxiedCopilotRuntimeAgent({
477
- runtimeUrl: copilotkit.runtimeUrl,
478
- agentId: resolvedAgentId,
479
- transport: copilotkit.runtimeTransport,
480
- credentials: copilotkit.credentials,
481
- runtimeMode: "pending"
482
- });
483
- copilotkit.applyHeadersToAgent(provisional);
484
- provisionalAgentCache.current.set(resolvedAgentId, provisional);
485
- return {
486
- agent: provisional,
487
- isReady: false
488
- };
489
- }
490
- if (isRuntimeConfigured && status === _copilotkit_core.CopilotKitCoreRuntimeConnectionStatus.Error) {
491
- const cached = provisionalAgentCache.current.get(resolvedAgentId);
492
- if (cached) return {
493
- agent: cached,
494
- isReady: false
495
- };
496
- const provisional = new _copilotkit_core.ProxiedCopilotRuntimeAgent({
497
- runtimeUrl: copilotkit.runtimeUrl,
498
- agentId: resolvedAgentId,
499
- transport: copilotkit.runtimeTransport,
500
- credentials: copilotkit.credentials,
501
- runtimeMode: "pending"
502
- });
503
- copilotkit.applyHeadersToAgent(provisional);
504
- provisionalAgentCache.current.set(resolvedAgentId, provisional);
505
- return {
506
- agent: provisional,
507
- isReady: false
508
- };
509
- }
510
- const knownAgents = Object.keys(copilotkit.agents ?? {});
511
- const runtimePart = isRuntimeConfigured ? `runtimeUrl=${copilotkit.runtimeUrl}` : "no runtimeUrl";
512
- throw new Error(`useAgent: Agent '${resolvedAgentId}' 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.");
513
- }, [
305
+ const headersGeneration = copilotkit.ɵheadersGeneration;
306
+ const { agent, isReady } = (0, react.useMemo)(() => resolver.resolve({
307
+ agentId: resolvedAgentId,
308
+ runtimeAgentId,
309
+ caller: "useAgent"
310
+ }), [
311
+ resolver,
312
+ revision,
514
313
  resolvedAgentId,
515
314
  runtimeAgentId,
516
- registeredProxyAgent,
517
315
  copilotkit.agents,
518
316
  copilotkit.runtimeConnectionStatus,
519
317
  copilotkit.runtimeUrl,
520
318
  copilotkit.runtimeTransport,
521
319
  copilotkit.credentials,
522
- JSON.stringify(copilotkit.headers)
320
+ headersGeneration
523
321
  ]);
524
- (0, react.useEffect)(() => {
525
- if (updateFlags.length === 0) return;
526
- let active = true;
527
- const handlers = {};
528
- let batchScheduled = false;
529
- const batchedForceUpdate = () => {
530
- if (!active) return;
531
- if (!batchScheduled) {
532
- batchScheduled = true;
533
- queueMicrotask(() => {
534
- batchScheduled = false;
535
- if (active) forceUpdate();
536
- });
537
- }
538
- };
539
- if (updateFlags.includes(UseAgentUpdate.OnMessagesChanged)) handlers.onMessagesChanged = batchedForceUpdate;
540
- if (updateFlags.includes(UseAgentUpdate.OnStateChanged)) handlers.onStateChanged = batchedForceUpdate;
541
- if (updateFlags.includes(UseAgentUpdate.OnRunStatusChanged)) {
542
- handlers.onRunInitialized = batchedForceUpdate;
543
- handlers.onRunStartedEvent = batchedForceUpdate;
544
- handlers.onRunFinalized = batchedForceUpdate;
545
- handlers.onRunFailed = batchedForceUpdate;
546
- handlers.onRunErrorEvent = batchedForceUpdate;
547
- }
548
- const subscription = copilotkit.subscribeToAgentWithOptions(agent, handlers, { throttleMs });
549
- return () => {
550
- active = false;
551
- subscription.unsubscribe();
552
- };
553
- }, [
322
+ (0, react.useEffect)(() => (0, _copilotkit_core.ɵsubscribeToAgentUpdates)(copilotkit, agent, {
323
+ updates: updateFlags,
324
+ throttleMs,
325
+ onUpdate: forceUpdate
326
+ }), [
554
327
  agent,
555
328
  forceUpdate,
556
329
  throttleMs,
@@ -558,16 +331,18 @@ function useAgent({ agentId, threadId, runtimeAgentId, updates, throttleMs } = {
558
331
  updateFlags
559
332
  ]);
560
333
  (0, react.useEffect)(() => {
561
- if ((0, _copilotkit_core.ɵisHttpAgent)(agent)) copilotkit.applyHeadersToAgent(agent);
562
- if (agent instanceof _copilotkit_core.ProxiedCopilotRuntimeAgent) agent.credentials = copilotkit.credentials;
334
+ resolver.refreshRequestSettings(agent);
563
335
  }, [
336
+ resolver,
564
337
  agent,
565
- JSON.stringify(copilotkit.headers),
338
+ headersGeneration,
566
339
  copilotkit.credentials
567
340
  ]);
568
- const configThreadId = chatConfig?.threadId;
569
- const configHasExplicitThreadId = chatConfig?.hasExplicitThreadId;
570
- const resolvedThreadId = threadId ?? (configHasExplicitThreadId ? configThreadId : void 0);
341
+ const resolvedThreadId = (0, _copilotkit_core.ɵresolveAgentThreadId)({
342
+ threadId,
343
+ chatThreadId: chatConfig?.threadId,
344
+ chatHasExplicitThreadId: chatConfig?.hasExplicitThreadId
345
+ });
571
346
  (0, react.useEffect)(() => {
572
347
  if (!resolvedThreadId) return;
573
348
  agent.threadId = resolvedThreadId;
@@ -655,6 +430,30 @@ function useDepsVersion(deps) {
655
430
 
656
431
  //#endregion
657
432
  //#region src/hooks/use-frontend-tool.tsx
433
+ /**
434
+ * Register a frontend tool while the component is mounted. The agent can
435
+ * call it, and its `render` component draws the call in the chat.
436
+ *
437
+ * A tool with the same name and agentId as a tool that is already registered
438
+ * (for example one from the provider's `tools`) overrides it while this
439
+ * component is mounted. When the component unmounts, the overridden tool is
440
+ * active again. The renderer stays registered after unmount, so past tool
441
+ * calls still render in the chat history.
442
+ *
443
+ * @param tool - The tool to register.
444
+ * @param deps - Extra values that re-register the tool when they change. Use
445
+ * it when the handler closes over a value that is not part of the tool.
446
+ *
447
+ * @example
448
+ * ```tsx
449
+ * useFrontendTool({
450
+ * name: "showWeather",
451
+ * description: "Show the weather for a city",
452
+ * parameters: z.object({ city: z.string() }),
453
+ * handler: async ({ city }) => `Sunny in ${city}`,
454
+ * });
455
+ * ```
456
+ */
658
457
  function useFrontendTool(tool, deps) {
659
458
  const { copilotkit } = (0, _copilotkit_react_core_context.useCopilotKit)();
660
459
  const depsVersion = useDepsVersion(deps);
@@ -663,11 +462,8 @@ function useFrontendTool(tool, deps) {
663
462
  if (copilotkit.getTool({
664
463
  toolName: name,
665
464
  agentId: tool.agentId
666
- })) {
667
- console.warn(`Tool '${name}' already exists for agent '${tool.agentId || "global"}'. Overriding with latest registration.`);
668
- copilotkit.removeTool(name, tool.agentId);
669
- }
670
- copilotkit.addTool(tool);
465
+ })) console.warn(`Tool '${name}' already exists for agent '${tool.agentId || "global"}'. Overriding with latest registration.`);
466
+ const unregister = copilotkit.addTool(tool);
671
467
  if (tool.render) copilotkit.addHookRenderToolCall({
672
468
  name,
673
469
  args: tool.parameters,
@@ -675,7 +471,7 @@ function useFrontendTool(tool, deps) {
675
471
  render: tool.render
676
472
  });
677
473
  return () => {
678
- copilotkit.removeTool(name, tool.agentId);
474
+ unregister();
679
475
  };
680
476
  }, [
681
477
  tool.name,
@@ -700,8 +496,10 @@ const EMPTY_TOOLS = [];
700
496
  *
701
497
  * Tools are keyed by `name` plus `agentId`, the same as `useFrontendTool`. A
702
498
  * tool that disappears from the array is unregistered on the next render, and
703
- * every tool is unregistered on unmount. Renderers stay registered after
704
- * unmount so past tool calls still render in the chat history.
499
+ * every tool is unregistered on unmount. A listed tool hides a tool with the
500
+ * same name and agentId (for example one from the provider's `tools`) until it
501
+ * is unregistered, and then the hidden tool is active again. Renderers stay
502
+ * registered after unmount so past tool calls still render in the chat history.
705
503
  *
706
504
  * @param tools - The tools to register. May be empty and may change length.
707
505
  * @param deps - Extra dependencies that force re-registration, compared by
@@ -751,15 +549,13 @@ function useFrontendTools(tools, deps) {
751
549
  deduped.set(key, tool);
752
550
  }
753
551
  const registered = [...deduped.values()];
552
+ const unregisters = [];
754
553
  for (const tool of registered) {
755
554
  if (copilotkit.getTool({
756
555
  toolName: tool.name,
757
556
  agentId: tool.agentId
758
- })) {
759
- console.warn(`Tool '${tool.name}' already exists for agent '${tool.agentId || "global"}'. Overriding with latest registration.`);
760
- copilotkit.removeTool(tool.name, tool.agentId);
761
- }
762
- copilotkit.addTool(tool);
557
+ })) console.warn(`Tool '${tool.name}' already exists for agent '${tool.agentId || "global"}'. Overriding with latest registration.`);
558
+ unregisters.push(copilotkit.addTool(tool));
763
559
  if (tool.render) copilotkit.addHookRenderToolCall({
764
560
  name: tool.name,
765
561
  args: tool.parameters,
@@ -768,7 +564,7 @@ function useFrontendTools(tools, deps) {
768
564
  });
769
565
  }
770
566
  return () => {
771
- for (const tool of registered) copilotkit.removeTool(tool.name, tool.agentId);
567
+ for (const unregister of unregisters) unregister();
772
568
  };
773
569
  }, [
774
570
  JSON.stringify(toolList.map((tool) => [
@@ -836,8 +632,7 @@ function useFrontendTools(tools, deps) {
836
632
  * ```
837
633
  */
838
634
  function useComponent(config, deps) {
839
- const prefix = `Use this tool to display the "${config.name}" component in the chat. This tool renders a visual UI component for the user.`;
840
- const fullDescription = config.description ? `${prefix}\n\n${config.description}` : prefix;
635
+ const fullDescription = (0, _copilotkit_core.ɵcomponentToolDescription)(config.name, config.description);
841
636
  useFrontendTool({
842
637
  name: config.name,
843
638
  description: fullDescription,
@@ -853,84 +648,18 @@ function useComponent(config, deps) {
853
648
 
854
649
  //#endregion
855
650
  //#region src/hooks/use-human-in-the-loop.tsx
856
- /** Registration name of a catch-all tool: handles any otherwise-unhandled call. */
857
- const WILDCARD_TOOL_NAME = "*";
858
651
  function useHumanInTheLoop(tool, deps) {
859
652
  const { copilotkit } = (0, _copilotkit_react_core_context.useCopilotKit)();
860
- const resolvePromiseRef = (0, react.useRef)(null);
861
- const cleanupAbortRef = (0, react.useRef)(null);
862
- const respond = (0, react.useCallback)(async (result) => {
863
- if (resolvePromiseRef.current) {
864
- cleanupAbortRef.current?.();
865
- cleanupAbortRef.current = null;
866
- resolvePromiseRef.current(result);
867
- resolvePromiseRef.current = null;
868
- }
869
- }, []);
870
- const handler = (0, react.useCallback)(async (_args, context) => {
871
- const signal = context?.signal;
872
- return new Promise((resolve, reject) => {
873
- if (signal?.aborted) {
874
- reject(/* @__PURE__ */ new Error("Human-in-the-loop interaction aborted"));
875
- return;
876
- }
877
- resolvePromiseRef.current = resolve;
878
- if (signal) {
879
- const onAbort = () => {
880
- cleanupAbortRef.current = null;
881
- resolvePromiseRef.current = null;
882
- reject(/* @__PURE__ */ new Error("Human-in-the-loop interaction aborted"));
883
- };
884
- signal.addEventListener("abort", onAbort, { once: true });
885
- cleanupAbortRef.current = () => {
886
- signal.removeEventListener("abort", onAbort);
887
- };
888
- }
889
- });
890
- }, []);
891
- const RenderComponent = (0, react.useCallback)((props) => {
892
- const ToolComponent = tool.render;
893
- const name = tool.name === WILDCARD_TOOL_NAME ? props.name : tool.name;
894
- if (props.status === _copilotkit_core.ToolCallStatus.InProgress) {
895
- const enhancedProps = {
896
- ...props,
897
- name,
898
- description: tool.description || "",
899
- agentId: tool.agentId,
900
- respond: void 0
901
- };
902
- return react.default.createElement(ToolComponent, enhancedProps);
903
- } else if (props.status === _copilotkit_core.ToolCallStatus.Executing) {
904
- const enhancedProps = {
905
- ...props,
906
- name,
907
- description: tool.description || "",
908
- agentId: tool.agentId,
909
- respond
910
- };
911
- return react.default.createElement(ToolComponent, enhancedProps);
912
- } else if (props.status === _copilotkit_core.ToolCallStatus.Complete) {
913
- const enhancedProps = {
914
- ...props,
915
- name,
916
- description: tool.description || "",
917
- agentId: tool.agentId,
918
- respond: void 0
919
- };
920
- return react.default.createElement(ToolComponent, enhancedProps);
921
- }
922
- return props;
923
- }, [
653
+ const registry = copilotkit.ɵhumanInTheLoop;
654
+ const RenderComponent = (0, react.useCallback)((props) => react.default.createElement(tool.render, (0, _copilotkit_core.ɵhitlRenderProps)(props, tool, registry)), [
924
655
  tool.render,
925
656
  tool.name,
926
657
  tool.description,
927
658
  tool.agentId,
928
- respond
659
+ registry
929
660
  ]);
930
661
  useFrontendTool({
931
- ...tool,
932
- type: "human-in-the-loop",
933
- handler,
662
+ ...(0, _copilotkit_core.ɵbuildHumanInTheLoopTool)(tool, registry),
934
663
  render: RenderComponent
935
664
  }, deps);
936
665
  (0, react.useLayoutEffect)(() => {
@@ -944,25 +673,8 @@ function useHumanInTheLoop(tool, deps) {
944
673
  ]);
945
674
  }
946
675
 
947
- //#endregion
948
- //#region src/types/interrupt.ts
949
- /** Name of the legacy custom event agents emit to signal an interrupt. */
950
- const INTERRUPT_EVENT_NAME = "on_interrupt";
951
-
952
676
  //#endregion
953
677
  //#region src/hooks/use-interrupt.tsx
954
- /** Recognize thenables returned by interrupt preprocessing handlers. */
955
- function isPromiseLike(value) {
956
- return (typeof value === "object" || typeof value === "function") && value !== null && typeof Reflect.get(value, "then") === "function";
957
- }
958
- /** Derive the legacy-compatible `event` for any pending interrupt. */
959
- function toLegacyEvent(pending) {
960
- if (pending.kind === "legacy") return pending.event;
961
- return {
962
- name: INTERRUPT_EVENT_NAME,
963
- value: pending.interrupts[0]
964
- };
965
- }
966
678
  /**
967
679
  * Handles agent interrupts with optional filtering, preprocessing, and resume behavior.
968
680
  *
@@ -996,228 +708,24 @@ function useInterrupt(config) {
996
708
  agentId: config.agentId,
997
709
  updates: []
998
710
  });
999
- const [pending, setPending] = (0, react.useState)(null);
1000
- const pendingRef = (0, react.useRef)(pending);
1001
- pendingRef.current = pending;
1002
- const [handlerResult, setHandlerResult] = (0, react.useState)(null);
1003
- const interruptStateRef = (0, react.useRef)(new _copilotkit_core.ɵInterruptState());
1004
- (0, react.useEffect)(() => {
1005
- let localLegacy = null;
1006
- let localStandard = null;
1007
- const subscription = agent.subscribe({
1008
- onCustomEvent: ({ event }) => {
1009
- if (event.name === INTERRUPT_EVENT_NAME) localLegacy = {
1010
- name: event.name,
1011
- value: event.value
1012
- };
1013
- },
1014
- onRunFinishedEvent: (params) => {
1015
- if (params.outcome === "interrupt") localStandard = params.interrupts;
1016
- },
1017
- onRunStartedEvent: (params) => {
1018
- if (!agent.pendingInterrupts?.length || params?.input?.resume !== void 0) (0, _copilotkit_core.ɵclearAgentInterruptState)(agent);
1019
- localLegacy = null;
1020
- localStandard = null;
1021
- interruptStateRef.current = new _copilotkit_core.ɵInterruptState();
1022
- setPending(null);
1023
- },
1024
- onRunFinalized: () => {
1025
- if (localStandard && localStandard.length > 0) {
1026
- interruptStateRef.current = (0, _copilotkit_core.ɵgetAgentInterruptState)(agent, localStandard);
1027
- setPending(interruptStateRef.current.pending);
1028
- } else if (localLegacy) {
1029
- interruptStateRef.current = new _copilotkit_core.ɵInterruptState();
1030
- interruptStateRef.current.setLegacy(localLegacy);
1031
- setPending(interruptStateRef.current.pending);
1032
- }
1033
- localLegacy = null;
1034
- localStandard = null;
1035
- },
1036
- onRunFailed: () => {
1037
- localLegacy = null;
1038
- localStandard = null;
1039
- interruptStateRef.current = new _copilotkit_core.ɵInterruptState();
1040
- setPending(null);
1041
- }
1042
- });
1043
- interruptStateRef.current = agent.pendingInterrupts?.length ? (0, _copilotkit_core.ɵgetAgentInterruptState)(agent) : new _copilotkit_core.ɵInterruptState();
1044
- setPending(interruptStateRef.current.pending);
1045
- return () => {
1046
- subscription.unsubscribe();
1047
- interruptStateRef.current = new _copilotkit_core.ɵInterruptState();
1048
- };
1049
- }, [agent]);
1050
- /** Record an explicit answer and resume once the complete batch is addressed. */
1051
- const resolve = (0, react.useCallback)(async (payload, interruptId) => {
1052
- const current = pendingRef.current;
1053
- if (!current) return;
1054
- if (current.kind === "standard" && current.interrupts.length > 1 && interruptId === void 0) console.warn(`[CopilotKit] useInterrupt: resolve()/cancel() called without an interruptId while ${current.interrupts.length} interrupts are open; defaulting to the first. Pass an interruptId to address a specific interrupt.`);
1055
- if (interruptStateRef.current.isCompletedToolCall(interruptId, agent.messages)) {
1056
- console.warn("[CopilotKit] useInterrupt: ignoring an answer for an already completed frontend tool call.");
1057
- return;
1058
- }
1059
- const decision = interruptStateRef.current.resolve(payload, interruptId, agent.messages);
1060
- if (decision.kind === "legacy-resume") try {
1061
- return await copilotkit.runAgent({
1062
- agent,
1063
- forwardedProps: { command: {
1064
- resume: decision.payload,
1065
- interruptEvent: decision.interruptValue
1066
- } }
1067
- });
1068
- } catch (err) {
1069
- console.error("[CopilotKit] useInterrupt resolve: runAgent rejected; clearing pending + rethrowing", err);
1070
- setPending(null);
1071
- throw err;
1072
- }
1073
- if (decision.kind === "expired") {
1074
- console.error(`[CopilotKit] useInterrupt: interrupt ${decision.interrupt.id} expired at ${decision.interrupt.expiresAt}; not resuming.`);
1075
- interruptStateRef.current = new _copilotkit_core.ɵInterruptState();
1076
- setPending(null);
1077
- return;
1078
- }
1079
- if (decision.kind !== "resume") return;
1080
- for (const toolResult of decision.toolResults) agent.addMessage({
1081
- id: (0, _ag_ui_client.randomUUID)(),
1082
- role: "tool",
1083
- toolCallId: toolResult.toolCallId,
1084
- content: toolResult.content
1085
- });
1086
- try {
1087
- return await copilotkit.runAgent({
1088
- agent,
1089
- resume: decision.resume
1090
- });
1091
- } catch (err) {
1092
- console.error("[CopilotKit] useInterrupt resolve: runAgent rejected; clearing pending + rethrowing", err);
1093
- interruptStateRef.current = new _copilotkit_core.ɵInterruptState();
1094
- setPending(null);
1095
- throw err;
1096
- }
1097
- }, [agent, copilotkit]);
1098
- /** Cancel a standard interrupt or dismiss a legacy interrupt locally. */
1099
- const cancel = (0, react.useCallback)(async (interruptId) => {
1100
- const current = pendingRef.current;
1101
- if (!current) return;
1102
- if (current.kind === "standard" && current.interrupts.length > 1 && interruptId === void 0) console.warn(`[CopilotKit] useInterrupt: resolve()/cancel() called without an interruptId while ${current.interrupts.length} interrupts are open; defaulting to the first. Pass an interruptId to address a specific interrupt.`);
1103
- if (interruptStateRef.current.isCompletedToolCall(interruptId, agent.messages)) {
1104
- console.warn("[CopilotKit] useInterrupt: ignoring an answer for an already completed frontend tool call.");
1105
- return;
1106
- }
1107
- const decision = interruptStateRef.current.cancel(interruptId, agent.messages);
1108
- if (decision.kind === "dismiss") {
1109
- console.warn("[CopilotKit] useInterrupt: cancel() is not supported for legacy on_interrupt interrupts; dismissing.");
1110
- interruptStateRef.current = new _copilotkit_core.ɵInterruptState();
1111
- setPending(null);
1112
- return;
1113
- }
1114
- if (decision.kind === "expired") {
1115
- console.error(`[CopilotKit] useInterrupt: interrupt ${decision.interrupt.id} expired at ${decision.interrupt.expiresAt}; not resuming.`);
1116
- interruptStateRef.current = new _copilotkit_core.ɵInterruptState();
1117
- setPending(null);
1118
- return;
1119
- }
1120
- if (decision.kind !== "resume") return;
1121
- for (const toolResult of decision.toolResults) agent.addMessage({
1122
- id: (0, _ag_ui_client.randomUUID)(),
1123
- role: "tool",
1124
- toolCallId: toolResult.toolCallId,
1125
- content: toolResult.content
1126
- });
1127
- try {
1128
- return await copilotkit.runAgent({
1129
- agent,
1130
- resume: decision.resume
1131
- });
1132
- } catch (err) {
1133
- console.error("[CopilotKit] useInterrupt resolve: runAgent rejected; clearing pending + rethrowing", err);
1134
- interruptStateRef.current = new _copilotkit_core.ɵInterruptState();
1135
- setPending(null);
1136
- throw err;
1137
- }
1138
- }, [agent, copilotkit]);
1139
711
  const renderRef = (0, react.useRef)(config.render);
1140
712
  renderRef.current = config.render;
1141
713
  const enabledRef = (0, react.useRef)(config.enabled);
1142
714
  enabledRef.current = config.enabled;
1143
715
  const handlerRef = (0, react.useRef)(config.handler);
1144
716
  handlerRef.current = config.handler;
1145
- const resolveRef = (0, react.useRef)(resolve);
1146
- resolveRef.current = resolve;
1147
- const cancelRef = (0, react.useRef)(cancel);
1148
- cancelRef.current = cancel;
1149
- /** Evaluate the consumer filter, logging failures and disabling their UI. */
1150
- const isEnabled = (event) => {
1151
- const predicate = enabledRef.current;
1152
- if (!predicate) return true;
1153
- try {
1154
- return predicate(event);
1155
- } catch (err) {
1156
- console.error("[CopilotKit] useInterrupt enabled predicate threw; treating interrupt as disabled:", err);
1157
- return false;
1158
- }
1159
- };
717
+ const copilotkitRef = (0, react.useRef)(copilotkit);
718
+ copilotkitRef.current = copilotkit;
719
+ const [controller] = (0, react.useState)(() => new _copilotkit_core.ɵInterruptController({ runAgent: (params) => copilotkitRef.current.runAgent(params) }, {
720
+ enabled: (event) => enabledRef.current?.(event) ?? true,
721
+ handler: (props) => handlerRef.current ? handlerRef.current(props) : null
722
+ }));
1160
723
  (0, react.useEffect)(() => {
1161
- if (!pending) {
1162
- setHandlerResult(null);
1163
- return;
1164
- }
1165
- const legacyEvent = toLegacyEvent(pending);
1166
- if (!isEnabled(legacyEvent)) {
1167
- setHandlerResult(null);
1168
- return;
1169
- }
1170
- const handler = handlerRef.current;
1171
- if (!handler) {
1172
- setHandlerResult(null);
1173
- return;
1174
- }
1175
- let cancelled = false;
1176
- let maybePromise;
1177
- try {
1178
- maybePromise = handler({
1179
- event: legacyEvent,
1180
- interrupt: pending.kind === "standard" ? pending.interrupts[0] : null,
1181
- interrupts: pending.kind === "standard" ? [...pending.interrupts] : [],
1182
- resolve: resolveRef.current,
1183
- cancel: cancelRef.current
1184
- });
1185
- } catch (err) {
1186
- console.error("[CopilotKit] useInterrupt handler threw; result will be null:", err);
1187
- if (!cancelled) setHandlerResult(null);
1188
- return () => {
1189
- cancelled = true;
1190
- };
1191
- }
1192
- if (isPromiseLike(maybePromise)) Promise.resolve(maybePromise).then((resolved) => {
1193
- if (!cancelled) setHandlerResult(resolved);
1194
- }).catch((err) => {
1195
- console.error("[CopilotKit] useInterrupt handler rejected; result will be null:", err);
1196
- if (!cancelled) setHandlerResult(null);
1197
- });
1198
- else setHandlerResult(maybePromise);
1199
- return () => {
1200
- cancelled = true;
1201
- };
1202
- }, [pending]);
1203
- const element = (0, react.useMemo)(() => {
1204
- if (!pending) return null;
1205
- const legacyEvent = toLegacyEvent(pending);
1206
- if (!isEnabled(legacyEvent)) return null;
1207
- return renderRef.current({
1208
- event: legacyEvent,
1209
- interrupt: pending.kind === "standard" ? pending.interrupts[0] : null,
1210
- interrupts: pending.kind === "standard" ? [...pending.interrupts] : [],
1211
- result: handlerResult,
1212
- resolve,
1213
- cancel
1214
- });
1215
- }, [
1216
- pending,
1217
- handlerResult,
1218
- resolve,
1219
- cancel
1220
- ]);
724
+ controller.connect(agent);
725
+ return () => controller.disconnect();
726
+ }, [controller, agent]);
727
+ const { renderProps } = (0, react.useSyncExternalStore)(controller.subscribe, controller.getSnapshot, controller.getSnapshot);
728
+ const element = (0, react.useMemo)(() => renderProps ? renderRef.current(renderProps) : null, [renderProps]);
1221
729
  (0, react.useEffect)(() => {
1222
730
  if (config.renderInChat === false) return;
1223
731
  copilotkit.setInterruptElement(element);
@@ -1246,210 +754,75 @@ function useSuggestions({ agentId } = {}) {
1246
754
  config?.agentId,
1247
755
  providerAgentId
1248
756
  ]);
1249
- const [suggestions, setSuggestions] = (0, react.useState)(() => {
1250
- return copilotkit.getSuggestions(resolvedAgentId).suggestions;
1251
- });
1252
- const [isLoading, setIsLoading] = (0, react.useState)(() => {
1253
- return copilotkit.getSuggestions(resolvedAgentId).isLoading;
1254
- });
757
+ const [result, setResult] = (0, react.useState)(() => copilotkit.getSuggestions(resolvedAgentId));
1255
758
  (0, react.useEffect)(() => {
1256
- const result = copilotkit.getSuggestions(resolvedAgentId);
1257
- setSuggestions(result.suggestions);
1258
- setIsLoading(result.isLoading);
759
+ setResult(copilotkit.getSuggestions(resolvedAgentId));
760
+ return (0, _copilotkit_core.ɵsubscribeToAgentSuggestions)(copilotkit, resolvedAgentId, setResult);
1259
761
  }, [copilotkit, resolvedAgentId]);
1260
- (0, react.useEffect)(() => {
1261
- const subscription = copilotkit.subscribe({
1262
- onSuggestionsChanged: ({ agentId: changedAgentId, suggestions }) => {
1263
- if (changedAgentId !== resolvedAgentId) return;
1264
- setSuggestions(suggestions);
1265
- },
1266
- onSuggestionsStartedLoading: ({ agentId: changedAgentId }) => {
1267
- if (changedAgentId !== resolvedAgentId) return;
1268
- setIsLoading(true);
1269
- },
1270
- onSuggestionsFinishedLoading: ({ agentId: changedAgentId }) => {
1271
- if (changedAgentId !== resolvedAgentId) return;
1272
- setIsLoading(false);
1273
- },
1274
- onSuggestionsConfigChanged: () => {
1275
- const result = copilotkit.getSuggestions(resolvedAgentId);
1276
- setSuggestions(result.suggestions);
1277
- setIsLoading(result.isLoading);
1278
- }
1279
- });
1280
- return () => {
1281
- subscription.unsubscribe();
1282
- };
762
+ const reloadSuggestions = (0, react.useCallback)(() => {
763
+ copilotkit.reloadSuggestions(resolvedAgentId);
764
+ }, [copilotkit, resolvedAgentId]);
765
+ const clearSuggestions = (0, react.useCallback)(() => {
766
+ copilotkit.clearSuggestions(resolvedAgentId);
1283
767
  }, [copilotkit, resolvedAgentId]);
1284
768
  return {
1285
- suggestions,
1286
- reloadSuggestions: (0, react.useCallback)(() => {
1287
- copilotkit.reloadSuggestions(resolvedAgentId);
1288
- }, [copilotkit, resolvedAgentId]),
1289
- clearSuggestions: (0, react.useCallback)(() => {
1290
- copilotkit.clearSuggestions(resolvedAgentId);
1291
- }, [copilotkit, resolvedAgentId]),
1292
- isLoading
769
+ suggestions: result.suggestions,
770
+ reloadSuggestions,
771
+ clearSuggestions,
772
+ isLoading: result.isLoading
1293
773
  };
1294
774
  }
1295
775
 
1296
776
  //#endregion
1297
777
  //#region src/hooks/use-configure-suggestions.tsx
778
+ /**
779
+ * Registers a suggestions configuration (dynamic or static) for the current
780
+ * chat. A global config (no `consumerAgentId`, or `"*"`) applies to every
781
+ * agent and loads for the surrounding chat's agent first.
782
+ *
783
+ * Pass `deps` to reload suggestions when values the config reads change.
784
+ *
785
+ * @example
786
+ * useConfigureSuggestions({
787
+ * instructions: "Suggest concise next steps for the user",
788
+ * available: "always",
789
+ * });
790
+ */
1298
791
  function useConfigureSuggestions(config, deps) {
1299
792
  const { copilotkit } = (0, _copilotkit_react_core_context.useCopilotKit)();
1300
793
  const chatConfig = useCopilotChatConfiguration();
794
+ const providerAgentId = (0, _copilotkit_react_core_context.useDefaultAgentId)();
795
+ const chatAgentId = chatConfig?.agentId ?? providerAgentId ?? _copilotkit_shared.DEFAULT_AGENT_ID;
1301
796
  const extraDeps = deps ?? [];
1302
- const resolvedConsumerAgentId = (0, react.useMemo)(() => chatConfig?.agentId ?? _copilotkit_shared.DEFAULT_AGENT_ID, [chatConfig?.agentId]);
1303
- const rawConsumerAgentId = (0, react.useMemo)(() => config ? config.consumerAgentId : void 0, [config]);
1304
- const normalizationCacheRef = (0, react.useRef)({
1305
- serialized: null,
1306
- config: null
797
+ const bindingRef = (0, react.useRef)(null);
798
+ const latestRef = (0, react.useRef)({
799
+ config,
800
+ chatAgentId
1307
801
  });
1308
- const { normalizedConfig, serializedConfig } = (0, react.useMemo)(() => {
1309
- if (!config) {
1310
- normalizationCacheRef.current = {
1311
- serialized: null,
1312
- config: null
1313
- };
1314
- return {
1315
- normalizedConfig: null,
1316
- serializedConfig: null
1317
- };
1318
- }
1319
- if (config.available === "disabled") {
1320
- normalizationCacheRef.current = {
1321
- serialized: null,
1322
- config: null
1323
- };
1324
- return {
1325
- normalizedConfig: null,
1326
- serializedConfig: null
1327
- };
1328
- }
1329
- let built;
1330
- if (isDynamicConfig(config)) built = { ...config };
1331
- else {
1332
- const normalizedSuggestions = normalizeStaticSuggestions(config.suggestions);
1333
- built = {
1334
- ...config,
1335
- suggestions: normalizedSuggestions
1336
- };
1337
- }
1338
- const serialized = JSON.stringify(built);
1339
- const cache = normalizationCacheRef.current;
1340
- if (cache.serialized === serialized && cache.config) return {
1341
- normalizedConfig: cache.config,
1342
- serializedConfig: serialized
1343
- };
1344
- normalizationCacheRef.current = {
1345
- serialized,
1346
- config: built
1347
- };
1348
- return {
1349
- normalizedConfig: built,
1350
- serializedConfig: serialized
1351
- };
1352
- }, [
802
+ latestRef.current = {
1353
803
  config,
1354
- resolvedConsumerAgentId,
1355
- ...extraDeps
1356
- ]);
1357
- const latestConfigRef = (0, react.useRef)(null);
1358
- latestConfigRef.current = normalizedConfig;
1359
- const previousSerializedConfigRef = (0, react.useRef)(null);
1360
- const targetAgentId = (0, react.useMemo)(() => {
1361
- if (!normalizedConfig) return resolvedConsumerAgentId;
1362
- const consumer = normalizedConfig.consumerAgentId;
1363
- if (!consumer || consumer === "*") return resolvedConsumerAgentId;
1364
- return consumer;
1365
- }, [normalizedConfig, resolvedConsumerAgentId]);
1366
- const isGlobalConfig = rawConsumerAgentId === void 0 || rawConsumerAgentId === "*";
1367
- const isDynamicConfigType = (0, react.useMemo)(() => !!normalizedConfig && "instructions" in normalizedConfig, [normalizedConfig]);
1368
- const requestReload = (0, react.useCallback)(() => {
1369
- if (!normalizedConfig) return;
1370
- if (isGlobalConfig) {
1371
- const seen = /* @__PURE__ */ new Set();
1372
- const agents = Object.values(copilotkit.agents ?? {});
1373
- for (const entry of agents) {
1374
- const agentId = entry.agentId;
1375
- if (!agentId) continue;
1376
- seen.add(agentId);
1377
- if (!entry.isRunning) copilotkit.reloadSuggestions(agentId);
1378
- }
1379
- if (targetAgentId && !seen.has(targetAgentId)) copilotkit.reloadSuggestions(targetAgentId);
1380
- return;
1381
- }
1382
- if (!targetAgentId) return;
1383
- copilotkit.reloadSuggestions(targetAgentId);
1384
- }, [
1385
- copilotkit,
1386
- isGlobalConfig,
1387
- normalizedConfig,
1388
- targetAgentId
1389
- ]);
804
+ chatAgentId
805
+ };
1390
806
  (0, react.useEffect)(() => {
1391
- if (!serializedConfig || !latestConfigRef.current) return;
1392
- const id = copilotkit.addSuggestionsConfig(latestConfigRef.current);
1393
- requestReload();
807
+ const latest = latestRef.current;
808
+ const binding = (0, _copilotkit_core.ɵbindSuggestionsConfig)(copilotkit, latest.config, { chatAgentId: latest.chatAgentId });
809
+ bindingRef.current = binding;
1394
810
  return () => {
1395
- copilotkit.removeSuggestionsConfig(id);
811
+ binding.dispose();
812
+ if (bindingRef.current === binding) bindingRef.current = null;
1396
813
  };
1397
- }, [
1398
- copilotkit,
1399
- serializedConfig,
1400
- requestReload
1401
- ]);
814
+ }, [copilotkit]);
1402
815
  (0, react.useEffect)(() => {
1403
- if (!normalizedConfig) {
1404
- previousSerializedConfigRef.current = null;
816
+ bindingRef.current?.update(config, { chatAgentId });
817
+ }, [config, chatAgentId]);
818
+ const depsMountedRef = (0, react.useRef)(false);
819
+ (0, react.useEffect)(() => {
820
+ if (!depsMountedRef.current) {
821
+ depsMountedRef.current = true;
1405
822
  return;
1406
823
  }
1407
- if (serializedConfig && previousSerializedConfigRef.current === serializedConfig) return;
1408
- if (serializedConfig) previousSerializedConfigRef.current = serializedConfig;
1409
- requestReload();
1410
- }, [
1411
- normalizedConfig,
1412
- requestReload,
1413
- serializedConfig
1414
- ]);
1415
- (0, react.useEffect)(() => {
1416
- if (!normalizedConfig || extraDeps.length === 0) return;
1417
- requestReload();
1418
- }, [
1419
- extraDeps.length,
1420
- normalizedConfig,
1421
- requestReload,
1422
- ...extraDeps
1423
- ]);
1424
- (0, react.useEffect)(() => {
1425
- if (!normalizedConfig || !isDynamicConfigType) return;
1426
- if (!targetAgentId) return;
1427
- if (!!copilotkit.getAgent(targetAgentId)) return;
1428
- const subscription = copilotkit.subscribe({ onAgentsChanged: () => {
1429
- if (copilotkit.getAgent(targetAgentId)) {
1430
- requestReload();
1431
- subscription.unsubscribe();
1432
- }
1433
- } });
1434
- return () => {
1435
- subscription.unsubscribe();
1436
- };
1437
- }, [
1438
- copilotkit,
1439
- normalizedConfig,
1440
- isDynamicConfigType,
1441
- targetAgentId,
1442
- requestReload
1443
- ]);
1444
- }
1445
- function isDynamicConfig(config) {
1446
- return "instructions" in config;
1447
- }
1448
- function normalizeStaticSuggestions(suggestions) {
1449
- return suggestions.map((suggestion) => ({
1450
- ...suggestion,
1451
- isLoading: suggestion.isLoading ?? false
1452
- }));
824
+ if (extraDeps.length > 0) bindingRef.current?.reload();
825
+ }, [extraDeps.length, ...extraDeps]);
1453
826
  }
1454
827
 
1455
828
  //#endregion
@@ -1457,10 +830,7 @@ function normalizeStaticSuggestions(suggestions) {
1457
830
  function useAgentContext(context) {
1458
831
  const { description, value } = context;
1459
832
  const { copilotkit } = (0, _copilotkit_react_core_context.useCopilotKit)();
1460
- const stringValue = (0, react.useMemo)(() => {
1461
- if (typeof value === "string") return value;
1462
- return JSON.stringify(value);
1463
- }, [value]);
833
+ const stringValue = (0, react.useMemo)(() => (0, _copilotkit_core.ɵserializeContextValue)(value), [value]);
1464
834
  (0, react.useLayoutEffect)(() => {
1465
835
  if (!copilotkit) return;
1466
836
  const id = copilotkit.addContext({
@@ -1479,12 +849,6 @@ function useAgentContext(context) {
1479
849
 
1480
850
  //#endregion
1481
851
  //#region src/hooks/use-threads.tsx
1482
- function useThreadStoreSelector(store, selector) {
1483
- return (0, react.useSyncExternalStore)((0, react.useCallback)((onStoreChange) => {
1484
- const subscription = store.select(selector).subscribe(onStoreChange);
1485
- return () => subscription.unsubscribe();
1486
- }, [store, selector]), () => selector(store.getState()), () => selector(store.getServerState()));
1487
- }
1488
852
  /**
1489
853
  * React hook for listing and managing CopilotKit Intelligence threads.
1490
854
  *
@@ -1528,117 +892,38 @@ function useThreadStoreSelector(store, selector) {
1528
892
  */
1529
893
  function useThreads({ agentId, includeArchived, limit, enabled = true }) {
1530
894
  const { copilotkit } = (0, _copilotkit_react_core_context.useCopilotKit)();
1531
- const [store] = (0, react.useState)(() => (0, _copilotkit_core.ɵcreateThreadStore)({ fetch: copilotkit.ɵruntimeFetch }));
1532
- const coreThreads = useThreadStoreSelector(store, _copilotkit_core.ɵselectThreads);
1533
- const threads = (0, react.useMemo)(() => coreThreads.map(({ id, agentId, name, archived, createdAt, updatedAt, lastRunAt }) => ({
1534
- id,
1535
- agentId,
1536
- name,
1537
- archived,
1538
- createdAt,
1539
- updatedAt,
1540
- ...lastRunAt !== void 0 ? { lastRunAt } : {}
1541
- })), [coreThreads]);
1542
- const storeIsLoading = useThreadStoreSelector(store, _copilotkit_core.ɵselectThreadsIsLoading);
1543
- const storeError = useThreadStoreSelector(store, _copilotkit_core.ɵselectThreadsError);
1544
- const fetchMoreError = useThreadStoreSelector(store, _copilotkit_core.ɵselectFetchMoreError);
1545
- const hasMoreThreads = useThreadStoreSelector(store, _copilotkit_core.ɵselectHasNextPage);
1546
- const isFetchingMoreThreads = useThreadStoreSelector(store, _copilotkit_core.ɵselectIsFetchingNextPage);
1547
- const isMutating = useThreadStoreSelector(store, _copilotkit_core.ɵselectIsMutating);
1548
- const headersKey = copilotkit.ɵheadersGeneration;
1549
- const runtimeStatus = copilotkit.runtimeConnectionStatus;
1550
- const threadListEndpointSupported = copilotkit.threadEndpoints?.list !== false;
1551
- const threadMutationsSupported = copilotkit.threadEndpoints?.mutations !== false;
1552
- const threadEndpointsUnavailable = !!copilotkit.runtimeUrl && runtimeStatus === _copilotkit_core.CopilotKitCoreRuntimeConnectionStatus.Connected && !threadListEndpointSupported;
1553
- const runtimeError = (0, react.useMemo)(() => {
1554
- if (copilotkit.runtimeUrl) return null;
1555
- return /* @__PURE__ */ new Error("Runtime URL is not configured");
1556
- }, [copilotkit.runtimeUrl]);
1557
- const threadEndpointsError = (0, react.useMemo)(() => {
1558
- if (!threadEndpointsUnavailable) return null;
1559
- return /* @__PURE__ */ new Error("Thread endpoints are not available on this CopilotKit runtime");
1560
- }, [threadEndpointsUnavailable]);
1561
- const threadMutationsError = (0, react.useMemo)(() => {
1562
- if (threadMutationsSupported) return null;
1563
- return /* @__PURE__ */ new Error("Thread mutations are not available on this CopilotKit runtime");
1564
- }, [threadMutationsSupported]);
1565
- const [hasDispatchedContext, setHasDispatchedContext] = (0, react.useState)(false);
1566
- const preConnectLoading = enabled && !!copilotkit.runtimeUrl && !threadEndpointsUnavailable && !hasDispatchedContext;
1567
- const [configErrorDismissed, setConfigErrorDismissed] = (0, react.useState)(false);
1568
- (0, react.useEffect)(() => {
1569
- setConfigErrorDismissed(false);
1570
- }, [runtimeError, threadEndpointsError]);
1571
- const activeRuntimeError = configErrorDismissed ? null : runtimeError;
1572
- const activeThreadEndpointsError = configErrorDismissed ? null : threadEndpointsError;
1573
- const isLoading = activeRuntimeError || activeThreadEndpointsError ? false : preConnectLoading || storeIsLoading;
1574
- const error = activeRuntimeError ?? activeThreadEndpointsError ?? storeError;
1575
- const listError = storeError;
1576
- (0, react.useEffect)(() => {
1577
- store.start();
1578
- return () => {
1579
- store.stop();
1580
- };
1581
- }, [store]);
1582
- (0, react.useEffect)(() => {
1583
- if (!enabled) return;
1584
- copilotkit.registerThreadStore(agentId, store);
1585
- return () => {
1586
- copilotkit.unregisterThreadStore(agentId);
1587
- };
1588
- }, [
1589
- copilotkit,
895
+ const [controller] = (0, react.useState)(() => new _copilotkit_core.ɵThreadsController((0, _copilotkit_core.ɵcreateThreadStore)({ fetch: copilotkit.ɵruntimeFetch }), {
896
+ core: copilotkit,
1590
897
  agentId,
1591
- store,
898
+ includeArchived,
899
+ limit,
1592
900
  enabled
1593
- ]);
901
+ }));
902
+ const { threads, isLoading, error, listError, fetchMoreError, hasMoreThreads, isFetchingMoreThreads, isMutating } = (0, react.useSyncExternalStore)(controller.subscribe, controller.getSnapshot, controller.getServerSnapshot);
903
+ (0, react.useEffect)(() => controller.start(), [controller]);
1594
904
  (0, react.useEffect)(() => {
1595
- if (!enabled) {
1596
- store.setContext(null);
1597
- setHasDispatchedContext(false);
1598
- return;
1599
- }
1600
- if (!copilotkit.runtimeUrl) {
1601
- store.setContext(null);
1602
- setHasDispatchedContext(false);
1603
- return;
1604
- }
1605
- if (runtimeStatus !== _copilotkit_core.CopilotKitCoreRuntimeConnectionStatus.Connected) return;
1606
- if (!threadListEndpointSupported) {
1607
- store.setContext(null);
1608
- setHasDispatchedContext(false);
1609
- return;
1610
- }
1611
- const context = {
1612
- runtimeUrl: copilotkit.runtimeUrl,
1613
- wsUrl: copilotkit.intelligence?.wsUrl,
905
+ controller.update({
906
+ core: copilotkit,
1614
907
  agentId,
1615
908
  includeArchived,
1616
- limit
1617
- };
1618
- store.setContext(context);
1619
- setHasDispatchedContext(true);
909
+ limit,
910
+ enabled
911
+ });
1620
912
  }, [
1621
- store,
913
+ controller,
914
+ copilotkit,
915
+ agentId,
916
+ includeArchived,
917
+ limit,
1622
918
  enabled,
1623
919
  copilotkit.runtimeUrl,
1624
- runtimeStatus,
1625
- headersKey,
920
+ copilotkit.runtimeConnectionStatus,
921
+ copilotkit.ɵheadersGeneration,
1626
922
  copilotkit.intelligence?.wsUrl,
1627
- threadListEndpointSupported,
1628
- agentId,
1629
- includeArchived,
1630
- limit
923
+ copilotkit.threadEndpoints?.list,
924
+ copilotkit.threadEndpoints?.mutations
1631
925
  ]);
1632
- const guardMutation = (0, react.useCallback)((mutation) => {
1633
- return (...args) => {
1634
- if (threadMutationsError) return Promise.reject(threadMutationsError);
1635
- return mutation(...args);
1636
- };
1637
- }, [threadMutationsError]);
1638
- const renameThread = (0, react.useMemo)(() => guardMutation((threadId, name) => store.renameThread(threadId, name)), [store, guardMutation]);
1639
- const archiveThread = (0, react.useMemo)(() => guardMutation((threadId) => store.archiveThread(threadId)), [store, guardMutation]);
1640
- const unarchiveThread = (0, react.useMemo)(() => guardMutation((threadId) => store.unarchiveThread(threadId)), [store, guardMutation]);
1641
- const deleteThread = (0, react.useMemo)(() => guardMutation((threadId) => store.deleteThread(threadId)), [store, guardMutation]);
926
+ const { fetchMoreThreads, refetchThreads, startNewThread, renameThread, archiveThread, unarchiveThread, deleteThread } = controller;
1642
927
  return {
1643
928
  threads,
1644
929
  isLoading,
@@ -1648,12 +933,9 @@ function useThreads({ agentId, includeArchived, limit, enabled = true }) {
1648
933
  hasMoreThreads,
1649
934
  isFetchingMoreThreads,
1650
935
  isMutating,
1651
- fetchMoreThreads: (0, react.useCallback)(() => store.fetchNextPage(), [store]),
1652
- refetchThreads: (0, react.useCallback)(() => store.refetchThreads(), [store]),
1653
- startNewThread: (0, react.useCallback)(() => {
1654
- setConfigErrorDismissed(true);
1655
- store.startNewThread();
1656
- }, [store]),
936
+ fetchMoreThreads,
937
+ refetchThreads,
938
+ startNewThread,
1657
939
  renameThread,
1658
940
  archiveThread,
1659
941
  unarchiveThread,
@@ -1664,7 +946,7 @@ function useThreads({ agentId, includeArchived, limit, enabled = true }) {
1664
946
  //#endregion
1665
947
  //#region src/types/defineToolCallRenderer.ts
1666
948
  function defineToolCallRenderer(def) {
1667
- const argsSchema = def.name === "*" && !def.args ? zod.z.any() : def.args;
949
+ const argsSchema = def.name === "*" && !def.args ? _copilotkit_shared.ɵanySchema : def.args;
1668
950
  return {
1669
951
  name: def.name,
1670
952
  args: argsSchema,
@@ -1766,29 +1048,11 @@ function useRenderTool(config, deps) {
1766
1048
  * but the tool call data hasn't changed.
1767
1049
  */
1768
1050
  const ToolCallRenderer = react.default.memo(function ToolCallRenderer({ toolCall, toolMessage, RenderComponent, isExecuting }) {
1769
- const args = (0, react.useMemo)(() => (0, _copilotkit_shared.partialJSONParse)(toolCall.function.arguments), [toolCall.function.arguments]);
1770
- const toolName = toolCall.function.name;
1771
- if (toolMessage) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(RenderComponent, {
1772
- name: toolName,
1773
- toolCallId: toolCall.id,
1774
- args,
1775
- status: _copilotkit_core.ToolCallStatus.Complete,
1776
- result: (0, _ag_ui_core.contentToText)(toolMessage.content)
1777
- });
1778
- else if (isExecuting) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(RenderComponent, {
1779
- name: toolName,
1780
- toolCallId: toolCall.id,
1781
- args,
1782
- status: _copilotkit_core.ToolCallStatus.Executing,
1783
- result: void 0
1784
- });
1785
- else return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(RenderComponent, {
1786
- name: toolName,
1787
- toolCallId: toolCall.id,
1788
- args,
1789
- status: _copilotkit_core.ToolCallStatus.InProgress,
1790
- result: void 0
1791
- });
1051
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(RenderComponent, { ...(0, react.useMemo)(() => (0, _copilotkit_core.ɵbuildToolCallRenderProps)(toolCall, toolMessage, { isExecuting }), [
1052
+ toolCall,
1053
+ toolMessage,
1054
+ isExecuting
1055
+ ]) });
1792
1056
  }, (prevProps, nextProps) => {
1793
1057
  if (prevProps.toolCall.id !== nextProps.toolCall.id) return false;
1794
1058
  if (prevProps.toolCall.function.name !== nextProps.toolCall.function.name) return false;
@@ -1800,25 +1064,21 @@ const ToolCallRenderer = react.default.memo(function ToolCallRenderer({ toolCall
1800
1064
  });
1801
1065
  const IS_DEVELOPMENT = process.env.NODE_ENV !== "production";
1802
1066
  /**
1803
- * Reports tool calls that resolved to no renderer.
1067
+ * Reports tool calls that resolved to no renderer, once per tool name.
1804
1068
  *
1805
1069
  * A tool call with no renderer paints an empty message container and says
1806
1070
  * nothing else, so the only signal a developer gets today is a blank space in
1807
- * the chat. This names the call and the renderers that *are* registered, which
1808
- * is the whole diagnosis when the cause is a name that does not match.
1071
+ * the chat.
1809
1072
  *
1810
1073
  * @param toolNames - The unmatched tool names collected during render.
1811
1074
  * @param registered - The registry as it stands now, re-read at report time.
1812
1075
  * @param alreadyWarned - Names already reported, mutated to keep this once per name.
1813
1076
  */
1814
1077
  function warnAboutUnrenderedToolCalls(toolNames, registered, alreadyWarned) {
1815
- const registeredNames = Array.from(new Set(registered.map((rc) => rc.name)));
1816
- const hasWildcard = registeredNames.includes("*");
1817
- for (const toolName of toolNames) {
1818
- if (hasWildcard || registeredNames.includes(toolName)) continue;
1819
- if (alreadyWarned.has(toolName)) continue;
1078
+ const warnings = (0, _copilotkit_core.ɵdescribeUnrenderedToolCalls)(toolNames.filter((name) => !alreadyWarned.has(name)), registered);
1079
+ for (const { toolName, message } of warnings) {
1820
1080
  alreadyWarned.add(toolName);
1821
- console.warn(`[CopilotKit] The agent called the tool "${toolName}", and no renderer is registered for it, so that message rendered nothing. ` + (registeredNames.length === 0 ? "No tool-call renderers are registered. " : `Registered renderers: ${registeredNames.map((name) => `"${name}"`).join(", ")}. `) + `Register one with useRenderTool({ name: "${toolName}", ... }), or call useDefaultRenderTool() for a built-in card that covers every tool the agent calls. This warning is development-only.`);
1081
+ console.warn(message);
1822
1082
  }
1823
1083
  }
1824
1084
  /**
@@ -1837,23 +1097,22 @@ function useToolCallRenderers() {
1837
1097
  */
1838
1098
  function useRenderToolCall() {
1839
1099
  const { copilotkit, executingToolCallIds } = (0, _copilotkit_react_core_context.useCopilotKit)();
1840
- const agentId = useCopilotChatConfiguration()?.agentId ?? _copilotkit_shared.DEFAULT_AGENT_ID;
1100
+ const agentId = (0, _copilotkit_core.ɵresolveToolCallAgentId)(useCopilotChatConfiguration()?.agentId, void 0);
1841
1101
  const unrenderedToolNames = (0, react.useRef)(/* @__PURE__ */ new Set());
1842
1102
  const warnedToolNames = (0, react.useRef)(/* @__PURE__ */ new Set());
1843
1103
  const renderToolCalls = useToolCallRenderers();
1844
1104
  const renderToolCall = (0, react.useCallback)(({ toolCall, toolMessage }) => {
1845
- const exactMatches = renderToolCalls.filter((rc) => rc.name === toolCall.function.name);
1846
- const renderConfig = exactMatches.find((rc) => rc.agentId === agentId) || exactMatches.find((rc) => !rc.agentId) || exactMatches[0] || renderToolCalls.find((rc) => rc.name === "*");
1105
+ const renderConfig = (0, _copilotkit_core.ɵresolveToolCallRenderer)(renderToolCalls, toolCall.function.name, agentId);
1847
1106
  if (!renderConfig) {
1848
1107
  if (IS_DEVELOPMENT) unrenderedToolNames.current.add(toolCall.function.name);
1849
1108
  return null;
1850
1109
  }
1851
- const RenderComponent = renderConfig.render;
1110
+ const isExecuting = executingToolCallIds.has(toolCall.id);
1852
1111
  return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ToolCallRenderer, {
1853
1112
  toolCall,
1854
1113
  toolMessage,
1855
- RenderComponent,
1856
- isExecuting: executingToolCallIds.has(toolCall.id)
1114
+ RenderComponent: renderConfig.render,
1115
+ isExecuting
1857
1116
  }, toolCall.id);
1858
1117
  }, [
1859
1118
  renderToolCalls,
@@ -1890,12 +1149,17 @@ function useRenderToolCall() {
1890
1149
  */
1891
1150
  function useCapabilities(agentId) {
1892
1151
  const { agent } = useAgent({ agentId });
1893
- if (agent && "capabilities" in agent) return agent.capabilities;
1152
+ return (0, _copilotkit_core.ɵgetAgentCapabilities)(agent);
1894
1153
  }
1895
1154
 
1896
1155
  //#endregion
1897
1156
  exports.CopilotChatConfigurationProvider = CopilotChatConfigurationProvider;
1898
- exports.CopilotChatDefaultLabels = CopilotChatDefaultLabels;
1157
+ Object.defineProperty(exports, 'CopilotChatDefaultLabels', {
1158
+ enumerable: true,
1159
+ get: function () {
1160
+ return _copilotkit_core.CopilotChatDefaultLabels;
1161
+ }
1162
+ });
1899
1163
  Object.defineProperty(exports, 'CopilotKitCoreReact', {
1900
1164
  enumerable: true,
1901
1165
  get: function () {
@@ -1924,4 +1188,5 @@ exports.useRenderTool = useRenderTool;
1924
1188
  exports.useRenderToolCall = useRenderToolCall;
1925
1189
  exports.useSuggestions = useSuggestions;
1926
1190
  exports.useThreads = useThreads;
1191
+ exports.ɵuseOwnedCore = ɵuseOwnedCore;
1927
1192
  //# sourceMappingURL=headless.cjs.map