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