@copilotkit/core 1.68.3 → 1.69.1

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/index.mjs CHANGED
@@ -1998,6 +1998,30 @@ const SUGGEST_TOOL = {
1998
1998
  }
1999
1999
  };
2000
2000
 
2001
+ //#endregion
2002
+ //#region src/core/tool-result-content.ts
2003
+ /**
2004
+ * Single authority for the forwarded-to-client sentinel used by StateManager
2005
+ * and RunHandler.
2006
+ */
2007
+ const FORWARDED_TO_CLIENT = "Forwarded to client";
2008
+ function normalizeToolResultContent(content) {
2009
+ if (typeof content === "string") return content.trim();
2010
+ if (Array.isArray(content)) {
2011
+ const text = content.flatMap((part) => {
2012
+ if (typeof part === "string") return [part];
2013
+ if (part && typeof part === "object" && "text" in part && typeof part.text === "string") return [part.text];
2014
+ return [];
2015
+ }).join("").trim();
2016
+ return text.length > 0 ? text : null;
2017
+ }
2018
+ if (content && typeof content === "object" && "text" in content && typeof content.text === "string") return content.text.trim();
2019
+ return null;
2020
+ }
2021
+ function isForwardedToClientPlaceholder(content) {
2022
+ return normalizeToolResultContent(content) === FORWARDED_TO_CLIENT;
2023
+ }
2024
+
2001
2025
  //#endregion
2002
2026
  //#region src/core/run-handler.ts
2003
2027
  /**
@@ -2181,8 +2205,8 @@ var RunHandler = class {
2181
2205
  * Connect an agent (establish initial connection)
2182
2206
  */
2183
2207
  async connectAgent({ agent }) {
2208
+ const incomingThreadId = agent.threadId ?? null;
2184
2209
  try {
2185
- const incomingThreadId = agent.threadId ?? null;
2186
2210
  const restoreKey = this.getConnectRestoreKey(agent);
2187
2211
  const isFreshRestore = incomingThreadId !== (this._lastConnectedThreadIdsByAgent.get(restoreKey) ?? null);
2188
2212
  this._lastConnectedThreadIdsByAgent.set(restoreKey, incomingThreadId);
@@ -2216,6 +2240,7 @@ var RunHandler = class {
2216
2240
  if (!(connectError.name === "AbortError" || connectError.message === "Fetch is aborted" || connectError.message === "signal is aborted without reason" || connectError.message === "component unmounted")) {
2217
2241
  const context = {};
2218
2242
  if (agent.agentId) context.agentId = agent.agentId;
2243
+ if (incomingThreadId) context.threadId = incomingThreadId;
2219
2244
  await this._internal.emitError({
2220
2245
  error: connectError,
2221
2246
  code: CopilotKitCoreErrorCode.AGENT_CONNECT_FAILED,
@@ -2362,21 +2387,7 @@ var RunHandler = class {
2362
2387
  return runAgentResult;
2363
2388
  }
2364
2389
  isFrontendPlaceholderResult(message) {
2365
- if (message.role !== "tool") return false;
2366
- return this.normalizeToolResultContent(message.content) === "Forwarded to client";
2367
- }
2368
- normalizeToolResultContent(content) {
2369
- if (typeof content === "string") return content.trim();
2370
- if (Array.isArray(content)) {
2371
- const text = content.flatMap((part) => {
2372
- if (typeof part === "string") return [part];
2373
- if (part && typeof part === "object" && "text" in part && typeof part.text === "string") return [part.text];
2374
- return [];
2375
- }).join("").trim();
2376
- return text.length > 0 ? text : null;
2377
- }
2378
- if (content && typeof content === "object" && "text" in content && typeof content.text === "string") return content.text.trim();
2379
- return null;
2390
+ return message.role === "tool" && isForwardedToClientPlaceholder(message.content);
2380
2391
  }
2381
2392
  /**
2382
2393
  * Shared handler execution logic used by executeSpecificTool, executeWildcardTool, and runTool.
@@ -2802,6 +2813,7 @@ const isContinuation = (input) => input.resume !== void 0 || Object.prototype.ha
2802
2813
  var StateManager = class {
2803
2814
  stateByRun = /* @__PURE__ */ new Map();
2804
2815
  messageToRun = /* @__PURE__ */ new Map();
2816
+ rawEventByMessage = /* @__PURE__ */ new Map();
2805
2817
  activeRun = /* @__PURE__ */ new Map();
2806
2818
  agentSubscriptions = /* @__PURE__ */ new Map();
2807
2819
  pendingContinuations = /* @__PURE__ */ new WeakMap();
@@ -2848,29 +2860,109 @@ var StateManager = class {
2848
2860
  let revoked = false;
2849
2861
  let subRunId;
2850
2862
  let runFinished = false;
2863
+ const pendingResults = /* @__PURE__ */ new WeakMap();
2864
+ const reconcilePendingResults = (historyMessages, input) => {
2865
+ const events = pendingResults.get(input);
2866
+ if (!events) return void 0;
2867
+ const messages = [...historyMessages];
2868
+ let changed = false;
2869
+ for (const event of events.values()) {
2870
+ const ownerIndex = messages.findIndex((message) => message.role === "assistant" && message.toolCalls?.some((toolCall) => toolCall.id === event.toolCallId));
2871
+ if (ownerIndex < 0) continue;
2872
+ const matchingIndexes = messages.reduce((indexes, message, index) => {
2873
+ if (message.role === "tool" && message.toolCallId === event.toolCallId) indexes.push(index);
2874
+ return indexes;
2875
+ }, []);
2876
+ const realIndex = matchingIndexes.find((index) => !isForwardedToClientPlaceholder(messages[index]?.content));
2877
+ if (realIndex !== void 0) {
2878
+ for (const duplicateIndex of matchingIndexes.filter((candidateIndex) => candidateIndex !== realIndex).sort((a, b) => b - a)) {
2879
+ messages.splice(duplicateIndex, 1);
2880
+ changed = true;
2881
+ }
2882
+ continue;
2883
+ }
2884
+ const placeholderIndex = matchingIndexes.find((index) => isForwardedToClientPlaceholder(messages[index]?.content));
2885
+ if (placeholderIndex !== void 0) {
2886
+ if (isForwardedToClientPlaceholder(event.content)) {
2887
+ for (const duplicateIndex of matchingIndexes.slice(1).sort((a, b) => b - a)) {
2888
+ messages.splice(duplicateIndex, 1);
2889
+ changed = true;
2890
+ }
2891
+ continue;
2892
+ }
2893
+ messages[placeholderIndex] = {
2894
+ ...messages[placeholderIndex],
2895
+ id: event.messageId,
2896
+ content: event.content
2897
+ };
2898
+ changed = true;
2899
+ for (const duplicateIndex of matchingIndexes.filter((candidateIndex) => candidateIndex !== placeholderIndex && isForwardedToClientPlaceholder(messages[candidateIndex]?.content)).sort((a, b) => b - a)) messages.splice(duplicateIndex, 1);
2900
+ continue;
2901
+ }
2902
+ const result = {
2903
+ id: event.messageId,
2904
+ role: "tool",
2905
+ toolCallId: event.toolCallId,
2906
+ content: event.content
2907
+ };
2908
+ let insertIndex = ownerIndex + 1;
2909
+ while (messages[insertIndex]?.role === "tool") insertIndex++;
2910
+ messages.splice(insertIndex, 0, result);
2911
+ changed = true;
2912
+ }
2913
+ return changed ? { messages } : void 0;
2914
+ };
2915
+ const clearPendingResults = (input) => {
2916
+ pendingResults.delete(input);
2917
+ };
2851
2918
  const effectiveInput = (input) => ({
2852
2919
  ...input,
2853
2920
  runId: subRunId ?? input.runId
2854
2921
  });
2855
2922
  const { unsubscribe } = agent.subscribe({
2856
- onRunStartedEvent: ({ input, state }) => {
2923
+ onRunStartedEvent: ({ event, input, state }) => {
2857
2924
  if (revoked) return;
2858
2925
  const internalContinuation = [...this.pendingContinuations.get(agent) ?? []].find((pending) => pending.expectedInput === input);
2859
2926
  internalContinuation?.cancel();
2860
- if (runFinished && input.runId === subRunId && !internalContinuation && !isContinuation(input)) subRunId = randomUUID();
2861
- else subRunId = internalContinuation?.expectedRunId ?? input.runId;
2927
+ if (internalContinuation) subRunId = internalContinuation.expectedRunId ?? event.runId ?? input.runId;
2928
+ else if (runFinished && input.runId === subRunId && !isContinuation(input) && (event.runId == null || event.runId === subRunId)) subRunId = randomUUID();
2929
+ else subRunId = event.runId || input.runId;
2862
2930
  runFinished = false;
2863
2931
  this.handleRunStarted(agent, effectiveInput(input), state);
2864
2932
  },
2865
- onRunFinishedEvent: ({ input, state }) => {
2933
+ onRunFinishedEvent: ({ input, state, messages }) => {
2866
2934
  if (revoked) return;
2867
2935
  runFinished = true;
2868
- this.handleRunFinished(agent, effectiveInput(input), state);
2936
+ const effective = effectiveInput(input);
2937
+ const mutation = reconcilePendingResults(messages, input);
2938
+ clearPendingResults(input);
2939
+ this.handleRunFinished(agent, effective, state);
2940
+ return mutation;
2869
2941
  },
2870
- onRunErrorEvent: ({ input, state }) => {
2942
+ onRunErrorEvent: ({ input, state, messages }) => {
2871
2943
  if (revoked) return;
2872
2944
  runFinished = true;
2873
- this.handleRunFinished(agent, effectiveInput(input), state);
2945
+ const effective = effectiveInput(input);
2946
+ const mutation = reconcilePendingResults(messages, input);
2947
+ this.handleRunFinished(agent, effective, state);
2948
+ return mutation;
2949
+ },
2950
+ onRunFailed: ({ input, messages }) => {
2951
+ if (revoked) return;
2952
+ return reconcilePendingResults(messages, input);
2953
+ },
2954
+ onRunFinalized: ({ input }) => {
2955
+ if (revoked) return;
2956
+ clearPendingResults(input);
2957
+ },
2958
+ onToolCallResultEvent: ({ event, input }) => {
2959
+ if (revoked) return;
2960
+ let events = pendingResults.get(input);
2961
+ if (!events) {
2962
+ events = /* @__PURE__ */ new Map();
2963
+ pendingResults.set(input, events);
2964
+ }
2965
+ events.set(event.toolCallId, event);
2874
2966
  },
2875
2967
  onStateSnapshotEvent: ({ event, input, state }) => {
2876
2968
  if (revoked) return;
@@ -2880,13 +2972,22 @@ var StateManager = class {
2880
2972
  if (revoked) return;
2881
2973
  this.handleStateDelta(agent, event, effectiveInput(input), state);
2882
2974
  },
2975
+ onTextMessageStartEvent: ({ event, input }) => {
2976
+ if (revoked) return;
2977
+ this.handleTextMessageStart(agent, event, effectiveInput(input));
2978
+ },
2883
2979
  onMessagesSnapshotEvent: ({ event, input, messages }) => {
2884
2980
  if (revoked) return;
2885
2981
  this.handleMessagesSnapshot(agent, event, effectiveInput(input), messages);
2982
+ this.pruneRawEvents(agent.agentId, input.threadId, event.messages, effectiveInput(input));
2886
2983
  },
2887
2984
  onNewMessage: ({ message, input }) => {
2888
2985
  if (revoked) return;
2889
2986
  this.handleNewMessage(agent, message, input ? effectiveInput(input) : void 0);
2987
+ },
2988
+ onMessagesChanged: ({ messages, input }) => {
2989
+ if (revoked) return;
2990
+ if (!input) this.pruneRawEvents(agent.agentId, agent.threadId, messages);
2890
2991
  }
2891
2992
  });
2892
2993
  this.agentSubscriptions.set(agentId, () => {
@@ -2904,6 +3005,7 @@ var StateManager = class {
2904
3005
  unsubscribe();
2905
3006
  this.agentSubscriptions.delete(agentId);
2906
3007
  }
3008
+ this.rawEventByMessage.delete(agentId);
2907
3009
  }
2908
3010
  /**
2909
3011
  * Get state for a specific run
@@ -2921,6 +3023,13 @@ var StateManager = class {
2921
3023
  return this.messageToRun.get(agentId)?.get(threadId)?.get(messageId);
2922
3024
  }
2923
3025
  /**
3026
+ * Get direct text-start metadata associated with a message.
3027
+ */
3028
+ getRawEventForMessage(agentId, threadId, messageId) {
3029
+ const rawEvent = this.rawEventByMessage.get(agentId)?.get(threadId)?.get(messageId);
3030
+ return rawEvent === void 0 ? void 0 : structuredClone_(rawEvent);
3031
+ }
3032
+ /**
2924
3033
  * Get all states for an agent's thread
2925
3034
  */
2926
3035
  getStatesForThread(agentId, threadId) {
@@ -2972,12 +3081,30 @@ var StateManager = class {
2972
3081
  this.saveState(agent.agentId, threadId, runId, state);
2973
3082
  }
2974
3083
  /**
3084
+ * Capture only defined metadata from a normalized direct text-start event.
3085
+ */
3086
+ handleTextMessageStart(agent, event, input) {
3087
+ if (!agent.agentId) return;
3088
+ const { threadId } = input;
3089
+ if (event.rawEvent === void 0) {
3090
+ const threadEvents = this.rawEventByMessage.get(agent.agentId)?.get(threadId);
3091
+ threadEvents?.delete(event.messageId);
3092
+ if (threadEvents?.size === 0) this.rawEventByMessage.get(agent.agentId)?.delete(threadId);
3093
+ if (this.rawEventByMessage.get(agent.agentId)?.size === 0) this.rawEventByMessage.delete(agent.agentId);
3094
+ return;
3095
+ }
3096
+ if (!this.rawEventByMessage.has(agent.agentId)) this.rawEventByMessage.set(agent.agentId, /* @__PURE__ */ new Map());
3097
+ const agentEvents = this.rawEventByMessage.get(agent.agentId);
3098
+ if (!agentEvents.has(threadId)) agentEvents.set(threadId, /* @__PURE__ */ new Map());
3099
+ agentEvents.get(threadId).set(event.messageId, event.rawEvent);
3100
+ }
3101
+ /**
2975
3102
  * Handle messages snapshot event
2976
3103
  */
2977
- handleMessagesSnapshot(agent, event, input, messages) {
3104
+ handleMessagesSnapshot(agent, event, input, _messages) {
2978
3105
  if (!agent.agentId) return;
2979
3106
  const { threadId, runId } = input;
2980
- for (const message of event.messages) this.associateMessageWithRun(agent.agentId, threadId, message.id, runId);
3107
+ for (const message of event.messages) if (this.getRunIdForMessage(agent.agentId, threadId, message.id) === void 0) this.associateMessageWithRun(agent.agentId, threadId, message.id, runId);
2981
3108
  }
2982
3109
  /**
2983
3110
  * Handle new message event
@@ -3011,12 +3138,23 @@ var StateManager = class {
3011
3138
  if (!agentMessages.has(threadId)) agentMessages.set(threadId, /* @__PURE__ */ new Map());
3012
3139
  agentMessages.get(threadId).set(messageId, runId);
3013
3140
  }
3141
+ pruneRawEvents(agentId, fallbackThreadId, messages, input) {
3142
+ const threadId = input?.threadId ?? fallbackThreadId;
3143
+ if (!threadId) return;
3144
+ const threadEvents = this.rawEventByMessage.get(agentId)?.get(threadId);
3145
+ if (!threadEvents) return;
3146
+ const messageIds = new Set(messages.map((message) => message.id));
3147
+ for (const messageId of threadEvents.keys()) if (!messageIds.has(messageId)) threadEvents.delete(messageId);
3148
+ if (threadEvents.size === 0) this.rawEventByMessage.get(agentId)?.delete(threadId);
3149
+ if (this.rawEventByMessage.get(agentId)?.size === 0) this.rawEventByMessage.delete(agentId);
3150
+ }
3014
3151
  /**
3015
3152
  * Clear all state for an agent
3016
3153
  */
3017
3154
  clearAgentState(agentId) {
3018
3155
  this.stateByRun.delete(agentId);
3019
3156
  this.messageToRun.delete(agentId);
3157
+ this.rawEventByMessage.delete(agentId);
3020
3158
  }
3021
3159
  /**
3022
3160
  * Clear all state for a thread
@@ -3024,6 +3162,7 @@ var StateManager = class {
3024
3162
  clearThreadState(agentId, threadId) {
3025
3163
  this.stateByRun.get(agentId)?.delete(threadId);
3026
3164
  this.messageToRun.get(agentId)?.delete(threadId);
3165
+ this.rawEventByMessage.get(agentId)?.delete(threadId);
3027
3166
  }
3028
3167
  };
3029
3168
 
@@ -4853,6 +4992,9 @@ var CopilotKitCore = class {
4853
4992
  getRunIdForMessage(agentId, threadId, messageId) {
4854
4993
  return this.stateManager.getRunIdForMessage(agentId, threadId, messageId);
4855
4994
  }
4995
+ getRawEventForMessage(agentId, threadId, messageId) {
4996
+ return this.stateManager.getRawEventForMessage(agentId, threadId, messageId);
4997
+ }
4856
4998
  getRunIdsForThread(agentId, threadId) {
4857
4999
  return this.stateManager.getRunIdsForThread(agentId, threadId);
4858
5000
  }
@@ -4882,6 +5024,67 @@ var CopilotKitCore = class {
4882
5024
  async waitForPendingFrameworkUpdates() {}
4883
5025
  };
4884
5026
 
5027
+ //#endregion
5028
+ //#region src/core/inspect-inject.ts
5029
+ const REMINT_ID_KEYS = [
5030
+ "messageId",
5031
+ "parentMessageId",
5032
+ "toolCallId",
5033
+ "runId"
5034
+ ];
5035
+ function newInspectorId() {
5036
+ if (typeof crypto !== "undefined" && "randomUUID" in crypto) return crypto.randomUUID();
5037
+ return `cpk-inject-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
5038
+ }
5039
+ function remintInspectorEventIds(events) {
5040
+ const mapped = /* @__PURE__ */ new Map();
5041
+ const idFor = (value) => {
5042
+ const existing = mapped.get(value);
5043
+ if (existing) return existing;
5044
+ const next = newInspectorId();
5045
+ mapped.set(value, next);
5046
+ return next;
5047
+ };
5048
+ return events.map((event) => {
5049
+ const copy = { ...event };
5050
+ for (const key of REMINT_ID_KEYS) {
5051
+ const value = copy[key];
5052
+ if (typeof value === "string" && value.length > 0) copy[key] = idFor(value);
5053
+ }
5054
+ return copy;
5055
+ });
5056
+ }
5057
+ /**
5058
+ * Inspector-only helper. Apply AG-UI events to a live agent through the
5059
+ * same runAgent path a real agent uses, so chat and frontend-tool handlers
5060
+ * update. Not a documented product API.
5061
+ */
5062
+ async function ɵinjectInspectorEvents(params) {
5063
+ const { core, agent, events } = params;
5064
+ if (agent.isRunning) throw new Error("The agent is running. Wait for the current run to end.");
5065
+ if (events.length === 0) throw new Error("Snippet JSON must be an array of events.");
5066
+ const before = new Set(agent.messages.map((message) => message.id));
5067
+ const originalRun = agent.run;
5068
+ const runEvents = remintInspectorEventIds(events);
5069
+ agent.run = (_input) => from(runEvents);
5070
+ try {
5071
+ await core.runAgent({ agent });
5072
+ } finally {
5073
+ agent.run = originalRun;
5074
+ }
5075
+ return { messageIds: agent.messages.filter((message) => !before.has(message.id)).map((message) => message.id) };
5076
+ }
5077
+ /**
5078
+ * Remove messages created by the last Inspector inject. Does not undo
5079
+ * frontend-tool handler side effects.
5080
+ */
5081
+ function ɵresetInspectorInject(params) {
5082
+ const drop = new Set(params.messageIds);
5083
+ if (drop.size === 0) return;
5084
+ const next = params.agent.messages.filter((message) => !drop.has(message.id));
5085
+ params.agent.setMessages(next);
5086
+ }
5087
+
4885
5088
  //#endregion
4886
5089
  //#region src/types.ts
4887
5090
  /**
@@ -5137,6 +5340,16 @@ function optionalString(value) {
5137
5340
  return typeof value === "string" && value.length > 0 ? value : void 0;
5138
5341
  }
5139
5342
  /**
5343
+ * REST `/threads` is agent-scoped. The Phoenix `user_meta` channel is not.
5344
+ * Drop live upserts that belong to a different agent, or one Inspector
5345
+ * `all-agents` flatten shows the same thread twice until a hard refresh.
5346
+ */
5347
+ function threadMetadataTargetsAgent(payload, agentId) {
5348
+ if (!agentId || payload.operation === "deleted") return true;
5349
+ const threadAgentId = optionalString(payload.thread.agentId);
5350
+ return !threadAgentId || threadAgentId === agentId;
5351
+ }
5352
+ /**
5140
5353
  * Converts gateway run-activity payloads into the internal TypeScript shape.
5141
5354
  */
5142
5355
  function normalizeThreadRunActivityNotification(payload) {
@@ -5562,7 +5775,7 @@ function createThreadStore(environment) {
5562
5775
  }))), ɵobservePhoenixJoinOutcome$(channel$).pipe(filter((outcome) => outcome.type !== "joined"), map((outcome) => outcome.type === "timeout" ? threadSocketEvents.joinTimedOut({ sessionId: action.sessionId }) : threadSocketEvents.joinFailed({ sessionId: action.sessionId })))).pipe(takeUntil(merge(shutdown$, fatalSocketShutdown$)));
5563
5776
  });
5564
5777
  }))),
5565
- createEffect((actions$, state$) => actions$.pipe(ofType(threadSocketEvents.metadataReceived), withLatestFrom(state$), filter(([action, state]) => action.sessionId === state.sessionId), map(([action, state]) => {
5778
+ createEffect((actions$, state$) => actions$.pipe(ofType(threadSocketEvents.metadataReceived), withLatestFrom(state$), filter(([action, state]) => action.sessionId === state.sessionId && threadMetadataTargetsAgent(action.payload, state.context?.agentId)), map(([action, state]) => {
5566
5779
  if (action.payload.operation === "deleted") return threadDomainEvents.threadDeleted({
5567
5780
  sessionId: action.sessionId,
5568
5781
  threadId: action.payload.deleted.id
@@ -5917,5 +6130,100 @@ var ɵInterruptState = class {
5917
6130
  };
5918
6131
 
5919
6132
  //#endregion
5920
- export { AgentRegistry, AgentThreadLockedError, ContextStore, CopilotKitCore, CopilotKitCoreErrorCode, CopilotKitCoreRuntimeConnectionStatus, IntelligenceAgent, MEMORY_ERROR_REGISTRY, MemoryError, ProxiedCopilotRuntimeAgent, RunHandler, StateManager, SuggestionEngine, ToolCallStatus, completePartialMarkdown, createActionGroup, createEffect, createReducer, createSelector, createStore, empty, ensureObjectArgs, isAbortError, isRunCompletionAware, ofType, on, parseToolArguments, props, select, ɵCOPILOTKIT_FEATURES, ɵInterruptState, ɵMAX_SOCKET_RETRIES, createMemoryStore as ɵcreateMemoryStore, ɵcreateThreadSelectors, createThreadStore as ɵcreateThreadStore, ɵisCopilotKitFeature, isRetryableStatus as ɵisRetryableMemoryStatus, ɵjoinPhoenixChannel$, ɵmapMemoryMetadataEvent, ɵmemoryAdapterEvents, ɵmemoryDomainEvents, ɵmemoryReducer, ɵmemoryRestEvents, ɵobservePhoenixEvent$, ɵobservePhoenixJoinOutcome$, ɵobservePhoenixSocketHealth$, ɵobservePhoenixSocketSignals$, ɵphoenixChannel$, ɵphoenixSocket$, ɵselectFetchMoreError, ɵselectHasNextPage, ɵselectIsFetchingNextPage, ɵselectIsMutating, ɵselectMemories, ɵselectMemoriesAvailable, ɵselectMemoriesError, ɵselectMemoriesIsLoading, ɵselectMemoriesIsMutating, ɵselectMemoriesRealtimeStatus, ɵselectThreads, ɵselectThreadsError, ɵselectThreadsIsLoading, ɵthreadAdapterEvents };
6133
+ //#region src/inspector-thread-bridge.ts
6134
+ const INSPECTOR_THREAD_BRIDGE_PLUGIN_ID = "cpk-inspector-thread";
6135
+ const EVENT_PREFIX = `copilotkit:${INSPECTOR_THREAD_BRIDGE_PLUGIN_ID}`;
6136
+ function eventName(suffix) {
6137
+ return `${EVENT_PREFIX}:${suffix}`;
6138
+ }
6139
+ function getEventTarget() {
6140
+ if (typeof window !== "undefined" && typeof window.addEventListener === "function") return window;
6141
+ if (typeof EventTarget === "undefined") return null;
6142
+ const sharedGlobal = globalThis;
6143
+ sharedGlobal.__COPILOTKIT_INSPECTOR_THREAD_EVENT_TARGET__ ??= new EventTarget();
6144
+ return sharedGlobal.__COPILOTKIT_INSPECTOR_THREAD_EVENT_TARGET__;
6145
+ }
6146
+ function createDetailEvent(name, detail) {
6147
+ if (typeof CustomEvent !== "undefined") return new CustomEvent(name, { detail });
6148
+ const event = new Event(name);
6149
+ Object.defineProperty(event, "detail", { value: detail });
6150
+ return event;
6151
+ }
6152
+ function detailFromEvent(event) {
6153
+ return event.detail;
6154
+ }
6155
+ /** The Inspector thread bridge is development-only. */
6156
+ function isInspectorThreadBridgeEnabled() {
6157
+ return process.env.NODE_ENV !== "production";
6158
+ }
6159
+ function createInspectorThreadRequestId() {
6160
+ if (typeof crypto !== "undefined" && "randomUUID" in crypto) return crypto.randomUUID();
6161
+ return `inspector-${Date.now()}-${Math.random().toString(36).slice(2)}`;
6162
+ }
6163
+ function dispatch(suffix, payload) {
6164
+ if (!isInspectorThreadBridgeEnabled()) return;
6165
+ const target = getEventTarget();
6166
+ if (!target) return;
6167
+ target.dispatchEvent(createDetailEvent(eventName(suffix), payload));
6168
+ }
6169
+ function on$1(suffix, handler) {
6170
+ if (!isInspectorThreadBridgeEnabled()) return () => void 0;
6171
+ const target = getEventTarget();
6172
+ if (!target) return () => void 0;
6173
+ const listener = (event) => {
6174
+ handler(detailFromEvent(event));
6175
+ };
6176
+ const name = eventName(suffix);
6177
+ target.addEventListener(name, listener);
6178
+ return () => target.removeEventListener(name, listener);
6179
+ }
6180
+ /**
6181
+ * Ask the first mounted official chat for the matching agent to load a thread.
6182
+ * Returns false when no chat claims the request synchronously.
6183
+ */
6184
+ function emitInspectorViewThread(payload) {
6185
+ if (!isInspectorThreadBridgeEnabled()) return false;
6186
+ const target = getEventTarget();
6187
+ if (!target) return false;
6188
+ const detail = {
6189
+ payload,
6190
+ claimed: false
6191
+ };
6192
+ target.dispatchEvent(createDetailEvent(eventName("view-thread"), detail));
6193
+ return detail.claimed;
6194
+ }
6195
+ function emitInspectorStopViewing(payload) {
6196
+ dispatch("stop-viewing", payload);
6197
+ }
6198
+ function emitInspectorActiveThread(payload) {
6199
+ dispatch("active-thread", payload);
6200
+ }
6201
+ function emitInspectorViewThreadResult(payload) {
6202
+ dispatch("view-thread-result", payload);
6203
+ }
6204
+ function onInspectorViewThread(handler) {
6205
+ if (!isInspectorThreadBridgeEnabled()) return () => void 0;
6206
+ const target = getEventTarget();
6207
+ if (!target) return () => void 0;
6208
+ const listener = (event) => {
6209
+ const detail = detailFromEvent(event);
6210
+ if (detail.claimed) return;
6211
+ detail.claimed = handler(detail.payload);
6212
+ };
6213
+ const name = eventName("view-thread");
6214
+ target.addEventListener(name, listener);
6215
+ return () => target.removeEventListener(name, listener);
6216
+ }
6217
+ function onInspectorStopViewing(handler) {
6218
+ return on$1("stop-viewing", handler);
6219
+ }
6220
+ function onInspectorActiveThread(handler) {
6221
+ return on$1("active-thread", handler);
6222
+ }
6223
+ function onInspectorViewThreadResult(handler) {
6224
+ return on$1("view-thread-result", handler);
6225
+ }
6226
+
6227
+ //#endregion
6228
+ export { AgentRegistry, AgentThreadLockedError, ContextStore, CopilotKitCore, CopilotKitCoreErrorCode, CopilotKitCoreRuntimeConnectionStatus, INSPECTOR_THREAD_BRIDGE_PLUGIN_ID, IntelligenceAgent, MEMORY_ERROR_REGISTRY, MemoryError, ProxiedCopilotRuntimeAgent, RunHandler, StateManager, SuggestionEngine, ToolCallStatus, completePartialMarkdown, createActionGroup, createEffect, createInspectorThreadRequestId, createReducer, createSelector, createStore, emitInspectorActiveThread, emitInspectorStopViewing, emitInspectorViewThread, emitInspectorViewThreadResult, empty, ensureObjectArgs, isAbortError, isInspectorThreadBridgeEnabled, isRunCompletionAware, ofType, on, onInspectorActiveThread, onInspectorStopViewing, onInspectorViewThread, onInspectorViewThreadResult, parseToolArguments, props, select, ɵCOPILOTKIT_FEATURES, ɵInterruptState, ɵMAX_SOCKET_RETRIES, createMemoryStore as ɵcreateMemoryStore, ɵcreateThreadSelectors, createThreadStore as ɵcreateThreadStore, ɵinjectInspectorEvents, ɵisCopilotKitFeature, isRetryableStatus as ɵisRetryableMemoryStatus, ɵjoinPhoenixChannel$, ɵmapMemoryMetadataEvent, ɵmemoryAdapterEvents, ɵmemoryDomainEvents, ɵmemoryReducer, ɵmemoryRestEvents, ɵobservePhoenixEvent$, ɵobservePhoenixJoinOutcome$, ɵobservePhoenixSocketHealth$, ɵobservePhoenixSocketSignals$, ɵphoenixChannel$, ɵphoenixSocket$, ɵresetInspectorInject, ɵselectFetchMoreError, ɵselectHasNextPage, ɵselectIsFetchingNextPage, ɵselectIsMutating, ɵselectMemories, ɵselectMemoriesAvailable, ɵselectMemoriesError, ɵselectMemoriesIsLoading, ɵselectMemoriesIsMutating, ɵselectMemoriesRealtimeStatus, ɵselectThreads, ɵselectThreadsError, ɵselectThreadsIsLoading, ɵthreadAdapterEvents };
5921
6229
  //# sourceMappingURL=index.mjs.map