@copilotkit/react-core 2.0.0-rc.20 → 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.
package/dist/headless.mjs CHANGED
@@ -1,11 +1,58 @@
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, ɵanySchema } from "@copilotkit/shared";
4
- import { CopilotChatDefaultLabels, CopilotChatDefaultLabels as CopilotChatDefaultLabels$1, CopilotKitCoreRuntimeConnectionStatus, INTERRUPT_EVENT_NAME, ProxiedCopilotRuntimeAgent, ToolCallStatus, ɵInterruptState, ɵclearAgentInterruptState, ɵcreateThreadStore, ɵgetAgentInterruptState, ɵisHttpAgent, ɵresolveToolCallRenderer, ɵselectFetchMoreError, ɵselectHasNextPage, ɵselectIsFetchingNextPage, ɵselectIsMutating, ɵselectThreads, ɵselectThreadsError, ɵselectThreadsIsLoading, ɵshallowEqualRecord } from "@copilotkit/core";
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";
5
4
  import { Fragment, jsx } from "react/jsx-runtime";
6
- import { randomUUID as randomUUID$1 } from "@ag-ui/client";
7
- import { contentToText } from "@ag-ui/core";
5
+ import { DEFAULT_AGENT_ID, ɵanySchema } from "@copilotkit/shared";
8
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
9
56
  //#region src/lib/shallow-stable-ref.ts
10
57
  /**
11
58
  * Shallow equality comparison for objects: same own keys, each holding the
@@ -46,25 +93,6 @@ function useShallowStableRef(value) {
46
93
 
47
94
  //#endregion
48
95
  //#region src/providers/CopilotChatConfigurationProvider.tsx
49
- /**
50
- * Mobile breakpoint below which the chat modal and the thread-list drawer are
51
- * mutually exclusive. At or above this width both surfaces may coexist. This
52
- * mirrors the `(max-width: 767px)` / `(min-width: 768px)` split already used by
53
- * CopilotChatInput and CopilotSidebarView.
54
- */
55
- const MOBILE_MAX_WIDTH_PX = 767;
56
- /**
57
- * Reports whether the current viewport is in the mobile range (`<768px`), where
58
- * the chat modal and drawer must not be open simultaneously. SSR-safe and
59
- * defensive against environments without `matchMedia` (treated as desktop, so
60
- * no mutual-exclusion constraint is applied).
61
- *
62
- * @returns `true` when the viewport is mobile-width, `false` otherwise.
63
- */
64
- function isMobileViewport() {
65
- if (typeof window === "undefined" || typeof window.matchMedia !== "function") return false;
66
- return window.matchMedia(`(max-width: ${MOBILE_MAX_WIDTH_PX}px)`).matches;
67
- }
68
96
  const CopilotChatConfiguration = createContext(null);
69
97
  const CopilotChatConfigurationProvider = ({ children, labels, agentId, threadId, hasExplicitThreadId, isModalDefaultOpen }) => {
70
98
  const parentConfig = useContext(CopilotChatConfiguration);
@@ -75,167 +103,67 @@ const CopilotChatConfigurationProvider = ({ children, labels, agentId, threadId,
75
103
  ...stableLabels
76
104
  }), [stableLabels, parentConfig?.labels]);
77
105
  const providerAgentId = useDefaultAgentId();
78
- const resolvedAgentId = agentId ?? parentConfig?.agentId ?? providerAgentId ?? DEFAULT_AGENT_ID;
79
- const threadIdPropIsAuthoritative = threadId !== void 0 && hasExplicitThreadId !== false;
80
- const isThreadIdControlled = threadIdPropIsAuthoritative;
81
- const [activeThreadOverride, setActiveThreadOverride] = useState(null);
82
- const resolvedThreadId = useMemo(() => {
83
- if (threadIdPropIsAuthoritative) return threadId;
84
- if (activeThreadOverride) return activeThreadOverride.threadId;
85
- if (parentConfig?.threadId) return parentConfig.threadId;
86
- if (threadId) return threadId;
87
- 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
+ });
88
125
  }, [
89
- threadIdPropIsAuthoritative,
126
+ store,
127
+ agentId,
90
128
  threadId,
91
- parentConfig?.threadId,
92
- activeThreadOverride
129
+ hasExplicitThreadId,
130
+ isModalDefaultOpen,
131
+ providerAgentId
93
132
  ]);
94
133
  const copilotkit = useContext(CopilotKitContext)?.copilotkit;
95
- const openThreadRef = useRef(null);
96
- const latestThreadIdRef = useRef(resolvedThreadId);
97
- latestThreadIdRef.current = resolvedThreadId;
98
134
  useEffect(() => {
99
135
  if (copilotkit === void 0) return;
100
- const registration = copilotkit.registerOpenThread({
101
- agentId: resolvedAgentId,
102
- threadId: latestThreadIdRef.current
103
- });
104
- openThreadRef.current = registration;
105
- return () => {
106
- registration.unregister();
107
- openThreadRef.current = null;
108
- };
109
- }, [copilotkit, resolvedAgentId]);
110
- useEffect(() => {
111
- openThreadRef.current?.update(resolvedThreadId);
112
- }, [resolvedThreadId]);
113
- const resolvedHasExplicitThreadId = (threadIdPropIsAuthoritative ? true : activeThreadOverride?.explicit ?? hasExplicitThreadId ?? false) || !!parentConfig?.hasExplicitThreadId;
114
- const [internalModalOpen, setInternalModalOpen] = useState(isModalDefaultOpen ?? true);
115
- const hasExplicitDefault = isModalDefaultOpen !== void 0;
116
- const setAndSync = useCallback((open) => {
117
- setInternalModalOpen(open);
118
- parentConfig?.setModalOpen(open);
119
- }, [parentConfig?.setModalOpen]);
120
- const isMounted = useRef(false);
121
- useEffect(() => {
122
- if (!hasExplicitDefault) return;
123
- if (!isMounted.current) {
124
- isMounted.current = true;
125
- return;
126
- }
127
- if (parentConfig?.isModalOpen === void 0) return;
128
- setInternalModalOpen(parentConfig.isModalOpen);
129
- }, [parentConfig?.isModalOpen, hasExplicitDefault]);
130
- const resolvedIsModalOpen = hasExplicitDefault ? internalModalOpen : parentConfig?.isModalOpen ?? internalModalOpen;
131
- const resolvedSetModalOpen = hasExplicitDefault ? setAndSync : parentConfig?.setModalOpen ?? setInternalModalOpen;
132
- const [ownDrawerOpen, setOwnDrawerOpen] = useState(false);
133
- const [ownDrawerCount, setOwnDrawerCount] = useState(0);
134
- const modalCloseRef = useRef(() => {});
135
- modalCloseRef.current = resolvedSetModalOpen;
136
- const registeredModalClosersRef = useRef([]);
137
- const ownRegisterModalCloser = useCallback((closeModal) => {
138
- registeredModalClosersRef.current.push(closeModal);
139
- return () => {
140
- registeredModalClosersRef.current = registeredModalClosersRef.current.filter((entry) => entry !== closeModal);
141
- };
142
- }, []);
143
- const ownSetDrawerOpen = useCallback((open) => {
144
- setOwnDrawerOpen(open);
145
- if (open && isMobileViewport()) {
146
- const registered = registeredModalClosersRef.current;
147
- (registered.length > 0 ? registered[registered.length - 1] : modalCloseRef.current)(false);
148
- }
149
- }, []);
150
- const ownRegisterDrawer = useCallback(() => {
151
- setOwnDrawerCount((count) => count + 1);
152
- return () => {
153
- setOwnDrawerCount((count) => Math.max(0, count - 1));
154
- };
155
- }, []);
156
- const resolvedDrawerOpen = parentConfig ? parentConfig.drawerOpen : ownDrawerOpen;
157
- const resolvedSetDrawerOpen = parentConfig ? parentConfig.setDrawerOpen : ownSetDrawerOpen;
158
- const resolvedDrawerRegistered = parentConfig ? parentConfig.drawerRegistered : ownDrawerCount > 0;
159
- const resolvedRegisterDrawer = parentConfig ? parentConfig.registerDrawer : ownRegisterDrawer;
160
- const resolvedRegisterModalCloser = parentConfig ? parentConfig.ɵregisterModalCloser : ownRegisterModalCloser;
161
- useEffect(() => {
162
- if (!hasExplicitDefault) return;
163
- return resolvedRegisterModalCloser(resolvedSetModalOpen);
164
- }, [
165
- hasExplicitDefault,
166
- resolvedRegisterModalCloser,
167
- resolvedSetModalOpen
168
- ]);
169
- const isThreadIdControlledRef = useRef(isThreadIdControlled);
170
- isThreadIdControlledRef.current = isThreadIdControlled;
171
- const ownSetActiveThreadId = useCallback((id, options) => {
172
- setActiveThreadOverride({
173
- threadId: id,
174
- explicit: options?.explicit ?? true
175
- });
176
- }, []);
177
- const ownStartNewThread = useCallback(() => {
178
- setActiveThreadOverride({
179
- threadId: randomUUID(),
180
- explicit: false
181
- });
182
- }, []);
183
- const parentSetActiveThreadId = parentConfig?.setActiveThreadId;
184
- const parentStartNewThread = parentConfig?.startNewThread;
185
- const resolvedSetActiveThreadId = useCallback((id, options) => {
186
- if (isThreadIdControlledRef.current) {
187
- console.warn("[CopilotKit] Ignoring setActiveThreadId(): threadId is controlled via the `threadId` prop on CopilotChatConfigurationProvider.");
188
- return;
189
- }
190
- if (parentSetActiveThreadId) {
191
- parentSetActiveThreadId(id, options);
192
- return;
193
- }
194
- ownSetActiveThreadId(id, options);
195
- }, [parentSetActiveThreadId, ownSetActiveThreadId]);
196
- const resolvedStartNewThread = useCallback(() => {
197
- if (isThreadIdControlledRef.current) {
198
- console.warn("[CopilotKit] Ignoring startNewThread(): threadId is controlled via the `threadId` prop on CopilotChatConfigurationProvider.");
199
- return;
200
- }
201
- if (parentStartNewThread) {
202
- parentStartNewThread();
203
- return;
204
- }
205
- ownStartNewThread();
206
- }, [parentStartNewThread, ownStartNewThread]);
207
- const setModalOpenWithDrawerExclusion = useCallback((open) => {
208
- if (open && isMobileViewport()) resolvedSetDrawerOpen(false);
209
- resolvedSetModalOpen(open);
210
- }, [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;
211
142
  const configurationValue = useMemo(() => ({
212
143
  labels: mergedLabels,
213
144
  agentId: resolvedAgentId,
214
145
  threadId: resolvedThreadId,
215
146
  hasExplicitThreadId: resolvedHasExplicitThreadId,
216
- isModalOpen: resolvedIsModalOpen,
217
- setModalOpen: setModalOpenWithDrawerExclusion,
218
- drawerOpen: resolvedDrawerOpen,
219
- setDrawerOpen: resolvedSetDrawerOpen,
220
- drawerRegistered: resolvedDrawerRegistered,
221
- registerDrawer: resolvedRegisterDrawer,
222
- ɵregisterModalCloser: resolvedRegisterModalCloser,
223
- setActiveThreadId: resolvedSetActiveThreadId,
224
- 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
225
157
  }), [
226
158
  mergedLabels,
227
159
  resolvedAgentId,
228
160
  resolvedThreadId,
229
161
  resolvedHasExplicitThreadId,
230
- resolvedIsModalOpen,
231
- setModalOpenWithDrawerExclusion,
232
- resolvedDrawerOpen,
233
- resolvedSetDrawerOpen,
234
- resolvedDrawerRegistered,
235
- resolvedRegisterDrawer,
236
- resolvedRegisterModalCloser,
237
- resolvedSetActiveThreadId,
238
- resolvedStartNewThread
162
+ isModalOpen,
163
+ setModalOpen,
164
+ drawerOpen,
165
+ drawerRegistered,
166
+ store
239
167
  ]);
240
168
  return /* @__PURE__ */ jsx(CopilotChatConfiguration.Provider, {
241
169
  value: configurationValue,
@@ -316,163 +244,57 @@ const ALL_UPDATES = [
316
244
  UseAgentUpdate.OnRunStatusChanged
317
245
  ];
318
246
  function useAgent({ agentId, threadId, runtimeAgentId, updates, throttleMs } = {}) {
319
- 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 }).`);
320
- 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}" }).`);
321
- 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
+ });
322
252
  const chatConfig = useCopilotChatConfiguration();
323
253
  const providerAgentId = useDefaultAgentId();
324
- const resolvedAgentId = agentId ?? chatConfig?.agentId ?? providerAgentId ?? DEFAULT_AGENT_ID;
254
+ const resolvedAgentId = ɵresolveAgentId({
255
+ agentId,
256
+ chatAgentId: chatConfig?.agentId,
257
+ providerAgentId
258
+ });
325
259
  const { copilotkit } = useCopilotKit$1();
260
+ const resolver = ɵgetAgentResolver(copilotkit);
261
+ const revision = useSyncExternalStore(resolver.subscribe, resolver.getSnapshot, resolver.getSnapshot);
326
262
  const providerThrottleMs = copilotkit.defaultThrottleMs;
327
263
  const [, forceUpdate] = useReducer((x) => x + 1, 0);
328
264
  const updateFlags = useMemo(() => updates ?? ALL_UPDATES, [JSON.stringify(updates)]);
329
- const provisionalAgentCache = useRef(/* @__PURE__ */ new Map());
330
- const [registeredProxyAgent, setRegisteredProxyAgent] = useState(null);
331
265
  useEffect(() => {
332
- if (runtimeAgentId == null) {
333
- setRegisteredProxyAgent(null);
334
- return;
335
- }
336
- const { agent: proxy, unregister } = copilotkit.registerProxiedAgent({
266
+ if (runtimeAgentId == null) return;
267
+ return resolver.bindProxy({
337
268
  agentId: resolvedAgentId,
338
269
  runtimeAgentId
339
270
  });
340
- provisionalAgentCache.current.delete(resolvedAgentId);
341
- setRegisteredProxyAgent(proxy);
342
- return () => {
343
- unregister();
344
- setRegisteredProxyAgent(null);
345
- };
346
271
  }, [
347
- copilotkit,
272
+ resolver,
348
273
  resolvedAgentId,
349
274
  runtimeAgentId
350
275
  ]);
351
- const { agent, isReady } = useMemo(() => {
352
- if (runtimeAgentId != null) {
353
- if (registeredProxyAgent) {
354
- provisionalAgentCache.current.delete(resolvedAgentId);
355
- return {
356
- agent: registeredProxyAgent,
357
- isReady: true
358
- };
359
- }
360
- const cached = provisionalAgentCache.current.get(resolvedAgentId);
361
- if (cached) {
362
- copilotkit.applyHeadersToAgent(cached);
363
- return {
364
- agent: cached,
365
- isReady: false
366
- };
367
- }
368
- const provisional = new ProxiedCopilotRuntimeAgent({
369
- runtimeUrl: copilotkit.runtimeUrl,
370
- agentId: resolvedAgentId,
371
- runtimeAgentId,
372
- transport: copilotkit.runtimeTransport,
373
- runtimeMode: "pending"
374
- });
375
- copilotkit.applyHeadersToAgent(provisional);
376
- provisionalAgentCache.current.set(resolvedAgentId, provisional);
377
- return {
378
- agent: provisional,
379
- isReady: false
380
- };
381
- }
382
- const existing = copilotkit.getAgent(resolvedAgentId);
383
- if (existing) {
384
- provisionalAgentCache.current.delete(resolvedAgentId);
385
- return {
386
- agent: existing,
387
- isReady: true
388
- };
389
- }
390
- const isRuntimeConfigured = copilotkit.runtimeUrl !== void 0;
391
- const status = copilotkit.runtimeConnectionStatus;
392
- if (isRuntimeConfigured && (status === CopilotKitCoreRuntimeConnectionStatus.Disconnected || status === CopilotKitCoreRuntimeConnectionStatus.Connecting)) {
393
- const cached = provisionalAgentCache.current.get(resolvedAgentId);
394
- if (cached) return {
395
- agent: cached,
396
- isReady: false
397
- };
398
- const provisional = new ProxiedCopilotRuntimeAgent({
399
- runtimeUrl: copilotkit.runtimeUrl,
400
- agentId: resolvedAgentId,
401
- transport: copilotkit.runtimeTransport,
402
- credentials: copilotkit.credentials,
403
- runtimeMode: "pending"
404
- });
405
- copilotkit.applyHeadersToAgent(provisional);
406
- provisionalAgentCache.current.set(resolvedAgentId, provisional);
407
- return {
408
- agent: provisional,
409
- isReady: false
410
- };
411
- }
412
- if (isRuntimeConfigured && status === CopilotKitCoreRuntimeConnectionStatus.Error) {
413
- const cached = provisionalAgentCache.current.get(resolvedAgentId);
414
- if (cached) return {
415
- agent: cached,
416
- isReady: false
417
- };
418
- const provisional = new ProxiedCopilotRuntimeAgent({
419
- runtimeUrl: copilotkit.runtimeUrl,
420
- agentId: resolvedAgentId,
421
- transport: copilotkit.runtimeTransport,
422
- credentials: copilotkit.credentials,
423
- runtimeMode: "pending"
424
- });
425
- copilotkit.applyHeadersToAgent(provisional);
426
- provisionalAgentCache.current.set(resolvedAgentId, provisional);
427
- return {
428
- agent: provisional,
429
- isReady: false
430
- };
431
- }
432
- const knownAgents = Object.keys(copilotkit.agents ?? {});
433
- const runtimePart = isRuntimeConfigured ? `runtimeUrl=${copilotkit.runtimeUrl}` : "no runtimeUrl";
434
- 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.");
435
- }, [
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,
436
284
  resolvedAgentId,
437
285
  runtimeAgentId,
438
- registeredProxyAgent,
439
286
  copilotkit.agents,
440
287
  copilotkit.runtimeConnectionStatus,
441
288
  copilotkit.runtimeUrl,
442
289
  copilotkit.runtimeTransport,
443
290
  copilotkit.credentials,
444
- JSON.stringify(copilotkit.headers)
291
+ headersGeneration
445
292
  ]);
446
- useEffect(() => {
447
- if (updateFlags.length === 0) return;
448
- let active = true;
449
- const handlers = {};
450
- let batchScheduled = false;
451
- const batchedForceUpdate = () => {
452
- if (!active) return;
453
- if (!batchScheduled) {
454
- batchScheduled = true;
455
- queueMicrotask(() => {
456
- batchScheduled = false;
457
- if (active) forceUpdate();
458
- });
459
- }
460
- };
461
- if (updateFlags.includes(UseAgentUpdate.OnMessagesChanged)) handlers.onMessagesChanged = batchedForceUpdate;
462
- if (updateFlags.includes(UseAgentUpdate.OnStateChanged)) handlers.onStateChanged = batchedForceUpdate;
463
- if (updateFlags.includes(UseAgentUpdate.OnRunStatusChanged)) {
464
- handlers.onRunInitialized = batchedForceUpdate;
465
- handlers.onRunStartedEvent = batchedForceUpdate;
466
- handlers.onRunFinalized = batchedForceUpdate;
467
- handlers.onRunFailed = batchedForceUpdate;
468
- handlers.onRunErrorEvent = batchedForceUpdate;
469
- }
470
- const subscription = copilotkit.subscribeToAgentWithOptions(agent, handlers, { throttleMs });
471
- return () => {
472
- active = false;
473
- subscription.unsubscribe();
474
- };
475
- }, [
293
+ useEffect(() => ɵsubscribeToAgentUpdates(copilotkit, agent, {
294
+ updates: updateFlags,
295
+ throttleMs,
296
+ onUpdate: forceUpdate
297
+ }), [
476
298
  agent,
477
299
  forceUpdate,
478
300
  throttleMs,
@@ -480,16 +302,18 @@ function useAgent({ agentId, threadId, runtimeAgentId, updates, throttleMs } = {
480
302
  updateFlags
481
303
  ]);
482
304
  useEffect(() => {
483
- if (ɵisHttpAgent(agent)) copilotkit.applyHeadersToAgent(agent);
484
- if (agent instanceof ProxiedCopilotRuntimeAgent) agent.credentials = copilotkit.credentials;
305
+ resolver.refreshRequestSettings(agent);
485
306
  }, [
307
+ resolver,
486
308
  agent,
487
- JSON.stringify(copilotkit.headers),
309
+ headersGeneration,
488
310
  copilotkit.credentials
489
311
  ]);
490
- const configThreadId = chatConfig?.threadId;
491
- const configHasExplicitThreadId = chatConfig?.hasExplicitThreadId;
492
- const resolvedThreadId = threadId ?? (configHasExplicitThreadId ? configThreadId : void 0);
312
+ const resolvedThreadId = ɵresolveAgentThreadId({
313
+ threadId,
314
+ chatThreadId: chatConfig?.threadId,
315
+ chatHasExplicitThreadId: chatConfig?.hasExplicitThreadId
316
+ });
493
317
  useEffect(() => {
494
318
  if (!resolvedThreadId) return;
495
319
  agent.threadId = resolvedThreadId;
@@ -779,8 +603,7 @@ function useFrontendTools(tools, deps) {
779
603
  * ```
780
604
  */
781
605
  function useComponent(config, deps) {
782
- const prefix = `Use this tool to display the "${config.name}" component in the chat. This tool renders a visual UI component for the user.`;
783
- const fullDescription = config.description ? `${prefix}\n\n${config.description}` : prefix;
606
+ const fullDescription = ɵcomponentToolDescription(config.name, config.description);
784
607
  useFrontendTool({
785
608
  name: config.name,
786
609
  description: fullDescription,
@@ -796,84 +619,18 @@ function useComponent(config, deps) {
796
619
 
797
620
  //#endregion
798
621
  //#region src/hooks/use-human-in-the-loop.tsx
799
- /** Registration name of a catch-all tool: handles any otherwise-unhandled call. */
800
- const WILDCARD_TOOL_NAME = "*";
801
622
  function useHumanInTheLoop(tool, deps) {
802
623
  const { copilotkit } = useCopilotKit$1();
803
- const resolvePromiseRef = useRef(null);
804
- const cleanupAbortRef = useRef(null);
805
- const respond = useCallback(async (result) => {
806
- if (resolvePromiseRef.current) {
807
- cleanupAbortRef.current?.();
808
- cleanupAbortRef.current = null;
809
- resolvePromiseRef.current(result);
810
- resolvePromiseRef.current = null;
811
- }
812
- }, []);
813
- const handler = useCallback(async (_args, context) => {
814
- const signal = context?.signal;
815
- return new Promise((resolve, reject) => {
816
- if (signal?.aborted) {
817
- reject(/* @__PURE__ */ new Error("Human-in-the-loop interaction aborted"));
818
- return;
819
- }
820
- resolvePromiseRef.current = resolve;
821
- if (signal) {
822
- const onAbort = () => {
823
- cleanupAbortRef.current = null;
824
- resolvePromiseRef.current = null;
825
- reject(/* @__PURE__ */ new Error("Human-in-the-loop interaction aborted"));
826
- };
827
- signal.addEventListener("abort", onAbort, { once: true });
828
- cleanupAbortRef.current = () => {
829
- signal.removeEventListener("abort", onAbort);
830
- };
831
- }
832
- });
833
- }, []);
834
- const RenderComponent = useCallback((props) => {
835
- const ToolComponent = tool.render;
836
- const name = tool.name === WILDCARD_TOOL_NAME ? props.name : tool.name;
837
- if (props.status === ToolCallStatus.InProgress) {
838
- const enhancedProps = {
839
- ...props,
840
- name,
841
- description: tool.description || "",
842
- agentId: tool.agentId,
843
- respond: void 0
844
- };
845
- return React.createElement(ToolComponent, enhancedProps);
846
- } else if (props.status === ToolCallStatus.Executing) {
847
- const enhancedProps = {
848
- ...props,
849
- name,
850
- description: tool.description || "",
851
- agentId: tool.agentId,
852
- respond
853
- };
854
- return React.createElement(ToolComponent, enhancedProps);
855
- } else if (props.status === ToolCallStatus.Complete) {
856
- const enhancedProps = {
857
- ...props,
858
- name,
859
- description: tool.description || "",
860
- agentId: tool.agentId,
861
- respond: void 0
862
- };
863
- return React.createElement(ToolComponent, enhancedProps);
864
- }
865
- return props;
866
- }, [
624
+ const registry = copilotkit.ɵhumanInTheLoop;
625
+ const RenderComponent = useCallback((props) => React.createElement(tool.render, ɵhitlRenderProps(props, tool, registry)), [
867
626
  tool.render,
868
627
  tool.name,
869
628
  tool.description,
870
629
  tool.agentId,
871
- respond
630
+ registry
872
631
  ]);
873
632
  useFrontendTool({
874
- ...tool,
875
- type: "human-in-the-loop",
876
- handler,
633
+ ...ɵbuildHumanInTheLoopTool(tool, registry),
877
634
  render: RenderComponent
878
635
  }, deps);
879
636
  useLayoutEffect(() => {
@@ -889,18 +646,6 @@ function useHumanInTheLoop(tool, deps) {
889
646
 
890
647
  //#endregion
891
648
  //#region src/hooks/use-interrupt.tsx
892
- /** Recognize thenables returned by interrupt preprocessing handlers. */
893
- function isPromiseLike(value) {
894
- return (typeof value === "object" || typeof value === "function") && value !== null && typeof Reflect.get(value, "then") === "function";
895
- }
896
- /** Derive the legacy-compatible `event` for any pending interrupt. */
897
- function toLegacyEvent(pending) {
898
- if (pending.kind === "legacy") return pending.event;
899
- return {
900
- name: INTERRUPT_EVENT_NAME,
901
- value: pending.interrupts[0]
902
- };
903
- }
904
649
  /**
905
650
  * Handles agent interrupts with optional filtering, preprocessing, and resume behavior.
906
651
  *
@@ -934,228 +679,24 @@ function useInterrupt(config) {
934
679
  agentId: config.agentId,
935
680
  updates: []
936
681
  });
937
- const [pending, setPending] = useState(null);
938
- const pendingRef = useRef(pending);
939
- pendingRef.current = pending;
940
- const [handlerResult, setHandlerResult] = useState(null);
941
- const interruptStateRef = useRef(new ɵInterruptState());
942
- useEffect(() => {
943
- let localLegacy = null;
944
- let localStandard = null;
945
- const subscription = agent.subscribe({
946
- onCustomEvent: ({ event }) => {
947
- if (event.name === INTERRUPT_EVENT_NAME) localLegacy = {
948
- name: event.name,
949
- value: event.value
950
- };
951
- },
952
- onRunFinishedEvent: (params) => {
953
- if (params.outcome === "interrupt") localStandard = params.interrupts;
954
- },
955
- onRunStartedEvent: (params) => {
956
- if (!agent.pendingInterrupts?.length || params?.input?.resume !== void 0) ɵclearAgentInterruptState(agent);
957
- localLegacy = null;
958
- localStandard = null;
959
- interruptStateRef.current = new ɵInterruptState();
960
- setPending(null);
961
- },
962
- onRunFinalized: () => {
963
- if (localStandard && localStandard.length > 0) {
964
- interruptStateRef.current = ɵgetAgentInterruptState(agent, localStandard);
965
- setPending(interruptStateRef.current.pending);
966
- } else if (localLegacy) {
967
- interruptStateRef.current = new ɵInterruptState();
968
- interruptStateRef.current.setLegacy(localLegacy);
969
- setPending(interruptStateRef.current.pending);
970
- }
971
- localLegacy = null;
972
- localStandard = null;
973
- },
974
- onRunFailed: () => {
975
- localLegacy = null;
976
- localStandard = null;
977
- interruptStateRef.current = new ɵInterruptState();
978
- setPending(null);
979
- }
980
- });
981
- interruptStateRef.current = agent.pendingInterrupts?.length ? ɵgetAgentInterruptState(agent) : new ɵInterruptState();
982
- setPending(interruptStateRef.current.pending);
983
- return () => {
984
- subscription.unsubscribe();
985
- interruptStateRef.current = new ɵInterruptState();
986
- };
987
- }, [agent]);
988
- /** Record an explicit answer and resume once the complete batch is addressed. */
989
- const resolve = useCallback(async (payload, interruptId) => {
990
- const current = pendingRef.current;
991
- if (!current) return;
992
- 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.`);
993
- if (interruptStateRef.current.isCompletedToolCall(interruptId, agent.messages)) {
994
- console.warn("[CopilotKit] useInterrupt: ignoring an answer for an already completed frontend tool call.");
995
- return;
996
- }
997
- const decision = interruptStateRef.current.resolve(payload, interruptId, agent.messages);
998
- if (decision.kind === "legacy-resume") try {
999
- return await copilotkit.runAgent({
1000
- agent,
1001
- forwardedProps: { command: {
1002
- resume: decision.payload,
1003
- interruptEvent: decision.interruptValue
1004
- } }
1005
- });
1006
- } catch (err) {
1007
- console.error("[CopilotKit] useInterrupt resolve: runAgent rejected; clearing pending + rethrowing", err);
1008
- setPending(null);
1009
- throw err;
1010
- }
1011
- if (decision.kind === "expired") {
1012
- console.error(`[CopilotKit] useInterrupt: interrupt ${decision.interrupt.id} expired at ${decision.interrupt.expiresAt}; not resuming.`);
1013
- interruptStateRef.current = new ɵInterruptState();
1014
- setPending(null);
1015
- return;
1016
- }
1017
- if (decision.kind !== "resume") return;
1018
- for (const toolResult of decision.toolResults) agent.addMessage({
1019
- id: randomUUID$1(),
1020
- role: "tool",
1021
- toolCallId: toolResult.toolCallId,
1022
- content: toolResult.content
1023
- });
1024
- try {
1025
- return await copilotkit.runAgent({
1026
- agent,
1027
- resume: decision.resume
1028
- });
1029
- } catch (err) {
1030
- console.error("[CopilotKit] useInterrupt resolve: runAgent rejected; clearing pending + rethrowing", err);
1031
- interruptStateRef.current = new ɵInterruptState();
1032
- setPending(null);
1033
- throw err;
1034
- }
1035
- }, [agent, copilotkit]);
1036
- /** Cancel a standard interrupt or dismiss a legacy interrupt locally. */
1037
- const cancel = useCallback(async (interruptId) => {
1038
- const current = pendingRef.current;
1039
- if (!current) return;
1040
- 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.`);
1041
- if (interruptStateRef.current.isCompletedToolCall(interruptId, agent.messages)) {
1042
- console.warn("[CopilotKit] useInterrupt: ignoring an answer for an already completed frontend tool call.");
1043
- return;
1044
- }
1045
- const decision = interruptStateRef.current.cancel(interruptId, agent.messages);
1046
- if (decision.kind === "dismiss") {
1047
- console.warn("[CopilotKit] useInterrupt: cancel() is not supported for legacy on_interrupt interrupts; dismissing.");
1048
- interruptStateRef.current = new ɵInterruptState();
1049
- setPending(null);
1050
- return;
1051
- }
1052
- if (decision.kind === "expired") {
1053
- console.error(`[CopilotKit] useInterrupt: interrupt ${decision.interrupt.id} expired at ${decision.interrupt.expiresAt}; not resuming.`);
1054
- interruptStateRef.current = new ɵInterruptState();
1055
- setPending(null);
1056
- return;
1057
- }
1058
- if (decision.kind !== "resume") return;
1059
- for (const toolResult of decision.toolResults) agent.addMessage({
1060
- id: randomUUID$1(),
1061
- role: "tool",
1062
- toolCallId: toolResult.toolCallId,
1063
- content: toolResult.content
1064
- });
1065
- try {
1066
- return await copilotkit.runAgent({
1067
- agent,
1068
- resume: decision.resume
1069
- });
1070
- } catch (err) {
1071
- console.error("[CopilotKit] useInterrupt resolve: runAgent rejected; clearing pending + rethrowing", err);
1072
- interruptStateRef.current = new ɵInterruptState();
1073
- setPending(null);
1074
- throw err;
1075
- }
1076
- }, [agent, copilotkit]);
1077
682
  const renderRef = useRef(config.render);
1078
683
  renderRef.current = config.render;
1079
684
  const enabledRef = useRef(config.enabled);
1080
685
  enabledRef.current = config.enabled;
1081
686
  const handlerRef = useRef(config.handler);
1082
687
  handlerRef.current = config.handler;
1083
- const resolveRef = useRef(resolve);
1084
- resolveRef.current = resolve;
1085
- const cancelRef = useRef(cancel);
1086
- cancelRef.current = cancel;
1087
- /** Evaluate the consumer filter, logging failures and disabling their UI. */
1088
- const isEnabled = (event) => {
1089
- const predicate = enabledRef.current;
1090
- if (!predicate) return true;
1091
- try {
1092
- return predicate(event);
1093
- } catch (err) {
1094
- console.error("[CopilotKit] useInterrupt enabled predicate threw; treating interrupt as disabled:", err);
1095
- return false;
1096
- }
1097
- };
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
+ }));
1098
694
  useEffect(() => {
1099
- if (!pending) {
1100
- setHandlerResult(null);
1101
- return;
1102
- }
1103
- const legacyEvent = toLegacyEvent(pending);
1104
- if (!isEnabled(legacyEvent)) {
1105
- setHandlerResult(null);
1106
- return;
1107
- }
1108
- const handler = handlerRef.current;
1109
- if (!handler) {
1110
- setHandlerResult(null);
1111
- return;
1112
- }
1113
- let cancelled = false;
1114
- let maybePromise;
1115
- try {
1116
- maybePromise = handler({
1117
- event: legacyEvent,
1118
- interrupt: pending.kind === "standard" ? pending.interrupts[0] ?? null : null,
1119
- interrupts: pending.kind === "standard" ? [...pending.interrupts] : [],
1120
- resolve: resolveRef.current,
1121
- cancel: cancelRef.current
1122
- });
1123
- } catch (err) {
1124
- console.error("[CopilotKit] useInterrupt handler threw; result will be null:", err);
1125
- if (!cancelled) setHandlerResult(null);
1126
- return () => {
1127
- cancelled = true;
1128
- };
1129
- }
1130
- if (isPromiseLike(maybePromise)) Promise.resolve(maybePromise).then((resolved) => {
1131
- if (!cancelled) setHandlerResult(resolved);
1132
- }).catch((err) => {
1133
- console.error("[CopilotKit] useInterrupt handler rejected; result will be null:", err);
1134
- if (!cancelled) setHandlerResult(null);
1135
- });
1136
- else setHandlerResult(maybePromise);
1137
- return () => {
1138
- cancelled = true;
1139
- };
1140
- }, [pending]);
1141
- const element = useMemo(() => {
1142
- if (!pending) return null;
1143
- const legacyEvent = toLegacyEvent(pending);
1144
- if (!isEnabled(legacyEvent)) return null;
1145
- return renderRef.current({
1146
- event: legacyEvent,
1147
- interrupt: pending.kind === "standard" ? pending.interrupts[0] ?? null : null,
1148
- interrupts: pending.kind === "standard" ? [...pending.interrupts] : [],
1149
- result: handlerResult,
1150
- resolve,
1151
- cancel
1152
- });
1153
- }, [
1154
- pending,
1155
- handlerResult,
1156
- resolve,
1157
- cancel
1158
- ]);
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]);
1159
700
  useEffect(() => {
1160
701
  if (config.renderInChat === false) return;
1161
702
  copilotkit.setInterruptElement(element);
@@ -1184,210 +725,75 @@ function useSuggestions({ agentId } = {}) {
1184
725
  config?.agentId,
1185
726
  providerAgentId
1186
727
  ]);
1187
- const [suggestions, setSuggestions] = useState(() => {
1188
- return copilotkit.getSuggestions(resolvedAgentId).suggestions;
1189
- });
1190
- const [isLoading, setIsLoading] = useState(() => {
1191
- return copilotkit.getSuggestions(resolvedAgentId).isLoading;
1192
- });
728
+ const [result, setResult] = useState(() => copilotkit.getSuggestions(resolvedAgentId));
1193
729
  useEffect(() => {
1194
- const result = copilotkit.getSuggestions(resolvedAgentId);
1195
- setSuggestions(result.suggestions);
1196
- setIsLoading(result.isLoading);
730
+ setResult(copilotkit.getSuggestions(resolvedAgentId));
731
+ return ɵsubscribeToAgentSuggestions(copilotkit, resolvedAgentId, setResult);
1197
732
  }, [copilotkit, resolvedAgentId]);
1198
- useEffect(() => {
1199
- const subscription = copilotkit.subscribe({
1200
- onSuggestionsChanged: ({ agentId: changedAgentId, suggestions }) => {
1201
- if (changedAgentId !== resolvedAgentId) return;
1202
- setSuggestions(suggestions);
1203
- },
1204
- onSuggestionsStartedLoading: ({ agentId: changedAgentId }) => {
1205
- if (changedAgentId !== resolvedAgentId) return;
1206
- setIsLoading(true);
1207
- },
1208
- onSuggestionsFinishedLoading: ({ agentId: changedAgentId }) => {
1209
- if (changedAgentId !== resolvedAgentId) return;
1210
- setIsLoading(false);
1211
- },
1212
- onSuggestionsConfigChanged: () => {
1213
- const result = copilotkit.getSuggestions(resolvedAgentId);
1214
- setSuggestions(result.suggestions);
1215
- setIsLoading(result.isLoading);
1216
- }
1217
- });
1218
- return () => {
1219
- subscription.unsubscribe();
1220
- };
733
+ const reloadSuggestions = useCallback(() => {
734
+ copilotkit.reloadSuggestions(resolvedAgentId);
735
+ }, [copilotkit, resolvedAgentId]);
736
+ const clearSuggestions = useCallback(() => {
737
+ copilotkit.clearSuggestions(resolvedAgentId);
1221
738
  }, [copilotkit, resolvedAgentId]);
1222
739
  return {
1223
- suggestions,
1224
- reloadSuggestions: useCallback(() => {
1225
- copilotkit.reloadSuggestions(resolvedAgentId);
1226
- }, [copilotkit, resolvedAgentId]),
1227
- clearSuggestions: useCallback(() => {
1228
- copilotkit.clearSuggestions(resolvedAgentId);
1229
- }, [copilotkit, resolvedAgentId]),
1230
- isLoading
740
+ suggestions: result.suggestions,
741
+ reloadSuggestions,
742
+ clearSuggestions,
743
+ isLoading: result.isLoading
1231
744
  };
1232
745
  }
1233
746
 
1234
747
  //#endregion
1235
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
+ */
1236
762
  function useConfigureSuggestions(config, deps) {
1237
763
  const { copilotkit } = useCopilotKit$1();
1238
764
  const chatConfig = useCopilotChatConfiguration();
765
+ const providerAgentId = useDefaultAgentId();
766
+ const chatAgentId = chatConfig?.agentId ?? providerAgentId ?? DEFAULT_AGENT_ID;
1239
767
  const extraDeps = deps ?? [];
1240
- const resolvedConsumerAgentId = useMemo(() => chatConfig?.agentId ?? DEFAULT_AGENT_ID, [chatConfig?.agentId]);
1241
- const rawConsumerAgentId = useMemo(() => config ? config.consumerAgentId : void 0, [config]);
1242
- const normalizationCacheRef = useRef({
1243
- serialized: null,
1244
- config: null
768
+ const bindingRef = useRef(null);
769
+ const latestRef = useRef({
770
+ config,
771
+ chatAgentId
1245
772
  });
1246
- const { normalizedConfig, serializedConfig } = useMemo(() => {
1247
- if (!config) {
1248
- normalizationCacheRef.current = {
1249
- serialized: null,
1250
- config: null
1251
- };
1252
- return {
1253
- normalizedConfig: null,
1254
- serializedConfig: null
1255
- };
1256
- }
1257
- if (config.available === "disabled") {
1258
- normalizationCacheRef.current = {
1259
- serialized: null,
1260
- config: null
1261
- };
1262
- return {
1263
- normalizedConfig: null,
1264
- serializedConfig: null
1265
- };
1266
- }
1267
- let built;
1268
- if (isDynamicConfig(config)) built = { ...config };
1269
- else {
1270
- const normalizedSuggestions = normalizeStaticSuggestions(config.suggestions);
1271
- built = {
1272
- ...config,
1273
- suggestions: normalizedSuggestions
1274
- };
1275
- }
1276
- const serialized = JSON.stringify(built);
1277
- const cache = normalizationCacheRef.current;
1278
- if (cache.serialized === serialized && cache.config) return {
1279
- normalizedConfig: cache.config,
1280
- serializedConfig: serialized
1281
- };
1282
- normalizationCacheRef.current = {
1283
- serialized,
1284
- config: built
1285
- };
1286
- return {
1287
- normalizedConfig: built,
1288
- serializedConfig: serialized
1289
- };
1290
- }, [
773
+ latestRef.current = {
1291
774
  config,
1292
- resolvedConsumerAgentId,
1293
- ...extraDeps
1294
- ]);
1295
- const latestConfigRef = useRef(null);
1296
- latestConfigRef.current = normalizedConfig;
1297
- const previousSerializedConfigRef = useRef(null);
1298
- const targetAgentId = useMemo(() => {
1299
- if (!normalizedConfig) return resolvedConsumerAgentId;
1300
- const consumer = normalizedConfig.consumerAgentId;
1301
- if (!consumer || consumer === "*") return resolvedConsumerAgentId;
1302
- return consumer;
1303
- }, [normalizedConfig, resolvedConsumerAgentId]);
1304
- const isGlobalConfig = rawConsumerAgentId === void 0 || rawConsumerAgentId === "*";
1305
- const isDynamicConfigType = useMemo(() => !!normalizedConfig && "instructions" in normalizedConfig, [normalizedConfig]);
1306
- const requestReload = useCallback(() => {
1307
- if (!normalizedConfig) return;
1308
- if (isGlobalConfig) {
1309
- const seen = /* @__PURE__ */ new Set();
1310
- const agents = Object.values(copilotkit.agents ?? {});
1311
- for (const entry of agents) {
1312
- const agentId = entry.agentId;
1313
- if (!agentId) continue;
1314
- seen.add(agentId);
1315
- if (!entry.isRunning) copilotkit.reloadSuggestions(agentId);
1316
- }
1317
- if (targetAgentId && !seen.has(targetAgentId)) copilotkit.reloadSuggestions(targetAgentId);
1318
- return;
1319
- }
1320
- if (!targetAgentId) return;
1321
- copilotkit.reloadSuggestions(targetAgentId);
1322
- }, [
1323
- copilotkit,
1324
- isGlobalConfig,
1325
- normalizedConfig,
1326
- targetAgentId
1327
- ]);
775
+ chatAgentId
776
+ };
1328
777
  useEffect(() => {
1329
- if (!serializedConfig || !latestConfigRef.current) return;
1330
- const id = copilotkit.addSuggestionsConfig(latestConfigRef.current);
1331
- requestReload();
778
+ const latest = latestRef.current;
779
+ const binding = ɵbindSuggestionsConfig(copilotkit, latest.config, { chatAgentId: latest.chatAgentId });
780
+ bindingRef.current = binding;
1332
781
  return () => {
1333
- copilotkit.removeSuggestionsConfig(id);
782
+ binding.dispose();
783
+ if (bindingRef.current === binding) bindingRef.current = null;
1334
784
  };
1335
- }, [
1336
- copilotkit,
1337
- serializedConfig,
1338
- requestReload
1339
- ]);
785
+ }, [copilotkit]);
1340
786
  useEffect(() => {
1341
- if (!normalizedConfig) {
1342
- 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;
1343
793
  return;
1344
794
  }
1345
- if (serializedConfig && previousSerializedConfigRef.current === serializedConfig) return;
1346
- if (serializedConfig) previousSerializedConfigRef.current = serializedConfig;
1347
- requestReload();
1348
- }, [
1349
- normalizedConfig,
1350
- requestReload,
1351
- serializedConfig
1352
- ]);
1353
- useEffect(() => {
1354
- if (!normalizedConfig || extraDeps.length === 0) return;
1355
- requestReload();
1356
- }, [
1357
- extraDeps.length,
1358
- normalizedConfig,
1359
- requestReload,
1360
- ...extraDeps
1361
- ]);
1362
- useEffect(() => {
1363
- if (!normalizedConfig || !isDynamicConfigType) return;
1364
- if (!targetAgentId) return;
1365
- if (!!copilotkit.getAgent(targetAgentId)) return;
1366
- const subscription = copilotkit.subscribe({ onAgentsChanged: () => {
1367
- if (copilotkit.getAgent(targetAgentId)) {
1368
- requestReload();
1369
- subscription.unsubscribe();
1370
- }
1371
- } });
1372
- return () => {
1373
- subscription.unsubscribe();
1374
- };
1375
- }, [
1376
- copilotkit,
1377
- normalizedConfig,
1378
- isDynamicConfigType,
1379
- targetAgentId,
1380
- requestReload
1381
- ]);
1382
- }
1383
- function isDynamicConfig(config) {
1384
- return "instructions" in config;
1385
- }
1386
- function normalizeStaticSuggestions(suggestions) {
1387
- return suggestions.map((suggestion) => ({
1388
- ...suggestion,
1389
- isLoading: suggestion.isLoading ?? false
1390
- }));
795
+ if (extraDeps.length > 0) bindingRef.current?.reload();
796
+ }, [extraDeps.length, ...extraDeps]);
1391
797
  }
1392
798
 
1393
799
  //#endregion
@@ -1395,10 +801,7 @@ function normalizeStaticSuggestions(suggestions) {
1395
801
  function useAgentContext(context) {
1396
802
  const { description, value } = context;
1397
803
  const { copilotkit } = useCopilotKit$1();
1398
- const stringValue = useMemo(() => {
1399
- if (typeof value === "string") return value;
1400
- return JSON.stringify(value);
1401
- }, [value]);
804
+ const stringValue = useMemo(() => ɵserializeContextValue(value), [value]);
1402
805
  useLayoutEffect(() => {
1403
806
  if (!copilotkit) return;
1404
807
  const id = copilotkit.addContext({
@@ -1417,12 +820,6 @@ function useAgentContext(context) {
1417
820
 
1418
821
  //#endregion
1419
822
  //#region src/hooks/use-threads.tsx
1420
- function useThreadStoreSelector(store, selector) {
1421
- return useSyncExternalStore(useCallback((onStoreChange) => {
1422
- const subscription = store.select(selector).subscribe(onStoreChange);
1423
- return () => subscription.unsubscribe();
1424
- }, [store, selector]), () => selector(store.getState()), () => selector(store.getServerState()));
1425
- }
1426
823
  /**
1427
824
  * React hook for listing and managing CopilotKit Intelligence threads.
1428
825
  *
@@ -1466,117 +863,38 @@ function useThreadStoreSelector(store, selector) {
1466
863
  */
1467
864
  function useThreads({ agentId, includeArchived, limit, enabled = true }) {
1468
865
  const { copilotkit } = useCopilotKit$1();
1469
- const [store] = useState(() => ɵcreateThreadStore({ fetch: copilotkit.ɵruntimeFetch }));
1470
- const coreThreads = useThreadStoreSelector(store, ɵselectThreads);
1471
- const threads = useMemo(() => coreThreads.map(({ id, agentId, name, archived, createdAt, updatedAt, lastRunAt }) => ({
1472
- id,
1473
- agentId,
1474
- name,
1475
- archived,
1476
- createdAt,
1477
- updatedAt,
1478
- ...lastRunAt !== void 0 ? { lastRunAt } : {}
1479
- })), [coreThreads]);
1480
- const storeIsLoading = useThreadStoreSelector(store, ɵselectThreadsIsLoading);
1481
- const storeError = useThreadStoreSelector(store, ɵselectThreadsError);
1482
- const fetchMoreError = useThreadStoreSelector(store, ɵselectFetchMoreError);
1483
- const hasMoreThreads = useThreadStoreSelector(store, ɵselectHasNextPage);
1484
- const isFetchingMoreThreads = useThreadStoreSelector(store, ɵselectIsFetchingNextPage);
1485
- const isMutating = useThreadStoreSelector(store, ɵselectIsMutating);
1486
- const headersKey = copilotkit.ɵheadersGeneration;
1487
- const runtimeStatus = copilotkit.runtimeConnectionStatus;
1488
- const threadListEndpointSupported = copilotkit.threadEndpoints?.list !== false;
1489
- const threadMutationsSupported = copilotkit.threadEndpoints?.mutations !== false;
1490
- const threadEndpointsUnavailable = !!copilotkit.runtimeUrl && runtimeStatus === CopilotKitCoreRuntimeConnectionStatus.Connected && !threadListEndpointSupported;
1491
- const runtimeError = useMemo(() => {
1492
- if (copilotkit.runtimeUrl) return null;
1493
- return /* @__PURE__ */ new Error("Runtime URL is not configured");
1494
- }, [copilotkit.runtimeUrl]);
1495
- const threadEndpointsError = useMemo(() => {
1496
- if (!threadEndpointsUnavailable) return null;
1497
- return /* @__PURE__ */ new Error("Thread endpoints are not available on this CopilotKit runtime");
1498
- }, [threadEndpointsUnavailable]);
1499
- const threadMutationsError = useMemo(() => {
1500
- if (threadMutationsSupported) return null;
1501
- return /* @__PURE__ */ new Error("Thread mutations are not available on this CopilotKit runtime");
1502
- }, [threadMutationsSupported]);
1503
- const [hasDispatchedContext, setHasDispatchedContext] = useState(false);
1504
- const preConnectLoading = enabled && !!copilotkit.runtimeUrl && !threadEndpointsUnavailable && !hasDispatchedContext;
1505
- const [configErrorDismissed, setConfigErrorDismissed] = useState(false);
1506
- useEffect(() => {
1507
- setConfigErrorDismissed(false);
1508
- }, [runtimeError, threadEndpointsError]);
1509
- const activeRuntimeError = configErrorDismissed ? null : runtimeError;
1510
- const activeThreadEndpointsError = configErrorDismissed ? null : threadEndpointsError;
1511
- const isLoading = activeRuntimeError || activeThreadEndpointsError ? false : preConnectLoading || storeIsLoading;
1512
- const error = activeRuntimeError ?? activeThreadEndpointsError ?? storeError;
1513
- const listError = storeError;
1514
- useEffect(() => {
1515
- store.start();
1516
- return () => {
1517
- store.stop();
1518
- };
1519
- }, [store]);
1520
- useEffect(() => {
1521
- if (!enabled) return;
1522
- copilotkit.registerThreadStore(agentId, store);
1523
- return () => {
1524
- copilotkit.unregisterThreadStore(agentId);
1525
- };
1526
- }, [
1527
- copilotkit,
866
+ const [controller] = useState(() => new ɵThreadsController(ɵcreateThreadStore({ fetch: copilotkit.ɵruntimeFetch }), {
867
+ core: copilotkit,
1528
868
  agentId,
1529
- store,
869
+ includeArchived,
870
+ limit,
1530
871
  enabled
1531
- ]);
872
+ }));
873
+ const { threads, isLoading, error, listError, fetchMoreError, hasMoreThreads, isFetchingMoreThreads, isMutating } = useSyncExternalStore(controller.subscribe, controller.getSnapshot, controller.getServerSnapshot);
874
+ useEffect(() => controller.start(), [controller]);
1532
875
  useEffect(() => {
1533
- if (!enabled) {
1534
- store.setContext(null);
1535
- setHasDispatchedContext(false);
1536
- return;
1537
- }
1538
- if (!copilotkit.runtimeUrl) {
1539
- store.setContext(null);
1540
- setHasDispatchedContext(false);
1541
- return;
1542
- }
1543
- if (runtimeStatus !== CopilotKitCoreRuntimeConnectionStatus.Connected) return;
1544
- if (!threadListEndpointSupported) {
1545
- store.setContext(null);
1546
- setHasDispatchedContext(false);
1547
- return;
1548
- }
1549
- const context = {
1550
- runtimeUrl: copilotkit.runtimeUrl,
1551
- wsUrl: copilotkit.intelligence?.wsUrl,
876
+ controller.update({
877
+ core: copilotkit,
1552
878
  agentId,
1553
879
  includeArchived,
1554
- limit
1555
- };
1556
- store.setContext(context);
1557
- setHasDispatchedContext(true);
880
+ limit,
881
+ enabled
882
+ });
1558
883
  }, [
1559
- store,
884
+ controller,
885
+ copilotkit,
886
+ agentId,
887
+ includeArchived,
888
+ limit,
1560
889
  enabled,
1561
890
  copilotkit.runtimeUrl,
1562
- runtimeStatus,
1563
- headersKey,
891
+ copilotkit.runtimeConnectionStatus,
892
+ copilotkit.ɵheadersGeneration,
1564
893
  copilotkit.intelligence?.wsUrl,
1565
- threadListEndpointSupported,
1566
- agentId,
1567
- includeArchived,
1568
- limit
894
+ copilotkit.threadEndpoints?.list,
895
+ copilotkit.threadEndpoints?.mutations
1569
896
  ]);
1570
- const guardMutation = useCallback((mutation) => {
1571
- return (...args) => {
1572
- if (threadMutationsError) return Promise.reject(threadMutationsError);
1573
- return mutation(...args);
1574
- };
1575
- }, [threadMutationsError]);
1576
- const renameThread = useMemo(() => guardMutation((threadId, name) => store.renameThread(threadId, name)), [store, guardMutation]);
1577
- const archiveThread = useMemo(() => guardMutation((threadId) => store.archiveThread(threadId)), [store, guardMutation]);
1578
- const unarchiveThread = useMemo(() => guardMutation((threadId) => store.unarchiveThread(threadId)), [store, guardMutation]);
1579
- const deleteThread = useMemo(() => guardMutation((threadId) => store.deleteThread(threadId)), [store, guardMutation]);
897
+ const { fetchMoreThreads, refetchThreads, startNewThread, renameThread, archiveThread, unarchiveThread, deleteThread } = controller;
1580
898
  return {
1581
899
  threads,
1582
900
  isLoading,
@@ -1586,12 +904,9 @@ function useThreads({ agentId, includeArchived, limit, enabled = true }) {
1586
904
  hasMoreThreads,
1587
905
  isFetchingMoreThreads,
1588
906
  isMutating,
1589
- fetchMoreThreads: useCallback(() => store.fetchNextPage(), [store]),
1590
- refetchThreads: useCallback(() => store.refetchThreads(), [store]),
1591
- startNewThread: useCallback(() => {
1592
- setConfigErrorDismissed(true);
1593
- store.startNewThread();
1594
- }, [store]),
907
+ fetchMoreThreads,
908
+ refetchThreads,
909
+ startNewThread,
1595
910
  renameThread,
1596
911
  archiveThread,
1597
912
  unarchiveThread,
@@ -1704,29 +1019,11 @@ function useRenderTool(config, deps) {
1704
1019
  * but the tool call data hasn't changed.
1705
1020
  */
1706
1021
  const ToolCallRenderer = React.memo(function ToolCallRenderer({ toolCall, toolMessage, RenderComponent, isExecuting }) {
1707
- const args = useMemo(() => partialJSONParse(toolCall.function.arguments), [toolCall.function.arguments]);
1708
- const toolName = toolCall.function.name;
1709
- if (toolMessage) return /* @__PURE__ */ jsx(RenderComponent, {
1710
- name: toolName,
1711
- toolCallId: toolCall.id,
1712
- args,
1713
- status: ToolCallStatus.Complete,
1714
- result: contentToText(toolMessage.content)
1715
- });
1716
- else if (isExecuting) return /* @__PURE__ */ jsx(RenderComponent, {
1717
- name: toolName,
1718
- toolCallId: toolCall.id,
1719
- args,
1720
- status: ToolCallStatus.Executing,
1721
- result: void 0
1722
- });
1723
- else return /* @__PURE__ */ jsx(RenderComponent, {
1724
- name: toolName,
1725
- toolCallId: toolCall.id,
1726
- args,
1727
- status: ToolCallStatus.InProgress,
1728
- result: void 0
1729
- });
1022
+ return /* @__PURE__ */ jsx(RenderComponent, { ...useMemo(() => ɵbuildToolCallRenderProps(toolCall, toolMessage, { isExecuting }), [
1023
+ toolCall,
1024
+ toolMessage,
1025
+ isExecuting
1026
+ ]) });
1730
1027
  }, (prevProps, nextProps) => {
1731
1028
  if (prevProps.toolCall.id !== nextProps.toolCall.id) return false;
1732
1029
  if (prevProps.toolCall.function.name !== nextProps.toolCall.function.name) return false;
@@ -1738,25 +1035,21 @@ const ToolCallRenderer = React.memo(function ToolCallRenderer({ toolCall, toolMe
1738
1035
  });
1739
1036
  const IS_DEVELOPMENT = process.env.NODE_ENV !== "production";
1740
1037
  /**
1741
- * Reports tool calls that resolved to no renderer.
1038
+ * Reports tool calls that resolved to no renderer, once per tool name.
1742
1039
  *
1743
1040
  * A tool call with no renderer paints an empty message container and says
1744
1041
  * nothing else, so the only signal a developer gets today is a blank space in
1745
- * the chat. This names the call and the renderers that *are* registered, which
1746
- * is the whole diagnosis when the cause is a name that does not match.
1042
+ * the chat.
1747
1043
  *
1748
1044
  * @param toolNames - The unmatched tool names collected during render.
1749
1045
  * @param registered - The registry as it stands now, re-read at report time.
1750
1046
  * @param alreadyWarned - Names already reported, mutated to keep this once per name.
1751
1047
  */
1752
1048
  function warnAboutUnrenderedToolCalls(toolNames, registered, alreadyWarned) {
1753
- const registeredNames = Array.from(new Set(registered.map((rc) => rc.name)));
1754
- const hasWildcard = registeredNames.includes("*");
1755
- for (const toolName of toolNames) {
1756
- if (hasWildcard || registeredNames.includes(toolName)) continue;
1757
- if (alreadyWarned.has(toolName)) continue;
1049
+ const warnings = ɵdescribeUnrenderedToolCalls(toolNames.filter((name) => !alreadyWarned.has(name)), registered);
1050
+ for (const { toolName, message } of warnings) {
1758
1051
  alreadyWarned.add(toolName);
1759
- 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);
1760
1053
  }
1761
1054
  }
1762
1055
  /**
@@ -1775,7 +1068,7 @@ function useToolCallRenderers() {
1775
1068
  */
1776
1069
  function useRenderToolCall() {
1777
1070
  const { copilotkit, executingToolCallIds } = useCopilotKit$1();
1778
- const agentId = useCopilotChatConfiguration()?.agentId ?? DEFAULT_AGENT_ID;
1071
+ const agentId = ɵresolveToolCallAgentId(useCopilotChatConfiguration()?.agentId, void 0);
1779
1072
  const unrenderedToolNames = useRef(/* @__PURE__ */ new Set());
1780
1073
  const warnedToolNames = useRef(/* @__PURE__ */ new Set());
1781
1074
  const renderToolCalls = useToolCallRenderers();
@@ -1827,9 +1120,9 @@ function useRenderToolCall() {
1827
1120
  */
1828
1121
  function useCapabilities(agentId) {
1829
1122
  const { agent } = useAgent({ agentId });
1830
- if (agent && "capabilities" in agent) return agent.capabilities;
1123
+ return ɵgetAgentCapabilities(agent);
1831
1124
  }
1832
1125
 
1833
1126
  //#endregion
1834
- 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 };
1835
1128
  //# sourceMappingURL=headless.mjs.map