@copilotkit/core 1.69.0 → 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.
@@ -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);
@@ -5105,6 +5209,67 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5105
5209
  async waitForPendingFrameworkUpdates() {}
5106
5210
  };
5107
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
+
5108
5273
  //#endregion
5109
5274
  //#region src/types.ts
5110
5275
  /**
@@ -6194,6 +6359,102 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
6194
6359
  };
6195
6360
  }
6196
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
+
6197
6458
  //#endregion
6198
6459
  exports.AgentRegistry = AgentRegistry;
6199
6460
  exports.AgentThreadLockedError = AgentThreadLockedError;
@@ -6201,6 +6462,7 @@ exports.ContextStore = ContextStore;
6201
6462
  exports.CopilotKitCore = CopilotKitCore;
6202
6463
  exports.CopilotKitCoreErrorCode = CopilotKitCoreErrorCode;
6203
6464
  exports.CopilotKitCoreRuntimeConnectionStatus = CopilotKitCoreRuntimeConnectionStatus;
6465
+ exports.INSPECTOR_THREAD_BRIDGE_PLUGIN_ID = INSPECTOR_THREAD_BRIDGE_PLUGIN_ID;
6204
6466
  exports.IntelligenceAgent = IntelligenceAgent;
6205
6467
  exports.MEMORY_ERROR_REGISTRY = MEMORY_ERROR_REGISTRY;
6206
6468
  exports.MemoryError = MemoryError;
@@ -6212,15 +6474,25 @@ exports.ToolCallStatus = ToolCallStatus;
6212
6474
  exports.completePartialMarkdown = completePartialMarkdown;
6213
6475
  exports.createActionGroup = createActionGroup;
6214
6476
  exports.createEffect = createEffect;
6477
+ exports.createInspectorThreadRequestId = createInspectorThreadRequestId;
6215
6478
  exports.createReducer = createReducer;
6216
6479
  exports.createSelector = createSelector;
6217
6480
  exports.createStore = createStore;
6481
+ exports.emitInspectorActiveThread = emitInspectorActiveThread;
6482
+ exports.emitInspectorStopViewing = emitInspectorStopViewing;
6483
+ exports.emitInspectorViewThread = emitInspectorViewThread;
6484
+ exports.emitInspectorViewThreadResult = emitInspectorViewThreadResult;
6218
6485
  exports.empty = empty;
6219
6486
  exports.ensureObjectArgs = ensureObjectArgs;
6220
6487
  exports.isAbortError = isAbortError;
6488
+ exports.isInspectorThreadBridgeEnabled = isInspectorThreadBridgeEnabled;
6221
6489
  exports.isRunCompletionAware = isRunCompletionAware;
6222
6490
  exports.ofType = ofType;
6223
6491
  exports.on = on;
6492
+ exports.onInspectorActiveThread = onInspectorActiveThread;
6493
+ exports.onInspectorStopViewing = onInspectorStopViewing;
6494
+ exports.onInspectorViewThread = onInspectorViewThread;
6495
+ exports.onInspectorViewThreadResult = onInspectorViewThreadResult;
6224
6496
  exports.parseToolArguments = parseToolArguments;
6225
6497
  exports.props = props;
6226
6498
  exports.select = select;
@@ -6230,6 +6502,7 @@ exports.ɵMAX_SOCKET_RETRIES = ɵMAX_SOCKET_RETRIES;
6230
6502
  exports.ɵcreateMemoryStore = createMemoryStore;
6231
6503
  exports.ɵcreateThreadSelectors = ɵcreateThreadSelectors;
6232
6504
  exports.ɵcreateThreadStore = createThreadStore;
6505
+ exports.ɵinjectInspectorEvents = ɵinjectInspectorEvents;
6233
6506
  exports.ɵisCopilotKitFeature = ɵisCopilotKitFeature;
6234
6507
  exports.ɵisRetryableMemoryStatus = isRetryableStatus;
6235
6508
  exports.ɵjoinPhoenixChannel$ = ɵjoinPhoenixChannel$;
@@ -6244,6 +6517,7 @@ exports.ɵobservePhoenixSocketHealth$ = ɵobservePhoenixSocketHealth$;
6244
6517
  exports.ɵobservePhoenixSocketSignals$ = ɵobservePhoenixSocketSignals$;
6245
6518
  exports.ɵphoenixChannel$ = ɵphoenixChannel$;
6246
6519
  exports.ɵphoenixSocket$ = ɵphoenixSocket$;
6520
+ exports.ɵresetInspectorInject = ɵresetInspectorInject;
6247
6521
  exports.ɵselectFetchMoreError = ɵselectFetchMoreError;
6248
6522
  exports.ɵselectHasNextPage = ɵselectHasNextPage;
6249
6523
  exports.ɵselectIsFetchingNextPage = ɵselectIsFetchingNextPage;