@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.cjs 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$ = (0, rxjs.defer)(() => new _ag_ui_client.CompatibilityBoundary().run(input, { run: () => connect ? connect(input, lifecycle) : self.connect(input) })).pipe((0, rxjs_operators.tap)((event) => {
138
- if (!isReplaying && event.type === _ag_ui_client.EventType.RUN_ERROR) liveErrors.add(event);
150
+ if (event.type !== _ag_ui_client.EventType.RUN_ERROR) return;
151
+ if (!isReplaying) liveErrors.add(event);
152
+ if (reportsReplayPhase) connectRunErrorPhases.set(event, isReplaying ? "replay" : "live");
139
153
  }), (0, _ag_ui_client.transformChunks)(self.debugLogger), (0, rxjs_operators.takeUntil)(activeRunDetach$));
140
154
  const applied$ = self.apply(input, source$, subscribers);
141
155
  await (0, rxjs.lastValueFrom)(self.processApplyEvents(input, applied$, subscribers).pipe((0, rxjs_operators.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,7 @@ var IntelligenceAgent = class IntelligenceAgent extends _ag_ui_client.AbstractAg
627
655
  };
628
656
  const replayFailed$ = channel$.pipe((0, rxjs_operators.switchMap)(({ channel }) => this.observeChannelEvent$(channel, REPLAY_FAILED_EVENT)), (0, rxjs_operators.tap)(() => {
629
657
  controlCursor.replayFailed = true;
658
+ if (options.streamMode === "run") throw new IntelligenceReplayFailedError(credentials.threadId, credentials.runId);
630
659
  }));
631
660
  const replayComplete$ = this.observeControlEvent$(input.threadId, channel$, REPLAY_COMPLETE_EVENT, controlCursor).pipe((0, rxjs_operators.tap)(() => {
632
661
  replayFinished = true;
@@ -3451,6 +3480,17 @@ var WebMCPRegistry = class {
3451
3480
  * takes no reason and whose signals never expose one.
3452
3481
  */
3453
3482
  const liveHITLStops = /* @__PURE__ */ new WeakMap();
3483
+ /**
3484
+ * Edits `agent.messages` by replacing the array instead of changing it in
3485
+ * place. The current array may be the one the agent emitted with its last
3486
+ * update, which subscribers and stored snapshots still hold. Like the in-place
3487
+ * edit it replaces, this notifies no subscriber.
3488
+ */
3489
+ function editAgentMessages(agent, edit) {
3490
+ const messages = [...agent.messages];
3491
+ edit(messages);
3492
+ agent.messages = messages;
3493
+ }
3454
3494
  function discardAbortedResult(signal, discardOnAbort, errorMessage) {
3455
3495
  return !!(discardOnAbort && signal?.aborted && !(liveHITLStops.get(signal)?.() && errorMessage));
3456
3496
  }
@@ -3787,7 +3827,7 @@ var RunHandler = class {
3787
3827
  forwardedProps: this._internal.properties,
3788
3828
  tools: this.buildFrontendTools(agent.agentId),
3789
3829
  context: this._internal.getContextForAgent(agent.agentId)
3790
- }, this.createAgentErrorSubscriber(agent));
3830
+ }, this.createAgentErrorSubscriber(agent, "connect"));
3791
3831
  if (this._connectionGenerations.get(agent) !== connection || (agent.threadId ?? null) !== incomingThreadId) return runAgentResult;
3792
3832
  const controller = new AbortController();
3793
3833
  const replay = this._interactionAbortControllers.get(agent) ?? {
@@ -3878,7 +3918,7 @@ var RunHandler = class {
3878
3918
  this._runDepth++;
3879
3919
  try {
3880
3920
  let logicalRunId = resumedRunId ?? runId;
3881
- const agentSubscriber = this.createAgentErrorSubscriber(agent);
3921
+ const agentSubscriber = this.createAgentErrorSubscriber(agent, "run");
3882
3922
  let started = false;
3883
3923
  const onRunStartedEvent = agentSubscriber.onRunStartedEvent;
3884
3924
  const onRunInitialized = agentSubscriber.onRunInitialized;
@@ -3965,7 +4005,7 @@ var RunHandler = class {
3965
4005
  if (existingResultIndex !== -1) newMessages.splice(existingResultIndex, 1);
3966
4006
  existingResult = void 0;
3967
4007
  const agentMsgIdx = agent.messages.findIndex((m) => m.role === "tool" && m.toolCallId === toolCall.id);
3968
- if (agentMsgIdx !== -1) agent.messages.splice(agentMsgIdx, 1);
4008
+ if (agentMsgIdx !== -1) editAgentMessages(agent, (messages) => messages.splice(agentMsgIdx, 1));
3969
4009
  }
3970
4010
  if (!existingResult) {
3971
4011
  executing.add(executionKey);
@@ -4135,7 +4175,7 @@ var RunHandler = class {
4135
4175
  toolCallId: toolCall.id,
4136
4176
  content: handlerResult.content
4137
4177
  };
4138
- agent.messages.splice(insertAt, 0, toolMessage);
4178
+ editAgentMessages(agent, (messages) => messages.splice(insertAt, 0, toolMessage));
4139
4179
  if (!handlerResult.error && tool?.followUp !== false) return true;
4140
4180
  }
4141
4181
  return false;
@@ -4228,7 +4268,7 @@ var RunHandler = class {
4228
4268
  toolCallId: toolCall.id,
4229
4269
  content: toolCallResult
4230
4270
  };
4231
- agent.messages.splice(insertAt, 0, toolMessage);
4271
+ editAgentMessages(agent, (messages) => messages.splice(insertAt, 0, toolMessage));
4232
4272
  if (!errorMessage && wildcardTool?.followUp !== false) return true;
4233
4273
  }
4234
4274
  return false;
@@ -4282,7 +4322,7 @@ var RunHandler = class {
4282
4322
  content: "",
4283
4323
  toolCalls: [assistantToolCall]
4284
4324
  };
4285
- agent.messages.push(assistantMessage);
4325
+ editAgentMessages(agent, (messages) => messages.push(assistantMessage));
4286
4326
  let handlerResult = {
4287
4327
  content: "",
4288
4328
  result: "",
@@ -4304,8 +4344,8 @@ var RunHandler = class {
4304
4344
  content: handlerResult.content
4305
4345
  };
4306
4346
  const assistantIndex = agent.messages.findIndex((m) => m.id === assistantMessage.id);
4307
- if (assistantIndex !== -1) agent.messages.splice(assistantIndex + 1, 0, toolResultMessage);
4308
- else agent.messages.push(toolResultMessage);
4347
+ if (assistantIndex !== -1) editAgentMessages(agent, (messages) => messages.splice(assistantIndex + 1, 0, toolResultMessage));
4348
+ else editAgentMessages(agent, (messages) => messages.push(toolResultMessage));
4309
4349
  if (!handlerResult.error && followUp !== false) {
4310
4350
  if (typeof followUp === "string" && followUp !== "generate") {
4311
4351
  const userMessage = {
@@ -4313,7 +4353,7 @@ var RunHandler = class {
4313
4353
  role: "user",
4314
4354
  content: followUp
4315
4355
  };
4316
- agent.messages.push(userMessage);
4356
+ editAgentMessages(agent, (messages) => messages.push(userMessage));
4317
4357
  }
4318
4358
  await this._internal.waitForPendingFrameworkUpdates();
4319
4359
  await this.runAgent({ agent });
@@ -4383,7 +4423,7 @@ var RunHandler = class {
4383
4423
  /**
4384
4424
  * Create an agent error subscriber
4385
4425
  */
4386
- createAgentErrorSubscriber(agent) {
4426
+ createAgentErrorSubscriber(agent, stream) {
4387
4427
  const emitAgentError = async (error, code, extraContext = {}) => {
4388
4428
  const context = { ...extraContext };
4389
4429
  if (agent.agentId) context.agentId = agent.agentId;
@@ -4406,7 +4446,8 @@ var RunHandler = class {
4406
4446
  await emitAgentError(rawError, CopilotKitCoreErrorCode.AGENT_RUN_ERROR_EVENT, {
4407
4447
  source: "onRunErrorEvent",
4408
4448
  event,
4409
- runtimeErrorCode: event?.code
4449
+ runtimeErrorCode: event?.code,
4450
+ phase: stream === "run" ? "live" : ɵgetConnectRunErrorPhase(event)
4410
4451
  });
4411
4452
  }
4412
4453
  };
@@ -6771,6 +6812,12 @@ let CopilotKitCoreErrorCode = /* @__PURE__ */ function(CopilotKitCoreErrorCode)
6771
6812
  CopilotKitCoreErrorCode["AGENT_CONNECT_FAILED"] = "agent_connect_failed";
6772
6813
  CopilotKitCoreErrorCode["AGENT_RUN_FAILED"] = "agent_run_failed";
6773
6814
  CopilotKitCoreErrorCode["AGENT_RUN_FAILED_EVENT"] = "agent_run_failed_event";
6815
+ /**
6816
+ * An agent emitted RUN_ERROR. `context.phase` (`RunErrorPhase`) is
6817
+ * `"replay"` when the error belongs to stored thread history replayed on
6818
+ * connect, `"live"` when the run is happening now, and `"unknown"` when the
6819
+ * transport cannot tell. Show a live-failure notice only for `"live"`.
6820
+ */
6774
6821
  CopilotKitCoreErrorCode["AGENT_RUN_ERROR_EVENT"] = "agent_run_error_event";
6775
6822
  CopilotKitCoreErrorCode["TOOL_ARGUMENT_PARSE_FAILED"] = "tool_argument_parse_failed";
6776
6823
  CopilotKitCoreErrorCode["TOOL_HANDLER_FAILED"] = "tool_handler_failed";
@@ -8841,6 +8888,7 @@ exports.CopilotKitCoreRuntimeConnectionStatus = CopilotKitCoreRuntimeConnectionS
8841
8888
  exports.CopilotKitHeaderResolutionError = CopilotKitHeaderResolutionError;
8842
8889
  exports.INSPECTOR_THREAD_BRIDGE_PLUGIN_ID = INSPECTOR_THREAD_BRIDGE_PLUGIN_ID;
8843
8890
  exports.IntelligenceAgent = IntelligenceAgent;
8891
+ exports.IntelligenceReplayFailedError = IntelligenceReplayFailedError;
8844
8892
  exports.MEMORY_ERROR_REGISTRY = MEMORY_ERROR_REGISTRY;
8845
8893
  exports.MemoryError = MemoryError;
8846
8894
  exports.ProxiedCopilotRuntimeAgent = ProxiedCopilotRuntimeAgent;