@copilotkit/react-core 1.62.1 → 1.62.2-canary.1784333495

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.
@@ -3650,12 +3650,13 @@ const CopilotKitProvider = ({ children, runtimeUrl, headers: headersProp = EMPTY
3650
3650
  }
3651
3651
  const copilotkit = copilotkitRef.current;
3652
3652
  (0, react.useEffect)(() => {
3653
- setRuntimeA2UIEnabled(copilotkit.a2uiEnabled);
3654
- const subscription = copilotkit.subscribe({ onRuntimeConnectionStatusChanged: () => {
3653
+ const syncRuntimeInfo = () => {
3655
3654
  setRuntimeA2UIEnabled(copilotkit.a2uiEnabled);
3656
3655
  setRuntimeOpenGenUIEnabled(copilotkit.openGenerativeUIEnabled);
3657
3656
  setRuntimeLicenseStatus(copilotkit.licenseStatus);
3658
- } });
3657
+ };
3658
+ const subscription = copilotkit.subscribe({ onRuntimeConnectionStatusChanged: syncRuntimeInfo });
3659
+ syncRuntimeInfo();
3659
3660
  return () => {
3660
3661
  subscription.unsubscribe();
3661
3662
  };
@@ -4381,57 +4382,58 @@ const ALL_UPDATES = [
4381
4382
  UseAgentUpdate.OnRunStatusChanged
4382
4383
  ];
4383
4384
  function useAgent({ agentId, updates, throttleMs } = {}) {
4384
- agentId ??= _copilotkit_shared.DEFAULT_AGENT_ID;
4385
+ const chatConfig = useCopilotChatConfiguration();
4386
+ const resolvedAgentId = agentId ?? chatConfig?.agentId ?? _copilotkit_shared.DEFAULT_AGENT_ID;
4385
4387
  const { copilotkit } = useCopilotKit();
4386
4388
  const providerThrottleMs = copilotkit.defaultThrottleMs;
4387
4389
  const [, forceUpdate] = (0, react.useReducer)((x) => x + 1, 0);
4388
4390
  const updateFlags = (0, react.useMemo)(() => updates ?? ALL_UPDATES, [JSON.stringify(updates)]);
4389
4391
  const provisionalAgentCache = (0, react.useRef)(/* @__PURE__ */ new Map());
4390
4392
  const agent = (0, react.useMemo)(() => {
4391
- const existing = copilotkit.getAgent(agentId);
4393
+ const existing = copilotkit.getAgent(resolvedAgentId);
4392
4394
  if (existing) {
4393
- provisionalAgentCache.current.delete(agentId);
4395
+ provisionalAgentCache.current.delete(resolvedAgentId);
4394
4396
  return existing;
4395
4397
  }
4396
4398
  const isRuntimeConfigured = copilotkit.runtimeUrl !== void 0;
4397
4399
  const status = copilotkit.runtimeConnectionStatus;
4398
4400
  if (isRuntimeConfigured && (status === _copilotkit_core.CopilotKitCoreRuntimeConnectionStatus.Disconnected || status === _copilotkit_core.CopilotKitCoreRuntimeConnectionStatus.Connecting)) {
4399
- const cached = provisionalAgentCache.current.get(agentId);
4401
+ const cached = provisionalAgentCache.current.get(resolvedAgentId);
4400
4402
  if (cached) {
4401
4403
  copilotkit.applyHeadersToAgent(cached);
4402
4404
  return cached;
4403
4405
  }
4404
4406
  const provisional = new _copilotkit_core.ProxiedCopilotRuntimeAgent({
4405
4407
  runtimeUrl: copilotkit.runtimeUrl,
4406
- agentId,
4408
+ agentId: resolvedAgentId,
4407
4409
  transport: copilotkit.runtimeTransport,
4408
4410
  runtimeMode: "pending"
4409
4411
  });
4410
4412
  copilotkit.applyHeadersToAgent(provisional);
4411
- provisionalAgentCache.current.set(agentId, provisional);
4413
+ provisionalAgentCache.current.set(resolvedAgentId, provisional);
4412
4414
  return provisional;
4413
4415
  }
4414
4416
  if (isRuntimeConfigured && status === _copilotkit_core.CopilotKitCoreRuntimeConnectionStatus.Error) {
4415
- const cached = provisionalAgentCache.current.get(agentId);
4417
+ const cached = provisionalAgentCache.current.get(resolvedAgentId);
4416
4418
  if (cached) {
4417
4419
  copilotkit.applyHeadersToAgent(cached);
4418
4420
  return cached;
4419
4421
  }
4420
4422
  const provisional = new _copilotkit_core.ProxiedCopilotRuntimeAgent({
4421
4423
  runtimeUrl: copilotkit.runtimeUrl,
4422
- agentId,
4424
+ agentId: resolvedAgentId,
4423
4425
  transport: copilotkit.runtimeTransport,
4424
4426
  runtimeMode: "pending"
4425
4427
  });
4426
4428
  copilotkit.applyHeadersToAgent(provisional);
4427
- provisionalAgentCache.current.set(agentId, provisional);
4429
+ provisionalAgentCache.current.set(resolvedAgentId, provisional);
4428
4430
  return provisional;
4429
4431
  }
4430
4432
  const knownAgents = Object.keys(copilotkit.agents ?? {});
4431
4433
  const runtimePart = isRuntimeConfigured ? `runtimeUrl=${copilotkit.runtimeUrl}` : "no runtimeUrl";
4432
- throw new Error(`useAgent: Agent '${agentId}' not found after runtime sync (${runtimePart}). ` + (knownAgents.length ? `Known agents: [${knownAgents.join(", ")}]` : "No agents registered.") + " Verify your runtime /info and/or agents__unsafe_dev_only.");
4434
+ 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.");
4433
4435
  }, [
4434
- agentId,
4436
+ resolvedAgentId,
4435
4437
  copilotkit.agents,
4436
4438
  copilotkit.runtimeConnectionStatus,
4437
4439
  copilotkit.runtimeUrl,
@@ -4476,7 +4478,6 @@ function useAgent({ agentId, updates, throttleMs } = {}) {
4476
4478
  (0, react.useEffect)(() => {
4477
4479
  if (agent instanceof _ag_ui_client.HttpAgent) copilotkit.applyHeadersToAgent(agent);
4478
4480
  }, [agent, JSON.stringify(copilotkit.headers)]);
4479
- const chatConfig = useCopilotChatConfiguration();
4480
4481
  const configThreadId = chatConfig?.threadId;
4481
4482
  const configHasExplicitThreadId = chatConfig?.hasExplicitThreadId;
4482
4483
  (0, react.useEffect)(() => {
@@ -4490,16 +4491,87 @@ function useAgent({ agentId, updates, throttleMs } = {}) {
4490
4491
  return { agent };
4491
4492
  }
4492
4493
 
4494
+ //#endregion
4495
+ //#region src/v2/hooks/use-subagent.tsx
4496
+ const warnedAmbiguousNames = /* @__PURE__ */ new Set();
4497
+ function resolveSubagent(subagents, subagentId, subagentName) {
4498
+ if (subagentId) {
4499
+ const match = subagents[subagentId];
4500
+ return match ? { ...match } : void 0;
4501
+ }
4502
+ if (subagentName) {
4503
+ const matches = Object.values(subagents).filter((s) => s.name === subagentName);
4504
+ if (matches.length === 0) return;
4505
+ const chosen = matches[matches.length - 1];
4506
+ return matches.length > 1 ? {
4507
+ ...chosen,
4508
+ isAmbiguous: true,
4509
+ matchCount: matches.length
4510
+ } : { ...chosen };
4511
+ }
4512
+ }
4513
+ /**
4514
+ * Read a subagent's live lifecycle state (name, description, running status)
4515
+ * from the CopilotKit core subagent registry, by id or by declared name.
4516
+ *
4517
+ * @example
4518
+ * const sub = useSubagent({ subagentId: message.subagentId });
4519
+ * // sub?.name, sub?.description, sub?.status
4520
+ */
4521
+ function useSubagent(params) {
4522
+ const { subagentId, subagentName, agentId } = params;
4523
+ const { copilotkit } = useCopilotKit();
4524
+ const config = useCopilotChatConfiguration();
4525
+ const resolvedAgentId = (0, react.useMemo)(() => agentId ?? config?.agentId ?? _copilotkit_shared.DEFAULT_AGENT_ID, [agentId, config?.agentId]);
4526
+ const [subagent, setSubagent] = (0, react.useState)(() => resolveSubagent(copilotkit.getSubagents(resolvedAgentId), subagentId, subagentName));
4527
+ (0, react.useEffect)(() => {
4528
+ setSubagent(resolveSubagent(copilotkit.getSubagents(resolvedAgentId), subagentId, subagentName));
4529
+ }, [
4530
+ copilotkit,
4531
+ resolvedAgentId,
4532
+ subagentId,
4533
+ subagentName
4534
+ ]);
4535
+ (0, react.useEffect)(() => {
4536
+ const subscription = copilotkit.subscribe({ onSubagentsChanged: ({ agentId: changedAgentId, subagents }) => {
4537
+ if (changedAgentId !== resolvedAgentId) return;
4538
+ setSubagent(resolveSubagent(subagents, subagentId, subagentName));
4539
+ } });
4540
+ return () => {
4541
+ subscription.unsubscribe();
4542
+ };
4543
+ }, [
4544
+ copilotkit,
4545
+ resolvedAgentId,
4546
+ subagentId,
4547
+ subagentName
4548
+ ]);
4549
+ (0, react.useEffect)(() => {
4550
+ if (process.env.NODE_ENV === "production" || !subagentName || !subagent?.isAmbiguous) return;
4551
+ const key = `${subagentName}:${subagent.matchCount}`;
4552
+ if (warnedAmbiguousNames.has(key)) return;
4553
+ warnedAmbiguousNames.add(key);
4554
+ console.warn(`[CopilotKit] useSubagent({ subagentName: ${JSON.stringify(subagentName)} }) matched ${subagent.matchCount} subagents. Returning the most recently started one; pass a subagentId for a stable reference.`);
4555
+ }, [
4556
+ subagentName,
4557
+ subagent?.isAmbiguous,
4558
+ subagent?.matchCount
4559
+ ]);
4560
+ return subagent;
4561
+ }
4562
+
4493
4563
  //#endregion
4494
4564
  //#region src/v2/hooks/use-capabilities.tsx
4495
4565
  /**
4496
- * Returns the capabilities declared by the given agent (or the default agent).
4566
+ * Returns the capabilities declared by the given agent (or the agent resolved
4567
+ * from the surrounding chat configuration, falling back to the default agent).
4497
4568
  * Capabilities are populated from the runtime `/info` response at connection
4498
4569
  * time. The hook reads them synchronously from the agent instance — there is
4499
4570
  * no separate loading state, but the value will be `undefined` until the
4500
4571
  * runtime handshake completes.
4501
4572
  *
4502
- * @param agentId - Optional agent ID. If omitted, uses the default agent.
4573
+ * @param agentId - Optional agent ID. If omitted, inherits the surrounding
4574
+ * chat configuration's agent, falling back to the default agent.
4503
4575
  * @returns The agent's capabilities, or `undefined` if the agent doesn't
4504
4576
  * declare capabilities.
4505
4577
  */
@@ -5072,6 +5144,7 @@ function useThreads$1({ agentId, includeArchived, limit, enabled = true }) {
5072
5144
  })), [coreThreads]);
5073
5145
  const storeIsLoading = useThreadStoreSelector(store, _copilotkit_core.ɵselectThreadsIsLoading);
5074
5146
  const storeError = useThreadStoreSelector(store, _copilotkit_core.ɵselectThreadsError);
5147
+ const fetchMoreError = useThreadStoreSelector(store, _copilotkit_core.ɵselectFetchMoreError);
5075
5148
  const hasMoreThreads = useThreadStoreSelector(store, _copilotkit_core.ɵselectHasNextPage);
5076
5149
  const isFetchingMoreThreads = useThreadStoreSelector(store, _copilotkit_core.ɵselectIsFetchingNextPage);
5077
5150
  const isMutating = useThreadStoreSelector(store, _copilotkit_core.ɵselectIsMutating);
@@ -5177,6 +5250,7 @@ function useThreads$1({ agentId, includeArchived, limit, enabled = true }) {
5177
5250
  isLoading,
5178
5251
  error,
5179
5252
  listError,
5253
+ fetchMoreError,
5180
5254
  hasMoreThreads,
5181
5255
  isFetchingMoreThreads,
5182
5256
  isMutating,
@@ -5193,6 +5267,70 @@ function useThreads$1({ agentId, includeArchived, limit, enabled = true }) {
5193
5267
  };
5194
5268
  }
5195
5269
 
5270
+ //#endregion
5271
+ //#region src/v2/hooks/use-memories.tsx
5272
+ function useMemoryStoreSelector(store, selector) {
5273
+ return (0, react.useSyncExternalStore)((0, react.useCallback)((onStoreChange) => {
5274
+ const subscription = store.select(selector).subscribe(onStoreChange);
5275
+ return () => subscription.unsubscribe();
5276
+ }, [store, selector]), () => selector(store.getState()), () => selector(store.getServerState()));
5277
+ }
5278
+ /**
5279
+ * React hook for listing and managing platform memories.
5280
+ *
5281
+ * Reads the memory store owned and wired by `CopilotKitCore`. On mount the
5282
+ * hook exposes the live list plus stable `addMemory` / `updateMemory` /
5283
+ * `removeMemory` / `refresh` callbacks. Mutations are server-authoritative:
5284
+ * each resolves once the platform confirms the operation and rejects with an
5285
+ * `Error` on failure.
5286
+ *
5287
+ * Realtime updates are automatic: the core's memory store opens its own
5288
+ * `user_meta:memories:<joinCode>` channel and applies `memory_metadata` deltas
5289
+ * to the list. You can still call `refresh()` to re-pull the REST snapshot on
5290
+ * demand.
5291
+ *
5292
+ * @returns Memory list state and stable mutation callbacks.
5293
+ *
5294
+ * @example
5295
+ * ```tsx
5296
+ * import { useMemories } from "@copilotkit/react-core";
5297
+ *
5298
+ * function MemoryList() {
5299
+ * const { memories, isLoading, isAvailable, addMemory, removeMemory } =
5300
+ * useMemories();
5301
+ *
5302
+ * if (!isAvailable) return null;
5303
+ * if (isLoading) return <p>Loading…</p>;
5304
+ *
5305
+ * return (
5306
+ * <ul>
5307
+ * {memories.map((m) => (
5308
+ * <li key={m.id}>
5309
+ * {m.content}
5310
+ * <button onClick={() => removeMemory(m.id)}>Delete</button>
5311
+ * </li>
5312
+ * ))}
5313
+ * </ul>
5314
+ * );
5315
+ * }
5316
+ * ```
5317
+ */
5318
+ function useMemories() {
5319
+ const { copilotkit } = useCopilotKit();
5320
+ const store = copilotkit.getMemoryStore();
5321
+ return {
5322
+ memories: useMemoryStoreSelector(store, _copilotkit_core.ɵselectMemories),
5323
+ isLoading: useMemoryStoreSelector(store, _copilotkit_core.ɵselectMemoriesIsLoading),
5324
+ error: useMemoryStoreSelector(store, _copilotkit_core.ɵselectMemoriesError),
5325
+ isAvailable: useMemoryStoreSelector(store, _copilotkit_core.ɵselectMemoriesAvailable),
5326
+ realtimeStatus: useMemoryStoreSelector(store, _copilotkit_core.ɵselectMemoriesRealtimeStatus),
5327
+ refresh: (0, react.useCallback)(() => store.refresh(), [store]),
5328
+ addMemory: (0, react.useCallback)((input) => store.addMemory(input), [store]),
5329
+ updateMemory: (0, react.useCallback)((id, changes) => store.updateMemory(id, changes), [store]),
5330
+ removeMemory: (0, react.useCallback)((id) => store.removeMemory(id), [store])
5331
+ };
5332
+ }
5333
+
5196
5334
  //#endregion
5197
5335
  //#region src/v2/lib/record-annotation.ts
5198
5336
  /**
@@ -7955,9 +8093,57 @@ function CopilotChat({ agentId, threadId, labels, chatView, isModalDefaultOpen,
7955
8093
  const { messageView: providedMessageView, suggestionView: providedSuggestionView, onStop: providedStopHandler, ...restProps } = props;
7956
8094
  const [lastConnectedThreadId, setLastConnectedThreadId] = (0, react.useState)(null);
7957
8095
  const isConnecting = hasExplicitThreadId && lastConnectedThreadId !== resolvedThreadId;
8096
+ const activeConnectCountRef = (0, react.useRef)(0);
8097
+ const pendingRunActivityReconnectRef = (0, react.useRef)(false);
8098
+ const runActivityReconnectGenerationRef = (0, react.useRef)(0);
8099
+ const activeLocalRunIdsRef = (0, react.useRef)(/* @__PURE__ */ new Set());
8100
+ const recentlyLocalRunIdsRef = (0, react.useRef)(/* @__PURE__ */ new Map());
8101
+ const activeWakeRunIdsRef = (0, react.useRef)(/* @__PURE__ */ new Set());
8102
+ const recentlyWakeRunIdsRef = (0, react.useRef)(/* @__PURE__ */ new Map());
8103
+ const pendingWakeRunIdRef = (0, react.useRef)(void 0);
8104
+ const startRunActivityReconnectRef = (0, react.useRef)(null);
8105
+ const runtimeStatus = copilotkit.runtimeConnectionStatus === _copilotkit_core.CopilotKitCoreRuntimeConnectionStatus.Connected ? "Connected" : copilotkit.runtimeConnectionStatus;
8106
+ const hasNativeIntelligenceRunActivity = hasExplicitThreadId && runtimeStatus === "Connected" && !!copilotkit.intelligence?.wsUrl && copilotkit.threadEndpoints?.realtimeMetadata === true;
8107
+ const [standaloneRunActivityStore] = (0, react.useState)(() => (0, _copilotkit_core.ɵcreateThreadStore)({ fetch: globalThis.fetch }));
7958
8108
  const previousThreadIdRef = (0, react.useRef)(null);
7959
8109
  const hasExplicitThreadIdRef = (0, react.useRef)(hasExplicitThreadId);
7960
8110
  hasExplicitThreadIdRef.current = hasExplicitThreadId;
8111
+ const rememberRecentlyLocalRunId = (0, react.useCallback)((runId) => {
8112
+ const existingTimeout = recentlyLocalRunIdsRef.current.get(runId);
8113
+ if (existingTimeout) clearTimeout(existingTimeout);
8114
+ const timeout = setTimeout(() => {
8115
+ recentlyLocalRunIdsRef.current.delete(runId);
8116
+ }, 3e4);
8117
+ recentlyLocalRunIdsRef.current.set(runId, timeout);
8118
+ }, []);
8119
+ const rememberRecentlyWakeRunId = (0, react.useCallback)((runId) => {
8120
+ const existingTimeout = recentlyWakeRunIdsRef.current.get(runId);
8121
+ if (existingTimeout) clearTimeout(existingTimeout);
8122
+ const timeout = setTimeout(() => {
8123
+ recentlyWakeRunIdsRef.current.delete(runId);
8124
+ }, 3e4);
8125
+ recentlyWakeRunIdsRef.current.set(runId, timeout);
8126
+ }, []);
8127
+ const isLocalActiveRunActivity = (0, react.useCallback)((notification) => {
8128
+ if (notification.agentId && notification.agentId !== resolvedAgentId) return false;
8129
+ if (!notification.runId || !activeLocalRunIdsRef.current.has(notification.runId) && !recentlyLocalRunIdsRef.current.has(notification.runId)) return false;
8130
+ const eventType = notification.eventType.toUpperCase();
8131
+ return eventType === "RUN_STARTED" || eventType === "RUN_FINISHED" || eventType === "RUN_ERROR";
8132
+ }, [resolvedAgentId]);
8133
+ (0, react.useEffect)(() => {
8134
+ const recentlyLocalRunIds = recentlyLocalRunIdsRef.current;
8135
+ const recentlyWakeRunIds = recentlyWakeRunIdsRef.current;
8136
+ return () => {
8137
+ recentlyLocalRunIds.forEach((timeout) => {
8138
+ clearTimeout(timeout);
8139
+ });
8140
+ recentlyLocalRunIds.clear();
8141
+ recentlyWakeRunIds.forEach((timeout) => {
8142
+ clearTimeout(timeout);
8143
+ });
8144
+ recentlyWakeRunIds.clear();
8145
+ };
8146
+ }, []);
7961
8147
  (0, react.useEffect)(() => {
7962
8148
  const threadChanged = previousThreadIdRef.current !== resolvedThreadId;
7963
8149
  previousThreadIdRef.current = resolvedThreadId;
@@ -7970,6 +8156,7 @@ function CopilotChat({ agentId, threadId, labels, chatView, isModalDefaultOpen,
7970
8156
  const connectAbortController = new AbortController();
7971
8157
  if (agent instanceof _ag_ui_client.HttpAgent) agent.abortController = connectAbortController;
7972
8158
  const connect = async (agentToConnect) => {
8159
+ activeConnectCountRef.current += 1;
7973
8160
  try {
7974
8161
  await copilotkit.connectAgent({ agent: agentToConnect });
7975
8162
  } catch (error) {
@@ -7980,6 +8167,14 @@ function CopilotChat({ agentId, threadId, labels, chatView, isModalDefaultOpen,
7980
8167
  if (!detached) setLastConnectedThreadId(resolvedThreadId);
7981
8168
  });
7982
8169
  else if (!hasExplicitThreadIdRef.current) agentToConnect.setMessages([]);
8170
+ activeConnectCountRef.current = Math.max(0, activeConnectCountRef.current - 1);
8171
+ if (!detached && activeConnectCountRef.current === 0) {
8172
+ const startReconnect = startRunActivityReconnectRef.current;
8173
+ if (pendingRunActivityReconnectRef.current && startReconnect) {
8174
+ pendingRunActivityReconnectRef.current = false;
8175
+ startReconnect(runActivityReconnectGenerationRef.current);
8176
+ }
8177
+ }
7983
8178
  }
7984
8179
  };
7985
8180
  connect(agent);
@@ -7994,6 +8189,119 @@ function CopilotChat({ agentId, threadId, labels, chatView, isModalDefaultOpen,
7994
8189
  resolvedAgentId,
7995
8190
  hasExplicitThreadId
7996
8191
  ]);
8192
+ (0, react.useEffect)(() => {
8193
+ if (!hasNativeIntelligenceRunActivity) return;
8194
+ const registeredThreadStore = copilotkit.getThreadStore(resolvedAgentId);
8195
+ const threadStore = registeredThreadStore ?? standaloneRunActivityStore;
8196
+ if (!threadStore?.subscribeToRunActivity) return;
8197
+ const ownsStandaloneStore = registeredThreadStore === void 0;
8198
+ if (ownsStandaloneStore) {
8199
+ threadStore.start();
8200
+ const context = copilotkit.runtimeUrl ? {
8201
+ runtimeUrl: copilotkit.runtimeUrl,
8202
+ headers: { ...copilotkit.headers },
8203
+ wsUrl: copilotkit.intelligence?.wsUrl,
8204
+ agentId: resolvedAgentId
8205
+ } : null;
8206
+ threadStore.setContext(context);
8207
+ }
8208
+ const generation = runActivityReconnectGenerationRef.current + 1;
8209
+ runActivityReconnectGenerationRef.current = generation;
8210
+ let detached = false;
8211
+ let wakeReconnectActive = false;
8212
+ let pendingAgentIdleDrain = null;
8213
+ const hasActiveAgentRun = () => activeLocalRunIdsRef.current.size > 0 || agent.isRunning;
8214
+ const scheduleAgentIdleDrain = () => {
8215
+ if (pendingAgentIdleDrain !== null) return;
8216
+ pendingAgentIdleDrain = setTimeout(() => {
8217
+ pendingAgentIdleDrain = null;
8218
+ if (detached || runActivityReconnectGenerationRef.current !== generation || !pendingRunActivityReconnectRef.current) return;
8219
+ if (hasActiveAgentRun()) {
8220
+ scheduleAgentIdleDrain();
8221
+ return;
8222
+ }
8223
+ startRunActivityReconnectRef.current?.(generation);
8224
+ }, 10);
8225
+ };
8226
+ const connect = async () => {
8227
+ activeConnectCountRef.current += 1;
8228
+ wakeReconnectActive = true;
8229
+ const wakeRunId = pendingWakeRunIdRef.current;
8230
+ pendingWakeRunIdRef.current = void 0;
8231
+ if (wakeRunId) activeWakeRunIdsRef.current.add(wakeRunId);
8232
+ let didConnect = false;
8233
+ try {
8234
+ await copilotkit.connectAgent({ agent });
8235
+ didConnect = true;
8236
+ } catch (error) {
8237
+ if (!detached) console.error("CopilotChat: run activity reconnect failed", error);
8238
+ } finally {
8239
+ if (wakeRunId) {
8240
+ activeWakeRunIdsRef.current.delete(wakeRunId);
8241
+ if (didConnect) rememberRecentlyWakeRunId(wakeRunId);
8242
+ }
8243
+ activeConnectCountRef.current = Math.max(0, activeConnectCountRef.current - 1);
8244
+ wakeReconnectActive = false;
8245
+ if (!detached && runActivityReconnectGenerationRef.current === generation && activeConnectCountRef.current === 0 && pendingRunActivityReconnectRef.current) {
8246
+ pendingRunActivityReconnectRef.current = false;
8247
+ connect();
8248
+ }
8249
+ }
8250
+ };
8251
+ startRunActivityReconnectRef.current = (requestedGeneration) => {
8252
+ if (detached || requestedGeneration !== generation || runActivityReconnectGenerationRef.current !== generation) return;
8253
+ if (hasActiveAgentRun()) {
8254
+ pendingRunActivityReconnectRef.current = true;
8255
+ scheduleAgentIdleDrain();
8256
+ return;
8257
+ }
8258
+ if (activeConnectCountRef.current > 0) {
8259
+ if (!wakeReconnectActive) pendingRunActivityReconnectRef.current = true;
8260
+ return;
8261
+ }
8262
+ pendingRunActivityReconnectRef.current = false;
8263
+ connect();
8264
+ };
8265
+ const subscription = threadStore.subscribeToRunActivity((notification) => {
8266
+ if (notification.threadId !== resolvedThreadId) return;
8267
+ if (notification.agentId && notification.agentId !== resolvedAgentId) return;
8268
+ if (isLocalActiveRunActivity(notification)) return;
8269
+ if (notification.runId && (activeWakeRunIdsRef.current.has(notification.runId) || recentlyWakeRunIdsRef.current.has(notification.runId))) return;
8270
+ pendingWakeRunIdRef.current = notification.runId;
8271
+ startRunActivityReconnectRef.current?.(generation);
8272
+ });
8273
+ return () => {
8274
+ detached = true;
8275
+ pendingRunActivityReconnectRef.current = false;
8276
+ pendingWakeRunIdRef.current = void 0;
8277
+ if (pendingAgentIdleDrain !== null) {
8278
+ clearTimeout(pendingAgentIdleDrain);
8279
+ pendingAgentIdleDrain = null;
8280
+ }
8281
+ if (startRunActivityReconnectRef.current) startRunActivityReconnectRef.current = null;
8282
+ if (wakeReconnectActive) agent.detachActiveRun().catch(() => {});
8283
+ activeWakeRunIdsRef.current.clear();
8284
+ subscription.unsubscribe();
8285
+ if (ownsStandaloneStore) {
8286
+ threadStore.setContext(null);
8287
+ threadStore.stop();
8288
+ }
8289
+ };
8290
+ }, [
8291
+ agent,
8292
+ resolvedAgentId,
8293
+ resolvedThreadId,
8294
+ hasExplicitThreadId,
8295
+ hasNativeIntelligenceRunActivity,
8296
+ copilotkit.runtimeConnectionStatus,
8297
+ copilotkit.runtimeUrl,
8298
+ copilotkit.headers,
8299
+ copilotkit.intelligence?.wsUrl,
8300
+ copilotkit.threadEndpoints?.realtimeMetadata,
8301
+ standaloneRunActivityStore,
8302
+ isLocalActiveRunActivity,
8303
+ rememberRecentlyWakeRunId
8304
+ ]);
7997
8305
  const waitForActiveRunToSettle = (0, react.useCallback)(async () => {
7998
8306
  const maybeAware = agent;
7999
8307
  const activeRunCompletionPromise = (0, _copilotkit_core.isRunCompletionAware)(maybeAware) ? maybeAware.activeRunCompletionPromise : void 0;
@@ -8042,15 +8350,34 @@ function CopilotChat({ agentId, threadId, labels, chatView, isModalDefaultOpen,
8042
8350
  role: "user",
8043
8351
  content: value
8044
8352
  });
8353
+ const localRunId = hasNativeIntelligenceRunActivity ? (0, _copilotkit_shared.randomUUID)() : void 0;
8354
+ if (localRunId) activeLocalRunIdsRef.current.add(localRunId);
8045
8355
  try {
8046
- await copilotkit.runAgent({ agent });
8356
+ await copilotkit.runAgent({
8357
+ agent,
8358
+ ...localRunId !== void 0 ? { runId: localRunId } : {}
8359
+ });
8047
8360
  } catch (error) {
8048
8361
  console.error("CopilotChat: runAgent failed", error);
8362
+ } finally {
8363
+ if (localRunId) {
8364
+ activeLocalRunIdsRef.current.delete(localRunId);
8365
+ rememberRecentlyLocalRunId(localRunId);
8366
+ }
8367
+ if (pendingRunActivityReconnectRef.current && activeLocalRunIdsRef.current.size === 0 && activeConnectCountRef.current === 0) {
8368
+ const startReconnect = startRunActivityReconnectRef.current;
8369
+ if (startReconnect) {
8370
+ pendingRunActivityReconnectRef.current = false;
8371
+ startReconnect(runActivityReconnectGenerationRef.current);
8372
+ }
8373
+ }
8049
8374
  }
8050
8375
  }, [
8051
8376
  agent,
8052
8377
  consumeAttachments,
8053
- waitForActiveRunToSettle
8378
+ waitForActiveRunToSettle,
8379
+ hasNativeIntelligenceRunActivity,
8380
+ rememberRecentlyLocalRunId
8054
8381
  ]);
8055
8382
  const handleSelectSuggestion = (0, react.useCallback)(async (suggestion) => {
8056
8383
  await waitForActiveRunToSettle();
@@ -8059,12 +8386,34 @@ function CopilotChat({ agentId, threadId, labels, chatView, isModalDefaultOpen,
8059
8386
  role: "user",
8060
8387
  content: suggestion.message
8061
8388
  });
8389
+ const localRunId = hasNativeIntelligenceRunActivity ? (0, _copilotkit_shared.randomUUID)() : void 0;
8390
+ if (localRunId) activeLocalRunIdsRef.current.add(localRunId);
8062
8391
  try {
8063
- await copilotkit.runAgent({ agent });
8392
+ await copilotkit.runAgent({
8393
+ agent,
8394
+ ...localRunId !== void 0 ? { runId: localRunId } : {}
8395
+ });
8064
8396
  } catch (error) {
8065
8397
  console.error("CopilotChat: runAgent failed after selecting suggestion", error);
8398
+ } finally {
8399
+ if (localRunId) {
8400
+ activeLocalRunIdsRef.current.delete(localRunId);
8401
+ rememberRecentlyLocalRunId(localRunId);
8402
+ }
8403
+ if (pendingRunActivityReconnectRef.current && activeLocalRunIdsRef.current.size === 0 && activeConnectCountRef.current === 0) {
8404
+ const startReconnect = startRunActivityReconnectRef.current;
8405
+ if (startReconnect) {
8406
+ pendingRunActivityReconnectRef.current = false;
8407
+ startReconnect(runActivityReconnectGenerationRef.current);
8408
+ }
8409
+ }
8066
8410
  }
8067
- }, [agent, waitForActiveRunToSettle]);
8411
+ }, [
8412
+ agent,
8413
+ waitForActiveRunToSettle,
8414
+ hasNativeIntelligenceRunActivity,
8415
+ rememberRecentlyLocalRunId
8416
+ ]);
8068
8417
  const stopCurrentRun = (0, react.useCallback)(() => {
8069
8418
  try {
8070
8419
  copilotkit.stopAgent({ agent });
@@ -8843,7 +9192,7 @@ function findChatInput(origin) {
8843
9192
  * during prerender to avoid hydration mismatch).
8844
9193
  * - Feeds the element domain data: `threads`, `loading`, `error`,
8845
9194
  * `activeThreadId`, `licensed`, fetch-more state.
8846
- * - Routes the element's nine outbound events to core thread operations
9195
+ * - Routes the element's outbound events to core thread operations
8847
9196
  * ({@link useThreads}) and chat-configuration changes.
8848
9197
  * - Registers with the surrounding chat configuration so the header
8849
9198
  * thread-list launcher appears, and binds the element `open` state to the
@@ -8870,16 +9219,16 @@ function findChatInput(origin) {
8870
9219
  * </CopilotKitProvider>
8871
9220
  * ```
8872
9221
  */
8873
- function CopilotThreadsDrawer({ agentId, onThreadSelect, onNewThread, onLicensed, licenseUrl, renderRow, label, limit, "data-testid": dataTestId = "copilot-threads-drawer" }) {
9222
+ function CopilotThreadsDrawer({ agentId, onThreadSelect, onNewThread, onLicensed, licenseUrl, renderRow, label, recentLabel, collapsible, onCollapseChange, limit, "data-testid": dataTestId = "copilot-threads-drawer" }) {
8874
9223
  const configuration = useCopilotChatConfiguration();
8875
9224
  const { status, checkFeature } = useLicenseContext();
8876
9225
  const licensePresent = status === "valid" || status === "expiring";
8877
9226
  const featureLicensed = checkFeature("threads");
8878
9227
  const licensed = licensePresent && featureLicensed;
8879
9228
  const licensePending = status === null;
8880
- const resolvedAgentId = agentId ?? configuration?.agentId ?? "default";
9229
+ const resolvedAgentId = agentId ?? configuration?.agentId ?? _copilotkit_shared.DEFAULT_AGENT_ID;
8881
9230
  const activeThreadId = configuration?.threadId ?? null;
8882
- const { threads, isLoading, listError, hasMoreThreads, isFetchingMoreThreads, archiveThread, unarchiveThread, deleteThread, fetchMoreThreads, refetchThreads, startNewThread } = useThreads$1({
9231
+ const { threads, isLoading, listError, fetchMoreError, hasMoreThreads, isFetchingMoreThreads, archiveThread, unarchiveThread, deleteThread, fetchMoreThreads, refetchThreads, startNewThread } = useThreads$1({
8883
9232
  agentId: resolvedAgentId,
8884
9233
  includeArchived: true,
8885
9234
  enabled: licensed,
@@ -8960,6 +9309,9 @@ function CopilotThreadsDrawer({ agentId, onThreadSelect, onNewThread, onLicensed
8960
9309
  const handleLoadMore = (0, react.useCallback)(() => {
8961
9310
  fetchMoreThreads();
8962
9311
  }, [fetchMoreThreads]);
9312
+ const handleCollapseChange = (0, react.useCallback)((collapsed) => {
9313
+ onCollapseChange?.(collapsed);
9314
+ }, [onCollapseChange]);
8963
9315
  const handlersRef = (0, react.useRef)({
8964
9316
  handleThreadSelected,
8965
9317
  handleNewThread,
@@ -8970,7 +9322,8 @@ function CopilotThreadsDrawer({ agentId, onThreadSelect, onNewThread, onLicensed
8970
9322
  handleRetry,
8971
9323
  handleOpenChange,
8972
9324
  handleLicensed,
8973
- handleLoadMore
9325
+ handleLoadMore,
9326
+ handleCollapseChange
8974
9327
  });
8975
9328
  handlersRef.current = {
8976
9329
  handleThreadSelected,
@@ -8982,7 +9335,8 @@ function CopilotThreadsDrawer({ agentId, onThreadSelect, onNewThread, onLicensed
8982
9335
  handleRetry,
8983
9336
  handleOpenChange,
8984
9337
  handleLicensed,
8985
- handleLoadMore
9338
+ handleLoadMore,
9339
+ handleCollapseChange
8986
9340
  };
8987
9341
  (0, react.useEffect)(() => {
8988
9342
  const el = elementRef.current;
@@ -9017,6 +9371,10 @@ function CopilotThreadsDrawer({ agentId, onThreadSelect, onNewThread, onLicensed
9017
9371
  };
9018
9372
  const onLicensedEvent = () => handlersRef.current.handleLicensed();
9019
9373
  const onLoadMore = () => handlersRef.current.handleLoadMore();
9374
+ const onCollapseChangeEvent = (event) => {
9375
+ const detail = event.detail;
9376
+ handlersRef.current.handleCollapseChange(detail.collapsed);
9377
+ };
9020
9378
  el.addEventListener("thread-selected", onThreadSelected);
9021
9379
  el.addEventListener("new-thread", onNewThreadEvent);
9022
9380
  el.addEventListener("archive", onArchive);
@@ -9027,6 +9385,7 @@ function CopilotThreadsDrawer({ agentId, onThreadSelect, onNewThread, onLicensed
9027
9385
  el.addEventListener("retry", onRetry);
9028
9386
  el.addEventListener("licensed", onLicensedEvent);
9029
9387
  el.addEventListener("load-more", onLoadMore);
9388
+ el.addEventListener("collapse-change", onCollapseChangeEvent);
9030
9389
  return () => {
9031
9390
  el.removeEventListener("thread-selected", onThreadSelected);
9032
9391
  el.removeEventListener("new-thread", onNewThreadEvent);
@@ -9038,6 +9397,7 @@ function CopilotThreadsDrawer({ agentId, onThreadSelect, onNewThread, onLicensed
9038
9397
  el.removeEventListener("retry", onRetry);
9039
9398
  el.removeEventListener("licensed", onLicensedEvent);
9040
9399
  el.removeEventListener("load-more", onLoadMore);
9400
+ el.removeEventListener("collapse-change", onCollapseChangeEvent);
9041
9401
  };
9042
9402
  }, [mounted]);
9043
9403
  (0, react.useEffect)(() => {
@@ -9054,9 +9414,11 @@ function CopilotThreadsDrawer({ agentId, onThreadSelect, onNewThread, onLicensed
9054
9414
  el.licensed = licensed || licensePending;
9055
9415
  el.hasMore = hasMoreThreads;
9056
9416
  el.fetchingMore = isFetchingMoreThreads;
9417
+ el.fetchMoreError = fetchMoreError ? fetchMoreError.message : null;
9057
9418
  }, [
9058
9419
  isLoading,
9059
9420
  listError,
9421
+ fetchMoreError,
9060
9422
  activeThreadId,
9061
9423
  licensed,
9062
9424
  licensePending,
@@ -9079,6 +9441,11 @@ function CopilotThreadsDrawer({ agentId, onThreadSelect, onNewThread, onLicensed
9079
9441
  if (!el) return;
9080
9442
  if (licenseUrl !== void 0) el.licenseUrl = licenseUrl;
9081
9443
  }, [licenseUrl, mounted]);
9444
+ (0, react.useEffect)(() => {
9445
+ const el = elementRef.current;
9446
+ if (!el) return;
9447
+ if (collapsible !== void 0) el.collapsible = collapsible;
9448
+ }, [collapsible, mounted]);
9082
9449
  const rowChildren = (0, react.useMemo)(() => {
9083
9450
  if (!renderRow) return null;
9084
9451
  return drawerThreads.map((drawerThread) => {
@@ -9099,7 +9466,8 @@ function CopilotThreadsDrawer({ agentId, onThreadSelect, onNewThread, onLicensed
9099
9466
  if (!mounted) return null;
9100
9467
  return react.default.createElement(_copilotkit_web_components_threads_drawer.COPILOTKIT_THREADS_DRAWER_TAG, {
9101
9468
  ref: elementRef,
9102
- "data-testid": dataTestId
9469
+ "data-testid": dataTestId,
9470
+ ...recentLabel !== void 0 ? { "recent-label": recentLabel } : {}
9103
9471
  }, rowChildren);
9104
9472
  }
9105
9473
  CopilotThreadsDrawer.displayName = "CopilotThreadsDrawer";
@@ -10752,8 +11120,18 @@ const usePredictStateSubscription = (agent) => {
10752
11120
  }, [agent, getSubscriber]);
10753
11121
  };
10754
11122
  function CopilotListenersAgentSubscription() {
10755
- const resolvedAgentId = useCopilotChatConfiguration()?.agentId;
10756
- const { agent } = useAgent({ agentId: resolvedAgentId });
11123
+ const { copilotkit } = useCopilotKit();
11124
+ const configAgentId = useCopilotChatConfiguration()?.agentId;
11125
+ const { agent } = useAgent({ agentId: (0, react.useMemo)(() => {
11126
+ const requested = configAgentId ?? _copilotkit_shared.DEFAULT_AGENT_ID;
11127
+ const registered = copilotkit.agents ?? {};
11128
+ if (registered[requested]) return requested;
11129
+ if (requested === _copilotkit_shared.DEFAULT_AGENT_ID) {
11130
+ const firstRegistered = Object.keys(registered)[0];
11131
+ if (firstRegistered) return firstRegistered;
11132
+ }
11133
+ return requested;
11134
+ }, [configAgentId, copilotkit.agents]) });
10757
11135
  usePredictStateSubscription(agent);
10758
11136
  return null;
10759
11137
  }
@@ -11706,6 +12084,12 @@ Object.defineProperty(exports, 'useLearningContainersInCurrentThread', {
11706
12084
  return useLearningContainersInCurrentThread;
11707
12085
  }
11708
12086
  });
12087
+ Object.defineProperty(exports, 'useMemories', {
12088
+ enumerable: true,
12089
+ get: function () {
12090
+ return useMemories;
12091
+ }
12092
+ });
11709
12093
  Object.defineProperty(exports, 'useRenderActivityMessage', {
11710
12094
  enumerable: true,
11711
12095
  get: function () {
@@ -11736,6 +12120,12 @@ Object.defineProperty(exports, 'useSandboxFunctions', {
11736
12120
  return useSandboxFunctions;
11737
12121
  }
11738
12122
  });
12123
+ Object.defineProperty(exports, 'useSubagent', {
12124
+ enumerable: true,
12125
+ get: function () {
12126
+ return useSubagent;
12127
+ }
12128
+ });
11739
12129
  Object.defineProperty(exports, 'useSuggestions', {
11740
12130
  enumerable: true,
11741
12131
  get: function () {
@@ -11760,4 +12150,4 @@ Object.defineProperty(exports, 'useToast', {
11760
12150
  return useToast;
11761
12151
  }
11762
12152
  });
11763
- //# sourceMappingURL=copilotkit-CdpDZi3i.cjs.map
12153
+ //# sourceMappingURL=copilotkit-DLwoVUsE.cjs.map