@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.cjs CHANGED
@@ -27,6 +27,15 @@ function ɵisHttpAgent(agent) {
27
27
 
28
28
  //#endregion
29
29
  //#region src/utils/connect-replay.ts
30
+ const connectRunErrorPhases = /* @__PURE__ */ new WeakMap();
31
+ /**
32
+ * The phase in which a connection received `event`, as recorded when it
33
+ * arrived. Events that did not come through a connection with replay
34
+ * boundaries report `unknown`.
35
+ */
36
+ function ɵgetConnectRunErrorPhase(event) {
37
+ return connectRunErrorPhases.get(event) ?? "unknown";
38
+ }
30
39
  /**
31
40
  * Runs an agent's `connect()` stream through the AbstractAgent apply pipeline
32
41
  * with the `verifyEvents` step omitted.
@@ -81,6 +90,7 @@ async function ɵconnectWithoutEventVerification(agent, parameters, subscriber,
81
90
  let result;
82
91
  const previousMessageIds = new Set(agent.messages.map((m) => m.id));
83
92
  let isReplaying = true;
93
+ let reportsReplayPhase = false;
84
94
  const liveErrors = /* @__PURE__ */ new WeakSet();
85
95
  const subscribers = [
86
96
  {
@@ -128,15 +138,19 @@ async function ɵconnectWithoutEventVerification(agent, parameters, subscriber,
128
138
  };
129
139
  const lifecycle = {
130
140
  onReplayStarted: () => {
141
+ reportsReplayPhase = true;
131
142
  isReplaying = true;
132
143
  agent.isRunning = true;
133
144
  },
134
145
  onReplayFinished: () => {
146
+ reportsReplayPhase = true;
135
147
  isReplaying = false;
136
148
  }
137
149
  };
138
150
  const source$ = (0, rxjs.defer)(() => new _ag_ui_client.CompatibilityBoundary().run(input, { run: () => connect ? connect(input, lifecycle) : self.connect(input) })).pipe((0, rxjs_operators.tap)((event) => {
139
- if (!isReplaying && event.type === _ag_ui_client.EventType.RUN_ERROR) liveErrors.add(event);
151
+ if (event.type !== _ag_ui_client.EventType.RUN_ERROR) return;
152
+ if (!isReplaying) liveErrors.add(event);
153
+ if (reportsReplayPhase) connectRunErrorPhases.set(event, isReplaying ? "replay" : "live");
140
154
  }), (0, _ag_ui_client.transformChunks)(self.debugLogger), (0, rxjs_operators.takeUntil)(activeRunDetach$));
141
155
  const applied$ = self.apply(input, source$, subscribers);
142
156
  await (0, rxjs.lastValueFrom)(self.processApplyEvents(input, applied$, subscribers).pipe((0, rxjs_operators.catchError)((error) => {
@@ -303,6 +317,20 @@ var AgentThreadLockedError = class extends Error {
303
317
  }
304
318
  };
305
319
  /**
320
+ * The gateway could not replay a live run's events, so the client cannot
321
+ * verify the run it is following. The run itself may still be going on the
322
+ * server; reconnecting to the thread shows its real state.
323
+ */
324
+ var IntelligenceReplayFailedError = class extends Error {
325
+ code = "INTELLIGENCE_REPLAY_FAILED";
326
+ constructor(threadId, runId) {
327
+ super("The run's events could not be replayed. Reconnect to the thread to check the run's status.");
328
+ this.threadId = threadId;
329
+ this.runId = runId;
330
+ this.name = "IntelligenceReplayFailedError";
331
+ }
332
+ };
333
+ /**
306
334
  * Type guard for {@link RunCompletionAware}. Returns true when `agent` exposes
307
335
  * an `activeRunCompletionPromise` property, so callers can await an in-flight
308
336
  * run without an `as unknown as` cast. Returns false for agents that don't
@@ -628,6 +656,11 @@ var IntelligenceAgent = class IntelligenceAgent extends _ag_ui_client.AbstractAg
628
656
  };
629
657
  const replayFailed$ = channel$.pipe((0, rxjs_operators.switchMap)(({ channel }) => this.observeChannelEvent$(channel, REPLAY_FAILED_EVENT)), (0, rxjs_operators.tap)(() => {
630
658
  controlCursor.replayFailed = true;
659
+ if (options.streamMode === "run") {
660
+ if (reconnectCursor === null) this.clearReconnectCursor(input.threadId);
661
+ else this.advanceLastSeenEventId(input.threadId, reconnectCursor);
662
+ throw new IntelligenceReplayFailedError(input.threadId, input.runId ?? null);
663
+ }
631
664
  }));
632
665
  const replayComplete$ = this.observeControlEvent$(input.threadId, channel$, REPLAY_COMPLETE_EVENT, controlCursor).pipe((0, rxjs_operators.tap)(() => {
633
666
  replayFinished = true;
@@ -3963,6 +3996,17 @@ var WebMCPRegistry = class {
3963
3996
  */
3964
3997
  const liveHITLStops = /* @__PURE__ */ new WeakMap();
3965
3998
  /**
3999
+ * Edits `agent.messages` by replacing the array instead of changing it in
4000
+ * place. The current array may be the one the agent emitted with its last
4001
+ * update, which subscribers and stored snapshots still hold. Like the in-place
4002
+ * edit it replaces, this notifies no subscriber.
4003
+ */
4004
+ function editAgentMessages(agent, edit) {
4005
+ const messages = [...agent.messages];
4006
+ edit(messages);
4007
+ agent.messages = messages;
4008
+ }
4009
+ /**
3966
4010
  * The message a failed tool call reports. An error thrown with an empty
3967
4011
  * message still means the call failed, so it gets a fallback rather than an
3968
4012
  * empty string, which everything downstream reads as success.
@@ -4338,7 +4382,7 @@ var RunHandler = class {
4338
4382
  forwardedProps: this._internal.getPropertiesForAgent(agent.agentId),
4339
4383
  tools: this.buildFrontendTools(agent.agentId),
4340
4384
  context: this._internal.getContextForAgent(agent.agentId)
4341
- }, this.createAgentErrorSubscriber(agent));
4385
+ }, this.createAgentErrorSubscriber(agent, "connect"));
4342
4386
  if (this._connectionGenerations.get(agent) !== connection || (agent.threadId ?? null) !== incomingThreadId) return runAgentResult;
4343
4387
  const controller = new AbortController();
4344
4388
  const replay = this._interactionAbortControllers.get(agent) ?? {
@@ -4442,7 +4486,7 @@ var RunHandler = class {
4442
4486
  agent
4443
4487
  }), "Subscriber onAgentRunStarted error:");
4444
4488
  let logicalRunId = resumedRunId ?? runId;
4445
- const agentSubscriber = this.createAgentErrorSubscriber(agent, controller.signal);
4489
+ const agentSubscriber = this.createAgentErrorSubscriber(agent, "run", controller.signal);
4446
4490
  let started = false;
4447
4491
  const onRunStartedEvent = agentSubscriber.onRunStartedEvent;
4448
4492
  const onRunInitialized = agentSubscriber.onRunInitialized;
@@ -4562,7 +4606,7 @@ var RunHandler = class {
4562
4606
  if (existingResultIndex !== -1) newMessages.splice(existingResultIndex, 1);
4563
4607
  existingResult = void 0;
4564
4608
  const agentMsgIdx = agent.messages.findIndex((m) => m.role === "tool" && m.toolCallId === toolCall.id);
4565
- if (agentMsgIdx !== -1) agent.messages.splice(agentMsgIdx, 1);
4609
+ if (agentMsgIdx !== -1) editAgentMessages(agent, (messages) => messages.splice(agentMsgIdx, 1));
4566
4610
  }
4567
4611
  if (!existingResult) {
4568
4612
  executing.add(executionKey);
@@ -4776,7 +4820,7 @@ var RunHandler = class {
4776
4820
  content: handlerResult.content,
4777
4821
  ...handlerResult.error ? { error: handlerResult.error } : {}
4778
4822
  };
4779
- agent.messages.splice(insertAt, 0, toolMessage);
4823
+ editAgentMessages(agent, (messages) => messages.splice(insertAt, 0, toolMessage));
4780
4824
  if (!handlerResult.error && tool?.followUp !== false) return true;
4781
4825
  }
4782
4826
  return false;
@@ -4869,7 +4913,7 @@ var RunHandler = class {
4869
4913
  content: toolCallResult,
4870
4914
  ...errorMessage ? { error: errorMessage } : {}
4871
4915
  };
4872
- agent.messages.splice(insertAt, 0, toolMessage);
4916
+ editAgentMessages(agent, (messages) => messages.splice(insertAt, 0, toolMessage));
4873
4917
  if (!errorMessage && wildcardTool?.followUp !== false) return true;
4874
4918
  }
4875
4919
  return false;
@@ -4923,7 +4967,7 @@ var RunHandler = class {
4923
4967
  content: "",
4924
4968
  toolCalls: [assistantToolCall]
4925
4969
  };
4926
- agent.messages.push(assistantMessage);
4970
+ editAgentMessages(agent, (messages) => messages.push(assistantMessage));
4927
4971
  let handlerResult = {
4928
4972
  content: "",
4929
4973
  result: "",
@@ -4946,8 +4990,8 @@ var RunHandler = class {
4946
4990
  ...handlerResult.error ? { error: handlerResult.error } : {}
4947
4991
  };
4948
4992
  const assistantIndex = agent.messages.findIndex((m) => m.id === assistantMessage.id);
4949
- if (assistantIndex !== -1) agent.messages.splice(assistantIndex + 1, 0, toolResultMessage);
4950
- else agent.messages.push(toolResultMessage);
4993
+ if (assistantIndex !== -1) editAgentMessages(agent, (messages) => messages.splice(assistantIndex + 1, 0, toolResultMessage));
4994
+ else editAgentMessages(agent, (messages) => messages.push(toolResultMessage));
4951
4995
  if (!handlerResult.error && followUp !== false) {
4952
4996
  if (typeof followUp === "string" && followUp !== "generate") {
4953
4997
  const userMessage = {
@@ -4955,7 +4999,7 @@ var RunHandler = class {
4955
4999
  role: "user",
4956
5000
  content: followUp
4957
5001
  };
4958
- agent.messages.push(userMessage);
5002
+ editAgentMessages(agent, (messages) => messages.push(userMessage));
4959
5003
  }
4960
5004
  await this._internal.waitForPendingFrameworkUpdates();
4961
5005
  await this.runAgent({ agent });
@@ -5025,7 +5069,7 @@ var RunHandler = class {
5025
5069
  /**
5026
5070
  * Create an agent error subscriber
5027
5071
  */
5028
- createAgentErrorSubscriber(agent, runSignal) {
5072
+ createAgentErrorSubscriber(agent, stream, runSignal) {
5029
5073
  const emitAgentError = async (error, code, extraContext = {}) => {
5030
5074
  const context = { ...extraContext };
5031
5075
  if (agent.agentId) context.agentId = agent.agentId;
@@ -5055,7 +5099,8 @@ var RunHandler = class {
5055
5099
  await emitAgentError(rawError, CopilotKitCoreErrorCode.AGENT_RUN_ERROR_EVENT, {
5056
5100
  source: "onRunErrorEvent",
5057
5101
  event,
5058
- runtimeErrorCode: event?.code
5102
+ runtimeErrorCode: event?.code,
5103
+ phase: stream === "run" ? "live" : ɵgetConnectRunErrorPhase(event)
5059
5104
  });
5060
5105
  }
5061
5106
  };
@@ -7441,6 +7486,12 @@ let CopilotKitCoreErrorCode = /* @__PURE__ */ function(CopilotKitCoreErrorCode)
7441
7486
  CopilotKitCoreErrorCode["AGENT_CONNECT_FAILED"] = "agent_connect_failed";
7442
7487
  CopilotKitCoreErrorCode["AGENT_RUN_FAILED"] = "agent_run_failed";
7443
7488
  CopilotKitCoreErrorCode["AGENT_RUN_FAILED_EVENT"] = "agent_run_failed_event";
7489
+ /**
7490
+ * An agent emitted RUN_ERROR. `context.phase` (`RunErrorPhase`) is
7491
+ * `"replay"` when the error belongs to stored thread history replayed on
7492
+ * connect, `"live"` when the run is happening now, and `"unknown"` when the
7493
+ * transport cannot tell. Show a live-failure notice only for `"live"`.
7494
+ */
7444
7495
  CopilotKitCoreErrorCode["AGENT_RUN_ERROR_EVENT"] = "agent_run_error_event";
7445
7496
  CopilotKitCoreErrorCode["TOOL_ARGUMENT_PARSE_FAILED"] = "tool_argument_parse_failed";
7446
7497
  CopilotKitCoreErrorCode["TOOL_HANDLER_FAILED"] = "tool_handler_failed";
@@ -10851,6 +10902,7 @@ exports.CopilotKitCoreRuntimeConnectionStatus = CopilotKitCoreRuntimeConnectionS
10851
10902
  exports.CopilotKitHeaderResolutionError = CopilotKitHeaderResolutionError;
10852
10903
  exports.INSPECTOR_THREAD_BRIDGE_PLUGIN_ID = INSPECTOR_THREAD_BRIDGE_PLUGIN_ID;
10853
10904
  exports.IntelligenceAgent = IntelligenceAgent;
10905
+ exports.IntelligenceReplayFailedError = IntelligenceReplayFailedError;
10854
10906
  exports.MEMORY_ERROR_REGISTRY = MEMORY_ERROR_REGISTRY;
10855
10907
  exports.MemoryError = MemoryError;
10856
10908
  exports.ProxiedCopilotRuntimeAgent = ProxiedCopilotRuntimeAgent;