@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.mjs CHANGED
@@ -1,22 +1,65 @@
1
1
  import { CopilotKitContext, CopilotKitCoreReact, useCopilotKit, useCopilotKit as useCopilotKit$1, useDefaultAgentId } from "@copilotkit/react-core/context";
2
2
  import React, { createContext, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore } from "react";
3
- import { DEFAULT_AGENT_ID, partialJSONParse, randomUUID } from "@copilotkit/shared";
3
+ import { CopilotChatDefaultLabels, CopilotChatDefaultLabels as CopilotChatDefaultLabels$1, ToolCallStatus, ɵChatConfigurationStore, ɵInterruptController, ɵThreadsController, ɵbindSuggestionsConfig, ɵbuildHumanInTheLoopTool, ɵbuildToolCallRenderProps, ɵcomponentToolDescription, ɵcreateThreadStore, ɵdescribeUnrenderedToolCalls, ɵgetAgentCapabilities, ɵgetAgentResolver, ɵhitlRenderProps, ɵresolveAgentId, ɵresolveAgentThreadId, ɵresolveToolCallAgentId, ɵresolveToolCallRenderer, ɵserializeContextValue, ɵshallowEqualRecord, ɵsubscribeToAgentSuggestions, ɵsubscribeToAgentUpdates, ɵvalidateAgentBinding } from "@copilotkit/core";
4
4
  import { Fragment, jsx } from "react/jsx-runtime";
5
- import { CopilotKitCoreRuntimeConnectionStatus, ProxiedCopilotRuntimeAgent, ToolCallStatus, ɵInterruptState, ɵclearAgentInterruptState, ɵcreateThreadStore, ɵgetAgentInterruptState, ɵisHttpAgent, ɵselectFetchMoreError, ɵselectHasNextPage, ɵselectIsFetchingNextPage, ɵselectIsMutating, ɵselectThreads, ɵselectThreadsError, ɵselectThreadsIsLoading } from "@copilotkit/core";
6
- import { randomUUID as randomUUID$1 } from "@ag-ui/client";
7
- import { z } from "zod";
8
- import { contentToText } from "@ag-ui/core";
5
+ import { DEFAULT_AGENT_ID, ɵanySchema } from "@copilotkit/shared";
9
6
 
7
+ //#region src/providers/use-owned-core.ts
8
+ /**
9
+ * @internal Create a core for the provider's lifetime and dispose it on
10
+ * unmount.
11
+ *
12
+ * The dispose waits one task. StrictMode (and Fast Refresh) unmount and
13
+ * remount effects in the same commit, so the remount cancels the pending
14
+ * dispose and the same core keeps working. When effects mount again after the
15
+ * core was really disposed (for example an `<Activity>` that was hidden and
16
+ * shown), the hook creates a new core and renders again: a disposed core is
17
+ * never reused.
18
+ *
19
+ * `ref` holds the current core. The provider owns it, so code that runs
20
+ * before the core exists can read `ref.current`.
21
+ *
22
+ * @example
23
+ * const coreRef = useRef<CopilotKitCoreReact | null>(null);
24
+ * const core = ɵuseOwnedCore(coreRef, () => new CopilotKitCoreReact(config));
25
+ */
26
+ function ɵuseOwnedCore(ref, create) {
27
+ const createRef = useRef(create);
28
+ createRef.current = create;
29
+ const pendingDispose = useRef(void 0);
30
+ const disposedRef = useRef(false);
31
+ const [, rerender] = useReducer((count) => count + 1, 0);
32
+ const current = ref.current ?? create();
33
+ ref.current = current;
34
+ useEffect(() => {
35
+ clearTimeout(pendingDispose.current);
36
+ pendingDispose.current = void 0;
37
+ let core = ref.current ?? createRef.current();
38
+ if (disposedRef.current) {
39
+ disposedRef.current = false;
40
+ core = createRef.current();
41
+ rerender();
42
+ }
43
+ ref.current = core;
44
+ return () => {
45
+ pendingDispose.current = setTimeout(() => {
46
+ pendingDispose.current = void 0;
47
+ disposedRef.current = true;
48
+ core.dispose();
49
+ }, 0);
50
+ };
51
+ }, [ref]);
52
+ return current;
53
+ }
54
+
55
+ //#endregion
10
56
  //#region src/lib/shallow-stable-ref.ts
11
57
  /**
12
- * Shallow equality comparison for objects.
58
+ * Shallow equality comparison for objects: same own keys, each holding the
59
+ * same value (`Object.is`). Core's `ɵshallowEqualRecord` holds the rule.
13
60
  */
14
61
  function shallowEqual(obj1, obj2) {
15
- const keys1 = Object.keys(obj1);
16
- const keys2 = Object.keys(obj2);
17
- if (keys1.length !== keys2.length) return false;
18
- for (const key of keys1) if (obj1[key] !== obj2[key]) return false;
19
- return true;
62
+ return ɵshallowEqualRecord(obj1, obj2);
20
63
  }
21
64
  /**
22
65
  * Returns true only for plain JS objects (`{}`), excluding arrays, Dates,
@@ -50,241 +93,77 @@ function useShallowStableRef(value) {
50
93
 
51
94
  //#endregion
52
95
  //#region src/providers/CopilotChatConfigurationProvider.tsx
53
- const CopilotChatDefaultLabels = {
54
- chatInputPlaceholder: "Type a message...",
55
- chatInputToolbarStartTranscribeButtonLabel: "Transcribe",
56
- chatInputToolbarCancelTranscribeButtonLabel: "Cancel",
57
- chatInputToolbarFinishTranscribeButtonLabel: "Finish",
58
- chatInputToolbarAddButtonLabel: "Add attachments",
59
- chatInputToolbarToolsButtonLabel: "Tools",
60
- chatInputToolbarSendButtonLabel: "Send message",
61
- chatInputToolbarStopButtonLabel: "Stop",
62
- assistantMessageToolbarCopyCodeLabel: "Copy",
63
- assistantMessageToolbarCopyCodeCopiedLabel: "Copied",
64
- assistantMessageToolbarCopyMessageLabel: "Copy",
65
- assistantMessageToolbarInspectorLabel: "View in Inspector",
66
- assistantMessageToolbarInspectorDescription: "Open this message in the Inspector",
67
- assistantMessageToolbarInspectorLocalOnlyLabel: "Local only",
68
- assistantMessageToolbarInspectorLocalOnlyDescription: "Only visible on localhost or loopback hosts in development. Never shown in production.",
69
- assistantMessageToolbarInspectorTitle: "CopilotKit Inspector",
70
- assistantMessageToolbarInspectorHideLabel: "Hide this icon",
71
- assistantMessageToolbarInspectorHideDescription: "Until you reload this page",
72
- assistantMessageToolbarThumbsUpLabel: "Good response",
73
- assistantMessageToolbarThumbsDownLabel: "Bad response",
74
- assistantMessageFeedbackCommentPlaceholder: "Add a comment (optional)",
75
- assistantMessageFeedbackCommentSubmitLabel: "Send comment",
76
- assistantMessageToolbarReadAloudLabel: "Read aloud",
77
- assistantMessageToolbarRegenerateLabel: "Regenerate",
78
- userMessageToolbarCopyMessageLabel: "Copy",
79
- userMessageToolbarEditMessageLabel: "Edit",
80
- userMessageToolbarPreviousBranchLabel: "Previous branch",
81
- userMessageToolbarNextBranchLabel: "Next branch",
82
- chatDisclaimerText: "AI can make mistakes. Please verify important information.",
83
- chatToggleOpenLabel: "Open chat",
84
- chatToggleCloseLabel: "Close chat",
85
- chatScrollToBottomLabel: "Scroll to bottom",
86
- modalHeaderTitle: "CopilotKit Chat",
87
- welcomeMessageText: "How can I help you today?",
88
- reasoningMessageThinkingLabel: "Thinking…",
89
- chatInputSlashMenuLabel: "Slash commands",
90
- chatInputSlashMenuEmptyText: "No commands found",
91
- attachmentRemoveButtonLabel: "Remove attachment",
92
- attachmentPlayVideoButtonLabel: "Play video",
93
- attachmentPreviewCloseButtonLabel: "Close preview",
94
- modalHeaderCloseButtonLabel: "Close",
95
- modalHeaderThreadsButtonLabel: "Open threads",
96
- sidebarLabel: "Copilot chat sidebar"
97
- };
98
- /**
99
- * Mobile breakpoint below which the chat modal and the thread-list drawer are
100
- * mutually exclusive. At or above this width both surfaces may coexist. This
101
- * mirrors the `(max-width: 767px)` / `(min-width: 768px)` split already used by
102
- * CopilotChatInput and CopilotSidebarView.
103
- */
104
- const MOBILE_MAX_WIDTH_PX = 767;
105
- /**
106
- * Reports whether the current viewport is in the mobile range (`<768px`), where
107
- * the chat modal and drawer must not be open simultaneously. SSR-safe and
108
- * defensive against environments without `matchMedia` (treated as desktop, so
109
- * no mutual-exclusion constraint is applied).
110
- *
111
- * @returns `true` when the viewport is mobile-width, `false` otherwise.
112
- */
113
- function isMobileViewport() {
114
- if (typeof window === "undefined" || typeof window.matchMedia !== "function") return false;
115
- return window.matchMedia(`(max-width: ${MOBILE_MAX_WIDTH_PX}px)`).matches;
116
- }
117
96
  const CopilotChatConfiguration = createContext(null);
118
97
  const CopilotChatConfigurationProvider = ({ children, labels, agentId, threadId, hasExplicitThreadId, isModalDefaultOpen }) => {
119
98
  const parentConfig = useContext(CopilotChatConfiguration);
120
99
  const stableLabels = useShallowStableRef(labels);
121
100
  const mergedLabels = useMemo(() => ({
122
- ...CopilotChatDefaultLabels,
101
+ ...CopilotChatDefaultLabels$1,
123
102
  ...parentConfig?.labels,
124
103
  ...stableLabels
125
104
  }), [stableLabels, parentConfig?.labels]);
126
105
  const providerAgentId = useDefaultAgentId();
127
- const resolvedAgentId = agentId ?? parentConfig?.agentId ?? providerAgentId ?? DEFAULT_AGENT_ID;
128
- const threadIdPropIsAuthoritative = threadId !== void 0 && hasExplicitThreadId !== false;
129
- const isThreadIdControlled = threadIdPropIsAuthoritative;
130
- const [activeThreadOverride, setActiveThreadOverride] = useState(null);
131
- const resolvedThreadId = useMemo(() => {
132
- if (threadIdPropIsAuthoritative) return threadId;
133
- if (activeThreadOverride) return activeThreadOverride.threadId;
134
- if (parentConfig?.threadId) return parentConfig.threadId;
135
- if (threadId) return threadId;
136
- return randomUUID();
106
+ const options = {
107
+ agentId,
108
+ threadId,
109
+ hasExplicitThreadId,
110
+ isModalDefaultOpen,
111
+ providerAgentId
112
+ };
113
+ const parentStore = parentConfig?.ɵstore ?? null;
114
+ const [store] = useState(() => new ɵChatConfigurationStore(options, parentStore));
115
+ store.ɵsetOptions(options);
116
+ const snapshot = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);
117
+ useEffect(() => {
118
+ store.update({
119
+ agentId,
120
+ threadId,
121
+ hasExplicitThreadId,
122
+ isModalDefaultOpen,
123
+ providerAgentId
124
+ });
137
125
  }, [
138
- threadIdPropIsAuthoritative,
126
+ store,
127
+ agentId,
139
128
  threadId,
140
- parentConfig?.threadId,
141
- activeThreadOverride
129
+ hasExplicitThreadId,
130
+ isModalDefaultOpen,
131
+ providerAgentId
142
132
  ]);
143
133
  const copilotkit = useContext(CopilotKitContext)?.copilotkit;
144
- const openThreadRef = useRef(null);
145
- const latestThreadIdRef = useRef(resolvedThreadId);
146
- latestThreadIdRef.current = resolvedThreadId;
147
134
  useEffect(() => {
148
135
  if (copilotkit === void 0) return;
149
- const registration = copilotkit.registerOpenThread({
150
- agentId: resolvedAgentId,
151
- threadId: latestThreadIdRef.current
152
- });
153
- openThreadRef.current = registration;
154
- return () => {
155
- registration.unregister();
156
- openThreadRef.current = null;
157
- };
158
- }, [copilotkit, resolvedAgentId]);
159
- useEffect(() => {
160
- openThreadRef.current?.update(resolvedThreadId);
161
- }, [resolvedThreadId]);
162
- const resolvedHasExplicitThreadId = (threadIdPropIsAuthoritative ? true : activeThreadOverride?.explicit ?? hasExplicitThreadId ?? false) || !!parentConfig?.hasExplicitThreadId;
163
- const [internalModalOpen, setInternalModalOpen] = useState(isModalDefaultOpen ?? true);
164
- const hasExplicitDefault = isModalDefaultOpen !== void 0;
165
- const setAndSync = useCallback((open) => {
166
- setInternalModalOpen(open);
167
- parentConfig?.setModalOpen(open);
168
- }, [parentConfig?.setModalOpen]);
169
- const isMounted = useRef(false);
170
- useEffect(() => {
171
- if (!hasExplicitDefault) return;
172
- if (!isMounted.current) {
173
- isMounted.current = true;
174
- return;
175
- }
176
- if (parentConfig?.isModalOpen === void 0) return;
177
- setInternalModalOpen(parentConfig.isModalOpen);
178
- }, [parentConfig?.isModalOpen, hasExplicitDefault]);
179
- const resolvedIsModalOpen = hasExplicitDefault ? internalModalOpen : parentConfig?.isModalOpen ?? internalModalOpen;
180
- const resolvedSetModalOpen = hasExplicitDefault ? setAndSync : parentConfig?.setModalOpen ?? setInternalModalOpen;
181
- const [ownDrawerOpen, setOwnDrawerOpen] = useState(false);
182
- const [ownDrawerCount, setOwnDrawerCount] = useState(0);
183
- const modalCloseRef = useRef(() => {});
184
- modalCloseRef.current = resolvedSetModalOpen;
185
- const registeredModalClosersRef = useRef([]);
186
- const ownRegisterModalCloser = useCallback((closeModal) => {
187
- registeredModalClosersRef.current.push(closeModal);
188
- return () => {
189
- registeredModalClosersRef.current = registeredModalClosersRef.current.filter((entry) => entry !== closeModal);
190
- };
191
- }, []);
192
- const ownSetDrawerOpen = useCallback((open) => {
193
- setOwnDrawerOpen(open);
194
- if (open && isMobileViewport()) {
195
- const registered = registeredModalClosersRef.current;
196
- (registered.length > 0 ? registered[registered.length - 1] : modalCloseRef.current)(false);
197
- }
198
- }, []);
199
- const ownRegisterDrawer = useCallback(() => {
200
- setOwnDrawerCount((count) => count + 1);
201
- return () => {
202
- setOwnDrawerCount((count) => Math.max(0, count - 1));
203
- };
204
- }, []);
205
- const resolvedDrawerOpen = parentConfig ? parentConfig.drawerOpen : ownDrawerOpen;
206
- const resolvedSetDrawerOpen = parentConfig ? parentConfig.setDrawerOpen : ownSetDrawerOpen;
207
- const resolvedDrawerRegistered = parentConfig ? parentConfig.drawerRegistered : ownDrawerCount > 0;
208
- const resolvedRegisterDrawer = parentConfig ? parentConfig.registerDrawer : ownRegisterDrawer;
209
- const resolvedRegisterModalCloser = parentConfig ? parentConfig.ɵregisterModalCloser : ownRegisterModalCloser;
210
- useEffect(() => {
211
- if (!hasExplicitDefault) return;
212
- return resolvedRegisterModalCloser(resolvedSetModalOpen);
213
- }, [
214
- hasExplicitDefault,
215
- resolvedRegisterModalCloser,
216
- resolvedSetModalOpen
217
- ]);
218
- const isThreadIdControlledRef = useRef(isThreadIdControlled);
219
- isThreadIdControlledRef.current = isThreadIdControlled;
220
- const ownSetActiveThreadId = useCallback((id, options) => {
221
- setActiveThreadOverride({
222
- threadId: id,
223
- explicit: options?.explicit ?? true
224
- });
225
- }, []);
226
- const ownStartNewThread = useCallback(() => {
227
- setActiveThreadOverride({
228
- threadId: randomUUID(),
229
- explicit: false
230
- });
231
- }, []);
232
- const parentSetActiveThreadId = parentConfig?.setActiveThreadId;
233
- const parentStartNewThread = parentConfig?.startNewThread;
234
- const resolvedSetActiveThreadId = useCallback((id, options) => {
235
- if (isThreadIdControlledRef.current) {
236
- console.warn("[CopilotKit] Ignoring setActiveThreadId(): threadId is controlled via the `threadId` prop on CopilotChatConfigurationProvider.");
237
- return;
238
- }
239
- if (parentSetActiveThreadId) {
240
- parentSetActiveThreadId(id, options);
241
- return;
242
- }
243
- ownSetActiveThreadId(id, options);
244
- }, [parentSetActiveThreadId, ownSetActiveThreadId]);
245
- const resolvedStartNewThread = useCallback(() => {
246
- if (isThreadIdControlledRef.current) {
247
- console.warn("[CopilotKit] Ignoring startNewThread(): threadId is controlled via the `threadId` prop on CopilotChatConfigurationProvider.");
248
- return;
249
- }
250
- if (parentStartNewThread) {
251
- parentStartNewThread();
252
- return;
253
- }
254
- ownStartNewThread();
255
- }, [parentStartNewThread, ownStartNewThread]);
256
- const setModalOpenWithDrawerExclusion = useCallback((open) => {
257
- if (open && isMobileViewport()) resolvedSetDrawerOpen(false);
258
- resolvedSetModalOpen(open);
259
- }, [resolvedSetModalOpen, resolvedSetDrawerOpen]);
136
+ return store.bindOpenThread(copilotkit);
137
+ }, [copilotkit, store]);
138
+ const ownsModal = isModalDefaultOpen !== void 0;
139
+ const isModalOpen = ownsModal || !parentConfig ? snapshot.isModalOpen : parentConfig.isModalOpen;
140
+ const setModalOpen = ownsModal || !parentConfig ? store.setModalOpen : parentConfig.setModalOpen;
141
+ const { agentId: resolvedAgentId, threadId: resolvedThreadId, hasExplicitThreadId: resolvedHasExplicitThreadId, drawerOpen, drawerRegistered } = snapshot;
260
142
  const configurationValue = useMemo(() => ({
261
143
  labels: mergedLabels,
262
144
  agentId: resolvedAgentId,
263
145
  threadId: resolvedThreadId,
264
146
  hasExplicitThreadId: resolvedHasExplicitThreadId,
265
- isModalOpen: resolvedIsModalOpen,
266
- setModalOpen: setModalOpenWithDrawerExclusion,
267
- drawerOpen: resolvedDrawerOpen,
268
- setDrawerOpen: resolvedSetDrawerOpen,
269
- drawerRegistered: resolvedDrawerRegistered,
270
- registerDrawer: resolvedRegisterDrawer,
271
- ɵregisterModalCloser: resolvedRegisterModalCloser,
272
- setActiveThreadId: resolvedSetActiveThreadId,
273
- startNewThread: resolvedStartNewThread
147
+ isModalOpen,
148
+ setModalOpen,
149
+ drawerOpen,
150
+ setDrawerOpen: store.setDrawerOpen,
151
+ drawerRegistered,
152
+ registerDrawer: store.registerDrawer,
153
+ ɵregisterModalCloser: store.registerModalCloser,
154
+ setActiveThreadId: store.setActiveThreadId,
155
+ startNewThread: store.startNewThread,
156
+ ɵstore: store
274
157
  }), [
275
158
  mergedLabels,
276
159
  resolvedAgentId,
277
160
  resolvedThreadId,
278
161
  resolvedHasExplicitThreadId,
279
- resolvedIsModalOpen,
280
- setModalOpenWithDrawerExclusion,
281
- resolvedDrawerOpen,
282
- resolvedSetDrawerOpen,
283
- resolvedDrawerRegistered,
284
- resolvedRegisterDrawer,
285
- resolvedRegisterModalCloser,
286
- resolvedSetActiveThreadId,
287
- resolvedStartNewThread
162
+ isModalOpen,
163
+ setModalOpen,
164
+ drawerOpen,
165
+ drawerRegistered,
166
+ store
288
167
  ]);
289
168
  return /* @__PURE__ */ jsx(CopilotChatConfiguration.Provider, {
290
169
  value: configurationValue,
@@ -365,163 +244,57 @@ const ALL_UPDATES = [
365
244
  UseAgentUpdate.OnRunStatusChanged
366
245
  ];
367
246
  function useAgent({ agentId, threadId, runtimeAgentId, updates, throttleMs } = {}) {
368
- 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 }).`);
369
- 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}" }).`);
370
- 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 "${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 }).`);
247
+ ɵvalidateAgentBinding({
248
+ agentId,
249
+ threadId,
250
+ runtimeAgentId
251
+ });
371
252
  const chatConfig = useCopilotChatConfiguration();
372
253
  const providerAgentId = useDefaultAgentId();
373
- const resolvedAgentId = agentId ?? chatConfig?.agentId ?? providerAgentId ?? DEFAULT_AGENT_ID;
254
+ const resolvedAgentId = ɵresolveAgentId({
255
+ agentId,
256
+ chatAgentId: chatConfig?.agentId,
257
+ providerAgentId
258
+ });
374
259
  const { copilotkit } = useCopilotKit$1();
260
+ const resolver = ɵgetAgentResolver(copilotkit);
261
+ const revision = useSyncExternalStore(resolver.subscribe, resolver.getSnapshot, resolver.getSnapshot);
375
262
  const providerThrottleMs = copilotkit.defaultThrottleMs;
376
263
  const [, forceUpdate] = useReducer((x) => x + 1, 0);
377
264
  const updateFlags = useMemo(() => updates ?? ALL_UPDATES, [JSON.stringify(updates)]);
378
- const provisionalAgentCache = useRef(/* @__PURE__ */ new Map());
379
- const [registeredProxyAgent, setRegisteredProxyAgent] = useState(null);
380
265
  useEffect(() => {
381
- if (runtimeAgentId == null) {
382
- setRegisteredProxyAgent(null);
383
- return;
384
- }
385
- const { agent: proxy, unregister } = copilotkit.registerProxiedAgent({
266
+ if (runtimeAgentId == null) return;
267
+ return resolver.bindProxy({
386
268
  agentId: resolvedAgentId,
387
269
  runtimeAgentId
388
270
  });
389
- provisionalAgentCache.current.delete(resolvedAgentId);
390
- setRegisteredProxyAgent(proxy);
391
- return () => {
392
- unregister();
393
- setRegisteredProxyAgent(null);
394
- };
395
271
  }, [
396
- copilotkit,
272
+ resolver,
397
273
  resolvedAgentId,
398
274
  runtimeAgentId
399
275
  ]);
400
- const { agent, isReady } = useMemo(() => {
401
- if (runtimeAgentId != null) {
402
- if (registeredProxyAgent) {
403
- provisionalAgentCache.current.delete(resolvedAgentId);
404
- return {
405
- agent: registeredProxyAgent,
406
- isReady: true
407
- };
408
- }
409
- const cached = provisionalAgentCache.current.get(resolvedAgentId);
410
- if (cached) {
411
- copilotkit.applyHeadersToAgent(cached);
412
- return {
413
- agent: cached,
414
- isReady: false
415
- };
416
- }
417
- const provisional = new ProxiedCopilotRuntimeAgent({
418
- runtimeUrl: copilotkit.runtimeUrl,
419
- agentId: resolvedAgentId,
420
- runtimeAgentId,
421
- transport: copilotkit.runtimeTransport,
422
- runtimeMode: "pending"
423
- });
424
- copilotkit.applyHeadersToAgent(provisional);
425
- provisionalAgentCache.current.set(resolvedAgentId, provisional);
426
- return {
427
- agent: provisional,
428
- isReady: false
429
- };
430
- }
431
- const existing = copilotkit.getAgent(resolvedAgentId);
432
- if (existing) {
433
- provisionalAgentCache.current.delete(resolvedAgentId);
434
- return {
435
- agent: existing,
436
- isReady: true
437
- };
438
- }
439
- const isRuntimeConfigured = copilotkit.runtimeUrl !== void 0;
440
- const status = copilotkit.runtimeConnectionStatus;
441
- if (isRuntimeConfigured && (status === CopilotKitCoreRuntimeConnectionStatus.Disconnected || status === CopilotKitCoreRuntimeConnectionStatus.Connecting)) {
442
- const cached = provisionalAgentCache.current.get(resolvedAgentId);
443
- if (cached) return {
444
- agent: cached,
445
- isReady: false
446
- };
447
- const provisional = new ProxiedCopilotRuntimeAgent({
448
- runtimeUrl: copilotkit.runtimeUrl,
449
- agentId: resolvedAgentId,
450
- transport: copilotkit.runtimeTransport,
451
- credentials: copilotkit.credentials,
452
- runtimeMode: "pending"
453
- });
454
- copilotkit.applyHeadersToAgent(provisional);
455
- provisionalAgentCache.current.set(resolvedAgentId, provisional);
456
- return {
457
- agent: provisional,
458
- isReady: false
459
- };
460
- }
461
- if (isRuntimeConfigured && status === CopilotKitCoreRuntimeConnectionStatus.Error) {
462
- const cached = provisionalAgentCache.current.get(resolvedAgentId);
463
- if (cached) return {
464
- agent: cached,
465
- isReady: false
466
- };
467
- const provisional = new ProxiedCopilotRuntimeAgent({
468
- runtimeUrl: copilotkit.runtimeUrl,
469
- agentId: resolvedAgentId,
470
- transport: copilotkit.runtimeTransport,
471
- credentials: copilotkit.credentials,
472
- runtimeMode: "pending"
473
- });
474
- copilotkit.applyHeadersToAgent(provisional);
475
- provisionalAgentCache.current.set(resolvedAgentId, provisional);
476
- return {
477
- agent: provisional,
478
- isReady: false
479
- };
480
- }
481
- const knownAgents = Object.keys(copilotkit.agents ?? {});
482
- const runtimePart = isRuntimeConfigured ? `runtimeUrl=${copilotkit.runtimeUrl}` : "no runtimeUrl";
483
- 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.");
484
- }, [
276
+ const headersGeneration = copilotkit.ɵheadersGeneration;
277
+ const { agent, isReady } = useMemo(() => resolver.resolve({
278
+ agentId: resolvedAgentId,
279
+ runtimeAgentId,
280
+ caller: "useAgent"
281
+ }), [
282
+ resolver,
283
+ revision,
485
284
  resolvedAgentId,
486
285
  runtimeAgentId,
487
- registeredProxyAgent,
488
286
  copilotkit.agents,
489
287
  copilotkit.runtimeConnectionStatus,
490
288
  copilotkit.runtimeUrl,
491
289
  copilotkit.runtimeTransport,
492
290
  copilotkit.credentials,
493
- JSON.stringify(copilotkit.headers)
291
+ headersGeneration
494
292
  ]);
495
- useEffect(() => {
496
- if (updateFlags.length === 0) return;
497
- let active = true;
498
- const handlers = {};
499
- let batchScheduled = false;
500
- const batchedForceUpdate = () => {
501
- if (!active) return;
502
- if (!batchScheduled) {
503
- batchScheduled = true;
504
- queueMicrotask(() => {
505
- batchScheduled = false;
506
- if (active) forceUpdate();
507
- });
508
- }
509
- };
510
- if (updateFlags.includes(UseAgentUpdate.OnMessagesChanged)) handlers.onMessagesChanged = batchedForceUpdate;
511
- if (updateFlags.includes(UseAgentUpdate.OnStateChanged)) handlers.onStateChanged = batchedForceUpdate;
512
- if (updateFlags.includes(UseAgentUpdate.OnRunStatusChanged)) {
513
- handlers.onRunInitialized = batchedForceUpdate;
514
- handlers.onRunStartedEvent = batchedForceUpdate;
515
- handlers.onRunFinalized = batchedForceUpdate;
516
- handlers.onRunFailed = batchedForceUpdate;
517
- handlers.onRunErrorEvent = batchedForceUpdate;
518
- }
519
- const subscription = copilotkit.subscribeToAgentWithOptions(agent, handlers, { throttleMs });
520
- return () => {
521
- active = false;
522
- subscription.unsubscribe();
523
- };
524
- }, [
293
+ useEffect(() => ɵsubscribeToAgentUpdates(copilotkit, agent, {
294
+ updates: updateFlags,
295
+ throttleMs,
296
+ onUpdate: forceUpdate
297
+ }), [
525
298
  agent,
526
299
  forceUpdate,
527
300
  throttleMs,
@@ -529,16 +302,18 @@ function useAgent({ agentId, threadId, runtimeAgentId, updates, throttleMs } = {
529
302
  updateFlags
530
303
  ]);
531
304
  useEffect(() => {
532
- if (ɵisHttpAgent(agent)) copilotkit.applyHeadersToAgent(agent);
533
- if (agent instanceof ProxiedCopilotRuntimeAgent) agent.credentials = copilotkit.credentials;
305
+ resolver.refreshRequestSettings(agent);
534
306
  }, [
307
+ resolver,
535
308
  agent,
536
- JSON.stringify(copilotkit.headers),
309
+ headersGeneration,
537
310
  copilotkit.credentials
538
311
  ]);
539
- const configThreadId = chatConfig?.threadId;
540
- const configHasExplicitThreadId = chatConfig?.hasExplicitThreadId;
541
- const resolvedThreadId = threadId ?? (configHasExplicitThreadId ? configThreadId : void 0);
312
+ const resolvedThreadId = ɵresolveAgentThreadId({
313
+ threadId,
314
+ chatThreadId: chatConfig?.threadId,
315
+ chatHasExplicitThreadId: chatConfig?.hasExplicitThreadId
316
+ });
542
317
  useEffect(() => {
543
318
  if (!resolvedThreadId) return;
544
319
  agent.threadId = resolvedThreadId;
@@ -626,6 +401,30 @@ function useDepsVersion(deps) {
626
401
 
627
402
  //#endregion
628
403
  //#region src/hooks/use-frontend-tool.tsx
404
+ /**
405
+ * Register a frontend tool while the component is mounted. The agent can
406
+ * call it, and its `render` component draws the call in the chat.
407
+ *
408
+ * A tool with the same name and agentId as a tool that is already registered
409
+ * (for example one from the provider's `tools`) overrides it while this
410
+ * component is mounted. When the component unmounts, the overridden tool is
411
+ * active again. The renderer stays registered after unmount, so past tool
412
+ * calls still render in the chat history.
413
+ *
414
+ * @param tool - The tool to register.
415
+ * @param deps - Extra values that re-register the tool when they change. Use
416
+ * it when the handler closes over a value that is not part of the tool.
417
+ *
418
+ * @example
419
+ * ```tsx
420
+ * useFrontendTool({
421
+ * name: "showWeather",
422
+ * description: "Show the weather for a city",
423
+ * parameters: z.object({ city: z.string() }),
424
+ * handler: async ({ city }) => `Sunny in ${city}`,
425
+ * });
426
+ * ```
427
+ */
629
428
  function useFrontendTool(tool, deps) {
630
429
  const { copilotkit } = useCopilotKit$1();
631
430
  const depsVersion = useDepsVersion(deps);
@@ -634,11 +433,8 @@ function useFrontendTool(tool, deps) {
634
433
  if (copilotkit.getTool({
635
434
  toolName: name,
636
435
  agentId: tool.agentId
637
- })) {
638
- console.warn(`Tool '${name}' already exists for agent '${tool.agentId || "global"}'. Overriding with latest registration.`);
639
- copilotkit.removeTool(name, tool.agentId);
640
- }
641
- copilotkit.addTool(tool);
436
+ })) console.warn(`Tool '${name}' already exists for agent '${tool.agentId || "global"}'. Overriding with latest registration.`);
437
+ const unregister = copilotkit.addTool(tool);
642
438
  if (tool.render) copilotkit.addHookRenderToolCall({
643
439
  name,
644
440
  args: tool.parameters,
@@ -646,7 +442,7 @@ function useFrontendTool(tool, deps) {
646
442
  render: tool.render
647
443
  });
648
444
  return () => {
649
- copilotkit.removeTool(name, tool.agentId);
445
+ unregister();
650
446
  };
651
447
  }, [
652
448
  tool.name,
@@ -671,8 +467,10 @@ const EMPTY_TOOLS = [];
671
467
  *
672
468
  * Tools are keyed by `name` plus `agentId`, the same as `useFrontendTool`. A
673
469
  * tool that disappears from the array is unregistered on the next render, and
674
- * every tool is unregistered on unmount. Renderers stay registered after
675
- * unmount so past tool calls still render in the chat history.
470
+ * every tool is unregistered on unmount. A listed tool hides a tool with the
471
+ * same name and agentId (for example one from the provider's `tools`) until it
472
+ * is unregistered, and then the hidden tool is active again. Renderers stay
473
+ * registered after unmount so past tool calls still render in the chat history.
676
474
  *
677
475
  * @param tools - The tools to register. May be empty and may change length.
678
476
  * @param deps - Extra dependencies that force re-registration, compared by
@@ -722,15 +520,13 @@ function useFrontendTools(tools, deps) {
722
520
  deduped.set(key, tool);
723
521
  }
724
522
  const registered = [...deduped.values()];
523
+ const unregisters = [];
725
524
  for (const tool of registered) {
726
525
  if (copilotkit.getTool({
727
526
  toolName: tool.name,
728
527
  agentId: tool.agentId
729
- })) {
730
- console.warn(`Tool '${tool.name}' already exists for agent '${tool.agentId || "global"}'. Overriding with latest registration.`);
731
- copilotkit.removeTool(tool.name, tool.agentId);
732
- }
733
- copilotkit.addTool(tool);
528
+ })) console.warn(`Tool '${tool.name}' already exists for agent '${tool.agentId || "global"}'. Overriding with latest registration.`);
529
+ unregisters.push(copilotkit.addTool(tool));
734
530
  if (tool.render) copilotkit.addHookRenderToolCall({
735
531
  name: tool.name,
736
532
  args: tool.parameters,
@@ -739,7 +535,7 @@ function useFrontendTools(tools, deps) {
739
535
  });
740
536
  }
741
537
  return () => {
742
- for (const tool of registered) copilotkit.removeTool(tool.name, tool.agentId);
538
+ for (const unregister of unregisters) unregister();
743
539
  };
744
540
  }, [
745
541
  JSON.stringify(toolList.map((tool) => [
@@ -807,8 +603,7 @@ function useFrontendTools(tools, deps) {
807
603
  * ```
808
604
  */
809
605
  function useComponent(config, deps) {
810
- const prefix = `Use this tool to display the "${config.name}" component in the chat. This tool renders a visual UI component for the user.`;
811
- const fullDescription = config.description ? `${prefix}\n\n${config.description}` : prefix;
606
+ const fullDescription = ɵcomponentToolDescription(config.name, config.description);
812
607
  useFrontendTool({
813
608
  name: config.name,
814
609
  description: fullDescription,
@@ -824,84 +619,18 @@ function useComponent(config, deps) {
824
619
 
825
620
  //#endregion
826
621
  //#region src/hooks/use-human-in-the-loop.tsx
827
- /** Registration name of a catch-all tool: handles any otherwise-unhandled call. */
828
- const WILDCARD_TOOL_NAME = "*";
829
622
  function useHumanInTheLoop(tool, deps) {
830
623
  const { copilotkit } = useCopilotKit$1();
831
- const resolvePromiseRef = useRef(null);
832
- const cleanupAbortRef = useRef(null);
833
- const respond = useCallback(async (result) => {
834
- if (resolvePromiseRef.current) {
835
- cleanupAbortRef.current?.();
836
- cleanupAbortRef.current = null;
837
- resolvePromiseRef.current(result);
838
- resolvePromiseRef.current = null;
839
- }
840
- }, []);
841
- const handler = useCallback(async (_args, context) => {
842
- const signal = context?.signal;
843
- return new Promise((resolve, reject) => {
844
- if (signal?.aborted) {
845
- reject(/* @__PURE__ */ new Error("Human-in-the-loop interaction aborted"));
846
- return;
847
- }
848
- resolvePromiseRef.current = resolve;
849
- if (signal) {
850
- const onAbort = () => {
851
- cleanupAbortRef.current = null;
852
- resolvePromiseRef.current = null;
853
- reject(/* @__PURE__ */ new Error("Human-in-the-loop interaction aborted"));
854
- };
855
- signal.addEventListener("abort", onAbort, { once: true });
856
- cleanupAbortRef.current = () => {
857
- signal.removeEventListener("abort", onAbort);
858
- };
859
- }
860
- });
861
- }, []);
862
- const RenderComponent = useCallback((props) => {
863
- const ToolComponent = tool.render;
864
- const name = tool.name === WILDCARD_TOOL_NAME ? props.name : tool.name;
865
- if (props.status === ToolCallStatus.InProgress) {
866
- const enhancedProps = {
867
- ...props,
868
- name,
869
- description: tool.description || "",
870
- agentId: tool.agentId,
871
- respond: void 0
872
- };
873
- return React.createElement(ToolComponent, enhancedProps);
874
- } else if (props.status === ToolCallStatus.Executing) {
875
- const enhancedProps = {
876
- ...props,
877
- name,
878
- description: tool.description || "",
879
- agentId: tool.agentId,
880
- respond
881
- };
882
- return React.createElement(ToolComponent, enhancedProps);
883
- } else if (props.status === ToolCallStatus.Complete) {
884
- const enhancedProps = {
885
- ...props,
886
- name,
887
- description: tool.description || "",
888
- agentId: tool.agentId,
889
- respond: void 0
890
- };
891
- return React.createElement(ToolComponent, enhancedProps);
892
- }
893
- return props;
894
- }, [
624
+ const registry = copilotkit.ɵhumanInTheLoop;
625
+ const RenderComponent = useCallback((props) => React.createElement(tool.render, ɵhitlRenderProps(props, tool, registry)), [
895
626
  tool.render,
896
627
  tool.name,
897
628
  tool.description,
898
629
  tool.agentId,
899
- respond
630
+ registry
900
631
  ]);
901
632
  useFrontendTool({
902
- ...tool,
903
- type: "human-in-the-loop",
904
- handler,
633
+ ...ɵbuildHumanInTheLoopTool(tool, registry),
905
634
  render: RenderComponent
906
635
  }, deps);
907
636
  useLayoutEffect(() => {
@@ -915,25 +644,8 @@ function useHumanInTheLoop(tool, deps) {
915
644
  ]);
916
645
  }
917
646
 
918
- //#endregion
919
- //#region src/types/interrupt.ts
920
- /** Name of the legacy custom event agents emit to signal an interrupt. */
921
- const INTERRUPT_EVENT_NAME = "on_interrupt";
922
-
923
647
  //#endregion
924
648
  //#region src/hooks/use-interrupt.tsx
925
- /** Recognize thenables returned by interrupt preprocessing handlers. */
926
- function isPromiseLike(value) {
927
- return (typeof value === "object" || typeof value === "function") && value !== null && typeof Reflect.get(value, "then") === "function";
928
- }
929
- /** Derive the legacy-compatible `event` for any pending interrupt. */
930
- function toLegacyEvent(pending) {
931
- if (pending.kind === "legacy") return pending.event;
932
- return {
933
- name: INTERRUPT_EVENT_NAME,
934
- value: pending.interrupts[0]
935
- };
936
- }
937
649
  /**
938
650
  * Handles agent interrupts with optional filtering, preprocessing, and resume behavior.
939
651
  *
@@ -967,228 +679,24 @@ function useInterrupt(config) {
967
679
  agentId: config.agentId,
968
680
  updates: []
969
681
  });
970
- const [pending, setPending] = useState(null);
971
- const pendingRef = useRef(pending);
972
- pendingRef.current = pending;
973
- const [handlerResult, setHandlerResult] = useState(null);
974
- const interruptStateRef = useRef(new ɵInterruptState());
975
- useEffect(() => {
976
- let localLegacy = null;
977
- let localStandard = null;
978
- const subscription = agent.subscribe({
979
- onCustomEvent: ({ event }) => {
980
- if (event.name === INTERRUPT_EVENT_NAME) localLegacy = {
981
- name: event.name,
982
- value: event.value
983
- };
984
- },
985
- onRunFinishedEvent: (params) => {
986
- if (params.outcome === "interrupt") localStandard = params.interrupts;
987
- },
988
- onRunStartedEvent: (params) => {
989
- if (!agent.pendingInterrupts?.length || params?.input?.resume !== void 0) ɵclearAgentInterruptState(agent);
990
- localLegacy = null;
991
- localStandard = null;
992
- interruptStateRef.current = new ɵInterruptState();
993
- setPending(null);
994
- },
995
- onRunFinalized: () => {
996
- if (localStandard && localStandard.length > 0) {
997
- interruptStateRef.current = ɵgetAgentInterruptState(agent, localStandard);
998
- setPending(interruptStateRef.current.pending);
999
- } else if (localLegacy) {
1000
- interruptStateRef.current = new ɵInterruptState();
1001
- interruptStateRef.current.setLegacy(localLegacy);
1002
- setPending(interruptStateRef.current.pending);
1003
- }
1004
- localLegacy = null;
1005
- localStandard = null;
1006
- },
1007
- onRunFailed: () => {
1008
- localLegacy = null;
1009
- localStandard = null;
1010
- interruptStateRef.current = new ɵInterruptState();
1011
- setPending(null);
1012
- }
1013
- });
1014
- interruptStateRef.current = agent.pendingInterrupts?.length ? ɵgetAgentInterruptState(agent) : new ɵInterruptState();
1015
- setPending(interruptStateRef.current.pending);
1016
- return () => {
1017
- subscription.unsubscribe();
1018
- interruptStateRef.current = new ɵInterruptState();
1019
- };
1020
- }, [agent]);
1021
- /** Record an explicit answer and resume once the complete batch is addressed. */
1022
- const resolve = useCallback(async (payload, interruptId) => {
1023
- const current = pendingRef.current;
1024
- if (!current) return;
1025
- 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.`);
1026
- if (interruptStateRef.current.isCompletedToolCall(interruptId, agent.messages)) {
1027
- console.warn("[CopilotKit] useInterrupt: ignoring an answer for an already completed frontend tool call.");
1028
- return;
1029
- }
1030
- const decision = interruptStateRef.current.resolve(payload, interruptId, agent.messages);
1031
- if (decision.kind === "legacy-resume") try {
1032
- return await copilotkit.runAgent({
1033
- agent,
1034
- forwardedProps: { command: {
1035
- resume: decision.payload,
1036
- interruptEvent: decision.interruptValue
1037
- } }
1038
- });
1039
- } catch (err) {
1040
- console.error("[CopilotKit] useInterrupt resolve: runAgent rejected; clearing pending + rethrowing", err);
1041
- setPending(null);
1042
- throw err;
1043
- }
1044
- if (decision.kind === "expired") {
1045
- console.error(`[CopilotKit] useInterrupt: interrupt ${decision.interrupt.id} expired at ${decision.interrupt.expiresAt}; not resuming.`);
1046
- interruptStateRef.current = new ɵInterruptState();
1047
- setPending(null);
1048
- return;
1049
- }
1050
- if (decision.kind !== "resume") return;
1051
- for (const toolResult of decision.toolResults) agent.addMessage({
1052
- id: randomUUID$1(),
1053
- role: "tool",
1054
- toolCallId: toolResult.toolCallId,
1055
- content: toolResult.content
1056
- });
1057
- try {
1058
- return await copilotkit.runAgent({
1059
- agent,
1060
- resume: decision.resume
1061
- });
1062
- } catch (err) {
1063
- console.error("[CopilotKit] useInterrupt resolve: runAgent rejected; clearing pending + rethrowing", err);
1064
- interruptStateRef.current = new ɵInterruptState();
1065
- setPending(null);
1066
- throw err;
1067
- }
1068
- }, [agent, copilotkit]);
1069
- /** Cancel a standard interrupt or dismiss a legacy interrupt locally. */
1070
- const cancel = useCallback(async (interruptId) => {
1071
- const current = pendingRef.current;
1072
- if (!current) return;
1073
- 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.`);
1074
- if (interruptStateRef.current.isCompletedToolCall(interruptId, agent.messages)) {
1075
- console.warn("[CopilotKit] useInterrupt: ignoring an answer for an already completed frontend tool call.");
1076
- return;
1077
- }
1078
- const decision = interruptStateRef.current.cancel(interruptId, agent.messages);
1079
- if (decision.kind === "dismiss") {
1080
- console.warn("[CopilotKit] useInterrupt: cancel() is not supported for legacy on_interrupt interrupts; dismissing.");
1081
- interruptStateRef.current = new ɵInterruptState();
1082
- setPending(null);
1083
- return;
1084
- }
1085
- if (decision.kind === "expired") {
1086
- console.error(`[CopilotKit] useInterrupt: interrupt ${decision.interrupt.id} expired at ${decision.interrupt.expiresAt}; not resuming.`);
1087
- interruptStateRef.current = new ɵInterruptState();
1088
- setPending(null);
1089
- return;
1090
- }
1091
- if (decision.kind !== "resume") return;
1092
- for (const toolResult of decision.toolResults) agent.addMessage({
1093
- id: randomUUID$1(),
1094
- role: "tool",
1095
- toolCallId: toolResult.toolCallId,
1096
- content: toolResult.content
1097
- });
1098
- try {
1099
- return await copilotkit.runAgent({
1100
- agent,
1101
- resume: decision.resume
1102
- });
1103
- } catch (err) {
1104
- console.error("[CopilotKit] useInterrupt resolve: runAgent rejected; clearing pending + rethrowing", err);
1105
- interruptStateRef.current = new ɵInterruptState();
1106
- setPending(null);
1107
- throw err;
1108
- }
1109
- }, [agent, copilotkit]);
1110
682
  const renderRef = useRef(config.render);
1111
683
  renderRef.current = config.render;
1112
684
  const enabledRef = useRef(config.enabled);
1113
685
  enabledRef.current = config.enabled;
1114
686
  const handlerRef = useRef(config.handler);
1115
687
  handlerRef.current = config.handler;
1116
- const resolveRef = useRef(resolve);
1117
- resolveRef.current = resolve;
1118
- const cancelRef = useRef(cancel);
1119
- cancelRef.current = cancel;
1120
- /** Evaluate the consumer filter, logging failures and disabling their UI. */
1121
- const isEnabled = (event) => {
1122
- const predicate = enabledRef.current;
1123
- if (!predicate) return true;
1124
- try {
1125
- return predicate(event);
1126
- } catch (err) {
1127
- console.error("[CopilotKit] useInterrupt enabled predicate threw; treating interrupt as disabled:", err);
1128
- return false;
1129
- }
1130
- };
688
+ const copilotkitRef = useRef(copilotkit);
689
+ copilotkitRef.current = copilotkit;
690
+ const [controller] = useState(() => new ɵInterruptController({ runAgent: (params) => copilotkitRef.current.runAgent(params) }, {
691
+ enabled: (event) => enabledRef.current?.(event) ?? true,
692
+ handler: (props) => handlerRef.current ? handlerRef.current(props) : null
693
+ }));
1131
694
  useEffect(() => {
1132
- if (!pending) {
1133
- setHandlerResult(null);
1134
- return;
1135
- }
1136
- const legacyEvent = toLegacyEvent(pending);
1137
- if (!isEnabled(legacyEvent)) {
1138
- setHandlerResult(null);
1139
- return;
1140
- }
1141
- const handler = handlerRef.current;
1142
- if (!handler) {
1143
- setHandlerResult(null);
1144
- return;
1145
- }
1146
- let cancelled = false;
1147
- let maybePromise;
1148
- try {
1149
- maybePromise = handler({
1150
- event: legacyEvent,
1151
- interrupt: pending.kind === "standard" ? pending.interrupts[0] : null,
1152
- interrupts: pending.kind === "standard" ? [...pending.interrupts] : [],
1153
- resolve: resolveRef.current,
1154
- cancel: cancelRef.current
1155
- });
1156
- } catch (err) {
1157
- console.error("[CopilotKit] useInterrupt handler threw; result will be null:", err);
1158
- if (!cancelled) setHandlerResult(null);
1159
- return () => {
1160
- cancelled = true;
1161
- };
1162
- }
1163
- if (isPromiseLike(maybePromise)) Promise.resolve(maybePromise).then((resolved) => {
1164
- if (!cancelled) setHandlerResult(resolved);
1165
- }).catch((err) => {
1166
- console.error("[CopilotKit] useInterrupt handler rejected; result will be null:", err);
1167
- if (!cancelled) setHandlerResult(null);
1168
- });
1169
- else setHandlerResult(maybePromise);
1170
- return () => {
1171
- cancelled = true;
1172
- };
1173
- }, [pending]);
1174
- const element = useMemo(() => {
1175
- if (!pending) return null;
1176
- const legacyEvent = toLegacyEvent(pending);
1177
- if (!isEnabled(legacyEvent)) return null;
1178
- return renderRef.current({
1179
- event: legacyEvent,
1180
- interrupt: pending.kind === "standard" ? pending.interrupts[0] : null,
1181
- interrupts: pending.kind === "standard" ? [...pending.interrupts] : [],
1182
- result: handlerResult,
1183
- resolve,
1184
- cancel
1185
- });
1186
- }, [
1187
- pending,
1188
- handlerResult,
1189
- resolve,
1190
- cancel
1191
- ]);
695
+ controller.connect(agent);
696
+ return () => controller.disconnect();
697
+ }, [controller, agent]);
698
+ const { renderProps } = useSyncExternalStore(controller.subscribe, controller.getSnapshot, controller.getSnapshot);
699
+ const element = useMemo(() => renderProps ? renderRef.current(renderProps) : null, [renderProps]);
1192
700
  useEffect(() => {
1193
701
  if (config.renderInChat === false) return;
1194
702
  copilotkit.setInterruptElement(element);
@@ -1217,210 +725,75 @@ function useSuggestions({ agentId } = {}) {
1217
725
  config?.agentId,
1218
726
  providerAgentId
1219
727
  ]);
1220
- const [suggestions, setSuggestions] = useState(() => {
1221
- return copilotkit.getSuggestions(resolvedAgentId).suggestions;
1222
- });
1223
- const [isLoading, setIsLoading] = useState(() => {
1224
- return copilotkit.getSuggestions(resolvedAgentId).isLoading;
1225
- });
728
+ const [result, setResult] = useState(() => copilotkit.getSuggestions(resolvedAgentId));
1226
729
  useEffect(() => {
1227
- const result = copilotkit.getSuggestions(resolvedAgentId);
1228
- setSuggestions(result.suggestions);
1229
- setIsLoading(result.isLoading);
730
+ setResult(copilotkit.getSuggestions(resolvedAgentId));
731
+ return ɵsubscribeToAgentSuggestions(copilotkit, resolvedAgentId, setResult);
1230
732
  }, [copilotkit, resolvedAgentId]);
1231
- useEffect(() => {
1232
- const subscription = copilotkit.subscribe({
1233
- onSuggestionsChanged: ({ agentId: changedAgentId, suggestions }) => {
1234
- if (changedAgentId !== resolvedAgentId) return;
1235
- setSuggestions(suggestions);
1236
- },
1237
- onSuggestionsStartedLoading: ({ agentId: changedAgentId }) => {
1238
- if (changedAgentId !== resolvedAgentId) return;
1239
- setIsLoading(true);
1240
- },
1241
- onSuggestionsFinishedLoading: ({ agentId: changedAgentId }) => {
1242
- if (changedAgentId !== resolvedAgentId) return;
1243
- setIsLoading(false);
1244
- },
1245
- onSuggestionsConfigChanged: () => {
1246
- const result = copilotkit.getSuggestions(resolvedAgentId);
1247
- setSuggestions(result.suggestions);
1248
- setIsLoading(result.isLoading);
1249
- }
1250
- });
1251
- return () => {
1252
- subscription.unsubscribe();
1253
- };
733
+ const reloadSuggestions = useCallback(() => {
734
+ copilotkit.reloadSuggestions(resolvedAgentId);
735
+ }, [copilotkit, resolvedAgentId]);
736
+ const clearSuggestions = useCallback(() => {
737
+ copilotkit.clearSuggestions(resolvedAgentId);
1254
738
  }, [copilotkit, resolvedAgentId]);
1255
739
  return {
1256
- suggestions,
1257
- reloadSuggestions: useCallback(() => {
1258
- copilotkit.reloadSuggestions(resolvedAgentId);
1259
- }, [copilotkit, resolvedAgentId]),
1260
- clearSuggestions: useCallback(() => {
1261
- copilotkit.clearSuggestions(resolvedAgentId);
1262
- }, [copilotkit, resolvedAgentId]),
1263
- isLoading
740
+ suggestions: result.suggestions,
741
+ reloadSuggestions,
742
+ clearSuggestions,
743
+ isLoading: result.isLoading
1264
744
  };
1265
745
  }
1266
746
 
1267
747
  //#endregion
1268
748
  //#region src/hooks/use-configure-suggestions.tsx
749
+ /**
750
+ * Registers a suggestions configuration (dynamic or static) for the current
751
+ * chat. A global config (no `consumerAgentId`, or `"*"`) applies to every
752
+ * agent and loads for the surrounding chat's agent first.
753
+ *
754
+ * Pass `deps` to reload suggestions when values the config reads change.
755
+ *
756
+ * @example
757
+ * useConfigureSuggestions({
758
+ * instructions: "Suggest concise next steps for the user",
759
+ * available: "always",
760
+ * });
761
+ */
1269
762
  function useConfigureSuggestions(config, deps) {
1270
763
  const { copilotkit } = useCopilotKit$1();
1271
764
  const chatConfig = useCopilotChatConfiguration();
765
+ const providerAgentId = useDefaultAgentId();
766
+ const chatAgentId = chatConfig?.agentId ?? providerAgentId ?? DEFAULT_AGENT_ID;
1272
767
  const extraDeps = deps ?? [];
1273
- const resolvedConsumerAgentId = useMemo(() => chatConfig?.agentId ?? DEFAULT_AGENT_ID, [chatConfig?.agentId]);
1274
- const rawConsumerAgentId = useMemo(() => config ? config.consumerAgentId : void 0, [config]);
1275
- const normalizationCacheRef = useRef({
1276
- serialized: null,
1277
- config: null
768
+ const bindingRef = useRef(null);
769
+ const latestRef = useRef({
770
+ config,
771
+ chatAgentId
1278
772
  });
1279
- const { normalizedConfig, serializedConfig } = useMemo(() => {
1280
- if (!config) {
1281
- normalizationCacheRef.current = {
1282
- serialized: null,
1283
- config: null
1284
- };
1285
- return {
1286
- normalizedConfig: null,
1287
- serializedConfig: null
1288
- };
1289
- }
1290
- if (config.available === "disabled") {
1291
- normalizationCacheRef.current = {
1292
- serialized: null,
1293
- config: null
1294
- };
1295
- return {
1296
- normalizedConfig: null,
1297
- serializedConfig: null
1298
- };
1299
- }
1300
- let built;
1301
- if (isDynamicConfig(config)) built = { ...config };
1302
- else {
1303
- const normalizedSuggestions = normalizeStaticSuggestions(config.suggestions);
1304
- built = {
1305
- ...config,
1306
- suggestions: normalizedSuggestions
1307
- };
1308
- }
1309
- const serialized = JSON.stringify(built);
1310
- const cache = normalizationCacheRef.current;
1311
- if (cache.serialized === serialized && cache.config) return {
1312
- normalizedConfig: cache.config,
1313
- serializedConfig: serialized
1314
- };
1315
- normalizationCacheRef.current = {
1316
- serialized,
1317
- config: built
1318
- };
1319
- return {
1320
- normalizedConfig: built,
1321
- serializedConfig: serialized
1322
- };
1323
- }, [
773
+ latestRef.current = {
1324
774
  config,
1325
- resolvedConsumerAgentId,
1326
- ...extraDeps
1327
- ]);
1328
- const latestConfigRef = useRef(null);
1329
- latestConfigRef.current = normalizedConfig;
1330
- const previousSerializedConfigRef = useRef(null);
1331
- const targetAgentId = useMemo(() => {
1332
- if (!normalizedConfig) return resolvedConsumerAgentId;
1333
- const consumer = normalizedConfig.consumerAgentId;
1334
- if (!consumer || consumer === "*") return resolvedConsumerAgentId;
1335
- return consumer;
1336
- }, [normalizedConfig, resolvedConsumerAgentId]);
1337
- const isGlobalConfig = rawConsumerAgentId === void 0 || rawConsumerAgentId === "*";
1338
- const isDynamicConfigType = useMemo(() => !!normalizedConfig && "instructions" in normalizedConfig, [normalizedConfig]);
1339
- const requestReload = useCallback(() => {
1340
- if (!normalizedConfig) return;
1341
- if (isGlobalConfig) {
1342
- const seen = /* @__PURE__ */ new Set();
1343
- const agents = Object.values(copilotkit.agents ?? {});
1344
- for (const entry of agents) {
1345
- const agentId = entry.agentId;
1346
- if (!agentId) continue;
1347
- seen.add(agentId);
1348
- if (!entry.isRunning) copilotkit.reloadSuggestions(agentId);
1349
- }
1350
- if (targetAgentId && !seen.has(targetAgentId)) copilotkit.reloadSuggestions(targetAgentId);
1351
- return;
1352
- }
1353
- if (!targetAgentId) return;
1354
- copilotkit.reloadSuggestions(targetAgentId);
1355
- }, [
1356
- copilotkit,
1357
- isGlobalConfig,
1358
- normalizedConfig,
1359
- targetAgentId
1360
- ]);
775
+ chatAgentId
776
+ };
1361
777
  useEffect(() => {
1362
- if (!serializedConfig || !latestConfigRef.current) return;
1363
- const id = copilotkit.addSuggestionsConfig(latestConfigRef.current);
1364
- requestReload();
778
+ const latest = latestRef.current;
779
+ const binding = ɵbindSuggestionsConfig(copilotkit, latest.config, { chatAgentId: latest.chatAgentId });
780
+ bindingRef.current = binding;
1365
781
  return () => {
1366
- copilotkit.removeSuggestionsConfig(id);
782
+ binding.dispose();
783
+ if (bindingRef.current === binding) bindingRef.current = null;
1367
784
  };
1368
- }, [
1369
- copilotkit,
1370
- serializedConfig,
1371
- requestReload
1372
- ]);
785
+ }, [copilotkit]);
1373
786
  useEffect(() => {
1374
- if (!normalizedConfig) {
1375
- previousSerializedConfigRef.current = null;
787
+ bindingRef.current?.update(config, { chatAgentId });
788
+ }, [config, chatAgentId]);
789
+ const depsMountedRef = useRef(false);
790
+ useEffect(() => {
791
+ if (!depsMountedRef.current) {
792
+ depsMountedRef.current = true;
1376
793
  return;
1377
794
  }
1378
- if (serializedConfig && previousSerializedConfigRef.current === serializedConfig) return;
1379
- if (serializedConfig) previousSerializedConfigRef.current = serializedConfig;
1380
- requestReload();
1381
- }, [
1382
- normalizedConfig,
1383
- requestReload,
1384
- serializedConfig
1385
- ]);
1386
- useEffect(() => {
1387
- if (!normalizedConfig || extraDeps.length === 0) return;
1388
- requestReload();
1389
- }, [
1390
- extraDeps.length,
1391
- normalizedConfig,
1392
- requestReload,
1393
- ...extraDeps
1394
- ]);
1395
- useEffect(() => {
1396
- if (!normalizedConfig || !isDynamicConfigType) return;
1397
- if (!targetAgentId) return;
1398
- if (!!copilotkit.getAgent(targetAgentId)) return;
1399
- const subscription = copilotkit.subscribe({ onAgentsChanged: () => {
1400
- if (copilotkit.getAgent(targetAgentId)) {
1401
- requestReload();
1402
- subscription.unsubscribe();
1403
- }
1404
- } });
1405
- return () => {
1406
- subscription.unsubscribe();
1407
- };
1408
- }, [
1409
- copilotkit,
1410
- normalizedConfig,
1411
- isDynamicConfigType,
1412
- targetAgentId,
1413
- requestReload
1414
- ]);
1415
- }
1416
- function isDynamicConfig(config) {
1417
- return "instructions" in config;
1418
- }
1419
- function normalizeStaticSuggestions(suggestions) {
1420
- return suggestions.map((suggestion) => ({
1421
- ...suggestion,
1422
- isLoading: suggestion.isLoading ?? false
1423
- }));
795
+ if (extraDeps.length > 0) bindingRef.current?.reload();
796
+ }, [extraDeps.length, ...extraDeps]);
1424
797
  }
1425
798
 
1426
799
  //#endregion
@@ -1428,10 +801,7 @@ function normalizeStaticSuggestions(suggestions) {
1428
801
  function useAgentContext(context) {
1429
802
  const { description, value } = context;
1430
803
  const { copilotkit } = useCopilotKit$1();
1431
- const stringValue = useMemo(() => {
1432
- if (typeof value === "string") return value;
1433
- return JSON.stringify(value);
1434
- }, [value]);
804
+ const stringValue = useMemo(() => ɵserializeContextValue(value), [value]);
1435
805
  useLayoutEffect(() => {
1436
806
  if (!copilotkit) return;
1437
807
  const id = copilotkit.addContext({
@@ -1450,12 +820,6 @@ function useAgentContext(context) {
1450
820
 
1451
821
  //#endregion
1452
822
  //#region src/hooks/use-threads.tsx
1453
- function useThreadStoreSelector(store, selector) {
1454
- return useSyncExternalStore(useCallback((onStoreChange) => {
1455
- const subscription = store.select(selector).subscribe(onStoreChange);
1456
- return () => subscription.unsubscribe();
1457
- }, [store, selector]), () => selector(store.getState()), () => selector(store.getServerState()));
1458
- }
1459
823
  /**
1460
824
  * React hook for listing and managing CopilotKit Intelligence threads.
1461
825
  *
@@ -1499,117 +863,38 @@ function useThreadStoreSelector(store, selector) {
1499
863
  */
1500
864
  function useThreads({ agentId, includeArchived, limit, enabled = true }) {
1501
865
  const { copilotkit } = useCopilotKit$1();
1502
- const [store] = useState(() => ɵcreateThreadStore({ fetch: copilotkit.ɵruntimeFetch }));
1503
- const coreThreads = useThreadStoreSelector(store, ɵselectThreads);
1504
- const threads = useMemo(() => coreThreads.map(({ id, agentId, name, archived, createdAt, updatedAt, lastRunAt }) => ({
1505
- id,
1506
- agentId,
1507
- name,
1508
- archived,
1509
- createdAt,
1510
- updatedAt,
1511
- ...lastRunAt !== void 0 ? { lastRunAt } : {}
1512
- })), [coreThreads]);
1513
- const storeIsLoading = useThreadStoreSelector(store, ɵselectThreadsIsLoading);
1514
- const storeError = useThreadStoreSelector(store, ɵselectThreadsError);
1515
- const fetchMoreError = useThreadStoreSelector(store, ɵselectFetchMoreError);
1516
- const hasMoreThreads = useThreadStoreSelector(store, ɵselectHasNextPage);
1517
- const isFetchingMoreThreads = useThreadStoreSelector(store, ɵselectIsFetchingNextPage);
1518
- const isMutating = useThreadStoreSelector(store, ɵselectIsMutating);
1519
- const headersKey = copilotkit.ɵheadersGeneration;
1520
- const runtimeStatus = copilotkit.runtimeConnectionStatus;
1521
- const threadListEndpointSupported = copilotkit.threadEndpoints?.list !== false;
1522
- const threadMutationsSupported = copilotkit.threadEndpoints?.mutations !== false;
1523
- const threadEndpointsUnavailable = !!copilotkit.runtimeUrl && runtimeStatus === CopilotKitCoreRuntimeConnectionStatus.Connected && !threadListEndpointSupported;
1524
- const runtimeError = useMemo(() => {
1525
- if (copilotkit.runtimeUrl) return null;
1526
- return /* @__PURE__ */ new Error("Runtime URL is not configured");
1527
- }, [copilotkit.runtimeUrl]);
1528
- const threadEndpointsError = useMemo(() => {
1529
- if (!threadEndpointsUnavailable) return null;
1530
- return /* @__PURE__ */ new Error("Thread endpoints are not available on this CopilotKit runtime");
1531
- }, [threadEndpointsUnavailable]);
1532
- const threadMutationsError = useMemo(() => {
1533
- if (threadMutationsSupported) return null;
1534
- return /* @__PURE__ */ new Error("Thread mutations are not available on this CopilotKit runtime");
1535
- }, [threadMutationsSupported]);
1536
- const [hasDispatchedContext, setHasDispatchedContext] = useState(false);
1537
- const preConnectLoading = enabled && !!copilotkit.runtimeUrl && !threadEndpointsUnavailable && !hasDispatchedContext;
1538
- const [configErrorDismissed, setConfigErrorDismissed] = useState(false);
1539
- useEffect(() => {
1540
- setConfigErrorDismissed(false);
1541
- }, [runtimeError, threadEndpointsError]);
1542
- const activeRuntimeError = configErrorDismissed ? null : runtimeError;
1543
- const activeThreadEndpointsError = configErrorDismissed ? null : threadEndpointsError;
1544
- const isLoading = activeRuntimeError || activeThreadEndpointsError ? false : preConnectLoading || storeIsLoading;
1545
- const error = activeRuntimeError ?? activeThreadEndpointsError ?? storeError;
1546
- const listError = storeError;
1547
- useEffect(() => {
1548
- store.start();
1549
- return () => {
1550
- store.stop();
1551
- };
1552
- }, [store]);
1553
- useEffect(() => {
1554
- if (!enabled) return;
1555
- copilotkit.registerThreadStore(agentId, store);
1556
- return () => {
1557
- copilotkit.unregisterThreadStore(agentId);
1558
- };
1559
- }, [
1560
- copilotkit,
866
+ const [controller] = useState(() => new ɵThreadsController(ɵcreateThreadStore({ fetch: copilotkit.ɵruntimeFetch }), {
867
+ core: copilotkit,
1561
868
  agentId,
1562
- store,
869
+ includeArchived,
870
+ limit,
1563
871
  enabled
1564
- ]);
872
+ }));
873
+ const { threads, isLoading, error, listError, fetchMoreError, hasMoreThreads, isFetchingMoreThreads, isMutating } = useSyncExternalStore(controller.subscribe, controller.getSnapshot, controller.getServerSnapshot);
874
+ useEffect(() => controller.start(), [controller]);
1565
875
  useEffect(() => {
1566
- if (!enabled) {
1567
- store.setContext(null);
1568
- setHasDispatchedContext(false);
1569
- return;
1570
- }
1571
- if (!copilotkit.runtimeUrl) {
1572
- store.setContext(null);
1573
- setHasDispatchedContext(false);
1574
- return;
1575
- }
1576
- if (runtimeStatus !== CopilotKitCoreRuntimeConnectionStatus.Connected) return;
1577
- if (!threadListEndpointSupported) {
1578
- store.setContext(null);
1579
- setHasDispatchedContext(false);
1580
- return;
1581
- }
1582
- const context = {
1583
- runtimeUrl: copilotkit.runtimeUrl,
1584
- wsUrl: copilotkit.intelligence?.wsUrl,
876
+ controller.update({
877
+ core: copilotkit,
1585
878
  agentId,
1586
879
  includeArchived,
1587
- limit
1588
- };
1589
- store.setContext(context);
1590
- setHasDispatchedContext(true);
880
+ limit,
881
+ enabled
882
+ });
1591
883
  }, [
1592
- store,
884
+ controller,
885
+ copilotkit,
886
+ agentId,
887
+ includeArchived,
888
+ limit,
1593
889
  enabled,
1594
890
  copilotkit.runtimeUrl,
1595
- runtimeStatus,
1596
- headersKey,
891
+ copilotkit.runtimeConnectionStatus,
892
+ copilotkit.ɵheadersGeneration,
1597
893
  copilotkit.intelligence?.wsUrl,
1598
- threadListEndpointSupported,
1599
- agentId,
1600
- includeArchived,
1601
- limit
894
+ copilotkit.threadEndpoints?.list,
895
+ copilotkit.threadEndpoints?.mutations
1602
896
  ]);
1603
- const guardMutation = useCallback((mutation) => {
1604
- return (...args) => {
1605
- if (threadMutationsError) return Promise.reject(threadMutationsError);
1606
- return mutation(...args);
1607
- };
1608
- }, [threadMutationsError]);
1609
- const renameThread = useMemo(() => guardMutation((threadId, name) => store.renameThread(threadId, name)), [store, guardMutation]);
1610
- const archiveThread = useMemo(() => guardMutation((threadId) => store.archiveThread(threadId)), [store, guardMutation]);
1611
- const unarchiveThread = useMemo(() => guardMutation((threadId) => store.unarchiveThread(threadId)), [store, guardMutation]);
1612
- const deleteThread = useMemo(() => guardMutation((threadId) => store.deleteThread(threadId)), [store, guardMutation]);
897
+ const { fetchMoreThreads, refetchThreads, startNewThread, renameThread, archiveThread, unarchiveThread, deleteThread } = controller;
1613
898
  return {
1614
899
  threads,
1615
900
  isLoading,
@@ -1619,12 +904,9 @@ function useThreads({ agentId, includeArchived, limit, enabled = true }) {
1619
904
  hasMoreThreads,
1620
905
  isFetchingMoreThreads,
1621
906
  isMutating,
1622
- fetchMoreThreads: useCallback(() => store.fetchNextPage(), [store]),
1623
- refetchThreads: useCallback(() => store.refetchThreads(), [store]),
1624
- startNewThread: useCallback(() => {
1625
- setConfigErrorDismissed(true);
1626
- store.startNewThread();
1627
- }, [store]),
907
+ fetchMoreThreads,
908
+ refetchThreads,
909
+ startNewThread,
1628
910
  renameThread,
1629
911
  archiveThread,
1630
912
  unarchiveThread,
@@ -1635,7 +917,7 @@ function useThreads({ agentId, includeArchived, limit, enabled = true }) {
1635
917
  //#endregion
1636
918
  //#region src/types/defineToolCallRenderer.ts
1637
919
  function defineToolCallRenderer(def) {
1638
- const argsSchema = def.name === "*" && !def.args ? z.any() : def.args;
920
+ const argsSchema = def.name === "*" && !def.args ? ɵanySchema : def.args;
1639
921
  return {
1640
922
  name: def.name,
1641
923
  args: argsSchema,
@@ -1737,29 +1019,11 @@ function useRenderTool(config, deps) {
1737
1019
  * but the tool call data hasn't changed.
1738
1020
  */
1739
1021
  const ToolCallRenderer = React.memo(function ToolCallRenderer({ toolCall, toolMessage, RenderComponent, isExecuting }) {
1740
- const args = useMemo(() => partialJSONParse(toolCall.function.arguments), [toolCall.function.arguments]);
1741
- const toolName = toolCall.function.name;
1742
- if (toolMessage) return /* @__PURE__ */ jsx(RenderComponent, {
1743
- name: toolName,
1744
- toolCallId: toolCall.id,
1745
- args,
1746
- status: ToolCallStatus.Complete,
1747
- result: contentToText(toolMessage.content)
1748
- });
1749
- else if (isExecuting) return /* @__PURE__ */ jsx(RenderComponent, {
1750
- name: toolName,
1751
- toolCallId: toolCall.id,
1752
- args,
1753
- status: ToolCallStatus.Executing,
1754
- result: void 0
1755
- });
1756
- else return /* @__PURE__ */ jsx(RenderComponent, {
1757
- name: toolName,
1758
- toolCallId: toolCall.id,
1759
- args,
1760
- status: ToolCallStatus.InProgress,
1761
- result: void 0
1762
- });
1022
+ return /* @__PURE__ */ jsx(RenderComponent, { ...useMemo(() => ɵbuildToolCallRenderProps(toolCall, toolMessage, { isExecuting }), [
1023
+ toolCall,
1024
+ toolMessage,
1025
+ isExecuting
1026
+ ]) });
1763
1027
  }, (prevProps, nextProps) => {
1764
1028
  if (prevProps.toolCall.id !== nextProps.toolCall.id) return false;
1765
1029
  if (prevProps.toolCall.function.name !== nextProps.toolCall.function.name) return false;
@@ -1771,25 +1035,21 @@ const ToolCallRenderer = React.memo(function ToolCallRenderer({ toolCall, toolMe
1771
1035
  });
1772
1036
  const IS_DEVELOPMENT = process.env.NODE_ENV !== "production";
1773
1037
  /**
1774
- * Reports tool calls that resolved to no renderer.
1038
+ * Reports tool calls that resolved to no renderer, once per tool name.
1775
1039
  *
1776
1040
  * A tool call with no renderer paints an empty message container and says
1777
1041
  * nothing else, so the only signal a developer gets today is a blank space in
1778
- * the chat. This names the call and the renderers that *are* registered, which
1779
- * is the whole diagnosis when the cause is a name that does not match.
1042
+ * the chat.
1780
1043
  *
1781
1044
  * @param toolNames - The unmatched tool names collected during render.
1782
1045
  * @param registered - The registry as it stands now, re-read at report time.
1783
1046
  * @param alreadyWarned - Names already reported, mutated to keep this once per name.
1784
1047
  */
1785
1048
  function warnAboutUnrenderedToolCalls(toolNames, registered, alreadyWarned) {
1786
- const registeredNames = Array.from(new Set(registered.map((rc) => rc.name)));
1787
- const hasWildcard = registeredNames.includes("*");
1788
- for (const toolName of toolNames) {
1789
- if (hasWildcard || registeredNames.includes(toolName)) continue;
1790
- if (alreadyWarned.has(toolName)) continue;
1049
+ const warnings = ɵdescribeUnrenderedToolCalls(toolNames.filter((name) => !alreadyWarned.has(name)), registered);
1050
+ for (const { toolName, message } of warnings) {
1791
1051
  alreadyWarned.add(toolName);
1792
- 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.`);
1052
+ console.warn(message);
1793
1053
  }
1794
1054
  }
1795
1055
  /**
@@ -1808,23 +1068,22 @@ function useToolCallRenderers() {
1808
1068
  */
1809
1069
  function useRenderToolCall() {
1810
1070
  const { copilotkit, executingToolCallIds } = useCopilotKit$1();
1811
- const agentId = useCopilotChatConfiguration()?.agentId ?? DEFAULT_AGENT_ID;
1071
+ const agentId = ɵresolveToolCallAgentId(useCopilotChatConfiguration()?.agentId, void 0);
1812
1072
  const unrenderedToolNames = useRef(/* @__PURE__ */ new Set());
1813
1073
  const warnedToolNames = useRef(/* @__PURE__ */ new Set());
1814
1074
  const renderToolCalls = useToolCallRenderers();
1815
1075
  const renderToolCall = useCallback(({ toolCall, toolMessage }) => {
1816
- const exactMatches = renderToolCalls.filter((rc) => rc.name === toolCall.function.name);
1817
- const renderConfig = exactMatches.find((rc) => rc.agentId === agentId) || exactMatches.find((rc) => !rc.agentId) || exactMatches[0] || renderToolCalls.find((rc) => rc.name === "*");
1076
+ const renderConfig = ɵresolveToolCallRenderer(renderToolCalls, toolCall.function.name, agentId);
1818
1077
  if (!renderConfig) {
1819
1078
  if (IS_DEVELOPMENT) unrenderedToolNames.current.add(toolCall.function.name);
1820
1079
  return null;
1821
1080
  }
1822
- const RenderComponent = renderConfig.render;
1081
+ const isExecuting = executingToolCallIds.has(toolCall.id);
1823
1082
  return /* @__PURE__ */ jsx(ToolCallRenderer, {
1824
1083
  toolCall,
1825
1084
  toolMessage,
1826
- RenderComponent,
1827
- isExecuting: executingToolCallIds.has(toolCall.id)
1085
+ RenderComponent: renderConfig.render,
1086
+ isExecuting
1828
1087
  }, toolCall.id);
1829
1088
  }, [
1830
1089
  renderToolCalls,
@@ -1861,9 +1120,9 @@ function useRenderToolCall() {
1861
1120
  */
1862
1121
  function useCapabilities(agentId) {
1863
1122
  const { agent } = useAgent({ agentId });
1864
- if (agent && "capabilities" in agent) return agent.capabilities;
1123
+ return ɵgetAgentCapabilities(agent);
1865
1124
  }
1866
1125
 
1867
1126
  //#endregion
1868
- export { CopilotChatConfigurationProvider, CopilotChatDefaultLabels, CopilotKitCoreReact, UseAgentUpdate, defineToolCallRenderer, useAgent, useAgentContext, useCapabilities, useComponent, useConfigureSuggestions, useCopilotChatConfiguration, useCopilotKit, useFrontendTool, useFrontendTools, useHumanInTheLoop, useInterrupt, useRenderTool, useRenderToolCall, useSuggestions, useThreads };
1127
+ export { CopilotChatConfigurationProvider, CopilotChatDefaultLabels, CopilotKitCoreReact, UseAgentUpdate, defineToolCallRenderer, useAgent, useAgentContext, useCapabilities, useComponent, useConfigureSuggestions, useCopilotChatConfiguration, useCopilotKit, useFrontendTool, useFrontendTools, useHumanInTheLoop, useInterrupt, useRenderTool, useRenderToolCall, useSuggestions, useThreads, ɵuseOwnedCore };
1869
1128
  //# sourceMappingURL=headless.mjs.map