@copilotkit/core 1.84.0 → 1.84.2-canary.1793807121

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -26,6 +26,15 @@ function ɵisHttpAgent(agent) {
26
26
 
27
27
  //#endregion
28
28
  //#region src/utils/connect-replay.ts
29
+ const connectRunErrorPhases = /* @__PURE__ */ new WeakMap();
30
+ /**
31
+ * The phase in which a connection received `event`, as recorded when it
32
+ * arrived. Events that did not come through a connection with replay
33
+ * boundaries report `unknown`.
34
+ */
35
+ function ɵgetConnectRunErrorPhase(event) {
36
+ return connectRunErrorPhases.get(event) ?? "unknown";
37
+ }
29
38
  /**
30
39
  * Runs an agent's `connect()` stream through the AbstractAgent apply pipeline
31
40
  * with the `verifyEvents` step omitted.
@@ -80,6 +89,7 @@ async function ɵconnectWithoutEventVerification(agent, parameters, subscriber,
80
89
  let result;
81
90
  const previousMessageIds = new Set(agent.messages.map((m) => m.id));
82
91
  let isReplaying = true;
92
+ let reportsReplayPhase = false;
83
93
  const liveErrors = /* @__PURE__ */ new WeakSet();
84
94
  const subscribers = [
85
95
  {
@@ -127,15 +137,19 @@ async function ɵconnectWithoutEventVerification(agent, parameters, subscriber,
127
137
  };
128
138
  const lifecycle = {
129
139
  onReplayStarted: () => {
140
+ reportsReplayPhase = true;
130
141
  isReplaying = true;
131
142
  agent.isRunning = true;
132
143
  },
133
144
  onReplayFinished: () => {
145
+ reportsReplayPhase = true;
134
146
  isReplaying = false;
135
147
  }
136
148
  };
137
149
  const source$ = defer(() => new CompatibilityBoundary().run(input, { run: () => connect ? connect(input, lifecycle) : self.connect(input) })).pipe(tap((event) => {
138
- if (!isReplaying && event.type === EventType.RUN_ERROR) liveErrors.add(event);
150
+ if (event.type !== EventType.RUN_ERROR) return;
151
+ if (!isReplaying) liveErrors.add(event);
152
+ if (reportsReplayPhase) connectRunErrorPhases.set(event, isReplaying ? "replay" : "live");
139
153
  }), transformChunks(self.debugLogger), takeUntil(activeRunDetach$));
140
154
  const applied$ = self.apply(input, source$, subscribers);
141
155
  await lastValueFrom(self.processApplyEvents(input, applied$, subscribers).pipe(catchError((error) => {
@@ -302,6 +316,20 @@ var AgentThreadLockedError = class extends Error {
302
316
  }
303
317
  };
304
318
  /**
319
+ * The gateway could not replay a live run's events, so the client cannot
320
+ * verify the run it is following. The run itself may still be going on the
321
+ * server; reconnecting to the thread shows its real state.
322
+ */
323
+ var IntelligenceReplayFailedError = class extends Error {
324
+ code = "INTELLIGENCE_REPLAY_FAILED";
325
+ constructor(threadId, runId) {
326
+ super("The run's events could not be replayed. Reconnect to the thread to check the run's status.");
327
+ this.threadId = threadId;
328
+ this.runId = runId;
329
+ this.name = "IntelligenceReplayFailedError";
330
+ }
331
+ };
332
+ /**
305
333
  * Type guard for {@link RunCompletionAware}. Returns true when `agent` exposes
306
334
  * an `activeRunCompletionPromise` property, so callers can await an in-flight
307
335
  * run without an `as unknown as` cast. Returns false for agents that don't
@@ -627,6 +655,11 @@ var IntelligenceAgent = class IntelligenceAgent extends AbstractAgent {
627
655
  };
628
656
  const replayFailed$ = channel$.pipe(switchMap$1(({ channel }) => this.observeChannelEvent$(channel, REPLAY_FAILED_EVENT)), tap(() => {
629
657
  controlCursor.replayFailed = true;
658
+ if (options.streamMode === "run") {
659
+ if (reconnectCursor === null) this.clearReconnectCursor(input.threadId);
660
+ else this.advanceLastSeenEventId(input.threadId, reconnectCursor);
661
+ throw new IntelligenceReplayFailedError(input.threadId, input.runId ?? null);
662
+ }
630
663
  }));
631
664
  const replayComplete$ = this.observeControlEvent$(input.threadId, channel$, REPLAY_COMPLETE_EVENT, controlCursor).pipe(tap(() => {
632
665
  replayFinished = true;
@@ -3962,6 +3995,17 @@ var WebMCPRegistry = class {
3962
3995
  */
3963
3996
  const liveHITLStops = /* @__PURE__ */ new WeakMap();
3964
3997
  /**
3998
+ * Edits `agent.messages` by replacing the array instead of changing it in
3999
+ * place. The current array may be the one the agent emitted with its last
4000
+ * update, which subscribers and stored snapshots still hold. Like the in-place
4001
+ * edit it replaces, this notifies no subscriber.
4002
+ */
4003
+ function editAgentMessages(agent, edit) {
4004
+ const messages = [...agent.messages];
4005
+ edit(messages);
4006
+ agent.messages = messages;
4007
+ }
4008
+ /**
3965
4009
  * The message a failed tool call reports. An error thrown with an empty
3966
4010
  * message still means the call failed, so it gets a fallback rather than an
3967
4011
  * empty string, which everything downstream reads as success.
@@ -4337,7 +4381,7 @@ var RunHandler = class {
4337
4381
  forwardedProps: this._internal.getPropertiesForAgent(agent.agentId),
4338
4382
  tools: this.buildFrontendTools(agent.agentId),
4339
4383
  context: this._internal.getContextForAgent(agent.agentId)
4340
- }, this.createAgentErrorSubscriber(agent));
4384
+ }, this.createAgentErrorSubscriber(agent, "connect"));
4341
4385
  if (this._connectionGenerations.get(agent) !== connection || (agent.threadId ?? null) !== incomingThreadId) return runAgentResult;
4342
4386
  const controller = new AbortController();
4343
4387
  const replay = this._interactionAbortControllers.get(agent) ?? {
@@ -4441,7 +4485,7 @@ var RunHandler = class {
4441
4485
  agent
4442
4486
  }), "Subscriber onAgentRunStarted error:");
4443
4487
  let logicalRunId = resumedRunId ?? runId;
4444
- const agentSubscriber = this.createAgentErrorSubscriber(agent, controller.signal);
4488
+ const agentSubscriber = this.createAgentErrorSubscriber(agent, "run", controller.signal);
4445
4489
  let started = false;
4446
4490
  const onRunStartedEvent = agentSubscriber.onRunStartedEvent;
4447
4491
  const onRunInitialized = agentSubscriber.onRunInitialized;
@@ -4561,7 +4605,7 @@ var RunHandler = class {
4561
4605
  if (existingResultIndex !== -1) newMessages.splice(existingResultIndex, 1);
4562
4606
  existingResult = void 0;
4563
4607
  const agentMsgIdx = agent.messages.findIndex((m) => m.role === "tool" && m.toolCallId === toolCall.id);
4564
- if (agentMsgIdx !== -1) agent.messages.splice(agentMsgIdx, 1);
4608
+ if (agentMsgIdx !== -1) editAgentMessages(agent, (messages) => messages.splice(agentMsgIdx, 1));
4565
4609
  }
4566
4610
  if (!existingResult) {
4567
4611
  executing.add(executionKey);
@@ -4775,7 +4819,7 @@ var RunHandler = class {
4775
4819
  content: handlerResult.content,
4776
4820
  ...handlerResult.error ? { error: handlerResult.error } : {}
4777
4821
  };
4778
- agent.messages.splice(insertAt, 0, toolMessage);
4822
+ editAgentMessages(agent, (messages) => messages.splice(insertAt, 0, toolMessage));
4779
4823
  if (!handlerResult.error && tool?.followUp !== false) return true;
4780
4824
  }
4781
4825
  return false;
@@ -4868,7 +4912,7 @@ var RunHandler = class {
4868
4912
  content: toolCallResult,
4869
4913
  ...errorMessage ? { error: errorMessage } : {}
4870
4914
  };
4871
- agent.messages.splice(insertAt, 0, toolMessage);
4915
+ editAgentMessages(agent, (messages) => messages.splice(insertAt, 0, toolMessage));
4872
4916
  if (!errorMessage && wildcardTool?.followUp !== false) return true;
4873
4917
  }
4874
4918
  return false;
@@ -4922,7 +4966,7 @@ var RunHandler = class {
4922
4966
  content: "",
4923
4967
  toolCalls: [assistantToolCall]
4924
4968
  };
4925
- agent.messages.push(assistantMessage);
4969
+ editAgentMessages(agent, (messages) => messages.push(assistantMessage));
4926
4970
  let handlerResult = {
4927
4971
  content: "",
4928
4972
  result: "",
@@ -4945,8 +4989,8 @@ var RunHandler = class {
4945
4989
  ...handlerResult.error ? { error: handlerResult.error } : {}
4946
4990
  };
4947
4991
  const assistantIndex = agent.messages.findIndex((m) => m.id === assistantMessage.id);
4948
- if (assistantIndex !== -1) agent.messages.splice(assistantIndex + 1, 0, toolResultMessage);
4949
- else agent.messages.push(toolResultMessage);
4992
+ if (assistantIndex !== -1) editAgentMessages(agent, (messages) => messages.splice(assistantIndex + 1, 0, toolResultMessage));
4993
+ else editAgentMessages(agent, (messages) => messages.push(toolResultMessage));
4950
4994
  if (!handlerResult.error && followUp !== false) {
4951
4995
  if (typeof followUp === "string" && followUp !== "generate") {
4952
4996
  const userMessage = {
@@ -4954,7 +4998,7 @@ var RunHandler = class {
4954
4998
  role: "user",
4955
4999
  content: followUp
4956
5000
  };
4957
- agent.messages.push(userMessage);
5001
+ editAgentMessages(agent, (messages) => messages.push(userMessage));
4958
5002
  }
4959
5003
  await this._internal.waitForPendingFrameworkUpdates();
4960
5004
  await this.runAgent({ agent });
@@ -5024,7 +5068,7 @@ var RunHandler = class {
5024
5068
  /**
5025
5069
  * Create an agent error subscriber
5026
5070
  */
5027
- createAgentErrorSubscriber(agent, runSignal) {
5071
+ createAgentErrorSubscriber(agent, stream, runSignal) {
5028
5072
  const emitAgentError = async (error, code, extraContext = {}) => {
5029
5073
  const context = { ...extraContext };
5030
5074
  if (agent.agentId) context.agentId = agent.agentId;
@@ -5054,7 +5098,8 @@ var RunHandler = class {
5054
5098
  await emitAgentError(rawError, CopilotKitCoreErrorCode.AGENT_RUN_ERROR_EVENT, {
5055
5099
  source: "onRunErrorEvent",
5056
5100
  event,
5057
- runtimeErrorCode: event?.code
5101
+ runtimeErrorCode: event?.code,
5102
+ phase: stream === "run" ? "live" : ɵgetConnectRunErrorPhase(event)
5058
5103
  });
5059
5104
  }
5060
5105
  };
@@ -7440,6 +7485,12 @@ let CopilotKitCoreErrorCode = /* @__PURE__ */ function(CopilotKitCoreErrorCode)
7440
7485
  CopilotKitCoreErrorCode["AGENT_CONNECT_FAILED"] = "agent_connect_failed";
7441
7486
  CopilotKitCoreErrorCode["AGENT_RUN_FAILED"] = "agent_run_failed";
7442
7487
  CopilotKitCoreErrorCode["AGENT_RUN_FAILED_EVENT"] = "agent_run_failed_event";
7488
+ /**
7489
+ * An agent emitted RUN_ERROR. `context.phase` (`RunErrorPhase`) is
7490
+ * `"replay"` when the error belongs to stored thread history replayed on
7491
+ * connect, `"live"` when the run is happening now, and `"unknown"` when the
7492
+ * transport cannot tell. Show a live-failure notice only for `"live"`.
7493
+ */
7443
7494
  CopilotKitCoreErrorCode["AGENT_RUN_ERROR_EVENT"] = "agent_run_error_event";
7444
7495
  CopilotKitCoreErrorCode["TOOL_ARGUMENT_PARSE_FAILED"] = "tool_argument_parse_failed";
7445
7496
  CopilotKitCoreErrorCode["TOOL_HANDLER_FAILED"] = "tool_handler_failed";
@@ -10840,5 +10891,5 @@ function segmentSurfaceProse(components, options = {}) {
10840
10891
  }
10841
10892
 
10842
10893
  //#endregion
10843
- export { A2UI_FENCE_LANGUAGE, AgentRegistry, AgentThreadLockedError, ContextStore, CopilotKitCore, CopilotKitCoreErrorCode, CopilotKitCoreRuntimeConnectionStatus, CopilotKitHeaderResolutionError, INSPECTOR_THREAD_BRIDGE_PLUGIN_ID, IntelligenceAgent, MEMORY_ERROR_REGISTRY, MemoryError, ProxiedCopilotRuntimeAgent, RunHandler, StateManager, SuggestionEngine, ToolCallStatus, WebMCPRegistry, classifySurfaceCards, completePartialMarkdown, createActionGroup, createEffect, createInspectorThreadRequestId, createReducer, createSelector, createStore, emitInspectorActiveThread, emitInspectorStopViewing, emitInspectorViewThread, emitInspectorViewThreadResult, empty, ensureObjectArgs, extractCompleteArrayItems, extractFenceOperations, extractStringField, flattenInformationalCards, getMarkdownOperationSurfaceId, getWebMCPModelContext, isAbortError, isInspectorThreadBridgeEnabled, isRunCompletionAware, ofType, on, onInspectorActiveThread, onInspectorStopViewing, onInspectorViewThread, onInspectorViewThreadResult, parseToolArguments, prepareSurfaceOperations, props, segmentSurfaceProse, select, splitA2UIMarkdown, ɵCOPILOTKIT_FEATURES, ɵInterruptState, ɵMAX_SOCKET_RETRIES, ɵRUNTIME_PROBE_TIMEOUT_MS, ɵTHREAD_REQUEST_TIMEOUT_MS, ɵclearAgentInterruptState, createMemoryStore as ɵcreateMemoryStore, ɵcreateThreadSelectors, createThreadStore as ɵcreateThreadStore, ɵgetAgentInterruptState, ɵisCopilotKitFeature, ɵisHttpAgent, isRetryableStatus as ɵisRetryableMemoryStatus, ɵjoinPhoenixChannel$, ɵmapMemoryMetadataEvent, ɵmemoryAdapterEvents, ɵmemoryDomainEvents, ɵmemoryReducer, ɵmemoryRestEvents, ɵobservePhoenixEvent$, ɵobservePhoenixJoinOutcome$, ɵobservePhoenixSocketHealth$, ɵobservePhoenixSocketSignals$, ɵphoenixChannel$, ɵphoenixSocket$, ɵselectFetchMoreError, ɵselectHasNextPage, ɵselectIsFetchingNextPage, ɵselectIsMutating, ɵselectMemories, ɵselectMemoriesAvailable, ɵselectMemoriesError, ɵselectMemoriesIsLoading, ɵselectMemoriesIsMutating, ɵselectMemoriesRealtimeStatus, ɵselectThreads, ɵselectThreadsError, ɵselectThreadsIsLoading, ɵthreadAdapterEvents, ɵwithHeaderDefaults };
10894
+ export { A2UI_FENCE_LANGUAGE, AgentRegistry, AgentThreadLockedError, ContextStore, CopilotKitCore, CopilotKitCoreErrorCode, CopilotKitCoreRuntimeConnectionStatus, CopilotKitHeaderResolutionError, INSPECTOR_THREAD_BRIDGE_PLUGIN_ID, IntelligenceAgent, IntelligenceReplayFailedError, MEMORY_ERROR_REGISTRY, MemoryError, ProxiedCopilotRuntimeAgent, RunHandler, StateManager, SuggestionEngine, ToolCallStatus, WebMCPRegistry, classifySurfaceCards, completePartialMarkdown, createActionGroup, createEffect, createInspectorThreadRequestId, createReducer, createSelector, createStore, emitInspectorActiveThread, emitInspectorStopViewing, emitInspectorViewThread, emitInspectorViewThreadResult, empty, ensureObjectArgs, extractCompleteArrayItems, extractFenceOperations, extractStringField, flattenInformationalCards, getMarkdownOperationSurfaceId, getWebMCPModelContext, isAbortError, isInspectorThreadBridgeEnabled, isRunCompletionAware, ofType, on, onInspectorActiveThread, onInspectorStopViewing, onInspectorViewThread, onInspectorViewThreadResult, parseToolArguments, prepareSurfaceOperations, props, segmentSurfaceProse, select, splitA2UIMarkdown, ɵCOPILOTKIT_FEATURES, ɵInterruptState, ɵMAX_SOCKET_RETRIES, ɵRUNTIME_PROBE_TIMEOUT_MS, ɵTHREAD_REQUEST_TIMEOUT_MS, ɵclearAgentInterruptState, createMemoryStore as ɵcreateMemoryStore, ɵcreateThreadSelectors, createThreadStore as ɵcreateThreadStore, ɵgetAgentInterruptState, ɵisCopilotKitFeature, ɵisHttpAgent, isRetryableStatus as ɵisRetryableMemoryStatus, ɵjoinPhoenixChannel$, ɵmapMemoryMetadataEvent, ɵmemoryAdapterEvents, ɵmemoryDomainEvents, ɵmemoryReducer, ɵmemoryRestEvents, ɵobservePhoenixEvent$, ɵobservePhoenixJoinOutcome$, ɵobservePhoenixSocketHealth$, ɵobservePhoenixSocketSignals$, ɵphoenixChannel$, ɵphoenixSocket$, ɵselectFetchMoreError, ɵselectHasNextPage, ɵselectIsFetchingNextPage, ɵselectIsMutating, ɵselectMemories, ɵselectMemoriesAvailable, ɵselectMemoriesError, ɵselectMemoriesIsLoading, ɵselectMemoriesIsMutating, ɵselectMemoriesRealtimeStatus, ɵselectThreads, ɵselectThreadsError, ɵselectThreadsIsLoading, ɵthreadAdapterEvents, ɵwithHeaderDefaults };
10844
10895
  //# sourceMappingURL=index.mjs.map