@copilotkit/core 1.79.1 → 1.79.2-canary.1792172552

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
@@ -25,6 +25,15 @@ function ɵisHttpAgent(agent) {
25
25
 
26
26
  //#endregion
27
27
  //#region src/utils/connect-replay.ts
28
+ const connectRunErrorPhases = /* @__PURE__ */ new WeakMap();
29
+ /**
30
+ * The phase in which a connection received `event`, as recorded when it
31
+ * arrived. Events that did not come through a connection with replay
32
+ * boundaries report `unknown`.
33
+ */
34
+ function ɵgetConnectRunErrorPhase(event) {
35
+ return connectRunErrorPhases.get(event) ?? "unknown";
36
+ }
28
37
  /**
29
38
  * Runs an agent's `connect()` stream through the AbstractAgent apply pipeline
30
39
  * with the `verifyEvents` step omitted.
@@ -79,6 +88,7 @@ async function ɵconnectWithoutEventVerification(agent, parameters, subscriber,
79
88
  let result;
80
89
  const previousMessageIds = new Set(agent.messages.map((m) => m.id));
81
90
  let isReplaying = true;
91
+ let reportsReplayPhase = false;
82
92
  const liveErrors = /* @__PURE__ */ new WeakSet();
83
93
  const subscribers = [
84
94
  {
@@ -126,15 +136,19 @@ async function ɵconnectWithoutEventVerification(agent, parameters, subscriber,
126
136
  };
127
137
  const lifecycle = {
128
138
  onReplayStarted: () => {
139
+ reportsReplayPhase = true;
129
140
  isReplaying = true;
130
141
  agent.isRunning = true;
131
142
  },
132
143
  onReplayFinished: () => {
144
+ reportsReplayPhase = true;
133
145
  isReplaying = false;
134
146
  }
135
147
  };
136
148
  const source$ = defer(() => new CompatibilityBoundary().run(input, { run: () => connect ? connect(input, lifecycle) : self.connect(input) })).pipe(tap((event) => {
137
- if (!isReplaying && event.type === EventType.RUN_ERROR) liveErrors.add(event);
149
+ if (event.type !== EventType.RUN_ERROR) return;
150
+ if (!isReplaying) liveErrors.add(event);
151
+ if (reportsReplayPhase) connectRunErrorPhases.set(event, isReplaying ? "replay" : "live");
138
152
  }), transformChunks(self.debugLogger), takeUntil(activeRunDetach$));
139
153
  const applied$ = self.apply(input, source$, subscribers);
140
154
  await lastValueFrom(self.processApplyEvents(input, applied$, subscribers).pipe(catchError((error) => {
@@ -301,6 +315,20 @@ var AgentThreadLockedError = class extends Error {
301
315
  }
302
316
  };
303
317
  /**
318
+ * The gateway could not replay a live run's events, so the client cannot
319
+ * verify the run it is following. The run itself may still be going on the
320
+ * server; reconnecting to the thread shows its real state.
321
+ */
322
+ var IntelligenceReplayFailedError = class extends Error {
323
+ code = "INTELLIGENCE_REPLAY_FAILED";
324
+ constructor(threadId, runId) {
325
+ super("The run's events could not be replayed. Reconnect to the thread to check the run's status.");
326
+ this.threadId = threadId;
327
+ this.runId = runId;
328
+ this.name = "IntelligenceReplayFailedError";
329
+ }
330
+ };
331
+ /**
304
332
  * Type guard for {@link RunCompletionAware}. Returns true when `agent` exposes
305
333
  * an `activeRunCompletionPromise` property, so callers can await an in-flight
306
334
  * run without an `as unknown as` cast. Returns false for agents that don't
@@ -626,6 +654,7 @@ var IntelligenceAgent = class IntelligenceAgent extends AbstractAgent {
626
654
  };
627
655
  const replayFailed$ = channel$.pipe(switchMap$1(({ channel }) => this.observeChannelEvent$(channel, REPLAY_FAILED_EVENT)), tap(() => {
628
656
  controlCursor.replayFailed = true;
657
+ if (options.streamMode === "run") throw new IntelligenceReplayFailedError(credentials.threadId, credentials.runId);
629
658
  }));
630
659
  const replayComplete$ = this.observeControlEvent$(input.threadId, channel$, REPLAY_COMPLETE_EVENT, controlCursor).pipe(tap(() => {
631
660
  replayFinished = true;
@@ -3450,6 +3479,17 @@ var WebMCPRegistry = class {
3450
3479
  * takes no reason and whose signals never expose one.
3451
3480
  */
3452
3481
  const liveHITLStops = /* @__PURE__ */ new WeakMap();
3482
+ /**
3483
+ * Edits `agent.messages` by replacing the array instead of changing it in
3484
+ * place. The current array may be the one the agent emitted with its last
3485
+ * update, which subscribers and stored snapshots still hold. Like the in-place
3486
+ * edit it replaces, this notifies no subscriber.
3487
+ */
3488
+ function editAgentMessages(agent, edit) {
3489
+ const messages = [...agent.messages];
3490
+ edit(messages);
3491
+ agent.messages = messages;
3492
+ }
3453
3493
  function discardAbortedResult(signal, discardOnAbort, errorMessage) {
3454
3494
  return !!(discardOnAbort && signal?.aborted && !(liveHITLStops.get(signal)?.() && errorMessage));
3455
3495
  }
@@ -3786,7 +3826,7 @@ var RunHandler = class {
3786
3826
  forwardedProps: this._internal.properties,
3787
3827
  tools: this.buildFrontendTools(agent.agentId),
3788
3828
  context: this._internal.getContextForAgent(agent.agentId)
3789
- }, this.createAgentErrorSubscriber(agent));
3829
+ }, this.createAgentErrorSubscriber(agent, "connect"));
3790
3830
  if (this._connectionGenerations.get(agent) !== connection || (agent.threadId ?? null) !== incomingThreadId) return runAgentResult;
3791
3831
  const controller = new AbortController();
3792
3832
  const replay = this._interactionAbortControllers.get(agent) ?? {
@@ -3877,7 +3917,7 @@ var RunHandler = class {
3877
3917
  this._runDepth++;
3878
3918
  try {
3879
3919
  let logicalRunId = resumedRunId ?? runId;
3880
- const agentSubscriber = this.createAgentErrorSubscriber(agent);
3920
+ const agentSubscriber = this.createAgentErrorSubscriber(agent, "run");
3881
3921
  let started = false;
3882
3922
  const onRunStartedEvent = agentSubscriber.onRunStartedEvent;
3883
3923
  const onRunInitialized = agentSubscriber.onRunInitialized;
@@ -3964,7 +4004,7 @@ var RunHandler = class {
3964
4004
  if (existingResultIndex !== -1) newMessages.splice(existingResultIndex, 1);
3965
4005
  existingResult = void 0;
3966
4006
  const agentMsgIdx = agent.messages.findIndex((m) => m.role === "tool" && m.toolCallId === toolCall.id);
3967
- if (agentMsgIdx !== -1) agent.messages.splice(agentMsgIdx, 1);
4007
+ if (agentMsgIdx !== -1) editAgentMessages(agent, (messages) => messages.splice(agentMsgIdx, 1));
3968
4008
  }
3969
4009
  if (!existingResult) {
3970
4010
  executing.add(executionKey);
@@ -4134,7 +4174,7 @@ var RunHandler = class {
4134
4174
  toolCallId: toolCall.id,
4135
4175
  content: handlerResult.content
4136
4176
  };
4137
- agent.messages.splice(insertAt, 0, toolMessage);
4177
+ editAgentMessages(agent, (messages) => messages.splice(insertAt, 0, toolMessage));
4138
4178
  if (!handlerResult.error && tool?.followUp !== false) return true;
4139
4179
  }
4140
4180
  return false;
@@ -4227,7 +4267,7 @@ var RunHandler = class {
4227
4267
  toolCallId: toolCall.id,
4228
4268
  content: toolCallResult
4229
4269
  };
4230
- agent.messages.splice(insertAt, 0, toolMessage);
4270
+ editAgentMessages(agent, (messages) => messages.splice(insertAt, 0, toolMessage));
4231
4271
  if (!errorMessage && wildcardTool?.followUp !== false) return true;
4232
4272
  }
4233
4273
  return false;
@@ -4281,7 +4321,7 @@ var RunHandler = class {
4281
4321
  content: "",
4282
4322
  toolCalls: [assistantToolCall]
4283
4323
  };
4284
- agent.messages.push(assistantMessage);
4324
+ editAgentMessages(agent, (messages) => messages.push(assistantMessage));
4285
4325
  let handlerResult = {
4286
4326
  content: "",
4287
4327
  result: "",
@@ -4303,8 +4343,8 @@ var RunHandler = class {
4303
4343
  content: handlerResult.content
4304
4344
  };
4305
4345
  const assistantIndex = agent.messages.findIndex((m) => m.id === assistantMessage.id);
4306
- if (assistantIndex !== -1) agent.messages.splice(assistantIndex + 1, 0, toolResultMessage);
4307
- else agent.messages.push(toolResultMessage);
4346
+ if (assistantIndex !== -1) editAgentMessages(agent, (messages) => messages.splice(assistantIndex + 1, 0, toolResultMessage));
4347
+ else editAgentMessages(agent, (messages) => messages.push(toolResultMessage));
4308
4348
  if (!handlerResult.error && followUp !== false) {
4309
4349
  if (typeof followUp === "string" && followUp !== "generate") {
4310
4350
  const userMessage = {
@@ -4312,7 +4352,7 @@ var RunHandler = class {
4312
4352
  role: "user",
4313
4353
  content: followUp
4314
4354
  };
4315
- agent.messages.push(userMessage);
4355
+ editAgentMessages(agent, (messages) => messages.push(userMessage));
4316
4356
  }
4317
4357
  await this._internal.waitForPendingFrameworkUpdates();
4318
4358
  await this.runAgent({ agent });
@@ -4382,7 +4422,7 @@ var RunHandler = class {
4382
4422
  /**
4383
4423
  * Create an agent error subscriber
4384
4424
  */
4385
- createAgentErrorSubscriber(agent) {
4425
+ createAgentErrorSubscriber(agent, stream) {
4386
4426
  const emitAgentError = async (error, code, extraContext = {}) => {
4387
4427
  const context = { ...extraContext };
4388
4428
  if (agent.agentId) context.agentId = agent.agentId;
@@ -4405,7 +4445,8 @@ var RunHandler = class {
4405
4445
  await emitAgentError(rawError, CopilotKitCoreErrorCode.AGENT_RUN_ERROR_EVENT, {
4406
4446
  source: "onRunErrorEvent",
4407
4447
  event,
4408
- runtimeErrorCode: event?.code
4448
+ runtimeErrorCode: event?.code,
4449
+ phase: stream === "run" ? "live" : ɵgetConnectRunErrorPhase(event)
4409
4450
  });
4410
4451
  }
4411
4452
  };
@@ -6770,6 +6811,12 @@ let CopilotKitCoreErrorCode = /* @__PURE__ */ function(CopilotKitCoreErrorCode)
6770
6811
  CopilotKitCoreErrorCode["AGENT_CONNECT_FAILED"] = "agent_connect_failed";
6771
6812
  CopilotKitCoreErrorCode["AGENT_RUN_FAILED"] = "agent_run_failed";
6772
6813
  CopilotKitCoreErrorCode["AGENT_RUN_FAILED_EVENT"] = "agent_run_failed_event";
6814
+ /**
6815
+ * An agent emitted RUN_ERROR. `context.phase` (`RunErrorPhase`) is
6816
+ * `"replay"` when the error belongs to stored thread history replayed on
6817
+ * connect, `"live"` when the run is happening now, and `"unknown"` when the
6818
+ * transport cannot tell. Show a live-failure notice only for `"live"`.
6819
+ */
6773
6820
  CopilotKitCoreErrorCode["AGENT_RUN_ERROR_EVENT"] = "agent_run_error_event";
6774
6821
  CopilotKitCoreErrorCode["TOOL_ARGUMENT_PARSE_FAILED"] = "tool_argument_parse_failed";
6775
6822
  CopilotKitCoreErrorCode["TOOL_HANDLER_FAILED"] = "tool_handler_failed";
@@ -8831,5 +8878,5 @@ function onInspectorViewThreadResult(handler) {
8831
8878
  }
8832
8879
 
8833
8880
  //#endregion
8834
- export { AgentRegistry, AgentThreadLockedError, ContextStore, CopilotKitCore, CopilotKitCoreErrorCode, CopilotKitCoreRuntimeConnectionStatus, CopilotKitHeaderResolutionError, INSPECTOR_THREAD_BRIDGE_PLUGIN_ID, IntelligenceAgent, MEMORY_ERROR_REGISTRY, MemoryError, ProxiedCopilotRuntimeAgent, RunHandler, StateManager, SuggestionEngine, ToolCallStatus, WebMCPRegistry, completePartialMarkdown, createActionGroup, createEffect, createInspectorThreadRequestId, createReducer, createSelector, createStore, emitInspectorActiveThread, emitInspectorStopViewing, emitInspectorViewThread, emitInspectorViewThreadResult, empty, ensureObjectArgs, getWebMCPModelContext, isAbortError, isInspectorThreadBridgeEnabled, isRunCompletionAware, ofType, on, onInspectorActiveThread, onInspectorStopViewing, onInspectorViewThread, onInspectorViewThreadResult, parseToolArguments, props, select, ɵCOPILOTKIT_FEATURES, ɵInterruptState, ɵMAX_SOCKET_RETRIES, ɵRUNTIME_PROBE_TIMEOUT_MS, ɵTHREAD_REQUEST_TIMEOUT_MS, createMemoryStore as ɵcreateMemoryStore, ɵcreateThreadSelectors, createThreadStore as ɵcreateThreadStore, ɵ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 };
8881
+ export { AgentRegistry, AgentThreadLockedError, ContextStore, CopilotKitCore, CopilotKitCoreErrorCode, CopilotKitCoreRuntimeConnectionStatus, CopilotKitHeaderResolutionError, INSPECTOR_THREAD_BRIDGE_PLUGIN_ID, IntelligenceAgent, IntelligenceReplayFailedError, MEMORY_ERROR_REGISTRY, MemoryError, ProxiedCopilotRuntimeAgent, RunHandler, StateManager, SuggestionEngine, ToolCallStatus, WebMCPRegistry, completePartialMarkdown, createActionGroup, createEffect, createInspectorThreadRequestId, createReducer, createSelector, createStore, emitInspectorActiveThread, emitInspectorStopViewing, emitInspectorViewThread, emitInspectorViewThreadResult, empty, ensureObjectArgs, getWebMCPModelContext, isAbortError, isInspectorThreadBridgeEnabled, isRunCompletionAware, ofType, on, onInspectorActiveThread, onInspectorStopViewing, onInspectorViewThread, onInspectorViewThreadResult, parseToolArguments, props, select, ɵCOPILOTKIT_FEATURES, ɵInterruptState, ɵMAX_SOCKET_RETRIES, ɵRUNTIME_PROBE_TIMEOUT_MS, ɵTHREAD_REQUEST_TIMEOUT_MS, createMemoryStore as ɵcreateMemoryStore, ɵcreateThreadSelectors, createThreadStore as ɵcreateThreadStore, ɵ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 };
8835
8882
  //# sourceMappingURL=index.mjs.map