@copilotkit/core 1.82.0 → 2.0.0-rc.0

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
@@ -1,8 +1,8 @@
1
1
  (function(global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@tanstack/pacer'), require('@ag-ui/client'), require('@copilotkit/shared'), require('rxjs'), require('rxjs/operators'), require('phoenix'), require('zod-to-json-schema'), require('@copilotkit/learning')) :
3
- typeof define === 'function' && define.amd ? define(['exports', '@tanstack/pacer', '@ag-ui/client', '@copilotkit/shared', 'rxjs', 'rxjs/operators', 'phoenix', 'zod-to-json-schema', '@copilotkit/learning'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.CopilotKitCore = {}), global._tanstack_pacer,global.AgUIClient,global.CopilotKitShared,global.rxjs,global.rxjs.operators,global.phoenix,global.zodToJsonSchema,global._copilotkit_learning));
5
- })(this, function(exports, _tanstack_pacer, _ag_ui_client, _copilotkit_shared, rxjs, rxjs_operators, phoenix, zod_to_json_schema, _copilotkit_learning) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@tanstack/pacer'), require('@ag-ui/client'), require('@copilotkit/shared'), require('rxjs'), require('rxjs/operators'), require('phoenix'), require('zod-to-json-schema'), require('@copilotkit/learning'), require('marked')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', '@tanstack/pacer', '@ag-ui/client', '@copilotkit/shared', 'rxjs', 'rxjs/operators', 'phoenix', 'zod-to-json-schema', '@copilotkit/learning', 'marked'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.CopilotKitCore = {}), global._tanstack_pacer,global.AgUIClient,global.CopilotKitShared,global.rxjs,global.rxjs.operators,global.phoenix,global.zodToJsonSchema,global._copilotkit_learning,global.marked));
5
+ })(this, function(exports, _tanstack_pacer, _ag_ui_client, _copilotkit_shared, rxjs, rxjs_operators, phoenix, zod_to_json_schema, _copilotkit_learning, marked) {
6
6
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
7
7
 
8
8
  //#region src/utils/http-agent.ts
@@ -855,10 +855,23 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
855
855
 
856
856
  //#endregion
857
857
  //#region src/core/message-filter.ts
858
+ /**
859
+ * The string ids of a message's tool calls.
860
+ *
861
+ * Malformed entries are ignored rather than thrown on, matching
862
+ * {@link ɵkeepToolResultsWithCalls}: a null or primitive entry, or an entry
863
+ * without a string `id`, opens no pair instead of failing the repair.
864
+ */
858
865
  function toolCallIdsOf(message) {
859
866
  const calls = message.toolCalls;
860
867
  if (!Array.isArray(calls)) return [];
861
- return calls.map((call) => call.id).filter((id) => Boolean(id));
868
+ const ids = [];
869
+ for (const call of calls) {
870
+ if (typeof call !== "object" || call === null) continue;
871
+ const id = call.id;
872
+ if (typeof id === "string" && id) ids.push(id);
873
+ }
874
+ return ids;
862
875
  }
863
876
  function resultCallIdOf(message) {
864
877
  if (message.role !== "tool") return void 0;
@@ -899,12 +912,25 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
899
912
  * untouched.
900
913
  */
901
914
  function ɵrepairToolCallPairs(kept, full) {
902
- const callIdToIssuer = /* @__PURE__ */ new Map();
903
- const callIdToResult = /* @__PURE__ */ new Map();
915
+ const pendingIssuersByCallId = /* @__PURE__ */ new Map();
916
+ const issuerIdToResultsByCallId = /* @__PURE__ */ new Map();
917
+ const resultIdToIssuer = /* @__PURE__ */ new Map();
904
918
  for (const message of full) {
905
- for (const callId of toolCallIdsOf(message)) callIdToIssuer.set(callId, message);
919
+ for (const callId of toolCallIdsOf(message)) push(pendingIssuersByCallId, callId, message);
906
920
  const resultCallId = resultCallIdOf(message);
907
- if (resultCallId !== void 0) callIdToResult.set(resultCallId, message);
921
+ if (resultCallId !== void 0) {
922
+ const pendingIssuers = pendingIssuersByCallId.get(resultCallId);
923
+ const issuer = pendingIssuers === null || pendingIssuers === void 0 ? void 0 : pendingIssuers.pop();
924
+ if (issuer) {
925
+ resultIdToIssuer.set(message.id, issuer);
926
+ let resultsByCallId = issuerIdToResultsByCallId.get(issuer.id);
927
+ if (!resultsByCallId) {
928
+ resultsByCallId = /* @__PURE__ */ new Map();
929
+ issuerIdToResultsByCallId.set(issuer.id, resultsByCallId);
930
+ }
931
+ push(resultsByCallId, resultCallId, message);
932
+ }
933
+ }
908
934
  }
909
935
  const repaired = [];
910
936
  const emitted = /* @__PURE__ */ new Set();
@@ -919,18 +945,18 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
919
945
  emit(message);
920
946
  if (expandedMessages.has(message)) return;
921
947
  expandedMessages.add(message);
948
+ const resultsByCallId = issuerIdToResultsByCallId.get(message.id);
922
949
  for (const callId of toolCallIdsOf(message)) {
923
- const result = callIdToResult.get(callId);
924
- if (result) emit(result);
950
+ var _resultsByCallId$get;
951
+ for (const result of (_resultsByCallId$get = resultsByCallId === null || resultsByCallId === void 0 ? void 0 : resultsByCallId.get(callId)) !== null && _resultsByCallId$get !== void 0 ? _resultsByCallId$get : []) emit(result);
925
952
  }
926
953
  };
927
954
  for (const message of kept) {
928
- const resultCallId = resultCallIdOf(message);
929
- if (resultCallId === void 0) {
955
+ if (resultCallIdOf(message) === void 0) {
930
956
  emitWithResults(message);
931
957
  continue;
932
958
  }
933
- const issuer = callIdToIssuer.get(resultCallId);
959
+ const issuer = resultIdToIssuer.get(message.id);
934
960
  if (issuer) {
935
961
  emitWithResults(issuer);
936
962
  continue;
@@ -3777,6 +3803,250 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3777
3803
  for (const value of Object.values(record)) stripAdditionalProperties(value);
3778
3804
  }
3779
3805
 
3806
+ //#endregion
3807
+ //#region \0@oxc-project+runtime@0.112.0/helpers/classPrivateFieldInitSpec.js
3808
+ function _classPrivateFieldInitSpec(e, t, a) {
3809
+ _checkPrivateRedeclaration(e, t), t.set(e, a);
3810
+ }
3811
+
3812
+ //#endregion
3813
+ //#region \0@oxc-project+runtime@0.112.0/helpers/classPrivateFieldGet2.js
3814
+ function _classPrivateFieldGet2(s, a) {
3815
+ return s.get(_assertClassBrand(s, a));
3816
+ }
3817
+
3818
+ //#endregion
3819
+ //#region \0@oxc-project+runtime@0.112.0/helpers/classPrivateFieldSet2.js
3820
+ function _classPrivateFieldSet2(s, a, r) {
3821
+ return s.set(_assertClassBrand(s, a), r), r;
3822
+ }
3823
+
3824
+ //#endregion
3825
+ //#region src/interrupt-state.ts
3826
+ /** Serialize a newly answered frontend call for the canonical message history. */
3827
+ function toolResultContent(response) {
3828
+ var _response$payload;
3829
+ if (response.status === "cancelled") return JSON.stringify({ status: "cancelled" });
3830
+ return JSON.stringify((_response$payload = response.payload) !== null && _response$payload !== void 0 ? _response$payload : { status: "resolved" });
3831
+ }
3832
+ var _responses = /* @__PURE__ */ new WeakMap();
3833
+ var _adoptedContent = /* @__PURE__ */ new WeakMap();
3834
+ var _pending = /* @__PURE__ */ new WeakMap();
3835
+ var _sealed = /* @__PURE__ */ new WeakMap();
3836
+ var _ɵInterruptState_brand = /* @__PURE__ */ new WeakSet();
3837
+ /**
3838
+ * @internal Framework-neutral interrupt response state shared by framework
3839
+ * adapters. Application authors must not depend on this API.
3840
+ */
3841
+ var ɵInterruptState = class {
3842
+ constructor() {
3843
+ _classPrivateMethodInitSpec(this, _ɵInterruptState_brand);
3844
+ _classPrivateFieldInitSpec(this, _responses, Object.create(null));
3845
+ _classPrivateFieldInitSpec(this, _adoptedContent, /* @__PURE__ */ new Map());
3846
+ _classPrivateFieldInitSpec(this, _pending, null);
3847
+ _classPrivateFieldInitSpec(this, _sealed, false);
3848
+ }
3849
+ /** Return the active normalized interrupt without exposing mutable state. */
3850
+ get pending() {
3851
+ const pending = _classPrivateFieldGet2(_pending, this);
3852
+ if ((pending === null || pending === void 0 ? void 0 : pending.kind) === "standard") return {
3853
+ kind: "standard",
3854
+ interrupts: [...pending.interrupts]
3855
+ };
3856
+ return pending;
3857
+ }
3858
+ /** Replace the current interrupt with a legacy custom-event interrupt. */
3859
+ setLegacy(event) {
3860
+ _assertClassBrand(_ɵInterruptState_brand, this, _replace).call(this, {
3861
+ kind: "legacy",
3862
+ event
3863
+ });
3864
+ }
3865
+ /** Replace the current interrupt with an AG-UI standard interrupt set. */
3866
+ setStandard(interrupts) {
3867
+ const ids = /* @__PURE__ */ new Set();
3868
+ const callIds = /* @__PURE__ */ new Set();
3869
+ for (const interrupt of interrupts) {
3870
+ if (ids.has(interrupt.id)) throw new Error(`Duplicate interrupt id: ${interrupt.id}`);
3871
+ ids.add(interrupt.id);
3872
+ if (interrupt.reason === "tool_call" && interrupt.toolCallId) {
3873
+ if (callIds.has(interrupt.toolCallId)) throw new Error(`Duplicate interrupt tool call: ${interrupt.toolCallId}`);
3874
+ callIds.add(interrupt.toolCallId);
3875
+ }
3876
+ }
3877
+ _assertClassBrand(_ɵInterruptState_brand, this, _replace).call(this, {
3878
+ kind: "standard",
3879
+ interrupts: [...interrupts]
3880
+ });
3881
+ }
3882
+ /** Clear all pending interrupt data and accumulated responses. */
3883
+ clear() {
3884
+ _classPrivateFieldSet2(_pending, this, null);
3885
+ _classPrivateFieldSet2(_sealed, this, false);
3886
+ _classPrivateFieldGet2(_adoptedContent, this).clear();
3887
+ for (const id of Object.keys(_classPrivateFieldGet2(_responses, this))) delete _classPrivateFieldGet2(_responses, this)[id];
3888
+ }
3889
+ /** Record a resolved response and return the next framework action. */
3890
+ resolve(payload, interruptId, messages = []) {
3891
+ const pending = _classPrivateFieldGet2(_pending, this);
3892
+ if (!pending || _classPrivateFieldGet2(_sealed, this)) return { kind: "ignored" };
3893
+ if (pending.kind === "legacy") {
3894
+ _classPrivateFieldSet2(_sealed, this, true);
3895
+ return {
3896
+ kind: "legacy-resume",
3897
+ payload,
3898
+ interruptValue: pending.event.value
3899
+ };
3900
+ }
3901
+ return _assertClassBrand(_ɵInterruptState_brand, this, _respond).call(this, pending.interrupts, interruptId, {
3902
+ status: "resolved",
3903
+ payload
3904
+ }, messages);
3905
+ }
3906
+ /** Record a cancelled response and return the next framework action. */
3907
+ cancel(interruptId, messages = []) {
3908
+ const pending = _classPrivateFieldGet2(_pending, this);
3909
+ if (!pending || _classPrivateFieldGet2(_sealed, this)) return { kind: "ignored" };
3910
+ if (pending.kind === "legacy") {
3911
+ _classPrivateFieldSet2(_sealed, this, true);
3912
+ return { kind: "dismiss" };
3913
+ }
3914
+ return _assertClassBrand(_ɵInterruptState_brand, this, _respond).call(this, pending.interrupts, interruptId, { status: "cancelled" }, messages);
3915
+ }
3916
+ /** Reject ambiguous assistant definitions before executing or answering a call. */
3917
+ validateToolCalls(messages) {
3918
+ var _classPrivateFieldGet2$1;
3919
+ if (((_classPrivateFieldGet2$1 = _classPrivateFieldGet2(_pending, this)) === null || _classPrivateFieldGet2$1 === void 0 ? void 0 : _classPrivateFieldGet2$1.kind) !== "standard") return;
3920
+ const pendingCalls = new Set(_classPrivateFieldGet2(_pending, this).interrupts.filter((interrupt) => interrupt.reason === "tool_call").map((interrupt) => interrupt.toolCallId));
3921
+ const seen = /* @__PURE__ */ new Set();
3922
+ for (const message of messages) {
3923
+ var _message$toolCalls;
3924
+ if (message.role !== "assistant") continue;
3925
+ for (const call of (_message$toolCalls = message.toolCalls) !== null && _message$toolCalls !== void 0 ? _message$toolCalls : []) {
3926
+ if (!pendingCalls.has(call.id)) continue;
3927
+ if (seen.has(call.id)) throw new Error(`Duplicate tool call definition: ${call.id}`);
3928
+ seen.add(call.id);
3929
+ }
3930
+ }
3931
+ }
3932
+ /** Let UI adapters ignore answers for exactly one successful frontend result. */
3933
+ isCompletedToolCall(interruptId, messages) {
3934
+ var _pending$interrupts$;
3935
+ const pending = _classPrivateFieldGet2(_pending, this);
3936
+ if ((pending === null || pending === void 0 ? void 0 : pending.kind) !== "standard") return false;
3937
+ const id = interruptId !== null && interruptId !== void 0 ? interruptId : (_pending$interrupts$ = pending.interrupts[0]) === null || _pending$interrupts$ === void 0 ? void 0 : _pending$interrupts$.id;
3938
+ const interrupt = pending.interrupts.find((entry) => entry.id === id);
3939
+ if ((interrupt === null || interrupt === void 0 ? void 0 : interrupt.reason) !== "tool_call" || !interrupt.toolCallId) return false;
3940
+ const results = messages.filter((message) => message.role === "tool" && message.toolCallId === interrupt.toolCallId && !isForwardedToClientPlaceholder(message.content));
3941
+ const result = results[0];
3942
+ return results.length === 1 && (result === null || result === void 0 ? void 0 : result.role) === "tool" && result.error === void 0;
3943
+ }
3944
+ /** Resume only when saved frontend results answer every pending interrupt. */
3945
+ resumeWithToolResults(messages) {
3946
+ const pending = _classPrivateFieldGet2(_pending, this);
3947
+ if ((pending === null || pending === void 0 ? void 0 : pending.kind) !== "standard" || _classPrivateFieldGet2(_sealed, this)) return { kind: "ignored" };
3948
+ return _assertClassBrand(_ɵInterruptState_brand, this, _decide).call(this, pending.interrupts, { ..._classPrivateFieldGet2(_responses, this) }, messages);
3949
+ }
3950
+ };
3951
+ /** Start a new batch with no decisions retained from the preceding run. */
3952
+ function _replace(pending) {
3953
+ this.clear();
3954
+ _classPrivateFieldSet2(_pending, this, pending);
3955
+ }
3956
+ /** Record one explicit answer and reconcile it with saved frontend results. */
3957
+ function _respond(interrupts, interruptId, response, messages) {
3958
+ var _interrupts$;
3959
+ const id = interruptId !== null && interruptId !== void 0 ? interruptId : (_interrupts$ = interrupts[0]) === null || _interrupts$ === void 0 ? void 0 : _interrupts$.id;
3960
+ if (!id || !interrupts.some((interrupt) => interrupt.id === id)) return { kind: "ignored" };
3961
+ return _assertClassBrand(_ɵInterruptState_brand, this, _decide).call(this, interrupts, {
3962
+ ..._classPrivateFieldGet2(_responses, this),
3963
+ [id]: response
3964
+ }, messages);
3965
+ }
3966
+ /** Claim a complete batch once, preserving saved results and partial answers. */
3967
+ function _decide(interrupts, responses, messages) {
3968
+ this.validateToolCalls(messages);
3969
+ const completed = /* @__PURE__ */ new Set();
3970
+ const adoptedContent = new Map(_classPrivateFieldGet2(_adoptedContent, this));
3971
+ for (const interrupt of interrupts) {
3972
+ if (interrupt.reason !== "tool_call" || !interrupt.toolCallId) continue;
3973
+ const results = messages.filter((message) => message.role === "tool" && message.toolCallId === interrupt.toolCallId && !isForwardedToClientPlaceholder(message.content));
3974
+ if (results.length > 1) throw new Error(`Duplicate tool results for ${interrupt.toolCallId}`);
3975
+ const result = results[0];
3976
+ if (!result && !adoptedContent.has(interrupt.id)) continue;
3977
+ const response = Object.prototype.hasOwnProperty.call(responses, interrupt.id) ? responses[interrupt.id] : void 0;
3978
+ if ((result === null || result === void 0 ? void 0 : result.role) === "tool" && result.error !== void 0) {
3979
+ adoptedContent.delete(interrupt.id);
3980
+ completed.add(interrupt.id);
3981
+ continue;
3982
+ }
3983
+ const content = result ? result.content : adoptedContent.get(interrupt.id);
3984
+ if (response && (response.status !== "resolved" || !sameValue(response.payload, content) && toolResultContent(response) !== content)) throw new Error(`Interrupt response conflicts with existing tool result for ${interrupt.toolCallId}`);
3985
+ responses[interrupt.id] = {
3986
+ status: "resolved",
3987
+ payload: content
3988
+ };
3989
+ adoptedContent.set(interrupt.id, content);
3990
+ if (result) completed.add(interrupt.id);
3991
+ }
3992
+ Object.assign(_classPrivateFieldGet2(_responses, this), responses);
3993
+ _classPrivateFieldSet2(_adoptedContent, this, adoptedContent);
3994
+ if (!interrupts.every((interrupt) => Object.prototype.hasOwnProperty.call(responses, interrupt.id))) return { kind: "waiting" };
3995
+ const expired = interrupts.find((interrupt) => {
3996
+ var _responses$interrupt$;
3997
+ return ((_responses$interrupt$ = responses[interrupt.id]) === null || _responses$interrupt$ === void 0 ? void 0 : _responses$interrupt$.status) !== "cancelled" && (0, _ag_ui_client.isInterruptExpired)(interrupt);
3998
+ });
3999
+ if (expired) {
4000
+ _classPrivateFieldSet2(_sealed, this, true);
4001
+ return {
4002
+ kind: "expired",
4003
+ interrupt: expired
4004
+ };
4005
+ }
4006
+ const mutableInterrupts = [...interrupts];
4007
+ const resume = (0, _ag_ui_client.buildResumeArray)(mutableInterrupts, responses);
4008
+ const toolResults = mutableInterrupts.flatMap((interrupt) => {
4009
+ if (!interrupt.toolCallId || interrupt.reason !== "tool_call" || completed.has(interrupt.id)) return [];
4010
+ return [{
4011
+ toolCallId: interrupt.toolCallId,
4012
+ content: adoptedContent.has(interrupt.id) ? adoptedContent.get(interrupt.id) : toolResultContent(responses[interrupt.id])
4013
+ }];
4014
+ });
4015
+ _classPrivateFieldSet2(_sealed, this, true);
4016
+ return {
4017
+ kind: "resume",
4018
+ resume,
4019
+ toolResults
4020
+ };
4021
+ }
4022
+ /** Compare JSON protocol values without depending on object key insertion order. */
4023
+ function sameValue(left, right) {
4024
+ if (left === right) return true;
4025
+ if (!left || !right || typeof left !== "object" || typeof right !== "object") return false;
4026
+ if (Array.isArray(left) || Array.isArray(right)) return Array.isArray(left) && Array.isArray(right) && left.length === right.length && left.every((value, index) => sameValue(value, right[index]));
4027
+ const a = left;
4028
+ const b = right;
4029
+ return Object.keys(a).length === Object.keys(b).length && Object.keys(a).every((key) => Object.prototype.hasOwnProperty.call(b, key) && sameValue(a[key], b[key]));
4030
+ }
4031
+ const agentInterruptStates = /* @__PURE__ */ new WeakMap();
4032
+ /** @internal Share decisions and the single resume claim for an agent's pending batch. */
4033
+ function ɵgetAgentInterruptState(agent, interrupts = agent.pendingInterrupts) {
4034
+ const current = agentInterruptStates.get(agent);
4035
+ if (current && current.threadId === agent.threadId && current.state.pending && sameValue(current.interrupts, interrupts)) return current.state;
4036
+ const state = new ɵInterruptState();
4037
+ state.setStandard(interrupts);
4038
+ agentInterruptStates.set(agent, {
4039
+ threadId: agent.threadId,
4040
+ interrupts: structuredClone(interrupts),
4041
+ state
4042
+ });
4043
+ return state;
4044
+ }
4045
+ /** @internal A new run owns a new batch, even if the server reuses interrupt IDs. */
4046
+ function ɵclearAgentInterruptState(agent) {
4047
+ agentInterruptStates.delete(agent);
4048
+ }
4049
+
3780
4050
  //#endregion
3781
4051
  //#region src/core/webmcp.ts
3782
4052
  /**
@@ -3946,6 +4216,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3946
4216
  _defineProperty(this, "_nextAnonymousAgentId", 0);
3947
4217
  _defineProperty(this, "_executingToolCalls", /* @__PURE__ */ new WeakMap());
3948
4218
  _defineProperty(this, "_connectionGenerations", /* @__PURE__ */ new WeakMap());
4219
+ _defineProperty(this, "_runGenerations", /* @__PURE__ */ new WeakMap());
3949
4220
  _defineProperty(this, "_interactionAbortControllers", /* @__PURE__ */ new WeakMap());
3950
4221
  }
3951
4222
  /**
@@ -4189,6 +4460,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4189
4460
  runAgentResult,
4190
4461
  agent,
4191
4462
  toolExecutionMode: "restore",
4463
+ connectionGeneration: connection,
4192
4464
  signal: controller.signal
4193
4465
  }).catch(async (error) => {
4194
4466
  await this._internal.emitError({
@@ -4227,6 +4499,9 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4227
4499
  */
4228
4500
  async runAgent({ agent, forwardedProps, resume, runId }, continuationHandoff, followUpOf) {
4229
4501
  var _this$_runDepths$get, _ref2, _ref3;
4502
+ this._connectionGenerations.set(agent, {});
4503
+ this._runGenerations.set(agent, {});
4504
+ ɵclearAgentInterruptState(agent);
4230
4505
  if (agent.agentId) this._internal.suggestionEngine.clearSuggestions(agent.agentId);
4231
4506
  try {
4232
4507
  const headersApplied = this._internal.prepareAgentHeadersForRun(agent);
@@ -4361,12 +4636,16 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4361
4636
  /**
4362
4637
  * Process agent result and execute tools
4363
4638
  */
4364
- async processAgentResult({ runAgentResult, agent, runId, toolExecutionMode = "all", runController, signal = runController === null || runController === void 0 ? void 0 : runController.signal }) {
4365
- var _this$_executingToolC;
4639
+ async processAgentResult({ runAgentResult, agent, runId, toolExecutionMode = "all", runController, signal = runController === null || runController === void 0 ? void 0 : runController.signal, connectionGeneration }) {
4640
+ var _agent$pendingInterru, _this$_executingToolC;
4366
4641
  const { newMessages } = runAgentResult;
4367
4642
  const agentId = agent.agentId;
4368
4643
  let needsFollowUp = false;
4644
+ let ownsHandlerFollowUp = false;
4645
+ const runGeneration = this._runGenerations.get(agent);
4369
4646
  const threadId = agent.threadId;
4647
+ const interruptState = ((_agent$pendingInterru = agent.pendingInterrupts) === null || _agent$pendingInterru === void 0 ? void 0 : _agent$pendingInterru.length) ? ɵgetAgentInterruptState(agent) : void 0;
4648
+ interruptState === null || interruptState === void 0 || interruptState.validateToolCalls(agent.messages);
4370
4649
  const executing = (_this$_executingToolC = this._executingToolCalls.get(agent)) !== null && _this$_executingToolC !== void 0 ? _this$_executingToolC : /* @__PURE__ */ new Set();
4371
4650
  this._executingToolCalls.set(agent, executing);
4372
4651
  const messagesToProcess = toolExecutionMode === "restore" ? agent.messages.filter((message) => message.role === "assistant" && this.isInLatestUserTurn(agent.messages, message.id)) : newMessages;
@@ -4390,11 +4669,16 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4390
4669
  return wildcardTool;
4391
4670
  };
4392
4671
  const executableTool = tool !== null && tool !== void 0 ? tool : getWildcardTool();
4393
- if (toolExecutionMode === "restore" && (!executableTool || executableTool.handler && executableTool.type !== "human-in-the-loop" && executableTool.reconnectBehavior !== "resume-pending")) continue;
4394
4672
  const executionKey = JSON.stringify([threadId, toolCall.id]);
4395
4673
  if ((signal === null || signal === void 0 ? void 0 : signal.aborted) || agent.threadId !== threadId || toolExecutionMode === "restore" && !this.isInLatestUserTurn(agent.messages, message.id) || executing.has(executionKey)) continue;
4396
4674
  const existingResultIndex = newMessages.findIndex((m) => m.role === "tool" && m.toolCallId === toolCall.id);
4397
4675
  let existingResult = (_agent$messages$find = agent.messages.find((m) => m.role === "tool" && m.toolCallId === toolCall.id)) !== null && _agent$messages$find !== void 0 ? _agent$messages$find : newMessages[existingResultIndex];
4676
+ if (existingResult && !this.isFrontendPlaceholderResult(existingResult)) {
4677
+ var _agent$pendingInterru2;
4678
+ if (executableTool && executableTool.followUp !== false && ((_agent$pendingInterru2 = agent.pendingInterrupts) === null || _agent$pendingInterru2 === void 0 ? void 0 : _agent$pendingInterru2.some((interrupt) => interrupt.reason === "tool_call" && interrupt.toolCallId === toolCall.id))) needsFollowUp = true;
4679
+ continue;
4680
+ }
4681
+ if (toolExecutionMode === "restore" && (!executableTool || executableTool.handler && executableTool.type !== "human-in-the-loop" && executableTool.reconnectBehavior !== "resume-pending")) continue;
4398
4682
  if (existingResult && this.isFrontendPlaceholderResult(existingResult) && (toolExecutionMode === "restore" || (executableTool === null || executableTool === void 0 ? void 0 : executableTool.handler))) {
4399
4683
  if (existingResultIndex !== -1) newMessages.splice(existingResultIndex, 1);
4400
4684
  existingResult = void 0;
@@ -4411,8 +4695,8 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4411
4695
  };
4412
4696
  const abortInteraction = () => {
4413
4697
  if (!interactionController) return;
4414
- const connectionGeneration = this._connectionGenerations.get(agent);
4415
- liveHITLStops.set(interactionController.signal, () => this._connectionGenerations.get(agent) === connectionGeneration && agent.threadId === threadId);
4698
+ const stopConnectionGeneration = this._connectionGenerations.get(agent);
4699
+ liveHITLStops.set(interactionController.signal, () => this._connectionGenerations.get(agent) === stopConnectionGeneration && agent.threadId === threadId);
4416
4700
  interactionController.abort();
4417
4701
  };
4418
4702
  if (interactionController) {
@@ -4425,11 +4709,17 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4425
4709
  const discardOnAbort = toolExecutionMode === "restore" || !!interactionController;
4426
4710
  try {
4427
4711
  if (tool) {
4428
- if (await this.executeSpecificTool(tool, toolCall, message, agent, agentId, executionSignal, discardOnAbort, toolExecutionMode === "restore")) needsFollowUp = true;
4712
+ if (await this.executeSpecificTool(tool, toolCall, message, agent, agentId, executionSignal, discardOnAbort, toolExecutionMode === "restore")) {
4713
+ ownsHandlerFollowUp || (ownsHandlerFollowUp = !!tool.handler);
4714
+ needsFollowUp = true;
4715
+ }
4429
4716
  } else {
4430
4717
  const fallbackTool = getWildcardTool();
4431
4718
  if (fallbackTool) {
4432
- if (await this.executeWildcardTool(fallbackTool, toolCall, message, agent, agentId, executionSignal, discardOnAbort, toolExecutionMode === "restore")) needsFollowUp = true;
4719
+ if (await this.executeWildcardTool(fallbackTool, toolCall, message, agent, agentId, executionSignal, discardOnAbort, toolExecutionMode === "restore")) {
4720
+ ownsHandlerFollowUp || (ownsHandlerFollowUp = !!fallbackTool.handler);
4721
+ needsFollowUp = true;
4722
+ }
4433
4723
  }
4434
4724
  }
4435
4725
  } finally {
@@ -4447,12 +4737,26 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4447
4737
  var _this$_runDepths$get3;
4448
4738
  if (((_this$_runDepths$get3 = this._runDepths.get(agent)) !== null && _this$_runDepths$get3 !== void 0 ? _this$_runDepths$get3 : 0) >= MAX_FOLLOW_UP_DEPTH) _copilotkit_shared.logger.warn(`[CopilotKit] Follow-up depth limit (${MAX_FOLLOW_UP_DEPTH}) reached for agent "${agentId}". Stopping recursive follow-up runs to prevent an infinite loop. This usually indicates a tool that keeps requesting a follow-up (e.g. the LLM repeatedly calling the same tool). Consider setting "followUp: false" on the offending tool.`);
4449
4739
  else {
4740
+ var _agent$pendingInterru3;
4450
4741
  await this._internal.waitForPendingFrameworkUpdates();
4742
+ if ((signal === null || signal === void 0 ? void 0 : signal.aborted) || agent.threadId !== threadId || this._runGenerations.get(agent) !== runGeneration || connectionGeneration && !ownsHandlerFollowUp && this._connectionGenerations.get(agent) !== connectionGeneration || interruptState && ɵgetAgentInterruptState(agent) !== interruptState) return runAgentResult;
4451
4743
  if (toolExecutionMode === "restore" && !messagesToProcess.some((message) => this.isInLatestUserTurn(agent.messages, message.id))) return runAgentResult;
4744
+ let resume;
4745
+ if ((_agent$pendingInterru3 = agent.pendingInterrupts) === null || _agent$pendingInterru3 === void 0 ? void 0 : _agent$pendingInterru3.length) {
4746
+ const decision = ɵgetAgentInterruptState(agent).resumeWithToolResults(agent.messages);
4747
+ if (decision.kind !== "resume") return runAgentResult;
4748
+ resume = decision.resume;
4749
+ for (const result of decision.toolResults) agent.addMessage({
4750
+ id: (0, _copilotkit_shared.randomUUID)(),
4751
+ role: "tool",
4752
+ ...result
4753
+ });
4754
+ }
4452
4755
  const continuationHandoff = this._internal.stateManager.markNextRunAsContinuation(agent, runId);
4453
4756
  return await this.runAgent({
4454
4757
  agent,
4455
- ...runId !== void 0 ? { runId } : {}
4758
+ ...runId !== void 0 ? { runId } : {},
4759
+ ...resume ? { resume } : {}
4456
4760
  }, continuationHandoff, runController);
4457
4761
  }
4458
4762
  }
@@ -8382,7 +8686,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
8382
8686
  }({});
8383
8687
 
8384
8688
  //#endregion
8385
- //#region src/utils/markdown.ts
8689
+ //#region src/utils/markdown/complete-partial-markdown.ts
8386
8690
  function completePartialMarkdown(input) {
8387
8691
  let s = input;
8388
8692
  const fenceMatches = Array.from(s.matchAll(/^(\s*)(`{3,}|~{3,})/gm));
@@ -8549,6 +8853,23 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
8549
8853
  return result;
8550
8854
  }
8551
8855
 
8856
+ //#endregion
8857
+ //#region src/utils/markdown/parse.ts
8858
+ /**
8859
+ * Parse a markdown string into a framework-agnostic token tree.
8860
+ *
8861
+ * Uses `marked`'s lexer (GFM enabled) so the result is DOM-free and can be
8862
+ * walked into React, Vue, or React Native elements by each framework's
8863
+ * built-in renderer.
8864
+ */
8865
+ function parseMarkdown(content, options = {}) {
8866
+ const src = !content ? "" : options.complete === false ? content : completePartialMarkdown(content);
8867
+ return marked.marked.lexer(src, {
8868
+ gfm: true,
8869
+ breaks: true
8870
+ });
8871
+ }
8872
+
8552
8873
  //#endregion
8553
8874
  //#region src/threads.ts
8554
8875
  const THREADS_CHANNEL_EVENT = "thread_metadata";
@@ -9333,138 +9654,6 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
9333
9654
  return FEATURE_SET.has(name);
9334
9655
  }
9335
9656
 
9336
- //#endregion
9337
- //#region \0@oxc-project+runtime@0.112.0/helpers/classPrivateFieldInitSpec.js
9338
- function _classPrivateFieldInitSpec(e, t, a) {
9339
- _checkPrivateRedeclaration(e, t), t.set(e, a);
9340
- }
9341
-
9342
- //#endregion
9343
- //#region \0@oxc-project+runtime@0.112.0/helpers/classPrivateFieldGet2.js
9344
- function _classPrivateFieldGet2(s, a) {
9345
- return s.get(_assertClassBrand(s, a));
9346
- }
9347
-
9348
- //#endregion
9349
- //#region \0@oxc-project+runtime@0.112.0/helpers/classPrivateFieldSet2.js
9350
- function _classPrivateFieldSet2(s, a, r) {
9351
- return s.set(_assertClassBrand(s, a), r), r;
9352
- }
9353
-
9354
- //#endregion
9355
- //#region src/interrupt-state.ts
9356
- function toolResultContent(response) {
9357
- var _response$payload;
9358
- if (response.status === "cancelled") return JSON.stringify({ status: "cancelled" });
9359
- return JSON.stringify((_response$payload = response.payload) !== null && _response$payload !== void 0 ? _response$payload : { status: "resolved" });
9360
- }
9361
- var _responses = /* @__PURE__ */ new WeakMap();
9362
- var _pending = /* @__PURE__ */ new WeakMap();
9363
- var _sealed = /* @__PURE__ */ new WeakMap();
9364
- var _ɵInterruptState_brand = /* @__PURE__ */ new WeakSet();
9365
- /**
9366
- * @internal Framework-neutral interrupt response state shared by framework
9367
- * adapters. Application authors must not depend on this API.
9368
- */
9369
- var ɵInterruptState = class {
9370
- constructor() {
9371
- _classPrivateMethodInitSpec(this, _ɵInterruptState_brand);
9372
- _classPrivateFieldInitSpec(this, _responses, {});
9373
- _classPrivateFieldInitSpec(this, _pending, null);
9374
- _classPrivateFieldInitSpec(this, _sealed, false);
9375
- }
9376
- /** Return the active normalized interrupt without exposing mutable state. */
9377
- get pending() {
9378
- const pending = _classPrivateFieldGet2(_pending, this);
9379
- if ((pending === null || pending === void 0 ? void 0 : pending.kind) === "standard") return {
9380
- kind: "standard",
9381
- interrupts: [...pending.interrupts]
9382
- };
9383
- return pending;
9384
- }
9385
- /** Replace the current interrupt with a legacy custom-event interrupt. */
9386
- setLegacy(event) {
9387
- _assertClassBrand(_ɵInterruptState_brand, this, _replace).call(this, {
9388
- kind: "legacy",
9389
- event
9390
- });
9391
- }
9392
- /** Replace the current interrupt with an AG-UI standard interrupt set. */
9393
- setStandard(interrupts) {
9394
- _assertClassBrand(_ɵInterruptState_brand, this, _replace).call(this, {
9395
- kind: "standard",
9396
- interrupts: [...interrupts]
9397
- });
9398
- }
9399
- /** Clear all pending interrupt data and accumulated responses. */
9400
- clear() {
9401
- _classPrivateFieldSet2(_pending, this, null);
9402
- _classPrivateFieldSet2(_sealed, this, false);
9403
- for (const id of Object.keys(_classPrivateFieldGet2(_responses, this))) delete _classPrivateFieldGet2(_responses, this)[id];
9404
- }
9405
- /** Record a resolved response and return the next framework action. */
9406
- resolve(payload, interruptId) {
9407
- const pending = _classPrivateFieldGet2(_pending, this);
9408
- if (!pending || _classPrivateFieldGet2(_sealed, this)) return { kind: "ignored" };
9409
- if (pending.kind === "legacy") {
9410
- _classPrivateFieldSet2(_sealed, this, true);
9411
- return {
9412
- kind: "legacy-resume",
9413
- payload,
9414
- interruptValue: pending.event.value
9415
- };
9416
- }
9417
- return _assertClassBrand(_ɵInterruptState_brand, this, _respond).call(this, pending.interrupts, interruptId, {
9418
- status: "resolved",
9419
- payload
9420
- });
9421
- }
9422
- /** Record a cancelled response and return the next framework action. */
9423
- cancel(interruptId) {
9424
- const pending = _classPrivateFieldGet2(_pending, this);
9425
- if (!pending || _classPrivateFieldGet2(_sealed, this)) return { kind: "ignored" };
9426
- if (pending.kind === "legacy") {
9427
- _classPrivateFieldSet2(_sealed, this, true);
9428
- return { kind: "dismiss" };
9429
- }
9430
- return _assertClassBrand(_ɵInterruptState_brand, this, _respond).call(this, pending.interrupts, interruptId, { status: "cancelled" });
9431
- }
9432
- };
9433
- function _replace(pending) {
9434
- this.clear();
9435
- _classPrivateFieldSet2(_pending, this, pending);
9436
- }
9437
- function _respond(interrupts, interruptId, response) {
9438
- var _interrupts$;
9439
- const id = interruptId !== null && interruptId !== void 0 ? interruptId : (_interrupts$ = interrupts[0]) === null || _interrupts$ === void 0 ? void 0 : _interrupts$.id;
9440
- if (!id || !interrupts.some((interrupt) => interrupt.id === id)) return { kind: "ignored" };
9441
- _classPrivateFieldGet2(_responses, this)[id] = response;
9442
- if (!interrupts.every((interrupt) => _classPrivateFieldGet2(_responses, this)[interrupt.id])) return { kind: "waiting" };
9443
- const expired = interrupts.find((interrupt) => (0, _ag_ui_client.isInterruptExpired)(interrupt));
9444
- if (expired) {
9445
- _classPrivateFieldSet2(_sealed, this, true);
9446
- return {
9447
- kind: "expired",
9448
- interrupt: expired
9449
- };
9450
- }
9451
- const mutableInterrupts = [...interrupts];
9452
- const resume = (0, _ag_ui_client.buildResumeArray)(mutableInterrupts, _classPrivateFieldGet2(_responses, this));
9453
- const toolResults = mutableInterrupts.flatMap((interrupt) => {
9454
- if (!interrupt.toolCallId || interrupt.reason !== "tool_call") return [];
9455
- return [{
9456
- toolCallId: interrupt.toolCallId,
9457
- content: toolResultContent(_classPrivateFieldGet2(_responses, this)[interrupt.id])
9458
- }];
9459
- });
9460
- _classPrivateFieldSet2(_sealed, this, true);
9461
- return {
9462
- kind: "resume",
9463
- resume,
9464
- toolResults
9465
- };
9466
- }
9467
-
9468
9657
  //#endregion
9469
9658
  //#region src/inspector-thread-bridge.ts
9470
9659
  const INSPECTOR_THREAD_BRIDGE_PLUGIN_ID = "cpk-inspector-thread";
@@ -10889,6 +11078,7 @@ exports.onInspectorActiveThread = onInspectorActiveThread;
10889
11078
  exports.onInspectorStopViewing = onInspectorStopViewing;
10890
11079
  exports.onInspectorViewThread = onInspectorViewThread;
10891
11080
  exports.onInspectorViewThreadResult = onInspectorViewThreadResult;
11081
+ exports.parseMarkdown = parseMarkdown;
10892
11082
  exports.parseToolArguments = parseToolArguments;
10893
11083
  exports.prepareSurfaceOperations = prepareSurfaceOperations;
10894
11084
  exports.props = props;
@@ -10900,9 +11090,11 @@ exports.ɵInterruptState = ɵInterruptState;
10900
11090
  exports.ɵMAX_SOCKET_RETRIES = ɵMAX_SOCKET_RETRIES;
10901
11091
  exports.ɵRUNTIME_PROBE_TIMEOUT_MS = ɵRUNTIME_PROBE_TIMEOUT_MS;
10902
11092
  exports.ɵTHREAD_REQUEST_TIMEOUT_MS = ɵTHREAD_REQUEST_TIMEOUT_MS;
11093
+ exports.ɵclearAgentInterruptState = ɵclearAgentInterruptState;
10903
11094
  exports.ɵcreateMemoryStore = createMemoryStore;
10904
11095
  exports.ɵcreateThreadSelectors = ɵcreateThreadSelectors;
10905
11096
  exports.ɵcreateThreadStore = createThreadStore;
11097
+ exports.ɵgetAgentInterruptState = ɵgetAgentInterruptState;
10906
11098
  exports.ɵisCopilotKitFeature = ɵisCopilotKitFeature;
10907
11099
  exports.ɵisHttpAgent = ɵisHttpAgent;
10908
11100
  exports.ɵisRetryableMemoryStatus = isRetryableStatus;