@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.cjs CHANGED
@@ -29,12 +29,59 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
29
29
  let _copilotkit_react_core_context = require("@copilotkit/react-core/context");
30
30
  let react = require("react");
31
31
  react = __toESM(react);
32
- let _copilotkit_shared = require("@copilotkit/shared");
33
32
  let _copilotkit_core = require("@copilotkit/core");
34
33
  let react_jsx_runtime = require("react/jsx-runtime");
35
- let _ag_ui_client = require("@ag-ui/client");
36
- let _ag_ui_core = require("@ag-ui/core");
34
+ let _copilotkit_shared = require("@copilotkit/shared");
35
+
36
+ //#region src/providers/use-owned-core.ts
37
+ /**
38
+ * @internal Create a core for the provider's lifetime and dispose it on
39
+ * unmount.
40
+ *
41
+ * The dispose waits one task. StrictMode (and Fast Refresh) unmount and
42
+ * remount effects in the same commit, so the remount cancels the pending
43
+ * dispose and the same core keeps working. When effects mount again after the
44
+ * core was really disposed (for example an `<Activity>` that was hidden and
45
+ * shown), the hook creates a new core and renders again: a disposed core is
46
+ * never reused.
47
+ *
48
+ * `ref` holds the current core. The provider owns it, so code that runs
49
+ * before the core exists can read `ref.current`.
50
+ *
51
+ * @example
52
+ * const coreRef = useRef<CopilotKitCoreReact | null>(null);
53
+ * const core = ɵuseOwnedCore(coreRef, () => new CopilotKitCoreReact(config));
54
+ */
55
+ function ɵuseOwnedCore(ref, create) {
56
+ const createRef = (0, react.useRef)(create);
57
+ createRef.current = create;
58
+ const pendingDispose = (0, react.useRef)(void 0);
59
+ const disposedRef = (0, react.useRef)(false);
60
+ const [, rerender] = (0, react.useReducer)((count) => count + 1, 0);
61
+ const current = ref.current ?? create();
62
+ ref.current = current;
63
+ (0, react.useEffect)(() => {
64
+ clearTimeout(pendingDispose.current);
65
+ pendingDispose.current = void 0;
66
+ let core = ref.current ?? createRef.current();
67
+ if (disposedRef.current) {
68
+ disposedRef.current = false;
69
+ core = createRef.current();
70
+ rerender();
71
+ }
72
+ ref.current = core;
73
+ return () => {
74
+ pendingDispose.current = setTimeout(() => {
75
+ pendingDispose.current = void 0;
76
+ disposedRef.current = true;
77
+ core.dispose();
78
+ }, 0);
79
+ };
80
+ }, [ref]);
81
+ return current;
82
+ }
37
83
 
84
+ //#endregion
38
85
  //#region src/lib/shallow-stable-ref.ts
39
86
  /**
40
87
  * Shallow equality comparison for objects: same own keys, each holding the
@@ -75,25 +122,6 @@ function useShallowStableRef(value) {
75
122
 
76
123
  //#endregion
77
124
  //#region src/providers/CopilotChatConfigurationProvider.tsx
78
- /**
79
- * Mobile breakpoint below which the chat modal and the thread-list drawer are
80
- * mutually exclusive. At or above this width both surfaces may coexist. This
81
- * mirrors the `(max-width: 767px)` / `(min-width: 768px)` split already used by
82
- * CopilotChatInput and CopilotSidebarView.
83
- */
84
- const MOBILE_MAX_WIDTH_PX = 767;
85
- /**
86
- * Reports whether the current viewport is in the mobile range (`<768px`), where
87
- * the chat modal and drawer must not be open simultaneously. SSR-safe and
88
- * defensive against environments without `matchMedia` (treated as desktop, so
89
- * no mutual-exclusion constraint is applied).
90
- *
91
- * @returns `true` when the viewport is mobile-width, `false` otherwise.
92
- */
93
- function isMobileViewport() {
94
- if (typeof window === "undefined" || typeof window.matchMedia !== "function") return false;
95
- return window.matchMedia(`(max-width: ${MOBILE_MAX_WIDTH_PX}px)`).matches;
96
- }
97
125
  const CopilotChatConfiguration = (0, react.createContext)(null);
98
126
  const CopilotChatConfigurationProvider = ({ children, labels, agentId, threadId, hasExplicitThreadId, isModalDefaultOpen }) => {
99
127
  const parentConfig = (0, react.useContext)(CopilotChatConfiguration);
@@ -104,167 +132,67 @@ const CopilotChatConfigurationProvider = ({ children, labels, agentId, threadId,
104
132
  ...stableLabels
105
133
  }), [stableLabels, parentConfig?.labels]);
106
134
  const providerAgentId = (0, _copilotkit_react_core_context.useDefaultAgentId)();
107
- const resolvedAgentId = agentId ?? parentConfig?.agentId ?? providerAgentId ?? _copilotkit_shared.DEFAULT_AGENT_ID;
108
- const threadIdPropIsAuthoritative = threadId !== void 0 && hasExplicitThreadId !== false;
109
- const isThreadIdControlled = threadIdPropIsAuthoritative;
110
- const [activeThreadOverride, setActiveThreadOverride] = (0, react.useState)(null);
111
- const resolvedThreadId = (0, react.useMemo)(() => {
112
- if (threadIdPropIsAuthoritative) return threadId;
113
- if (activeThreadOverride) return activeThreadOverride.threadId;
114
- if (parentConfig?.threadId) return parentConfig.threadId;
115
- if (threadId) return threadId;
116
- return (0, _copilotkit_shared.randomUUID)();
135
+ const options = {
136
+ agentId,
137
+ threadId,
138
+ hasExplicitThreadId,
139
+ isModalDefaultOpen,
140
+ providerAgentId
141
+ };
142
+ const parentStore = parentConfig?.ɵstore ?? null;
143
+ const [store] = (0, react.useState)(() => new _copilotkit_core.ɵChatConfigurationStore(options, parentStore));
144
+ store.ɵsetOptions(options);
145
+ const snapshot = (0, react.useSyncExternalStore)(store.subscribe, store.getSnapshot, store.getSnapshot);
146
+ (0, react.useEffect)(() => {
147
+ store.update({
148
+ agentId,
149
+ threadId,
150
+ hasExplicitThreadId,
151
+ isModalDefaultOpen,
152
+ providerAgentId
153
+ });
117
154
  }, [
118
- threadIdPropIsAuthoritative,
155
+ store,
156
+ agentId,
119
157
  threadId,
120
- parentConfig?.threadId,
121
- activeThreadOverride
158
+ hasExplicitThreadId,
159
+ isModalDefaultOpen,
160
+ providerAgentId
122
161
  ]);
123
162
  const copilotkit = (0, react.useContext)(_copilotkit_react_core_context.CopilotKitContext)?.copilotkit;
124
- const openThreadRef = (0, react.useRef)(null);
125
- const latestThreadIdRef = (0, react.useRef)(resolvedThreadId);
126
- latestThreadIdRef.current = resolvedThreadId;
127
163
  (0, react.useEffect)(() => {
128
164
  if (copilotkit === void 0) return;
129
- const registration = copilotkit.registerOpenThread({
130
- agentId: resolvedAgentId,
131
- threadId: latestThreadIdRef.current
132
- });
133
- openThreadRef.current = registration;
134
- return () => {
135
- registration.unregister();
136
- openThreadRef.current = null;
137
- };
138
- }, [copilotkit, resolvedAgentId]);
139
- (0, react.useEffect)(() => {
140
- openThreadRef.current?.update(resolvedThreadId);
141
- }, [resolvedThreadId]);
142
- const resolvedHasExplicitThreadId = (threadIdPropIsAuthoritative ? true : activeThreadOverride?.explicit ?? hasExplicitThreadId ?? false) || !!parentConfig?.hasExplicitThreadId;
143
- const [internalModalOpen, setInternalModalOpen] = (0, react.useState)(isModalDefaultOpen ?? true);
144
- const hasExplicitDefault = isModalDefaultOpen !== void 0;
145
- const setAndSync = (0, react.useCallback)((open) => {
146
- setInternalModalOpen(open);
147
- parentConfig?.setModalOpen(open);
148
- }, [parentConfig?.setModalOpen]);
149
- const isMounted = (0, react.useRef)(false);
150
- (0, react.useEffect)(() => {
151
- if (!hasExplicitDefault) return;
152
- if (!isMounted.current) {
153
- isMounted.current = true;
154
- return;
155
- }
156
- if (parentConfig?.isModalOpen === void 0) return;
157
- setInternalModalOpen(parentConfig.isModalOpen);
158
- }, [parentConfig?.isModalOpen, hasExplicitDefault]);
159
- const resolvedIsModalOpen = hasExplicitDefault ? internalModalOpen : parentConfig?.isModalOpen ?? internalModalOpen;
160
- const resolvedSetModalOpen = hasExplicitDefault ? setAndSync : parentConfig?.setModalOpen ?? setInternalModalOpen;
161
- const [ownDrawerOpen, setOwnDrawerOpen] = (0, react.useState)(false);
162
- const [ownDrawerCount, setOwnDrawerCount] = (0, react.useState)(0);
163
- const modalCloseRef = (0, react.useRef)(() => {});
164
- modalCloseRef.current = resolvedSetModalOpen;
165
- const registeredModalClosersRef = (0, react.useRef)([]);
166
- const ownRegisterModalCloser = (0, react.useCallback)((closeModal) => {
167
- registeredModalClosersRef.current.push(closeModal);
168
- return () => {
169
- registeredModalClosersRef.current = registeredModalClosersRef.current.filter((entry) => entry !== closeModal);
170
- };
171
- }, []);
172
- const ownSetDrawerOpen = (0, react.useCallback)((open) => {
173
- setOwnDrawerOpen(open);
174
- if (open && isMobileViewport()) {
175
- const registered = registeredModalClosersRef.current;
176
- (registered.length > 0 ? registered[registered.length - 1] : modalCloseRef.current)(false);
177
- }
178
- }, []);
179
- const ownRegisterDrawer = (0, react.useCallback)(() => {
180
- setOwnDrawerCount((count) => count + 1);
181
- return () => {
182
- setOwnDrawerCount((count) => Math.max(0, count - 1));
183
- };
184
- }, []);
185
- const resolvedDrawerOpen = parentConfig ? parentConfig.drawerOpen : ownDrawerOpen;
186
- const resolvedSetDrawerOpen = parentConfig ? parentConfig.setDrawerOpen : ownSetDrawerOpen;
187
- const resolvedDrawerRegistered = parentConfig ? parentConfig.drawerRegistered : ownDrawerCount > 0;
188
- const resolvedRegisterDrawer = parentConfig ? parentConfig.registerDrawer : ownRegisterDrawer;
189
- const resolvedRegisterModalCloser = parentConfig ? parentConfig.ɵregisterModalCloser : ownRegisterModalCloser;
190
- (0, react.useEffect)(() => {
191
- if (!hasExplicitDefault) return;
192
- return resolvedRegisterModalCloser(resolvedSetModalOpen);
193
- }, [
194
- hasExplicitDefault,
195
- resolvedRegisterModalCloser,
196
- resolvedSetModalOpen
197
- ]);
198
- const isThreadIdControlledRef = (0, react.useRef)(isThreadIdControlled);
199
- isThreadIdControlledRef.current = isThreadIdControlled;
200
- const ownSetActiveThreadId = (0, react.useCallback)((id, options) => {
201
- setActiveThreadOverride({
202
- threadId: id,
203
- explicit: options?.explicit ?? true
204
- });
205
- }, []);
206
- const ownStartNewThread = (0, react.useCallback)(() => {
207
- setActiveThreadOverride({
208
- threadId: (0, _copilotkit_shared.randomUUID)(),
209
- explicit: false
210
- });
211
- }, []);
212
- const parentSetActiveThreadId = parentConfig?.setActiveThreadId;
213
- const parentStartNewThread = parentConfig?.startNewThread;
214
- const resolvedSetActiveThreadId = (0, react.useCallback)((id, options) => {
215
- if (isThreadIdControlledRef.current) {
216
- console.warn("[CopilotKit] Ignoring setActiveThreadId(): threadId is controlled via the `threadId` prop on CopilotChatConfigurationProvider.");
217
- return;
218
- }
219
- if (parentSetActiveThreadId) {
220
- parentSetActiveThreadId(id, options);
221
- return;
222
- }
223
- ownSetActiveThreadId(id, options);
224
- }, [parentSetActiveThreadId, ownSetActiveThreadId]);
225
- const resolvedStartNewThread = (0, react.useCallback)(() => {
226
- if (isThreadIdControlledRef.current) {
227
- console.warn("[CopilotKit] Ignoring startNewThread(): threadId is controlled via the `threadId` prop on CopilotChatConfigurationProvider.");
228
- return;
229
- }
230
- if (parentStartNewThread) {
231
- parentStartNewThread();
232
- return;
233
- }
234
- ownStartNewThread();
235
- }, [parentStartNewThread, ownStartNewThread]);
236
- const setModalOpenWithDrawerExclusion = (0, react.useCallback)((open) => {
237
- if (open && isMobileViewport()) resolvedSetDrawerOpen(false);
238
- resolvedSetModalOpen(open);
239
- }, [resolvedSetModalOpen, resolvedSetDrawerOpen]);
165
+ return store.bindOpenThread(copilotkit);
166
+ }, [copilotkit, store]);
167
+ const ownsModal = isModalDefaultOpen !== void 0;
168
+ const isModalOpen = ownsModal || !parentConfig ? snapshot.isModalOpen : parentConfig.isModalOpen;
169
+ const setModalOpen = ownsModal || !parentConfig ? store.setModalOpen : parentConfig.setModalOpen;
170
+ const { agentId: resolvedAgentId, threadId: resolvedThreadId, hasExplicitThreadId: resolvedHasExplicitThreadId, drawerOpen, drawerRegistered } = snapshot;
240
171
  const configurationValue = (0, react.useMemo)(() => ({
241
172
  labels: mergedLabels,
242
173
  agentId: resolvedAgentId,
243
174
  threadId: resolvedThreadId,
244
175
  hasExplicitThreadId: resolvedHasExplicitThreadId,
245
- isModalOpen: resolvedIsModalOpen,
246
- setModalOpen: setModalOpenWithDrawerExclusion,
247
- drawerOpen: resolvedDrawerOpen,
248
- setDrawerOpen: resolvedSetDrawerOpen,
249
- drawerRegistered: resolvedDrawerRegistered,
250
- registerDrawer: resolvedRegisterDrawer,
251
- ɵregisterModalCloser: resolvedRegisterModalCloser,
252
- setActiveThreadId: resolvedSetActiveThreadId,
253
- startNewThread: resolvedStartNewThread
176
+ isModalOpen,
177
+ setModalOpen,
178
+ drawerOpen,
179
+ setDrawerOpen: store.setDrawerOpen,
180
+ drawerRegistered,
181
+ registerDrawer: store.registerDrawer,
182
+ ɵregisterModalCloser: store.registerModalCloser,
183
+ setActiveThreadId: store.setActiveThreadId,
184
+ startNewThread: store.startNewThread,
185
+ ɵstore: store
254
186
  }), [
255
187
  mergedLabels,
256
188
  resolvedAgentId,
257
189
  resolvedThreadId,
258
190
  resolvedHasExplicitThreadId,
259
- resolvedIsModalOpen,
260
- setModalOpenWithDrawerExclusion,
261
- resolvedDrawerOpen,
262
- resolvedSetDrawerOpen,
263
- resolvedDrawerRegistered,
264
- resolvedRegisterDrawer,
265
- resolvedRegisterModalCloser,
266
- resolvedSetActiveThreadId,
267
- resolvedStartNewThread
191
+ isModalOpen,
192
+ setModalOpen,
193
+ drawerOpen,
194
+ drawerRegistered,
195
+ store
268
196
  ]);
269
197
  return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotChatConfiguration.Provider, {
270
198
  value: configurationValue,
@@ -345,163 +273,57 @@ const ALL_UPDATES = [
345
273
  UseAgentUpdate.OnRunStatusChanged
346
274
  ];
347
275
  function useAgent({ agentId, threadId, runtimeAgentId, updates, throttleMs } = {}) {
348
- 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 }).`);
349
- 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}" }).`);
350
- if (runtimeAgentId != null && agentId == null) throw new Error(`useAgent: \`runtimeAgentId\` requires an explicit \`agentId\`. The proxied agent is registered under \`agentId\`, and the usual fallbacks (chat configuration, then "${_copilotkit_shared.DEFAULT_AGENT_ID}") name agents that already exist — registering over one throws or shadows it. Pick a local id for this hook, e.g. useAgent({ agentId: "chat-1", runtimeAgentId: "${runtimeAgentId}", threadId }).`);
276
+ (0, _copilotkit_core.ɵvalidateAgentBinding)({
277
+ agentId,
278
+ threadId,
279
+ runtimeAgentId
280
+ });
351
281
  const chatConfig = useCopilotChatConfiguration();
352
282
  const providerAgentId = (0, _copilotkit_react_core_context.useDefaultAgentId)();
353
- const resolvedAgentId = agentId ?? chatConfig?.agentId ?? providerAgentId ?? _copilotkit_shared.DEFAULT_AGENT_ID;
283
+ const resolvedAgentId = (0, _copilotkit_core.ɵresolveAgentId)({
284
+ agentId,
285
+ chatAgentId: chatConfig?.agentId,
286
+ providerAgentId
287
+ });
354
288
  const { copilotkit } = (0, _copilotkit_react_core_context.useCopilotKit)();
289
+ const resolver = (0, _copilotkit_core.ɵgetAgentResolver)(copilotkit);
290
+ const revision = (0, react.useSyncExternalStore)(resolver.subscribe, resolver.getSnapshot, resolver.getSnapshot);
355
291
  const providerThrottleMs = copilotkit.defaultThrottleMs;
356
292
  const [, forceUpdate] = (0, react.useReducer)((x) => x + 1, 0);
357
293
  const updateFlags = (0, react.useMemo)(() => updates ?? ALL_UPDATES, [JSON.stringify(updates)]);
358
- const provisionalAgentCache = (0, react.useRef)(/* @__PURE__ */ new Map());
359
- const [registeredProxyAgent, setRegisteredProxyAgent] = (0, react.useState)(null);
360
294
  (0, react.useEffect)(() => {
361
- if (runtimeAgentId == null) {
362
- setRegisteredProxyAgent(null);
363
- return;
364
- }
365
- const { agent: proxy, unregister } = copilotkit.registerProxiedAgent({
295
+ if (runtimeAgentId == null) return;
296
+ return resolver.bindProxy({
366
297
  agentId: resolvedAgentId,
367
298
  runtimeAgentId
368
299
  });
369
- provisionalAgentCache.current.delete(resolvedAgentId);
370
- setRegisteredProxyAgent(proxy);
371
- return () => {
372
- unregister();
373
- setRegisteredProxyAgent(null);
374
- };
375
300
  }, [
376
- copilotkit,
301
+ resolver,
377
302
  resolvedAgentId,
378
303
  runtimeAgentId
379
304
  ]);
380
- const { agent, isReady } = (0, react.useMemo)(() => {
381
- if (runtimeAgentId != null) {
382
- if (registeredProxyAgent) {
383
- provisionalAgentCache.current.delete(resolvedAgentId);
384
- return {
385
- agent: registeredProxyAgent,
386
- isReady: true
387
- };
388
- }
389
- const cached = provisionalAgentCache.current.get(resolvedAgentId);
390
- if (cached) {
391
- copilotkit.applyHeadersToAgent(cached);
392
- return {
393
- agent: cached,
394
- isReady: false
395
- };
396
- }
397
- const provisional = new _copilotkit_core.ProxiedCopilotRuntimeAgent({
398
- runtimeUrl: copilotkit.runtimeUrl,
399
- agentId: resolvedAgentId,
400
- runtimeAgentId,
401
- transport: copilotkit.runtimeTransport,
402
- runtimeMode: "pending"
403
- });
404
- copilotkit.applyHeadersToAgent(provisional);
405
- provisionalAgentCache.current.set(resolvedAgentId, provisional);
406
- return {
407
- agent: provisional,
408
- isReady: false
409
- };
410
- }
411
- const existing = copilotkit.getAgent(resolvedAgentId);
412
- if (existing) {
413
- provisionalAgentCache.current.delete(resolvedAgentId);
414
- return {
415
- agent: existing,
416
- isReady: true
417
- };
418
- }
419
- const isRuntimeConfigured = copilotkit.runtimeUrl !== void 0;
420
- const status = copilotkit.runtimeConnectionStatus;
421
- if (isRuntimeConfigured && (status === _copilotkit_core.CopilotKitCoreRuntimeConnectionStatus.Disconnected || status === _copilotkit_core.CopilotKitCoreRuntimeConnectionStatus.Connecting)) {
422
- const cached = provisionalAgentCache.current.get(resolvedAgentId);
423
- if (cached) return {
424
- agent: cached,
425
- isReady: false
426
- };
427
- const provisional = new _copilotkit_core.ProxiedCopilotRuntimeAgent({
428
- runtimeUrl: copilotkit.runtimeUrl,
429
- agentId: resolvedAgentId,
430
- transport: copilotkit.runtimeTransport,
431
- credentials: copilotkit.credentials,
432
- runtimeMode: "pending"
433
- });
434
- copilotkit.applyHeadersToAgent(provisional);
435
- provisionalAgentCache.current.set(resolvedAgentId, provisional);
436
- return {
437
- agent: provisional,
438
- isReady: false
439
- };
440
- }
441
- if (isRuntimeConfigured && status === _copilotkit_core.CopilotKitCoreRuntimeConnectionStatus.Error) {
442
- const cached = provisionalAgentCache.current.get(resolvedAgentId);
443
- if (cached) return {
444
- agent: cached,
445
- isReady: false
446
- };
447
- const provisional = new _copilotkit_core.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
- const knownAgents = Object.keys(copilotkit.agents ?? {});
462
- const runtimePart = isRuntimeConfigured ? `runtimeUrl=${copilotkit.runtimeUrl}` : "no runtimeUrl";
463
- 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.");
464
- }, [
305
+ const headersGeneration = copilotkit.ɵheadersGeneration;
306
+ const { agent, isReady } = (0, react.useMemo)(() => resolver.resolve({
307
+ agentId: resolvedAgentId,
308
+ runtimeAgentId,
309
+ caller: "useAgent"
310
+ }), [
311
+ resolver,
312
+ revision,
465
313
  resolvedAgentId,
466
314
  runtimeAgentId,
467
- registeredProxyAgent,
468
315
  copilotkit.agents,
469
316
  copilotkit.runtimeConnectionStatus,
470
317
  copilotkit.runtimeUrl,
471
318
  copilotkit.runtimeTransport,
472
319
  copilotkit.credentials,
473
- JSON.stringify(copilotkit.headers)
320
+ headersGeneration
474
321
  ]);
475
- (0, react.useEffect)(() => {
476
- if (updateFlags.length === 0) return;
477
- let active = true;
478
- const handlers = {};
479
- let batchScheduled = false;
480
- const batchedForceUpdate = () => {
481
- if (!active) return;
482
- if (!batchScheduled) {
483
- batchScheduled = true;
484
- queueMicrotask(() => {
485
- batchScheduled = false;
486
- if (active) forceUpdate();
487
- });
488
- }
489
- };
490
- if (updateFlags.includes(UseAgentUpdate.OnMessagesChanged)) handlers.onMessagesChanged = batchedForceUpdate;
491
- if (updateFlags.includes(UseAgentUpdate.OnStateChanged)) handlers.onStateChanged = batchedForceUpdate;
492
- if (updateFlags.includes(UseAgentUpdate.OnRunStatusChanged)) {
493
- handlers.onRunInitialized = batchedForceUpdate;
494
- handlers.onRunStartedEvent = batchedForceUpdate;
495
- handlers.onRunFinalized = batchedForceUpdate;
496
- handlers.onRunFailed = batchedForceUpdate;
497
- handlers.onRunErrorEvent = batchedForceUpdate;
498
- }
499
- const subscription = copilotkit.subscribeToAgentWithOptions(agent, handlers, { throttleMs });
500
- return () => {
501
- active = false;
502
- subscription.unsubscribe();
503
- };
504
- }, [
322
+ (0, react.useEffect)(() => (0, _copilotkit_core.ɵsubscribeToAgentUpdates)(copilotkit, agent, {
323
+ updates: updateFlags,
324
+ throttleMs,
325
+ onUpdate: forceUpdate
326
+ }), [
505
327
  agent,
506
328
  forceUpdate,
507
329
  throttleMs,
@@ -509,16 +331,18 @@ function useAgent({ agentId, threadId, runtimeAgentId, updates, throttleMs } = {
509
331
  updateFlags
510
332
  ]);
511
333
  (0, react.useEffect)(() => {
512
- if ((0, _copilotkit_core.ɵisHttpAgent)(agent)) copilotkit.applyHeadersToAgent(agent);
513
- if (agent instanceof _copilotkit_core.ProxiedCopilotRuntimeAgent) agent.credentials = copilotkit.credentials;
334
+ resolver.refreshRequestSettings(agent);
514
335
  }, [
336
+ resolver,
515
337
  agent,
516
- JSON.stringify(copilotkit.headers),
338
+ headersGeneration,
517
339
  copilotkit.credentials
518
340
  ]);
519
- const configThreadId = chatConfig?.threadId;
520
- const configHasExplicitThreadId = chatConfig?.hasExplicitThreadId;
521
- const resolvedThreadId = threadId ?? (configHasExplicitThreadId ? configThreadId : void 0);
341
+ const resolvedThreadId = (0, _copilotkit_core.ɵresolveAgentThreadId)({
342
+ threadId,
343
+ chatThreadId: chatConfig?.threadId,
344
+ chatHasExplicitThreadId: chatConfig?.hasExplicitThreadId
345
+ });
522
346
  (0, react.useEffect)(() => {
523
347
  if (!resolvedThreadId) return;
524
348
  agent.threadId = resolvedThreadId;
@@ -808,8 +632,7 @@ function useFrontendTools(tools, deps) {
808
632
  * ```
809
633
  */
810
634
  function useComponent(config, deps) {
811
- const prefix = `Use this tool to display the "${config.name}" component in the chat. This tool renders a visual UI component for the user.`;
812
- const fullDescription = config.description ? `${prefix}\n\n${config.description}` : prefix;
635
+ const fullDescription = (0, _copilotkit_core.ɵcomponentToolDescription)(config.name, config.description);
813
636
  useFrontendTool({
814
637
  name: config.name,
815
638
  description: fullDescription,
@@ -825,84 +648,18 @@ function useComponent(config, deps) {
825
648
 
826
649
  //#endregion
827
650
  //#region src/hooks/use-human-in-the-loop.tsx
828
- /** Registration name of a catch-all tool: handles any otherwise-unhandled call. */
829
- const WILDCARD_TOOL_NAME = "*";
830
651
  function useHumanInTheLoop(tool, deps) {
831
652
  const { copilotkit } = (0, _copilotkit_react_core_context.useCopilotKit)();
832
- const resolvePromiseRef = (0, react.useRef)(null);
833
- const cleanupAbortRef = (0, react.useRef)(null);
834
- const respond = (0, react.useCallback)(async (result) => {
835
- if (resolvePromiseRef.current) {
836
- cleanupAbortRef.current?.();
837
- cleanupAbortRef.current = null;
838
- resolvePromiseRef.current(result);
839
- resolvePromiseRef.current = null;
840
- }
841
- }, []);
842
- const handler = (0, react.useCallback)(async (_args, context) => {
843
- const signal = context?.signal;
844
- return new Promise((resolve, reject) => {
845
- if (signal?.aborted) {
846
- reject(/* @__PURE__ */ new Error("Human-in-the-loop interaction aborted"));
847
- return;
848
- }
849
- resolvePromiseRef.current = resolve;
850
- if (signal) {
851
- const onAbort = () => {
852
- cleanupAbortRef.current = null;
853
- resolvePromiseRef.current = null;
854
- reject(/* @__PURE__ */ new Error("Human-in-the-loop interaction aborted"));
855
- };
856
- signal.addEventListener("abort", onAbort, { once: true });
857
- cleanupAbortRef.current = () => {
858
- signal.removeEventListener("abort", onAbort);
859
- };
860
- }
861
- });
862
- }, []);
863
- const RenderComponent = (0, react.useCallback)((props) => {
864
- const ToolComponent = tool.render;
865
- const name = tool.name === WILDCARD_TOOL_NAME ? props.name : tool.name;
866
- if (props.status === _copilotkit_core.ToolCallStatus.InProgress) {
867
- const enhancedProps = {
868
- ...props,
869
- name,
870
- description: tool.description || "",
871
- agentId: tool.agentId,
872
- respond: void 0
873
- };
874
- return react.default.createElement(ToolComponent, enhancedProps);
875
- } else if (props.status === _copilotkit_core.ToolCallStatus.Executing) {
876
- const enhancedProps = {
877
- ...props,
878
- name,
879
- description: tool.description || "",
880
- agentId: tool.agentId,
881
- respond
882
- };
883
- return react.default.createElement(ToolComponent, enhancedProps);
884
- } else if (props.status === _copilotkit_core.ToolCallStatus.Complete) {
885
- const enhancedProps = {
886
- ...props,
887
- name,
888
- description: tool.description || "",
889
- agentId: tool.agentId,
890
- respond: void 0
891
- };
892
- return react.default.createElement(ToolComponent, enhancedProps);
893
- }
894
- return props;
895
- }, [
653
+ const registry = copilotkit.ɵhumanInTheLoop;
654
+ const RenderComponent = (0, react.useCallback)((props) => react.default.createElement(tool.render, (0, _copilotkit_core.ɵhitlRenderProps)(props, tool, registry)), [
896
655
  tool.render,
897
656
  tool.name,
898
657
  tool.description,
899
658
  tool.agentId,
900
- respond
659
+ registry
901
660
  ]);
902
661
  useFrontendTool({
903
- ...tool,
904
- type: "human-in-the-loop",
905
- handler,
662
+ ...(0, _copilotkit_core.ɵbuildHumanInTheLoopTool)(tool, registry),
906
663
  render: RenderComponent
907
664
  }, deps);
908
665
  (0, react.useLayoutEffect)(() => {
@@ -918,18 +675,6 @@ function useHumanInTheLoop(tool, deps) {
918
675
 
919
676
  //#endregion
920
677
  //#region src/hooks/use-interrupt.tsx
921
- /** Recognize thenables returned by interrupt preprocessing handlers. */
922
- function isPromiseLike(value) {
923
- return (typeof value === "object" || typeof value === "function") && value !== null && typeof Reflect.get(value, "then") === "function";
924
- }
925
- /** Derive the legacy-compatible `event` for any pending interrupt. */
926
- function toLegacyEvent(pending) {
927
- if (pending.kind === "legacy") return pending.event;
928
- return {
929
- name: _copilotkit_core.INTERRUPT_EVENT_NAME,
930
- value: pending.interrupts[0]
931
- };
932
- }
933
678
  /**
934
679
  * Handles agent interrupts with optional filtering, preprocessing, and resume behavior.
935
680
  *
@@ -963,228 +708,24 @@ function useInterrupt(config) {
963
708
  agentId: config.agentId,
964
709
  updates: []
965
710
  });
966
- const [pending, setPending] = (0, react.useState)(null);
967
- const pendingRef = (0, react.useRef)(pending);
968
- pendingRef.current = pending;
969
- const [handlerResult, setHandlerResult] = (0, react.useState)(null);
970
- const interruptStateRef = (0, react.useRef)(new _copilotkit_core.ɵInterruptState());
971
- (0, react.useEffect)(() => {
972
- let localLegacy = null;
973
- let localStandard = null;
974
- const subscription = agent.subscribe({
975
- onCustomEvent: ({ event }) => {
976
- if (event.name === _copilotkit_core.INTERRUPT_EVENT_NAME) localLegacy = {
977
- name: event.name,
978
- value: event.value
979
- };
980
- },
981
- onRunFinishedEvent: (params) => {
982
- if (params.outcome === "interrupt") localStandard = params.interrupts;
983
- },
984
- onRunStartedEvent: (params) => {
985
- if (!agent.pendingInterrupts?.length || params?.input?.resume !== void 0) (0, _copilotkit_core.ɵclearAgentInterruptState)(agent);
986
- localLegacy = null;
987
- localStandard = null;
988
- interruptStateRef.current = new _copilotkit_core.ɵInterruptState();
989
- setPending(null);
990
- },
991
- onRunFinalized: () => {
992
- if (localStandard && localStandard.length > 0) {
993
- interruptStateRef.current = (0, _copilotkit_core.ɵgetAgentInterruptState)(agent, localStandard);
994
- setPending(interruptStateRef.current.pending);
995
- } else if (localLegacy) {
996
- interruptStateRef.current = new _copilotkit_core.ɵInterruptState();
997
- interruptStateRef.current.setLegacy(localLegacy);
998
- setPending(interruptStateRef.current.pending);
999
- }
1000
- localLegacy = null;
1001
- localStandard = null;
1002
- },
1003
- onRunFailed: () => {
1004
- localLegacy = null;
1005
- localStandard = null;
1006
- interruptStateRef.current = new _copilotkit_core.ɵInterruptState();
1007
- setPending(null);
1008
- }
1009
- });
1010
- interruptStateRef.current = agent.pendingInterrupts?.length ? (0, _copilotkit_core.ɵgetAgentInterruptState)(agent) : new _copilotkit_core.ɵInterruptState();
1011
- setPending(interruptStateRef.current.pending);
1012
- return () => {
1013
- subscription.unsubscribe();
1014
- interruptStateRef.current = new _copilotkit_core.ɵInterruptState();
1015
- };
1016
- }, [agent]);
1017
- /** Record an explicit answer and resume once the complete batch is addressed. */
1018
- const resolve = (0, react.useCallback)(async (payload, interruptId) => {
1019
- const current = pendingRef.current;
1020
- if (!current) return;
1021
- 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.`);
1022
- if (interruptStateRef.current.isCompletedToolCall(interruptId, agent.messages)) {
1023
- console.warn("[CopilotKit] useInterrupt: ignoring an answer for an already completed frontend tool call.");
1024
- return;
1025
- }
1026
- const decision = interruptStateRef.current.resolve(payload, interruptId, agent.messages);
1027
- if (decision.kind === "legacy-resume") try {
1028
- return await copilotkit.runAgent({
1029
- agent,
1030
- forwardedProps: { command: {
1031
- resume: decision.payload,
1032
- interruptEvent: decision.interruptValue
1033
- } }
1034
- });
1035
- } catch (err) {
1036
- console.error("[CopilotKit] useInterrupt resolve: runAgent rejected; clearing pending + rethrowing", err);
1037
- setPending(null);
1038
- throw err;
1039
- }
1040
- if (decision.kind === "expired") {
1041
- console.error(`[CopilotKit] useInterrupt: interrupt ${decision.interrupt.id} expired at ${decision.interrupt.expiresAt}; not resuming.`);
1042
- interruptStateRef.current = new _copilotkit_core.ɵInterruptState();
1043
- setPending(null);
1044
- return;
1045
- }
1046
- if (decision.kind !== "resume") return;
1047
- for (const toolResult of decision.toolResults) agent.addMessage({
1048
- id: (0, _ag_ui_client.randomUUID)(),
1049
- role: "tool",
1050
- toolCallId: toolResult.toolCallId,
1051
- content: toolResult.content
1052
- });
1053
- try {
1054
- return await copilotkit.runAgent({
1055
- agent,
1056
- resume: decision.resume
1057
- });
1058
- } catch (err) {
1059
- console.error("[CopilotKit] useInterrupt resolve: runAgent rejected; clearing pending + rethrowing", err);
1060
- interruptStateRef.current = new _copilotkit_core.ɵInterruptState();
1061
- setPending(null);
1062
- throw err;
1063
- }
1064
- }, [agent, copilotkit]);
1065
- /** Cancel a standard interrupt or dismiss a legacy interrupt locally. */
1066
- const cancel = (0, react.useCallback)(async (interruptId) => {
1067
- const current = pendingRef.current;
1068
- if (!current) return;
1069
- 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.`);
1070
- if (interruptStateRef.current.isCompletedToolCall(interruptId, agent.messages)) {
1071
- console.warn("[CopilotKit] useInterrupt: ignoring an answer for an already completed frontend tool call.");
1072
- return;
1073
- }
1074
- const decision = interruptStateRef.current.cancel(interruptId, agent.messages);
1075
- if (decision.kind === "dismiss") {
1076
- console.warn("[CopilotKit] useInterrupt: cancel() is not supported for legacy on_interrupt interrupts; dismissing.");
1077
- interruptStateRef.current = new _copilotkit_core.ɵInterruptState();
1078
- setPending(null);
1079
- return;
1080
- }
1081
- if (decision.kind === "expired") {
1082
- console.error(`[CopilotKit] useInterrupt: interrupt ${decision.interrupt.id} expired at ${decision.interrupt.expiresAt}; not resuming.`);
1083
- interruptStateRef.current = new _copilotkit_core.ɵInterruptState();
1084
- setPending(null);
1085
- return;
1086
- }
1087
- if (decision.kind !== "resume") return;
1088
- for (const toolResult of decision.toolResults) agent.addMessage({
1089
- id: (0, _ag_ui_client.randomUUID)(),
1090
- role: "tool",
1091
- toolCallId: toolResult.toolCallId,
1092
- content: toolResult.content
1093
- });
1094
- try {
1095
- return await copilotkit.runAgent({
1096
- agent,
1097
- resume: decision.resume
1098
- });
1099
- } catch (err) {
1100
- console.error("[CopilotKit] useInterrupt resolve: runAgent rejected; clearing pending + rethrowing", err);
1101
- interruptStateRef.current = new _copilotkit_core.ɵInterruptState();
1102
- setPending(null);
1103
- throw err;
1104
- }
1105
- }, [agent, copilotkit]);
1106
711
  const renderRef = (0, react.useRef)(config.render);
1107
712
  renderRef.current = config.render;
1108
713
  const enabledRef = (0, react.useRef)(config.enabled);
1109
714
  enabledRef.current = config.enabled;
1110
715
  const handlerRef = (0, react.useRef)(config.handler);
1111
716
  handlerRef.current = config.handler;
1112
- const resolveRef = (0, react.useRef)(resolve);
1113
- resolveRef.current = resolve;
1114
- const cancelRef = (0, react.useRef)(cancel);
1115
- cancelRef.current = cancel;
1116
- /** Evaluate the consumer filter, logging failures and disabling their UI. */
1117
- const isEnabled = (event) => {
1118
- const predicate = enabledRef.current;
1119
- if (!predicate) return true;
1120
- try {
1121
- return predicate(event);
1122
- } catch (err) {
1123
- console.error("[CopilotKit] useInterrupt enabled predicate threw; treating interrupt as disabled:", err);
1124
- return false;
1125
- }
1126
- };
717
+ const copilotkitRef = (0, react.useRef)(copilotkit);
718
+ copilotkitRef.current = copilotkit;
719
+ const [controller] = (0, react.useState)(() => new _copilotkit_core.ɵInterruptController({ runAgent: (params) => copilotkitRef.current.runAgent(params) }, {
720
+ enabled: (event) => enabledRef.current?.(event) ?? true,
721
+ handler: (props) => handlerRef.current ? handlerRef.current(props) : null
722
+ }));
1127
723
  (0, react.useEffect)(() => {
1128
- if (!pending) {
1129
- setHandlerResult(null);
1130
- return;
1131
- }
1132
- const legacyEvent = toLegacyEvent(pending);
1133
- if (!isEnabled(legacyEvent)) {
1134
- setHandlerResult(null);
1135
- return;
1136
- }
1137
- const handler = handlerRef.current;
1138
- if (!handler) {
1139
- setHandlerResult(null);
1140
- return;
1141
- }
1142
- let cancelled = false;
1143
- let maybePromise;
1144
- try {
1145
- maybePromise = handler({
1146
- event: legacyEvent,
1147
- interrupt: pending.kind === "standard" ? pending.interrupts[0] ?? null : null,
1148
- interrupts: pending.kind === "standard" ? [...pending.interrupts] : [],
1149
- resolve: resolveRef.current,
1150
- cancel: cancelRef.current
1151
- });
1152
- } catch (err) {
1153
- console.error("[CopilotKit] useInterrupt handler threw; result will be null:", err);
1154
- if (!cancelled) setHandlerResult(null);
1155
- return () => {
1156
- cancelled = true;
1157
- };
1158
- }
1159
- if (isPromiseLike(maybePromise)) Promise.resolve(maybePromise).then((resolved) => {
1160
- if (!cancelled) setHandlerResult(resolved);
1161
- }).catch((err) => {
1162
- console.error("[CopilotKit] useInterrupt handler rejected; result will be null:", err);
1163
- if (!cancelled) setHandlerResult(null);
1164
- });
1165
- else setHandlerResult(maybePromise);
1166
- return () => {
1167
- cancelled = true;
1168
- };
1169
- }, [pending]);
1170
- const element = (0, react.useMemo)(() => {
1171
- if (!pending) return null;
1172
- const legacyEvent = toLegacyEvent(pending);
1173
- if (!isEnabled(legacyEvent)) return null;
1174
- return renderRef.current({
1175
- event: legacyEvent,
1176
- interrupt: pending.kind === "standard" ? pending.interrupts[0] ?? null : null,
1177
- interrupts: pending.kind === "standard" ? [...pending.interrupts] : [],
1178
- result: handlerResult,
1179
- resolve,
1180
- cancel
1181
- });
1182
- }, [
1183
- pending,
1184
- handlerResult,
1185
- resolve,
1186
- cancel
1187
- ]);
724
+ controller.connect(agent);
725
+ return () => controller.disconnect();
726
+ }, [controller, agent]);
727
+ const { renderProps } = (0, react.useSyncExternalStore)(controller.subscribe, controller.getSnapshot, controller.getSnapshot);
728
+ const element = (0, react.useMemo)(() => renderProps ? renderRef.current(renderProps) : null, [renderProps]);
1188
729
  (0, react.useEffect)(() => {
1189
730
  if (config.renderInChat === false) return;
1190
731
  copilotkit.setInterruptElement(element);
@@ -1213,210 +754,75 @@ function useSuggestions({ agentId } = {}) {
1213
754
  config?.agentId,
1214
755
  providerAgentId
1215
756
  ]);
1216
- const [suggestions, setSuggestions] = (0, react.useState)(() => {
1217
- return copilotkit.getSuggestions(resolvedAgentId).suggestions;
1218
- });
1219
- const [isLoading, setIsLoading] = (0, react.useState)(() => {
1220
- return copilotkit.getSuggestions(resolvedAgentId).isLoading;
1221
- });
757
+ const [result, setResult] = (0, react.useState)(() => copilotkit.getSuggestions(resolvedAgentId));
1222
758
  (0, react.useEffect)(() => {
1223
- const result = copilotkit.getSuggestions(resolvedAgentId);
1224
- setSuggestions(result.suggestions);
1225
- setIsLoading(result.isLoading);
759
+ setResult(copilotkit.getSuggestions(resolvedAgentId));
760
+ return (0, _copilotkit_core.ɵsubscribeToAgentSuggestions)(copilotkit, resolvedAgentId, setResult);
1226
761
  }, [copilotkit, resolvedAgentId]);
1227
- (0, react.useEffect)(() => {
1228
- const subscription = copilotkit.subscribe({
1229
- onSuggestionsChanged: ({ agentId: changedAgentId, suggestions }) => {
1230
- if (changedAgentId !== resolvedAgentId) return;
1231
- setSuggestions(suggestions);
1232
- },
1233
- onSuggestionsStartedLoading: ({ agentId: changedAgentId }) => {
1234
- if (changedAgentId !== resolvedAgentId) return;
1235
- setIsLoading(true);
1236
- },
1237
- onSuggestionsFinishedLoading: ({ agentId: changedAgentId }) => {
1238
- if (changedAgentId !== resolvedAgentId) return;
1239
- setIsLoading(false);
1240
- },
1241
- onSuggestionsConfigChanged: () => {
1242
- const result = copilotkit.getSuggestions(resolvedAgentId);
1243
- setSuggestions(result.suggestions);
1244
- setIsLoading(result.isLoading);
1245
- }
1246
- });
1247
- return () => {
1248
- subscription.unsubscribe();
1249
- };
762
+ const reloadSuggestions = (0, react.useCallback)(() => {
763
+ copilotkit.reloadSuggestions(resolvedAgentId);
764
+ }, [copilotkit, resolvedAgentId]);
765
+ const clearSuggestions = (0, react.useCallback)(() => {
766
+ copilotkit.clearSuggestions(resolvedAgentId);
1250
767
  }, [copilotkit, resolvedAgentId]);
1251
768
  return {
1252
- suggestions,
1253
- reloadSuggestions: (0, react.useCallback)(() => {
1254
- copilotkit.reloadSuggestions(resolvedAgentId);
1255
- }, [copilotkit, resolvedAgentId]),
1256
- clearSuggestions: (0, react.useCallback)(() => {
1257
- copilotkit.clearSuggestions(resolvedAgentId);
1258
- }, [copilotkit, resolvedAgentId]),
1259
- isLoading
769
+ suggestions: result.suggestions,
770
+ reloadSuggestions,
771
+ clearSuggestions,
772
+ isLoading: result.isLoading
1260
773
  };
1261
774
  }
1262
775
 
1263
776
  //#endregion
1264
777
  //#region src/hooks/use-configure-suggestions.tsx
778
+ /**
779
+ * Registers a suggestions configuration (dynamic or static) for the current
780
+ * chat. A global config (no `consumerAgentId`, or `"*"`) applies to every
781
+ * agent and loads for the surrounding chat's agent first.
782
+ *
783
+ * Pass `deps` to reload suggestions when values the config reads change.
784
+ *
785
+ * @example
786
+ * useConfigureSuggestions({
787
+ * instructions: "Suggest concise next steps for the user",
788
+ * available: "always",
789
+ * });
790
+ */
1265
791
  function useConfigureSuggestions(config, deps) {
1266
792
  const { copilotkit } = (0, _copilotkit_react_core_context.useCopilotKit)();
1267
793
  const chatConfig = useCopilotChatConfiguration();
794
+ const providerAgentId = (0, _copilotkit_react_core_context.useDefaultAgentId)();
795
+ const chatAgentId = chatConfig?.agentId ?? providerAgentId ?? _copilotkit_shared.DEFAULT_AGENT_ID;
1268
796
  const extraDeps = deps ?? [];
1269
- const resolvedConsumerAgentId = (0, react.useMemo)(() => chatConfig?.agentId ?? _copilotkit_shared.DEFAULT_AGENT_ID, [chatConfig?.agentId]);
1270
- const rawConsumerAgentId = (0, react.useMemo)(() => config ? config.consumerAgentId : void 0, [config]);
1271
- const normalizationCacheRef = (0, react.useRef)({
1272
- serialized: null,
1273
- config: null
797
+ const bindingRef = (0, react.useRef)(null);
798
+ const latestRef = (0, react.useRef)({
799
+ config,
800
+ chatAgentId
1274
801
  });
1275
- const { normalizedConfig, serializedConfig } = (0, react.useMemo)(() => {
1276
- if (!config) {
1277
- normalizationCacheRef.current = {
1278
- serialized: null,
1279
- config: null
1280
- };
1281
- return {
1282
- normalizedConfig: null,
1283
- serializedConfig: null
1284
- };
1285
- }
1286
- if (config.available === "disabled") {
1287
- normalizationCacheRef.current = {
1288
- serialized: null,
1289
- config: null
1290
- };
1291
- return {
1292
- normalizedConfig: null,
1293
- serializedConfig: null
1294
- };
1295
- }
1296
- let built;
1297
- if (isDynamicConfig(config)) built = { ...config };
1298
- else {
1299
- const normalizedSuggestions = normalizeStaticSuggestions(config.suggestions);
1300
- built = {
1301
- ...config,
1302
- suggestions: normalizedSuggestions
1303
- };
1304
- }
1305
- const serialized = JSON.stringify(built);
1306
- const cache = normalizationCacheRef.current;
1307
- if (cache.serialized === serialized && cache.config) return {
1308
- normalizedConfig: cache.config,
1309
- serializedConfig: serialized
1310
- };
1311
- normalizationCacheRef.current = {
1312
- serialized,
1313
- config: built
1314
- };
1315
- return {
1316
- normalizedConfig: built,
1317
- serializedConfig: serialized
1318
- };
1319
- }, [
802
+ latestRef.current = {
1320
803
  config,
1321
- resolvedConsumerAgentId,
1322
- ...extraDeps
1323
- ]);
1324
- const latestConfigRef = (0, react.useRef)(null);
1325
- latestConfigRef.current = normalizedConfig;
1326
- const previousSerializedConfigRef = (0, react.useRef)(null);
1327
- const targetAgentId = (0, react.useMemo)(() => {
1328
- if (!normalizedConfig) return resolvedConsumerAgentId;
1329
- const consumer = normalizedConfig.consumerAgentId;
1330
- if (!consumer || consumer === "*") return resolvedConsumerAgentId;
1331
- return consumer;
1332
- }, [normalizedConfig, resolvedConsumerAgentId]);
1333
- const isGlobalConfig = rawConsumerAgentId === void 0 || rawConsumerAgentId === "*";
1334
- const isDynamicConfigType = (0, react.useMemo)(() => !!normalizedConfig && "instructions" in normalizedConfig, [normalizedConfig]);
1335
- const requestReload = (0, react.useCallback)(() => {
1336
- if (!normalizedConfig) return;
1337
- if (isGlobalConfig) {
1338
- const seen = /* @__PURE__ */ new Set();
1339
- const agents = Object.values(copilotkit.agents ?? {});
1340
- for (const entry of agents) {
1341
- const agentId = entry.agentId;
1342
- if (!agentId) continue;
1343
- seen.add(agentId);
1344
- if (!entry.isRunning) copilotkit.reloadSuggestions(agentId);
1345
- }
1346
- if (targetAgentId && !seen.has(targetAgentId)) copilotkit.reloadSuggestions(targetAgentId);
1347
- return;
1348
- }
1349
- if (!targetAgentId) return;
1350
- copilotkit.reloadSuggestions(targetAgentId);
1351
- }, [
1352
- copilotkit,
1353
- isGlobalConfig,
1354
- normalizedConfig,
1355
- targetAgentId
1356
- ]);
804
+ chatAgentId
805
+ };
1357
806
  (0, react.useEffect)(() => {
1358
- if (!serializedConfig || !latestConfigRef.current) return;
1359
- const id = copilotkit.addSuggestionsConfig(latestConfigRef.current);
1360
- requestReload();
807
+ const latest = latestRef.current;
808
+ const binding = (0, _copilotkit_core.ɵbindSuggestionsConfig)(copilotkit, latest.config, { chatAgentId: latest.chatAgentId });
809
+ bindingRef.current = binding;
1361
810
  return () => {
1362
- copilotkit.removeSuggestionsConfig(id);
811
+ binding.dispose();
812
+ if (bindingRef.current === binding) bindingRef.current = null;
1363
813
  };
1364
- }, [
1365
- copilotkit,
1366
- serializedConfig,
1367
- requestReload
1368
- ]);
814
+ }, [copilotkit]);
1369
815
  (0, react.useEffect)(() => {
1370
- if (!normalizedConfig) {
1371
- previousSerializedConfigRef.current = null;
816
+ bindingRef.current?.update(config, { chatAgentId });
817
+ }, [config, chatAgentId]);
818
+ const depsMountedRef = (0, react.useRef)(false);
819
+ (0, react.useEffect)(() => {
820
+ if (!depsMountedRef.current) {
821
+ depsMountedRef.current = true;
1372
822
  return;
1373
823
  }
1374
- if (serializedConfig && previousSerializedConfigRef.current === serializedConfig) return;
1375
- if (serializedConfig) previousSerializedConfigRef.current = serializedConfig;
1376
- requestReload();
1377
- }, [
1378
- normalizedConfig,
1379
- requestReload,
1380
- serializedConfig
1381
- ]);
1382
- (0, react.useEffect)(() => {
1383
- if (!normalizedConfig || extraDeps.length === 0) return;
1384
- requestReload();
1385
- }, [
1386
- extraDeps.length,
1387
- normalizedConfig,
1388
- requestReload,
1389
- ...extraDeps
1390
- ]);
1391
- (0, react.useEffect)(() => {
1392
- if (!normalizedConfig || !isDynamicConfigType) return;
1393
- if (!targetAgentId) return;
1394
- if (!!copilotkit.getAgent(targetAgentId)) return;
1395
- const subscription = copilotkit.subscribe({ onAgentsChanged: () => {
1396
- if (copilotkit.getAgent(targetAgentId)) {
1397
- requestReload();
1398
- subscription.unsubscribe();
1399
- }
1400
- } });
1401
- return () => {
1402
- subscription.unsubscribe();
1403
- };
1404
- }, [
1405
- copilotkit,
1406
- normalizedConfig,
1407
- isDynamicConfigType,
1408
- targetAgentId,
1409
- requestReload
1410
- ]);
1411
- }
1412
- function isDynamicConfig(config) {
1413
- return "instructions" in config;
1414
- }
1415
- function normalizeStaticSuggestions(suggestions) {
1416
- return suggestions.map((suggestion) => ({
1417
- ...suggestion,
1418
- isLoading: suggestion.isLoading ?? false
1419
- }));
824
+ if (extraDeps.length > 0) bindingRef.current?.reload();
825
+ }, [extraDeps.length, ...extraDeps]);
1420
826
  }
1421
827
 
1422
828
  //#endregion
@@ -1424,10 +830,7 @@ function normalizeStaticSuggestions(suggestions) {
1424
830
  function useAgentContext(context) {
1425
831
  const { description, value } = context;
1426
832
  const { copilotkit } = (0, _copilotkit_react_core_context.useCopilotKit)();
1427
- const stringValue = (0, react.useMemo)(() => {
1428
- if (typeof value === "string") return value;
1429
- return JSON.stringify(value);
1430
- }, [value]);
833
+ const stringValue = (0, react.useMemo)(() => (0, _copilotkit_core.ɵserializeContextValue)(value), [value]);
1431
834
  (0, react.useLayoutEffect)(() => {
1432
835
  if (!copilotkit) return;
1433
836
  const id = copilotkit.addContext({
@@ -1446,12 +849,6 @@ function useAgentContext(context) {
1446
849
 
1447
850
  //#endregion
1448
851
  //#region src/hooks/use-threads.tsx
1449
- function useThreadStoreSelector(store, selector) {
1450
- return (0, react.useSyncExternalStore)((0, react.useCallback)((onStoreChange) => {
1451
- const subscription = store.select(selector).subscribe(onStoreChange);
1452
- return () => subscription.unsubscribe();
1453
- }, [store, selector]), () => selector(store.getState()), () => selector(store.getServerState()));
1454
- }
1455
852
  /**
1456
853
  * React hook for listing and managing CopilotKit Intelligence threads.
1457
854
  *
@@ -1495,117 +892,38 @@ function useThreadStoreSelector(store, selector) {
1495
892
  */
1496
893
  function useThreads({ agentId, includeArchived, limit, enabled = true }) {
1497
894
  const { copilotkit } = (0, _copilotkit_react_core_context.useCopilotKit)();
1498
- const [store] = (0, react.useState)(() => (0, _copilotkit_core.ɵcreateThreadStore)({ fetch: copilotkit.ɵruntimeFetch }));
1499
- const coreThreads = useThreadStoreSelector(store, _copilotkit_core.ɵselectThreads);
1500
- const threads = (0, react.useMemo)(() => coreThreads.map(({ id, agentId, name, archived, createdAt, updatedAt, lastRunAt }) => ({
1501
- id,
895
+ const [controller] = (0, react.useState)(() => new _copilotkit_core.ɵThreadsController((0, _copilotkit_core.ɵcreateThreadStore)({ fetch: copilotkit.ɵruntimeFetch }), {
896
+ core: copilotkit,
1502
897
  agentId,
1503
- name,
1504
- archived,
1505
- createdAt,
1506
- updatedAt,
1507
- ...lastRunAt !== void 0 ? { lastRunAt } : {}
1508
- })), [coreThreads]);
1509
- const storeIsLoading = useThreadStoreSelector(store, _copilotkit_core.ɵselectThreadsIsLoading);
1510
- const storeError = useThreadStoreSelector(store, _copilotkit_core.ɵselectThreadsError);
1511
- const fetchMoreError = useThreadStoreSelector(store, _copilotkit_core.ɵselectFetchMoreError);
1512
- const hasMoreThreads = useThreadStoreSelector(store, _copilotkit_core.ɵselectHasNextPage);
1513
- const isFetchingMoreThreads = useThreadStoreSelector(store, _copilotkit_core.ɵselectIsFetchingNextPage);
1514
- const isMutating = useThreadStoreSelector(store, _copilotkit_core.ɵselectIsMutating);
1515
- const headersKey = copilotkit.ɵheadersGeneration;
1516
- const runtimeStatus = copilotkit.runtimeConnectionStatus;
1517
- const threadListEndpointSupported = copilotkit.threadEndpoints?.list !== false;
1518
- const threadMutationsSupported = copilotkit.threadEndpoints?.mutations !== false;
1519
- const threadEndpointsUnavailable = !!copilotkit.runtimeUrl && runtimeStatus === _copilotkit_core.CopilotKitCoreRuntimeConnectionStatus.Connected && !threadListEndpointSupported;
1520
- const runtimeError = (0, react.useMemo)(() => {
1521
- if (copilotkit.runtimeUrl) return null;
1522
- return /* @__PURE__ */ new Error("Runtime URL is not configured");
1523
- }, [copilotkit.runtimeUrl]);
1524
- const threadEndpointsError = (0, react.useMemo)(() => {
1525
- if (!threadEndpointsUnavailable) return null;
1526
- return /* @__PURE__ */ new Error("Thread endpoints are not available on this CopilotKit runtime");
1527
- }, [threadEndpointsUnavailable]);
1528
- const threadMutationsError = (0, react.useMemo)(() => {
1529
- if (threadMutationsSupported) return null;
1530
- return /* @__PURE__ */ new Error("Thread mutations are not available on this CopilotKit runtime");
1531
- }, [threadMutationsSupported]);
1532
- const [hasDispatchedContext, setHasDispatchedContext] = (0, react.useState)(false);
1533
- const preConnectLoading = enabled && !!copilotkit.runtimeUrl && !threadEndpointsUnavailable && !hasDispatchedContext;
1534
- const [configErrorDismissed, setConfigErrorDismissed] = (0, react.useState)(false);
1535
- (0, react.useEffect)(() => {
1536
- setConfigErrorDismissed(false);
1537
- }, [runtimeError, threadEndpointsError]);
1538
- const activeRuntimeError = configErrorDismissed ? null : runtimeError;
1539
- const activeThreadEndpointsError = configErrorDismissed ? null : threadEndpointsError;
1540
- const isLoading = activeRuntimeError || activeThreadEndpointsError ? false : preConnectLoading || storeIsLoading;
1541
- const error = activeRuntimeError ?? activeThreadEndpointsError ?? storeError;
1542
- const listError = storeError;
1543
- (0, react.useEffect)(() => {
1544
- store.start();
1545
- return () => {
1546
- store.stop();
1547
- };
1548
- }, [store]);
1549
- (0, react.useEffect)(() => {
1550
- if (!enabled) return;
1551
- copilotkit.registerThreadStore(agentId, store);
1552
- return () => {
1553
- copilotkit.unregisterThreadStore(agentId);
1554
- };
1555
- }, [
1556
- copilotkit,
1557
- agentId,
1558
- store,
898
+ includeArchived,
899
+ limit,
1559
900
  enabled
1560
- ]);
901
+ }));
902
+ const { threads, isLoading, error, listError, fetchMoreError, hasMoreThreads, isFetchingMoreThreads, isMutating } = (0, react.useSyncExternalStore)(controller.subscribe, controller.getSnapshot, controller.getServerSnapshot);
903
+ (0, react.useEffect)(() => controller.start(), [controller]);
1561
904
  (0, react.useEffect)(() => {
1562
- if (!enabled) {
1563
- store.setContext(null);
1564
- setHasDispatchedContext(false);
1565
- return;
1566
- }
1567
- if (!copilotkit.runtimeUrl) {
1568
- store.setContext(null);
1569
- setHasDispatchedContext(false);
1570
- return;
1571
- }
1572
- if (runtimeStatus !== _copilotkit_core.CopilotKitCoreRuntimeConnectionStatus.Connected) return;
1573
- if (!threadListEndpointSupported) {
1574
- store.setContext(null);
1575
- setHasDispatchedContext(false);
1576
- return;
1577
- }
1578
- const context = {
1579
- runtimeUrl: copilotkit.runtimeUrl,
1580
- wsUrl: copilotkit.intelligence?.wsUrl,
905
+ controller.update({
906
+ core: copilotkit,
1581
907
  agentId,
1582
908
  includeArchived,
1583
- limit
1584
- };
1585
- store.setContext(context);
1586
- setHasDispatchedContext(true);
909
+ limit,
910
+ enabled
911
+ });
1587
912
  }, [
1588
- store,
913
+ controller,
914
+ copilotkit,
915
+ agentId,
916
+ includeArchived,
917
+ limit,
1589
918
  enabled,
1590
919
  copilotkit.runtimeUrl,
1591
- runtimeStatus,
1592
- headersKey,
920
+ copilotkit.runtimeConnectionStatus,
921
+ copilotkit.ɵheadersGeneration,
1593
922
  copilotkit.intelligence?.wsUrl,
1594
- threadListEndpointSupported,
1595
- agentId,
1596
- includeArchived,
1597
- limit
923
+ copilotkit.threadEndpoints?.list,
924
+ copilotkit.threadEndpoints?.mutations
1598
925
  ]);
1599
- const guardMutation = (0, react.useCallback)((mutation) => {
1600
- return (...args) => {
1601
- if (threadMutationsError) return Promise.reject(threadMutationsError);
1602
- return mutation(...args);
1603
- };
1604
- }, [threadMutationsError]);
1605
- const renameThread = (0, react.useMemo)(() => guardMutation((threadId, name) => store.renameThread(threadId, name)), [store, guardMutation]);
1606
- const archiveThread = (0, react.useMemo)(() => guardMutation((threadId) => store.archiveThread(threadId)), [store, guardMutation]);
1607
- const unarchiveThread = (0, react.useMemo)(() => guardMutation((threadId) => store.unarchiveThread(threadId)), [store, guardMutation]);
1608
- const deleteThread = (0, react.useMemo)(() => guardMutation((threadId) => store.deleteThread(threadId)), [store, guardMutation]);
926
+ const { fetchMoreThreads, refetchThreads, startNewThread, renameThread, archiveThread, unarchiveThread, deleteThread } = controller;
1609
927
  return {
1610
928
  threads,
1611
929
  isLoading,
@@ -1615,12 +933,9 @@ function useThreads({ agentId, includeArchived, limit, enabled = true }) {
1615
933
  hasMoreThreads,
1616
934
  isFetchingMoreThreads,
1617
935
  isMutating,
1618
- fetchMoreThreads: (0, react.useCallback)(() => store.fetchNextPage(), [store]),
1619
- refetchThreads: (0, react.useCallback)(() => store.refetchThreads(), [store]),
1620
- startNewThread: (0, react.useCallback)(() => {
1621
- setConfigErrorDismissed(true);
1622
- store.startNewThread();
1623
- }, [store]),
936
+ fetchMoreThreads,
937
+ refetchThreads,
938
+ startNewThread,
1624
939
  renameThread,
1625
940
  archiveThread,
1626
941
  unarchiveThread,
@@ -1733,29 +1048,11 @@ function useRenderTool(config, deps) {
1733
1048
  * but the tool call data hasn't changed.
1734
1049
  */
1735
1050
  const ToolCallRenderer = react.default.memo(function ToolCallRenderer({ toolCall, toolMessage, RenderComponent, isExecuting }) {
1736
- const args = (0, react.useMemo)(() => (0, _copilotkit_shared.partialJSONParse)(toolCall.function.arguments), [toolCall.function.arguments]);
1737
- const toolName = toolCall.function.name;
1738
- if (toolMessage) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(RenderComponent, {
1739
- name: toolName,
1740
- toolCallId: toolCall.id,
1741
- args,
1742
- status: _copilotkit_core.ToolCallStatus.Complete,
1743
- result: (0, _ag_ui_core.contentToText)(toolMessage.content)
1744
- });
1745
- else if (isExecuting) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(RenderComponent, {
1746
- name: toolName,
1747
- toolCallId: toolCall.id,
1748
- args,
1749
- status: _copilotkit_core.ToolCallStatus.Executing,
1750
- result: void 0
1751
- });
1752
- else return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(RenderComponent, {
1753
- name: toolName,
1754
- toolCallId: toolCall.id,
1755
- args,
1756
- status: _copilotkit_core.ToolCallStatus.InProgress,
1757
- result: void 0
1758
- });
1051
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(RenderComponent, { ...(0, react.useMemo)(() => (0, _copilotkit_core.ɵbuildToolCallRenderProps)(toolCall, toolMessage, { isExecuting }), [
1052
+ toolCall,
1053
+ toolMessage,
1054
+ isExecuting
1055
+ ]) });
1759
1056
  }, (prevProps, nextProps) => {
1760
1057
  if (prevProps.toolCall.id !== nextProps.toolCall.id) return false;
1761
1058
  if (prevProps.toolCall.function.name !== nextProps.toolCall.function.name) return false;
@@ -1767,25 +1064,21 @@ const ToolCallRenderer = react.default.memo(function ToolCallRenderer({ toolCall
1767
1064
  });
1768
1065
  const IS_DEVELOPMENT = process.env.NODE_ENV !== "production";
1769
1066
  /**
1770
- * Reports tool calls that resolved to no renderer.
1067
+ * Reports tool calls that resolved to no renderer, once per tool name.
1771
1068
  *
1772
1069
  * A tool call with no renderer paints an empty message container and says
1773
1070
  * nothing else, so the only signal a developer gets today is a blank space in
1774
- * the chat. This names the call and the renderers that *are* registered, which
1775
- * is the whole diagnosis when the cause is a name that does not match.
1071
+ * the chat.
1776
1072
  *
1777
1073
  * @param toolNames - The unmatched tool names collected during render.
1778
1074
  * @param registered - The registry as it stands now, re-read at report time.
1779
1075
  * @param alreadyWarned - Names already reported, mutated to keep this once per name.
1780
1076
  */
1781
1077
  function warnAboutUnrenderedToolCalls(toolNames, registered, alreadyWarned) {
1782
- const registeredNames = Array.from(new Set(registered.map((rc) => rc.name)));
1783
- const hasWildcard = registeredNames.includes("*");
1784
- for (const toolName of toolNames) {
1785
- if (hasWildcard || registeredNames.includes(toolName)) continue;
1786
- if (alreadyWarned.has(toolName)) continue;
1078
+ const warnings = (0, _copilotkit_core.ɵdescribeUnrenderedToolCalls)(toolNames.filter((name) => !alreadyWarned.has(name)), registered);
1079
+ for (const { toolName, message } of warnings) {
1787
1080
  alreadyWarned.add(toolName);
1788
- console.warn(`[CopilotKit] The agent called the tool "${toolName}", and no renderer is registered for it, so that message rendered nothing. ` + (registeredNames.length === 0 ? "No tool-call renderers are registered. " : `Registered renderers: ${registeredNames.map((name) => `"${name}"`).join(", ")}. `) + `Register one with useRenderTool({ name: "${toolName}", ... }), or call useDefaultRenderTool() for a built-in card that covers every tool the agent calls. This warning is development-only.`);
1081
+ console.warn(message);
1789
1082
  }
1790
1083
  }
1791
1084
  /**
@@ -1804,7 +1097,7 @@ function useToolCallRenderers() {
1804
1097
  */
1805
1098
  function useRenderToolCall() {
1806
1099
  const { copilotkit, executingToolCallIds } = (0, _copilotkit_react_core_context.useCopilotKit)();
1807
- const agentId = useCopilotChatConfiguration()?.agentId ?? _copilotkit_shared.DEFAULT_AGENT_ID;
1100
+ const agentId = (0, _copilotkit_core.ɵresolveToolCallAgentId)(useCopilotChatConfiguration()?.agentId, void 0);
1808
1101
  const unrenderedToolNames = (0, react.useRef)(/* @__PURE__ */ new Set());
1809
1102
  const warnedToolNames = (0, react.useRef)(/* @__PURE__ */ new Set());
1810
1103
  const renderToolCalls = useToolCallRenderers();
@@ -1856,7 +1149,7 @@ function useRenderToolCall() {
1856
1149
  */
1857
1150
  function useCapabilities(agentId) {
1858
1151
  const { agent } = useAgent({ agentId });
1859
- if (agent && "capabilities" in agent) return agent.capabilities;
1152
+ return (0, _copilotkit_core.ɵgetAgentCapabilities)(agent);
1860
1153
  }
1861
1154
 
1862
1155
  //#endregion
@@ -1895,4 +1188,5 @@ exports.useRenderTool = useRenderTool;
1895
1188
  exports.useRenderToolCall = useRenderToolCall;
1896
1189
  exports.useSuggestions = useSuggestions;
1897
1190
  exports.useThreads = useThreads;
1191
+ exports.ɵuseOwnedCore = ɵuseOwnedCore;
1898
1192
  //# sourceMappingURL=headless.cjs.map