@copilotkit/core 1.69.0 → 1.69.2

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.
@@ -2983,6 +2995,74 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2983
2995
  let revoked = false;
2984
2996
  let subRunId;
2985
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
+ };
2986
3066
  const effectiveInput = (input) => {
2987
3067
  var _subRunId;
2988
3068
  return {
@@ -3004,15 +3084,39 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3004
3084
  runFinished = false;
3005
3085
  this.handleRunStarted(agent, effectiveInput(input), state);
3006
3086
  },
3007
- onRunFinishedEvent: ({ input, state }) => {
3087
+ onRunFinishedEvent: ({ input, state, messages }) => {
3008
3088
  if (revoked) return;
3009
3089
  runFinished = true;
3010
- 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;
3011
3095
  },
3012
- onRunErrorEvent: ({ input, state }) => {
3096
+ onRunErrorEvent: ({ input, state, messages }) => {
3013
3097
  if (revoked) return;
3014
3098
  runFinished = true;
3015
- 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);
3016
3120
  },
3017
3121
  onStateSnapshotEvent: ({ event, input, state }) => {
3018
3122
  if (revoked) return;
@@ -3160,7 +3264,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3160
3264
  /**
3161
3265
  * Handle messages snapshot event
3162
3266
  */
3163
- handleMessagesSnapshot(agent, event, input, messages) {
3267
+ handleMessagesSnapshot(agent, event, input, _messages) {
3164
3268
  if (!agent.agentId) return;
3165
3269
  const { threadId, runId } = input;
3166
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);
@@ -6194,6 +6298,102 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
6194
6298
  };
6195
6299
  }
6196
6300
 
6301
+ //#endregion
6302
+ //#region src/inspector-thread-bridge.ts
6303
+ const INSPECTOR_THREAD_BRIDGE_PLUGIN_ID = "cpk-inspector-thread";
6304
+ const EVENT_PREFIX = `copilotkit:${INSPECTOR_THREAD_BRIDGE_PLUGIN_ID}`;
6305
+ function eventName(suffix) {
6306
+ return `${EVENT_PREFIX}:${suffix}`;
6307
+ }
6308
+ function getEventTarget() {
6309
+ var _sharedGlobal$__COPIL;
6310
+ if (typeof window !== "undefined" && typeof window.addEventListener === "function") return window;
6311
+ if (typeof EventTarget === "undefined") return null;
6312
+ const sharedGlobal = globalThis;
6313
+ (_sharedGlobal$__COPIL = sharedGlobal.__COPILOTKIT_INSPECTOR_THREAD_EVENT_TARGET__) !== null && _sharedGlobal$__COPIL !== void 0 || (sharedGlobal.__COPILOTKIT_INSPECTOR_THREAD_EVENT_TARGET__ = new EventTarget());
6314
+ return sharedGlobal.__COPILOTKIT_INSPECTOR_THREAD_EVENT_TARGET__;
6315
+ }
6316
+ function createDetailEvent(name, detail) {
6317
+ if (typeof CustomEvent !== "undefined") return new CustomEvent(name, { detail });
6318
+ const event = new Event(name);
6319
+ Object.defineProperty(event, "detail", { value: detail });
6320
+ return event;
6321
+ }
6322
+ function detailFromEvent(event) {
6323
+ return event.detail;
6324
+ }
6325
+ /** The Inspector thread bridge is development-only. */
6326
+ function isInspectorThreadBridgeEnabled() {
6327
+ return process.env.NODE_ENV !== "production";
6328
+ }
6329
+ function createInspectorThreadRequestId() {
6330
+ if (typeof crypto !== "undefined" && "randomUUID" in crypto) return crypto.randomUUID();
6331
+ return `inspector-${Date.now()}-${Math.random().toString(36).slice(2)}`;
6332
+ }
6333
+ function dispatch(suffix, payload) {
6334
+ if (!isInspectorThreadBridgeEnabled()) return;
6335
+ const target = getEventTarget();
6336
+ if (!target) return;
6337
+ target.dispatchEvent(createDetailEvent(eventName(suffix), payload));
6338
+ }
6339
+ function on$1(suffix, handler) {
6340
+ if (!isInspectorThreadBridgeEnabled()) return () => void 0;
6341
+ const target = getEventTarget();
6342
+ if (!target) return () => void 0;
6343
+ const listener = (event) => {
6344
+ handler(detailFromEvent(event));
6345
+ };
6346
+ const name = eventName(suffix);
6347
+ target.addEventListener(name, listener);
6348
+ return () => target.removeEventListener(name, listener);
6349
+ }
6350
+ /**
6351
+ * Ask the first mounted official chat for the matching agent to load a thread.
6352
+ * Returns false when no chat claims the request synchronously.
6353
+ */
6354
+ function emitInspectorViewThread(payload) {
6355
+ if (!isInspectorThreadBridgeEnabled()) return false;
6356
+ const target = getEventTarget();
6357
+ if (!target) return false;
6358
+ const detail = {
6359
+ payload,
6360
+ claimed: false
6361
+ };
6362
+ target.dispatchEvent(createDetailEvent(eventName("view-thread"), detail));
6363
+ return detail.claimed;
6364
+ }
6365
+ function emitInspectorStopViewing(payload) {
6366
+ dispatch("stop-viewing", payload);
6367
+ }
6368
+ function emitInspectorActiveThread(payload) {
6369
+ dispatch("active-thread", payload);
6370
+ }
6371
+ function emitInspectorViewThreadResult(payload) {
6372
+ dispatch("view-thread-result", payload);
6373
+ }
6374
+ function onInspectorViewThread(handler) {
6375
+ if (!isInspectorThreadBridgeEnabled()) return () => void 0;
6376
+ const target = getEventTarget();
6377
+ if (!target) return () => void 0;
6378
+ const listener = (event) => {
6379
+ const detail = detailFromEvent(event);
6380
+ if (detail.claimed) return;
6381
+ detail.claimed = handler(detail.payload);
6382
+ };
6383
+ const name = eventName("view-thread");
6384
+ target.addEventListener(name, listener);
6385
+ return () => target.removeEventListener(name, listener);
6386
+ }
6387
+ function onInspectorStopViewing(handler) {
6388
+ return on$1("stop-viewing", handler);
6389
+ }
6390
+ function onInspectorActiveThread(handler) {
6391
+ return on$1("active-thread", handler);
6392
+ }
6393
+ function onInspectorViewThreadResult(handler) {
6394
+ return on$1("view-thread-result", handler);
6395
+ }
6396
+
6197
6397
  //#endregion
6198
6398
  exports.AgentRegistry = AgentRegistry;
6199
6399
  exports.AgentThreadLockedError = AgentThreadLockedError;
@@ -6201,6 +6401,7 @@ exports.ContextStore = ContextStore;
6201
6401
  exports.CopilotKitCore = CopilotKitCore;
6202
6402
  exports.CopilotKitCoreErrorCode = CopilotKitCoreErrorCode;
6203
6403
  exports.CopilotKitCoreRuntimeConnectionStatus = CopilotKitCoreRuntimeConnectionStatus;
6404
+ exports.INSPECTOR_THREAD_BRIDGE_PLUGIN_ID = INSPECTOR_THREAD_BRIDGE_PLUGIN_ID;
6204
6405
  exports.IntelligenceAgent = IntelligenceAgent;
6205
6406
  exports.MEMORY_ERROR_REGISTRY = MEMORY_ERROR_REGISTRY;
6206
6407
  exports.MemoryError = MemoryError;
@@ -6212,15 +6413,25 @@ exports.ToolCallStatus = ToolCallStatus;
6212
6413
  exports.completePartialMarkdown = completePartialMarkdown;
6213
6414
  exports.createActionGroup = createActionGroup;
6214
6415
  exports.createEffect = createEffect;
6416
+ exports.createInspectorThreadRequestId = createInspectorThreadRequestId;
6215
6417
  exports.createReducer = createReducer;
6216
6418
  exports.createSelector = createSelector;
6217
6419
  exports.createStore = createStore;
6420
+ exports.emitInspectorActiveThread = emitInspectorActiveThread;
6421
+ exports.emitInspectorStopViewing = emitInspectorStopViewing;
6422
+ exports.emitInspectorViewThread = emitInspectorViewThread;
6423
+ exports.emitInspectorViewThreadResult = emitInspectorViewThreadResult;
6218
6424
  exports.empty = empty;
6219
6425
  exports.ensureObjectArgs = ensureObjectArgs;
6220
6426
  exports.isAbortError = isAbortError;
6427
+ exports.isInspectorThreadBridgeEnabled = isInspectorThreadBridgeEnabled;
6221
6428
  exports.isRunCompletionAware = isRunCompletionAware;
6222
6429
  exports.ofType = ofType;
6223
6430
  exports.on = on;
6431
+ exports.onInspectorActiveThread = onInspectorActiveThread;
6432
+ exports.onInspectorStopViewing = onInspectorStopViewing;
6433
+ exports.onInspectorViewThread = onInspectorViewThread;
6434
+ exports.onInspectorViewThreadResult = onInspectorViewThreadResult;
6224
6435
  exports.parseToolArguments = parseToolArguments;
6225
6436
  exports.props = props;
6226
6437
  exports.select = select;