@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.umd.js CHANGED
@@ -2143,6 +2143,30 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2143
2143
  }
2144
2144
  };
2145
2145
 
2146
+ //#endregion
2147
+ //#region src/core/tool-result-content.ts
2148
+ /**
2149
+ * Single authority for the forwarded-to-client sentinel used by StateManager
2150
+ * and RunHandler.
2151
+ */
2152
+ const FORWARDED_TO_CLIENT = "Forwarded to client";
2153
+ function normalizeToolResultContent(content) {
2154
+ if (typeof content === "string") return content.trim();
2155
+ if (Array.isArray(content)) {
2156
+ const text = content.flatMap((part) => {
2157
+ if (typeof part === "string") return [part];
2158
+ if (part && typeof part === "object" && "text" in part && typeof part.text === "string") return [part.text];
2159
+ return [];
2160
+ }).join("").trim();
2161
+ return text.length > 0 ? text : null;
2162
+ }
2163
+ if (content && typeof content === "object" && "text" in content && typeof content.text === "string") return content.text.trim();
2164
+ return null;
2165
+ }
2166
+ function isForwardedToClientPlaceholder(content) {
2167
+ return normalizeToolResultContent(content) === FORWARDED_TO_CLIENT;
2168
+ }
2169
+
2146
2170
  //#endregion
2147
2171
  //#region src/core/run-handler.ts
2148
2172
  /**
@@ -2285,9 +2309,10 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2285
2309
  * Connect an agent (establish initial connection)
2286
2310
  */
2287
2311
  async connectAgent({ agent }) {
2312
+ var _agent$threadId;
2313
+ const incomingThreadId = (_agent$threadId = agent.threadId) !== null && _agent$threadId !== void 0 ? _agent$threadId : null;
2288
2314
  try {
2289
- var _agent$threadId, _this$_lastConnectedT;
2290
- const incomingThreadId = (_agent$threadId = agent.threadId) !== null && _agent$threadId !== void 0 ? _agent$threadId : null;
2315
+ var _this$_lastConnectedT;
2291
2316
  const restoreKey = this.getConnectRestoreKey(agent);
2292
2317
  const isFreshRestore = incomingThreadId !== ((_this$_lastConnectedT = this._lastConnectedThreadIdsByAgent.get(restoreKey)) !== null && _this$_lastConnectedT !== void 0 ? _this$_lastConnectedT : null);
2293
2318
  this._lastConnectedThreadIdsByAgent.set(restoreKey, incomingThreadId);
@@ -2324,6 +2349,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2324
2349
  if (!(connectError.name === "AbortError" || connectError.message === "Fetch is aborted" || connectError.message === "signal is aborted without reason" || connectError.message === "component unmounted")) {
2325
2350
  const context = {};
2326
2351
  if (agent.agentId) context.agentId = agent.agentId;
2352
+ if (incomingThreadId) context.threadId = incomingThreadId;
2327
2353
  await this._internal.emitError({
2328
2354
  error: connectError,
2329
2355
  code: CopilotKitCoreErrorCode.AGENT_CONNECT_FAILED,
@@ -2474,21 +2500,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2474
2500
  return runAgentResult;
2475
2501
  }
2476
2502
  isFrontendPlaceholderResult(message) {
2477
- if (message.role !== "tool") return false;
2478
- return this.normalizeToolResultContent(message.content) === "Forwarded to client";
2479
- }
2480
- normalizeToolResultContent(content) {
2481
- if (typeof content === "string") return content.trim();
2482
- if (Array.isArray(content)) {
2483
- const text = content.flatMap((part) => {
2484
- if (typeof part === "string") return [part];
2485
- if (part && typeof part === "object" && "text" in part && typeof part.text === "string") return [part.text];
2486
- return [];
2487
- }).join("").trim();
2488
- return text.length > 0 ? text : null;
2489
- }
2490
- if (content && typeof content === "object" && "text" in content && typeof content.text === "string") return content.text.trim();
2491
- return null;
2503
+ return message.role === "tool" && isForwardedToClientPlaceholder(message.content);
2492
2504
  }
2493
2505
  /**
2494
2506
  * Shared handler execution logic used by executeSpecificTool, executeWildcardTool, and runTool.
@@ -2938,6 +2950,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2938
2950
  this.core = core;
2939
2951
  _defineProperty(this, "stateByRun", /* @__PURE__ */ new Map());
2940
2952
  _defineProperty(this, "messageToRun", /* @__PURE__ */ new Map());
2953
+ _defineProperty(this, "rawEventByMessage", /* @__PURE__ */ new Map());
2941
2954
  _defineProperty(this, "activeRun", /* @__PURE__ */ new Map());
2942
2955
  _defineProperty(this, "agentSubscriptions", /* @__PURE__ */ new Map());
2943
2956
  _defineProperty(this, "pendingContinuations", /* @__PURE__ */ new WeakMap());
@@ -2982,6 +2995,74 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2982
2995
  let revoked = false;
2983
2996
  let subRunId;
2984
2997
  let runFinished = false;
2998
+ const pendingResults = /* @__PURE__ */ new WeakMap();
2999
+ const reconcilePendingResults = (historyMessages, input) => {
3000
+ const events = pendingResults.get(input);
3001
+ if (!events) return void 0;
3002
+ const messages = [...historyMessages];
3003
+ let changed = false;
3004
+ for (const event of events.values()) {
3005
+ var _messages$insertIndex;
3006
+ const ownerIndex = messages.findIndex((message) => {
3007
+ var _message$toolCalls;
3008
+ return message.role === "assistant" && ((_message$toolCalls = message.toolCalls) === null || _message$toolCalls === void 0 ? void 0 : _message$toolCalls.some((toolCall) => toolCall.id === event.toolCallId));
3009
+ });
3010
+ if (ownerIndex < 0) continue;
3011
+ const matchingIndexes = messages.reduce((indexes, message, index) => {
3012
+ if (message.role === "tool" && message.toolCallId === event.toolCallId) indexes.push(index);
3013
+ return indexes;
3014
+ }, []);
3015
+ const realIndex = matchingIndexes.find((index) => {
3016
+ var _messages$index;
3017
+ return !isForwardedToClientPlaceholder((_messages$index = messages[index]) === null || _messages$index === void 0 ? void 0 : _messages$index.content);
3018
+ });
3019
+ if (realIndex !== void 0) {
3020
+ for (const duplicateIndex of matchingIndexes.filter((candidateIndex) => candidateIndex !== realIndex).sort((a, b) => b - a)) {
3021
+ messages.splice(duplicateIndex, 1);
3022
+ changed = true;
3023
+ }
3024
+ continue;
3025
+ }
3026
+ const placeholderIndex = matchingIndexes.find((index) => {
3027
+ var _messages$index2;
3028
+ return isForwardedToClientPlaceholder((_messages$index2 = messages[index]) === null || _messages$index2 === void 0 ? void 0 : _messages$index2.content);
3029
+ });
3030
+ if (placeholderIndex !== void 0) {
3031
+ if (isForwardedToClientPlaceholder(event.content)) {
3032
+ for (const duplicateIndex of matchingIndexes.slice(1).sort((a, b) => b - a)) {
3033
+ messages.splice(duplicateIndex, 1);
3034
+ changed = true;
3035
+ }
3036
+ continue;
3037
+ }
3038
+ messages[placeholderIndex] = {
3039
+ ...messages[placeholderIndex],
3040
+ id: event.messageId,
3041
+ content: event.content
3042
+ };
3043
+ changed = true;
3044
+ for (const duplicateIndex of matchingIndexes.filter((candidateIndex) => {
3045
+ var _messages$candidateIn;
3046
+ return candidateIndex !== placeholderIndex && isForwardedToClientPlaceholder((_messages$candidateIn = messages[candidateIndex]) === null || _messages$candidateIn === void 0 ? void 0 : _messages$candidateIn.content);
3047
+ }).sort((a, b) => b - a)) messages.splice(duplicateIndex, 1);
3048
+ continue;
3049
+ }
3050
+ const result = {
3051
+ id: event.messageId,
3052
+ role: "tool",
3053
+ toolCallId: event.toolCallId,
3054
+ content: event.content
3055
+ };
3056
+ let insertIndex = ownerIndex + 1;
3057
+ while (((_messages$insertIndex = messages[insertIndex]) === null || _messages$insertIndex === void 0 ? void 0 : _messages$insertIndex.role) === "tool") insertIndex++;
3058
+ messages.splice(insertIndex, 0, result);
3059
+ changed = true;
3060
+ }
3061
+ return changed ? { messages } : void 0;
3062
+ };
3063
+ const clearPendingResults = (input) => {
3064
+ pendingResults.delete(input);
3065
+ };
2985
3066
  const effectiveInput = (input) => {
2986
3067
  var _subRunId;
2987
3068
  return {
@@ -2990,28 +3071,52 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2990
3071
  };
2991
3072
  };
2992
3073
  const { unsubscribe } = agent.subscribe({
2993
- onRunStartedEvent: ({ input, state }) => {
3074
+ onRunStartedEvent: ({ event, input, state }) => {
2994
3075
  if (revoked) return;
2995
3076
  const pendingForAgent = this.pendingContinuations.get(agent);
2996
3077
  const internalContinuation = [...pendingForAgent !== null && pendingForAgent !== void 0 ? pendingForAgent : []].find((pending) => pending.expectedInput === input);
2997
3078
  internalContinuation === null || internalContinuation === void 0 || internalContinuation.cancel();
2998
- if (runFinished && input.runId === subRunId && !internalContinuation && !isContinuation(input)) subRunId = (0, _ag_ui_client.randomUUID)();
2999
- else {
3000
- var _internalContinuation;
3001
- subRunId = (_internalContinuation = internalContinuation === null || internalContinuation === void 0 ? void 0 : internalContinuation.expectedRunId) !== null && _internalContinuation !== void 0 ? _internalContinuation : input.runId;
3002
- }
3079
+ if (internalContinuation) {
3080
+ var _ref, _internalContinuation;
3081
+ subRunId = (_ref = (_internalContinuation = internalContinuation.expectedRunId) !== null && _internalContinuation !== void 0 ? _internalContinuation : event.runId) !== null && _ref !== void 0 ? _ref : input.runId;
3082
+ } else if (runFinished && input.runId === subRunId && !isContinuation(input) && (event.runId == null || event.runId === subRunId)) subRunId = (0, _ag_ui_client.randomUUID)();
3083
+ else subRunId = event.runId || input.runId;
3003
3084
  runFinished = false;
3004
3085
  this.handleRunStarted(agent, effectiveInput(input), state);
3005
3086
  },
3006
- onRunFinishedEvent: ({ input, state }) => {
3087
+ onRunFinishedEvent: ({ input, state, messages }) => {
3007
3088
  if (revoked) return;
3008
3089
  runFinished = true;
3009
- this.handleRunFinished(agent, effectiveInput(input), state);
3090
+ const effective = effectiveInput(input);
3091
+ const mutation = reconcilePendingResults(messages, input);
3092
+ clearPendingResults(input);
3093
+ this.handleRunFinished(agent, effective, state);
3094
+ return mutation;
3010
3095
  },
3011
- onRunErrorEvent: ({ input, state }) => {
3096
+ onRunErrorEvent: ({ input, state, messages }) => {
3012
3097
  if (revoked) return;
3013
3098
  runFinished = true;
3014
- this.handleRunFinished(agent, effectiveInput(input), state);
3099
+ const effective = effectiveInput(input);
3100
+ const mutation = reconcilePendingResults(messages, input);
3101
+ this.handleRunFinished(agent, effective, state);
3102
+ return mutation;
3103
+ },
3104
+ onRunFailed: ({ input, messages }) => {
3105
+ if (revoked) return;
3106
+ return reconcilePendingResults(messages, input);
3107
+ },
3108
+ onRunFinalized: ({ input }) => {
3109
+ if (revoked) return;
3110
+ clearPendingResults(input);
3111
+ },
3112
+ onToolCallResultEvent: ({ event, input }) => {
3113
+ if (revoked) return;
3114
+ let events = pendingResults.get(input);
3115
+ if (!events) {
3116
+ events = /* @__PURE__ */ new Map();
3117
+ pendingResults.set(input, events);
3118
+ }
3119
+ events.set(event.toolCallId, event);
3015
3120
  },
3016
3121
  onStateSnapshotEvent: ({ event, input, state }) => {
3017
3122
  if (revoked) return;
@@ -3021,13 +3126,22 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3021
3126
  if (revoked) return;
3022
3127
  this.handleStateDelta(agent, event, effectiveInput(input), state);
3023
3128
  },
3129
+ onTextMessageStartEvent: ({ event, input }) => {
3130
+ if (revoked) return;
3131
+ this.handleTextMessageStart(agent, event, effectiveInput(input));
3132
+ },
3024
3133
  onMessagesSnapshotEvent: ({ event, input, messages }) => {
3025
3134
  if (revoked) return;
3026
3135
  this.handleMessagesSnapshot(agent, event, effectiveInput(input), messages);
3136
+ this.pruneRawEvents(agent.agentId, input.threadId, event.messages, effectiveInput(input));
3027
3137
  },
3028
3138
  onNewMessage: ({ message, input }) => {
3029
3139
  if (revoked) return;
3030
3140
  this.handleNewMessage(agent, message, input ? effectiveInput(input) : void 0);
3141
+ },
3142
+ onMessagesChanged: ({ messages, input }) => {
3143
+ if (revoked) return;
3144
+ if (!input) this.pruneRawEvents(agent.agentId, agent.threadId, messages);
3031
3145
  }
3032
3146
  });
3033
3147
  this.agentSubscriptions.set(agentId, () => {
@@ -3045,6 +3159,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3045
3159
  unsubscribe();
3046
3160
  this.agentSubscriptions.delete(agentId);
3047
3161
  }
3162
+ this.rawEventByMessage.delete(agentId);
3048
3163
  }
3049
3164
  /**
3050
3165
  * Get state for a specific run
@@ -3064,6 +3179,14 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3064
3179
  return (_this$messageToRun$ge = this.messageToRun.get(agentId)) === null || _this$messageToRun$ge === void 0 || (_this$messageToRun$ge = _this$messageToRun$ge.get(threadId)) === null || _this$messageToRun$ge === void 0 ? void 0 : _this$messageToRun$ge.get(messageId);
3065
3180
  }
3066
3181
  /**
3182
+ * Get direct text-start metadata associated with a message.
3183
+ */
3184
+ getRawEventForMessage(agentId, threadId, messageId) {
3185
+ var _this$rawEventByMessa;
3186
+ const rawEvent = (_this$rawEventByMessa = this.rawEventByMessage.get(agentId)) === null || _this$rawEventByMessa === void 0 || (_this$rawEventByMessa = _this$rawEventByMessa.get(threadId)) === null || _this$rawEventByMessa === void 0 ? void 0 : _this$rawEventByMessa.get(messageId);
3187
+ return rawEvent === void 0 ? void 0 : (0, _ag_ui_client.structuredClone_)(rawEvent);
3188
+ }
3189
+ /**
3067
3190
  * Get all states for an agent's thread
3068
3191
  */
3069
3192
  getStatesForThread(agentId, threadId) {
@@ -3117,12 +3240,34 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3117
3240
  this.saveState(agent.agentId, threadId, runId, state);
3118
3241
  }
3119
3242
  /**
3243
+ * Capture only defined metadata from a normalized direct text-start event.
3244
+ */
3245
+ handleTextMessageStart(agent, event, input) {
3246
+ if (!agent.agentId) return;
3247
+ const { threadId } = input;
3248
+ if (event.rawEvent === void 0) {
3249
+ var _this$rawEventByMessa2, _this$rawEventByMessa4;
3250
+ const threadEvents = (_this$rawEventByMessa2 = this.rawEventByMessage.get(agent.agentId)) === null || _this$rawEventByMessa2 === void 0 ? void 0 : _this$rawEventByMessa2.get(threadId);
3251
+ threadEvents === null || threadEvents === void 0 || threadEvents.delete(event.messageId);
3252
+ if ((threadEvents === null || threadEvents === void 0 ? void 0 : threadEvents.size) === 0) {
3253
+ var _this$rawEventByMessa3;
3254
+ (_this$rawEventByMessa3 = this.rawEventByMessage.get(agent.agentId)) === null || _this$rawEventByMessa3 === void 0 || _this$rawEventByMessa3.delete(threadId);
3255
+ }
3256
+ if (((_this$rawEventByMessa4 = this.rawEventByMessage.get(agent.agentId)) === null || _this$rawEventByMessa4 === void 0 ? void 0 : _this$rawEventByMessa4.size) === 0) this.rawEventByMessage.delete(agent.agentId);
3257
+ return;
3258
+ }
3259
+ if (!this.rawEventByMessage.has(agent.agentId)) this.rawEventByMessage.set(agent.agentId, /* @__PURE__ */ new Map());
3260
+ const agentEvents = this.rawEventByMessage.get(agent.agentId);
3261
+ if (!agentEvents.has(threadId)) agentEvents.set(threadId, /* @__PURE__ */ new Map());
3262
+ agentEvents.get(threadId).set(event.messageId, event.rawEvent);
3263
+ }
3264
+ /**
3120
3265
  * Handle messages snapshot event
3121
3266
  */
3122
- handleMessagesSnapshot(agent, event, input, messages) {
3267
+ handleMessagesSnapshot(agent, event, input, _messages) {
3123
3268
  if (!agent.agentId) return;
3124
3269
  const { threadId, runId } = input;
3125
- for (const message of event.messages) this.associateMessageWithRun(agent.agentId, threadId, message.id, runId);
3270
+ for (const message of event.messages) if (this.getRunIdForMessage(agent.agentId, threadId, message.id) === void 0) this.associateMessageWithRun(agent.agentId, threadId, message.id, runId);
3126
3271
  }
3127
3272
  /**
3128
3273
  * Handle new message event
@@ -3157,20 +3302,36 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3157
3302
  if (!agentMessages.has(threadId)) agentMessages.set(threadId, /* @__PURE__ */ new Map());
3158
3303
  agentMessages.get(threadId).set(messageId, runId);
3159
3304
  }
3305
+ pruneRawEvents(agentId, fallbackThreadId, messages, input) {
3306
+ var _input$threadId, _this$rawEventByMessa5, _this$rawEventByMessa7;
3307
+ const threadId = (_input$threadId = input === null || input === void 0 ? void 0 : input.threadId) !== null && _input$threadId !== void 0 ? _input$threadId : fallbackThreadId;
3308
+ if (!threadId) return;
3309
+ const threadEvents = (_this$rawEventByMessa5 = this.rawEventByMessage.get(agentId)) === null || _this$rawEventByMessa5 === void 0 ? void 0 : _this$rawEventByMessa5.get(threadId);
3310
+ if (!threadEvents) return;
3311
+ const messageIds = new Set(messages.map((message) => message.id));
3312
+ for (const messageId of threadEvents.keys()) if (!messageIds.has(messageId)) threadEvents.delete(messageId);
3313
+ if (threadEvents.size === 0) {
3314
+ var _this$rawEventByMessa6;
3315
+ (_this$rawEventByMessa6 = this.rawEventByMessage.get(agentId)) === null || _this$rawEventByMessa6 === void 0 || _this$rawEventByMessa6.delete(threadId);
3316
+ }
3317
+ if (((_this$rawEventByMessa7 = this.rawEventByMessage.get(agentId)) === null || _this$rawEventByMessa7 === void 0 ? void 0 : _this$rawEventByMessa7.size) === 0) this.rawEventByMessage.delete(agentId);
3318
+ }
3160
3319
  /**
3161
3320
  * Clear all state for an agent
3162
3321
  */
3163
3322
  clearAgentState(agentId) {
3164
3323
  this.stateByRun.delete(agentId);
3165
3324
  this.messageToRun.delete(agentId);
3325
+ this.rawEventByMessage.delete(agentId);
3166
3326
  }
3167
3327
  /**
3168
3328
  * Clear all state for a thread
3169
3329
  */
3170
3330
  clearThreadState(agentId, threadId) {
3171
- var _this$stateByRun$get4, _this$messageToRun$ge2;
3331
+ var _this$stateByRun$get4, _this$messageToRun$ge2, _this$rawEventByMessa8;
3172
3332
  (_this$stateByRun$get4 = this.stateByRun.get(agentId)) === null || _this$stateByRun$get4 === void 0 || _this$stateByRun$get4.delete(threadId);
3173
3333
  (_this$messageToRun$ge2 = this.messageToRun.get(agentId)) === null || _this$messageToRun$ge2 === void 0 || _this$messageToRun$ge2.delete(threadId);
3334
+ (_this$rawEventByMessa8 = this.rawEventByMessage.get(agentId)) === null || _this$rawEventByMessa8 === void 0 || _this$rawEventByMessa8.delete(threadId);
3174
3335
  }
3175
3336
  };
3176
3337
 
@@ -5016,6 +5177,9 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5016
5177
  getRunIdForMessage(agentId, threadId, messageId) {
5017
5178
  return this.stateManager.getRunIdForMessage(agentId, threadId, messageId);
5018
5179
  }
5180
+ getRawEventForMessage(agentId, threadId, messageId) {
5181
+ return this.stateManager.getRawEventForMessage(agentId, threadId, messageId);
5182
+ }
5019
5183
  getRunIdsForThread(agentId, threadId) {
5020
5184
  return this.stateManager.getRunIdsForThread(agentId, threadId);
5021
5185
  }
@@ -5045,6 +5209,67 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5045
5209
  async waitForPendingFrameworkUpdates() {}
5046
5210
  };
5047
5211
 
5212
+ //#endregion
5213
+ //#region src/core/inspect-inject.ts
5214
+ const REMINT_ID_KEYS = [
5215
+ "messageId",
5216
+ "parentMessageId",
5217
+ "toolCallId",
5218
+ "runId"
5219
+ ];
5220
+ function newInspectorId() {
5221
+ if (typeof crypto !== "undefined" && "randomUUID" in crypto) return crypto.randomUUID();
5222
+ return `cpk-inject-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
5223
+ }
5224
+ function remintInspectorEventIds(events) {
5225
+ const mapped = /* @__PURE__ */ new Map();
5226
+ const idFor = (value) => {
5227
+ const existing = mapped.get(value);
5228
+ if (existing) return existing;
5229
+ const next = newInspectorId();
5230
+ mapped.set(value, next);
5231
+ return next;
5232
+ };
5233
+ return events.map((event) => {
5234
+ const copy = { ...event };
5235
+ for (const key of REMINT_ID_KEYS) {
5236
+ const value = copy[key];
5237
+ if (typeof value === "string" && value.length > 0) copy[key] = idFor(value);
5238
+ }
5239
+ return copy;
5240
+ });
5241
+ }
5242
+ /**
5243
+ * Inspector-only helper. Apply AG-UI events to a live agent through the
5244
+ * same runAgent path a real agent uses, so chat and frontend-tool handlers
5245
+ * update. Not a documented product API.
5246
+ */
5247
+ async function ɵinjectInspectorEvents(params) {
5248
+ const { core, agent, events } = params;
5249
+ if (agent.isRunning) throw new Error("The agent is running. Wait for the current run to end.");
5250
+ if (events.length === 0) throw new Error("Snippet JSON must be an array of events.");
5251
+ const before = new Set(agent.messages.map((message) => message.id));
5252
+ const originalRun = agent.run;
5253
+ const runEvents = remintInspectorEventIds(events);
5254
+ agent.run = (_input) => (0, rxjs.from)(runEvents);
5255
+ try {
5256
+ await core.runAgent({ agent });
5257
+ } finally {
5258
+ agent.run = originalRun;
5259
+ }
5260
+ return { messageIds: agent.messages.filter((message) => !before.has(message.id)).map((message) => message.id) };
5261
+ }
5262
+ /**
5263
+ * Remove messages created by the last Inspector inject. Does not undo
5264
+ * frontend-tool handler side effects.
5265
+ */
5266
+ function ɵresetInspectorInject(params) {
5267
+ const drop = new Set(params.messageIds);
5268
+ if (drop.size === 0) return;
5269
+ const next = params.agent.messages.filter((message) => !drop.has(message.id));
5270
+ params.agent.setMessages(next);
5271
+ }
5272
+
5048
5273
  //#endregion
5049
5274
  //#region src/types.ts
5050
5275
  /**
@@ -5301,6 +5526,16 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5301
5526
  return typeof value === "string" && value.length > 0 ? value : void 0;
5302
5527
  }
5303
5528
  /**
5529
+ * REST `/threads` is agent-scoped. The Phoenix `user_meta` channel is not.
5530
+ * Drop live upserts that belong to a different agent, or one Inspector
5531
+ * `all-agents` flatten shows the same thread twice until a hard refresh.
5532
+ */
5533
+ function threadMetadataTargetsAgent(payload, agentId) {
5534
+ if (!agentId || payload.operation === "deleted") return true;
5535
+ const threadAgentId = optionalString(payload.thread.agentId);
5536
+ return !threadAgentId || threadAgentId === agentId;
5537
+ }
5538
+ /**
5304
5539
  * Converts gateway run-activity payloads into the internal TypeScript shape.
5305
5540
  */
5306
5541
  function normalizeThreadRunActivityNotification(payload) {
@@ -5733,13 +5968,16 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5733
5968
  }))), ɵ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$)));
5734
5969
  });
5735
5970
  }))),
5736
- 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]) => {
5971
+ createEffect((actions$, state$) => actions$.pipe(ofType(threadSocketEvents.metadataReceived), (0, rxjs_operators.withLatestFrom)(state$), (0, rxjs_operators.filter)(([action, state]) => {
5737
5972
  var _state$context4;
5973
+ return action.sessionId === state.sessionId && threadMetadataTargetsAgent(action.payload, (_state$context4 = state.context) === null || _state$context4 === void 0 ? void 0 : _state$context4.agentId);
5974
+ }), (0, rxjs_operators.map)(([action, state]) => {
5975
+ var _state$context5;
5738
5976
  if (action.payload.operation === "deleted") return threadDomainEvents.threadDeleted({
5739
5977
  sessionId: action.sessionId,
5740
5978
  threadId: action.payload.deleted.id
5741
5979
  });
5742
- if (action.payload.operation === "archived" && !((_state$context4 = state.context) === null || _state$context4 === void 0 ? void 0 : _state$context4.includeArchived)) return threadDomainEvents.threadDeleted({
5980
+ if (action.payload.operation === "archived" && !((_state$context5 = state.context) === null || _state$context5 === void 0 ? void 0 : _state$context5.includeArchived)) return threadDomainEvents.threadDeleted({
5743
5981
  sessionId: action.sessionId,
5744
5982
  threadId: action.payload.threadId
5745
5983
  });
@@ -6121,6 +6359,102 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
6121
6359
  };
6122
6360
  }
6123
6361
 
6362
+ //#endregion
6363
+ //#region src/inspector-thread-bridge.ts
6364
+ const INSPECTOR_THREAD_BRIDGE_PLUGIN_ID = "cpk-inspector-thread";
6365
+ const EVENT_PREFIX = `copilotkit:${INSPECTOR_THREAD_BRIDGE_PLUGIN_ID}`;
6366
+ function eventName(suffix) {
6367
+ return `${EVENT_PREFIX}:${suffix}`;
6368
+ }
6369
+ function getEventTarget() {
6370
+ var _sharedGlobal$__COPIL;
6371
+ if (typeof window !== "undefined" && typeof window.addEventListener === "function") return window;
6372
+ if (typeof EventTarget === "undefined") return null;
6373
+ const sharedGlobal = globalThis;
6374
+ (_sharedGlobal$__COPIL = sharedGlobal.__COPILOTKIT_INSPECTOR_THREAD_EVENT_TARGET__) !== null && _sharedGlobal$__COPIL !== void 0 || (sharedGlobal.__COPILOTKIT_INSPECTOR_THREAD_EVENT_TARGET__ = new EventTarget());
6375
+ return sharedGlobal.__COPILOTKIT_INSPECTOR_THREAD_EVENT_TARGET__;
6376
+ }
6377
+ function createDetailEvent(name, detail) {
6378
+ if (typeof CustomEvent !== "undefined") return new CustomEvent(name, { detail });
6379
+ const event = new Event(name);
6380
+ Object.defineProperty(event, "detail", { value: detail });
6381
+ return event;
6382
+ }
6383
+ function detailFromEvent(event) {
6384
+ return event.detail;
6385
+ }
6386
+ /** The Inspector thread bridge is development-only. */
6387
+ function isInspectorThreadBridgeEnabled() {
6388
+ return process.env.NODE_ENV !== "production";
6389
+ }
6390
+ function createInspectorThreadRequestId() {
6391
+ if (typeof crypto !== "undefined" && "randomUUID" in crypto) return crypto.randomUUID();
6392
+ return `inspector-${Date.now()}-${Math.random().toString(36).slice(2)}`;
6393
+ }
6394
+ function dispatch(suffix, payload) {
6395
+ if (!isInspectorThreadBridgeEnabled()) return;
6396
+ const target = getEventTarget();
6397
+ if (!target) return;
6398
+ target.dispatchEvent(createDetailEvent(eventName(suffix), payload));
6399
+ }
6400
+ function on$1(suffix, handler) {
6401
+ if (!isInspectorThreadBridgeEnabled()) return () => void 0;
6402
+ const target = getEventTarget();
6403
+ if (!target) return () => void 0;
6404
+ const listener = (event) => {
6405
+ handler(detailFromEvent(event));
6406
+ };
6407
+ const name = eventName(suffix);
6408
+ target.addEventListener(name, listener);
6409
+ return () => target.removeEventListener(name, listener);
6410
+ }
6411
+ /**
6412
+ * Ask the first mounted official chat for the matching agent to load a thread.
6413
+ * Returns false when no chat claims the request synchronously.
6414
+ */
6415
+ function emitInspectorViewThread(payload) {
6416
+ if (!isInspectorThreadBridgeEnabled()) return false;
6417
+ const target = getEventTarget();
6418
+ if (!target) return false;
6419
+ const detail = {
6420
+ payload,
6421
+ claimed: false
6422
+ };
6423
+ target.dispatchEvent(createDetailEvent(eventName("view-thread"), detail));
6424
+ return detail.claimed;
6425
+ }
6426
+ function emitInspectorStopViewing(payload) {
6427
+ dispatch("stop-viewing", payload);
6428
+ }
6429
+ function emitInspectorActiveThread(payload) {
6430
+ dispatch("active-thread", payload);
6431
+ }
6432
+ function emitInspectorViewThreadResult(payload) {
6433
+ dispatch("view-thread-result", payload);
6434
+ }
6435
+ function onInspectorViewThread(handler) {
6436
+ if (!isInspectorThreadBridgeEnabled()) return () => void 0;
6437
+ const target = getEventTarget();
6438
+ if (!target) return () => void 0;
6439
+ const listener = (event) => {
6440
+ const detail = detailFromEvent(event);
6441
+ if (detail.claimed) return;
6442
+ detail.claimed = handler(detail.payload);
6443
+ };
6444
+ const name = eventName("view-thread");
6445
+ target.addEventListener(name, listener);
6446
+ return () => target.removeEventListener(name, listener);
6447
+ }
6448
+ function onInspectorStopViewing(handler) {
6449
+ return on$1("stop-viewing", handler);
6450
+ }
6451
+ function onInspectorActiveThread(handler) {
6452
+ return on$1("active-thread", handler);
6453
+ }
6454
+ function onInspectorViewThreadResult(handler) {
6455
+ return on$1("view-thread-result", handler);
6456
+ }
6457
+
6124
6458
  //#endregion
6125
6459
  exports.AgentRegistry = AgentRegistry;
6126
6460
  exports.AgentThreadLockedError = AgentThreadLockedError;
@@ -6128,6 +6462,7 @@ exports.ContextStore = ContextStore;
6128
6462
  exports.CopilotKitCore = CopilotKitCore;
6129
6463
  exports.CopilotKitCoreErrorCode = CopilotKitCoreErrorCode;
6130
6464
  exports.CopilotKitCoreRuntimeConnectionStatus = CopilotKitCoreRuntimeConnectionStatus;
6465
+ exports.INSPECTOR_THREAD_BRIDGE_PLUGIN_ID = INSPECTOR_THREAD_BRIDGE_PLUGIN_ID;
6131
6466
  exports.IntelligenceAgent = IntelligenceAgent;
6132
6467
  exports.MEMORY_ERROR_REGISTRY = MEMORY_ERROR_REGISTRY;
6133
6468
  exports.MemoryError = MemoryError;
@@ -6139,15 +6474,25 @@ exports.ToolCallStatus = ToolCallStatus;
6139
6474
  exports.completePartialMarkdown = completePartialMarkdown;
6140
6475
  exports.createActionGroup = createActionGroup;
6141
6476
  exports.createEffect = createEffect;
6477
+ exports.createInspectorThreadRequestId = createInspectorThreadRequestId;
6142
6478
  exports.createReducer = createReducer;
6143
6479
  exports.createSelector = createSelector;
6144
6480
  exports.createStore = createStore;
6481
+ exports.emitInspectorActiveThread = emitInspectorActiveThread;
6482
+ exports.emitInspectorStopViewing = emitInspectorStopViewing;
6483
+ exports.emitInspectorViewThread = emitInspectorViewThread;
6484
+ exports.emitInspectorViewThreadResult = emitInspectorViewThreadResult;
6145
6485
  exports.empty = empty;
6146
6486
  exports.ensureObjectArgs = ensureObjectArgs;
6147
6487
  exports.isAbortError = isAbortError;
6488
+ exports.isInspectorThreadBridgeEnabled = isInspectorThreadBridgeEnabled;
6148
6489
  exports.isRunCompletionAware = isRunCompletionAware;
6149
6490
  exports.ofType = ofType;
6150
6491
  exports.on = on;
6492
+ exports.onInspectorActiveThread = onInspectorActiveThread;
6493
+ exports.onInspectorStopViewing = onInspectorStopViewing;
6494
+ exports.onInspectorViewThread = onInspectorViewThread;
6495
+ exports.onInspectorViewThreadResult = onInspectorViewThreadResult;
6151
6496
  exports.parseToolArguments = parseToolArguments;
6152
6497
  exports.props = props;
6153
6498
  exports.select = select;
@@ -6157,6 +6502,7 @@ exports.ɵMAX_SOCKET_RETRIES = ɵMAX_SOCKET_RETRIES;
6157
6502
  exports.ɵcreateMemoryStore = createMemoryStore;
6158
6503
  exports.ɵcreateThreadSelectors = ɵcreateThreadSelectors;
6159
6504
  exports.ɵcreateThreadStore = createThreadStore;
6505
+ exports.ɵinjectInspectorEvents = ɵinjectInspectorEvents;
6160
6506
  exports.ɵisCopilotKitFeature = ɵisCopilotKitFeature;
6161
6507
  exports.ɵisRetryableMemoryStatus = isRetryableStatus;
6162
6508
  exports.ɵjoinPhoenixChannel$ = ɵjoinPhoenixChannel$;
@@ -6171,6 +6517,7 @@ exports.ɵobservePhoenixSocketHealth$ = ɵobservePhoenixSocketHealth$;
6171
6517
  exports.ɵobservePhoenixSocketSignals$ = ɵobservePhoenixSocketSignals$;
6172
6518
  exports.ɵphoenixChannel$ = ɵphoenixChannel$;
6173
6519
  exports.ɵphoenixSocket$ = ɵphoenixSocket$;
6520
+ exports.ɵresetInspectorInject = ɵresetInspectorInject;
6174
6521
  exports.ɵselectFetchMoreError = ɵselectFetchMoreError;
6175
6522
  exports.ɵselectHasNextPage = ɵselectHasNextPage;
6176
6523
  exports.ɵselectIsFetchingNextPage = ɵselectIsFetchingNextPage;