@copilotkit/core 1.83.0 → 2.0.0-rc.1

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
@@ -7,6 +7,7 @@ let rxjs_operators = require("rxjs/operators");
7
7
  let phoenix = require("phoenix");
8
8
  let zod_to_json_schema = require("zod-to-json-schema");
9
9
  let _copilotkit_learning = require("@copilotkit/learning");
10
+ let marked = require("marked");
10
11
 
11
12
  //#region src/utils/http-agent.ts
12
13
  /**
@@ -802,10 +803,23 @@ function isRuntimeInfoRequestError(error) {
802
803
 
803
804
  //#endregion
804
805
  //#region src/core/message-filter.ts
806
+ /**
807
+ * The string ids of a message's tool calls.
808
+ *
809
+ * Malformed entries are ignored rather than thrown on, matching
810
+ * {@link ɵkeepToolResultsWithCalls}: a null or primitive entry, or an entry
811
+ * without a string `id`, opens no pair instead of failing the repair.
812
+ */
805
813
  function toolCallIdsOf(message) {
806
814
  const calls = message.toolCalls;
807
815
  if (!Array.isArray(calls)) return [];
808
- return calls.map((call) => call.id).filter((id) => Boolean(id));
816
+ const ids = [];
817
+ for (const call of calls) {
818
+ if (typeof call !== "object" || call === null) continue;
819
+ const id = call.id;
820
+ if (typeof id === "string" && id) ids.push(id);
821
+ }
822
+ return ids;
809
823
  }
810
824
  function resultCallIdOf(message) {
811
825
  if (message.role !== "tool") return void 0;
@@ -846,12 +860,24 @@ function resultCallIdOf(message) {
846
860
  * untouched.
847
861
  */
848
862
  function ɵrepairToolCallPairs(kept, full) {
849
- const callIdToIssuer = /* @__PURE__ */ new Map();
850
- const callIdToResult = /* @__PURE__ */ new Map();
863
+ const pendingIssuersByCallId = /* @__PURE__ */ new Map();
864
+ const issuerIdToResultsByCallId = /* @__PURE__ */ new Map();
865
+ const resultIdToIssuer = /* @__PURE__ */ new Map();
851
866
  for (const message of full) {
852
- for (const callId of toolCallIdsOf(message)) callIdToIssuer.set(callId, message);
867
+ for (const callId of toolCallIdsOf(message)) push(pendingIssuersByCallId, callId, message);
853
868
  const resultCallId = resultCallIdOf(message);
854
- if (resultCallId !== void 0) callIdToResult.set(resultCallId, message);
869
+ if (resultCallId !== void 0) {
870
+ const issuer = pendingIssuersByCallId.get(resultCallId)?.pop();
871
+ if (issuer) {
872
+ resultIdToIssuer.set(message.id, issuer);
873
+ let resultsByCallId = issuerIdToResultsByCallId.get(issuer.id);
874
+ if (!resultsByCallId) {
875
+ resultsByCallId = /* @__PURE__ */ new Map();
876
+ issuerIdToResultsByCallId.set(issuer.id, resultsByCallId);
877
+ }
878
+ push(resultsByCallId, resultCallId, message);
879
+ }
880
+ }
855
881
  }
856
882
  const repaired = [];
857
883
  const emitted = /* @__PURE__ */ new Set();
@@ -866,18 +892,15 @@ function ɵrepairToolCallPairs(kept, full) {
866
892
  emit(message);
867
893
  if (expandedMessages.has(message)) return;
868
894
  expandedMessages.add(message);
869
- for (const callId of toolCallIdsOf(message)) {
870
- const result = callIdToResult.get(callId);
871
- if (result) emit(result);
872
- }
895
+ const resultsByCallId = issuerIdToResultsByCallId.get(message.id);
896
+ for (const callId of toolCallIdsOf(message)) for (const result of resultsByCallId?.get(callId) ?? []) emit(result);
873
897
  };
874
898
  for (const message of kept) {
875
- const resultCallId = resultCallIdOf(message);
876
- if (resultCallId === void 0) {
899
+ if (resultCallIdOf(message) === void 0) {
877
900
  emitWithResults(message);
878
901
  continue;
879
902
  }
880
- const issuer = callIdToIssuer.get(resultCallId);
903
+ const issuer = resultIdToIssuer.get(message.id);
881
904
  if (issuer) {
882
905
  emitWithResults(issuer);
883
906
  continue;
@@ -3623,6 +3646,216 @@ function stripAdditionalProperties(schema) {
3623
3646
  for (const value of Object.values(record)) stripAdditionalProperties(value);
3624
3647
  }
3625
3648
 
3649
+ //#endregion
3650
+ //#region src/interrupt-state.ts
3651
+ /** Serialize a newly answered frontend call for the canonical message history. */
3652
+ function toolResultContent(response) {
3653
+ if (response.status === "cancelled") return JSON.stringify({ status: "cancelled" });
3654
+ return JSON.stringify(response.payload ?? { status: "resolved" });
3655
+ }
3656
+ /**
3657
+ * @internal Framework-neutral interrupt response state shared by framework
3658
+ * adapters. Application authors must not depend on this API.
3659
+ */
3660
+ var ɵInterruptState = class {
3661
+ #responses = Object.create(null);
3662
+ #adoptedContent = /* @__PURE__ */ new Map();
3663
+ #pending = null;
3664
+ #sealed = false;
3665
+ /** Return the active normalized interrupt without exposing mutable state. */
3666
+ get pending() {
3667
+ const pending = this.#pending;
3668
+ if (pending?.kind === "standard") return {
3669
+ kind: "standard",
3670
+ interrupts: [...pending.interrupts]
3671
+ };
3672
+ return pending;
3673
+ }
3674
+ /** Replace the current interrupt with a legacy custom-event interrupt. */
3675
+ setLegacy(event) {
3676
+ this.#replace({
3677
+ kind: "legacy",
3678
+ event
3679
+ });
3680
+ }
3681
+ /** Replace the current interrupt with an AG-UI standard interrupt set. */
3682
+ setStandard(interrupts) {
3683
+ const ids = /* @__PURE__ */ new Set();
3684
+ const callIds = /* @__PURE__ */ new Set();
3685
+ for (const interrupt of interrupts) {
3686
+ if (ids.has(interrupt.id)) throw new Error(`Duplicate interrupt id: ${interrupt.id}`);
3687
+ ids.add(interrupt.id);
3688
+ if (interrupt.reason === "tool_call" && interrupt.toolCallId) {
3689
+ if (callIds.has(interrupt.toolCallId)) throw new Error(`Duplicate interrupt tool call: ${interrupt.toolCallId}`);
3690
+ callIds.add(interrupt.toolCallId);
3691
+ }
3692
+ }
3693
+ this.#replace({
3694
+ kind: "standard",
3695
+ interrupts: [...interrupts]
3696
+ });
3697
+ }
3698
+ /** Clear all pending interrupt data and accumulated responses. */
3699
+ clear() {
3700
+ this.#pending = null;
3701
+ this.#sealed = false;
3702
+ this.#adoptedContent.clear();
3703
+ for (const id of Object.keys(this.#responses)) delete this.#responses[id];
3704
+ }
3705
+ /** Record a resolved response and return the next framework action. */
3706
+ resolve(payload, interruptId, messages = []) {
3707
+ const pending = this.#pending;
3708
+ if (!pending || this.#sealed) return { kind: "ignored" };
3709
+ if (pending.kind === "legacy") {
3710
+ this.#sealed = true;
3711
+ return {
3712
+ kind: "legacy-resume",
3713
+ payload,
3714
+ interruptValue: pending.event.value
3715
+ };
3716
+ }
3717
+ return this.#respond(pending.interrupts, interruptId, {
3718
+ status: "resolved",
3719
+ payload
3720
+ }, messages);
3721
+ }
3722
+ /** Record a cancelled response and return the next framework action. */
3723
+ cancel(interruptId, messages = []) {
3724
+ const pending = this.#pending;
3725
+ if (!pending || this.#sealed) return { kind: "ignored" };
3726
+ if (pending.kind === "legacy") {
3727
+ this.#sealed = true;
3728
+ return { kind: "dismiss" };
3729
+ }
3730
+ return this.#respond(pending.interrupts, interruptId, { status: "cancelled" }, messages);
3731
+ }
3732
+ /** Reject ambiguous assistant definitions before executing or answering a call. */
3733
+ validateToolCalls(messages) {
3734
+ if (this.#pending?.kind !== "standard") return;
3735
+ const pendingCalls = new Set(this.#pending.interrupts.filter((interrupt) => interrupt.reason === "tool_call").map((interrupt) => interrupt.toolCallId));
3736
+ const seen = /* @__PURE__ */ new Set();
3737
+ for (const message of messages) {
3738
+ if (message.role !== "assistant") continue;
3739
+ for (const call of message.toolCalls ?? []) {
3740
+ if (!pendingCalls.has(call.id)) continue;
3741
+ if (seen.has(call.id)) throw new Error(`Duplicate tool call definition: ${call.id}`);
3742
+ seen.add(call.id);
3743
+ }
3744
+ }
3745
+ }
3746
+ /** Let UI adapters ignore answers for exactly one successful frontend result. */
3747
+ isCompletedToolCall(interruptId, messages) {
3748
+ const pending = this.#pending;
3749
+ if (pending?.kind !== "standard") return false;
3750
+ const id = interruptId ?? pending.interrupts[0]?.id;
3751
+ const interrupt = pending.interrupts.find((entry) => entry.id === id);
3752
+ if (interrupt?.reason !== "tool_call" || !interrupt.toolCallId) return false;
3753
+ const results = messages.filter((message) => message.role === "tool" && message.toolCallId === interrupt.toolCallId && !isForwardedToClientPlaceholder(message.content));
3754
+ const result = results[0];
3755
+ return results.length === 1 && result?.role === "tool" && result.error === void 0;
3756
+ }
3757
+ /** Resume only when saved frontend results answer every pending interrupt. */
3758
+ resumeWithToolResults(messages) {
3759
+ const pending = this.#pending;
3760
+ if (pending?.kind !== "standard" || this.#sealed) return { kind: "ignored" };
3761
+ return this.#decide(pending.interrupts, { ...this.#responses }, messages);
3762
+ }
3763
+ /** Start a new batch with no decisions retained from the preceding run. */
3764
+ #replace(pending) {
3765
+ this.clear();
3766
+ this.#pending = pending;
3767
+ }
3768
+ /** Record one explicit answer and reconcile it with saved frontend results. */
3769
+ #respond(interrupts, interruptId, response, messages) {
3770
+ const id = interruptId ?? interrupts[0]?.id;
3771
+ if (!id || !interrupts.some((interrupt) => interrupt.id === id)) return { kind: "ignored" };
3772
+ return this.#decide(interrupts, {
3773
+ ...this.#responses,
3774
+ [id]: response
3775
+ }, messages);
3776
+ }
3777
+ /** Claim a complete batch once, preserving saved results and partial answers. */
3778
+ #decide(interrupts, responses, messages) {
3779
+ this.validateToolCalls(messages);
3780
+ const completed = /* @__PURE__ */ new Set();
3781
+ const adoptedContent = new Map(this.#adoptedContent);
3782
+ for (const interrupt of interrupts) {
3783
+ if (interrupt.reason !== "tool_call" || !interrupt.toolCallId) continue;
3784
+ const results = messages.filter((message) => message.role === "tool" && message.toolCallId === interrupt.toolCallId && !isForwardedToClientPlaceholder(message.content));
3785
+ if (results.length > 1) throw new Error(`Duplicate tool results for ${interrupt.toolCallId}`);
3786
+ const result = results[0];
3787
+ if (!result && !adoptedContent.has(interrupt.id)) continue;
3788
+ const response = Object.prototype.hasOwnProperty.call(responses, interrupt.id) ? responses[interrupt.id] : void 0;
3789
+ if (result?.role === "tool" && result.error !== void 0) {
3790
+ adoptedContent.delete(interrupt.id);
3791
+ completed.add(interrupt.id);
3792
+ continue;
3793
+ }
3794
+ const content = result ? result.content : adoptedContent.get(interrupt.id);
3795
+ 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}`);
3796
+ responses[interrupt.id] = {
3797
+ status: "resolved",
3798
+ payload: content
3799
+ };
3800
+ adoptedContent.set(interrupt.id, content);
3801
+ if (result) completed.add(interrupt.id);
3802
+ }
3803
+ Object.assign(this.#responses, responses);
3804
+ this.#adoptedContent = adoptedContent;
3805
+ if (!interrupts.every((interrupt) => Object.prototype.hasOwnProperty.call(responses, interrupt.id))) return { kind: "waiting" };
3806
+ const expired = interrupts.find((interrupt) => responses[interrupt.id]?.status !== "cancelled" && (0, _ag_ui_client.isInterruptExpired)(interrupt));
3807
+ if (expired) {
3808
+ this.#sealed = true;
3809
+ return {
3810
+ kind: "expired",
3811
+ interrupt: expired
3812
+ };
3813
+ }
3814
+ const mutableInterrupts = [...interrupts];
3815
+ const resume = (0, _ag_ui_client.buildResumeArray)(mutableInterrupts, responses);
3816
+ const toolResults = mutableInterrupts.flatMap((interrupt) => {
3817
+ if (!interrupt.toolCallId || interrupt.reason !== "tool_call" || completed.has(interrupt.id)) return [];
3818
+ return [{
3819
+ toolCallId: interrupt.toolCallId,
3820
+ content: adoptedContent.has(interrupt.id) ? adoptedContent.get(interrupt.id) : toolResultContent(responses[interrupt.id])
3821
+ }];
3822
+ });
3823
+ this.#sealed = true;
3824
+ return {
3825
+ kind: "resume",
3826
+ resume,
3827
+ toolResults
3828
+ };
3829
+ }
3830
+ };
3831
+ /** Compare JSON protocol values without depending on object key insertion order. */
3832
+ function sameValue(left, right) {
3833
+ if (left === right) return true;
3834
+ if (!left || !right || typeof left !== "object" || typeof right !== "object") return false;
3835
+ 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]));
3836
+ const a = left;
3837
+ const b = right;
3838
+ 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]));
3839
+ }
3840
+ const agentInterruptStates = /* @__PURE__ */ new WeakMap();
3841
+ /** @internal Share decisions and the single resume claim for an agent's pending batch. */
3842
+ function ɵgetAgentInterruptState(agent, interrupts = agent.pendingInterrupts) {
3843
+ const current = agentInterruptStates.get(agent);
3844
+ if (current && current.threadId === agent.threadId && current.state.pending && sameValue(current.interrupts, interrupts)) return current.state;
3845
+ const state = new ɵInterruptState();
3846
+ state.setStandard(interrupts);
3847
+ agentInterruptStates.set(agent, {
3848
+ threadId: agent.threadId,
3849
+ interrupts: structuredClone(interrupts),
3850
+ state
3851
+ });
3852
+ return state;
3853
+ }
3854
+ /** @internal A new run owns a new batch, even if the server reuses interrupt IDs. */
3855
+ function ɵclearAgentInterruptState(agent) {
3856
+ agentInterruptStates.delete(agent);
3857
+ }
3858
+
3626
3859
  //#endregion
3627
3860
  //#region src/core/webmcp.ts
3628
3861
  /**
@@ -3879,6 +4112,7 @@ var RunHandler = class {
3879
4112
  /** Prevent reconnects from starting an interaction already executing locally. */
3880
4113
  _executingToolCalls = /* @__PURE__ */ new WeakMap();
3881
4114
  _connectionGenerations = /* @__PURE__ */ new WeakMap();
4115
+ _runGenerations = /* @__PURE__ */ new WeakMap();
3882
4116
  _interactionAbortControllers = /* @__PURE__ */ new WeakMap();
3883
4117
  constructor(core) {
3884
4118
  this.core = core;
@@ -4117,6 +4351,7 @@ var RunHandler = class {
4117
4351
  runAgentResult,
4118
4352
  agent,
4119
4353
  toolExecutionMode: "restore",
4354
+ connectionGeneration: connection,
4120
4355
  signal: controller.signal
4121
4356
  }).catch(async (error) => {
4122
4357
  await this._internal.emitError({
@@ -4154,6 +4389,9 @@ var RunHandler = class {
4154
4389
  * Run an agent
4155
4390
  */
4156
4391
  async runAgent({ agent, forwardedProps, resume, runId }, continuationHandoff, followUpOf) {
4392
+ this._connectionGenerations.set(agent, {});
4393
+ this._runGenerations.set(agent, {});
4394
+ ɵclearAgentInterruptState(agent);
4157
4395
  if (agent.agentId) this._internal.suggestionEngine.clearSuggestions(agent.agentId);
4158
4396
  try {
4159
4397
  const headersApplied = this._internal.prepareAgentHeadersForRun(agent);
@@ -4283,11 +4521,15 @@ var RunHandler = class {
4283
4521
  /**
4284
4522
  * Process agent result and execute tools
4285
4523
  */
4286
- async processAgentResult({ runAgentResult, agent, runId, toolExecutionMode = "all", runController, signal = runController?.signal }) {
4524
+ async processAgentResult({ runAgentResult, agent, runId, toolExecutionMode = "all", runController, signal = runController?.signal, connectionGeneration }) {
4287
4525
  const { newMessages } = runAgentResult;
4288
4526
  const agentId = agent.agentId;
4289
4527
  let needsFollowUp = false;
4528
+ let ownsHandlerFollowUp = false;
4529
+ const runGeneration = this._runGenerations.get(agent);
4290
4530
  const threadId = agent.threadId;
4531
+ const interruptState = agent.pendingInterrupts?.length ? ɵgetAgentInterruptState(agent) : void 0;
4532
+ interruptState?.validateToolCalls(agent.messages);
4291
4533
  const executing = this._executingToolCalls.get(agent) ?? /* @__PURE__ */ new Set();
4292
4534
  this._executingToolCalls.set(agent, executing);
4293
4535
  const messagesToProcess = toolExecutionMode === "restore" ? agent.messages.filter((message) => message.role === "assistant" && this.isInLatestUserTurn(agent.messages, message.id)) : newMessages;
@@ -4307,11 +4549,15 @@ var RunHandler = class {
4307
4549
  return wildcardTool;
4308
4550
  };
4309
4551
  const executableTool = tool ?? getWildcardTool();
4310
- if (toolExecutionMode === "restore" && (!executableTool || executableTool.handler && executableTool.type !== "human-in-the-loop" && executableTool.reconnectBehavior !== "resume-pending")) continue;
4311
4552
  const executionKey = JSON.stringify([threadId, toolCall.id]);
4312
4553
  if (signal?.aborted || agent.threadId !== threadId || toolExecutionMode === "restore" && !this.isInLatestUserTurn(agent.messages, message.id) || executing.has(executionKey)) continue;
4313
4554
  const existingResultIndex = newMessages.findIndex((m) => m.role === "tool" && m.toolCallId === toolCall.id);
4314
4555
  let existingResult = agent.messages.find((m) => m.role === "tool" && m.toolCallId === toolCall.id) ?? newMessages[existingResultIndex];
4556
+ if (existingResult && !this.isFrontendPlaceholderResult(existingResult)) {
4557
+ if (executableTool && executableTool.followUp !== false && agent.pendingInterrupts?.some((interrupt) => interrupt.reason === "tool_call" && interrupt.toolCallId === toolCall.id)) needsFollowUp = true;
4558
+ continue;
4559
+ }
4560
+ if (toolExecutionMode === "restore" && (!executableTool || executableTool.handler && executableTool.type !== "human-in-the-loop" && executableTool.reconnectBehavior !== "resume-pending")) continue;
4315
4561
  if (existingResult && this.isFrontendPlaceholderResult(existingResult) && (toolExecutionMode === "restore" || executableTool?.handler)) {
4316
4562
  if (existingResultIndex !== -1) newMessages.splice(existingResultIndex, 1);
4317
4563
  existingResult = void 0;
@@ -4327,8 +4573,8 @@ var RunHandler = class {
4327
4573
  };
4328
4574
  const abortInteraction = () => {
4329
4575
  if (!interactionController) return;
4330
- const connectionGeneration = this._connectionGenerations.get(agent);
4331
- liveHITLStops.set(interactionController.signal, () => this._connectionGenerations.get(agent) === connectionGeneration && agent.threadId === threadId);
4576
+ const stopConnectionGeneration = this._connectionGenerations.get(agent);
4577
+ liveHITLStops.set(interactionController.signal, () => this._connectionGenerations.get(agent) === stopConnectionGeneration && agent.threadId === threadId);
4332
4578
  interactionController.abort();
4333
4579
  };
4334
4580
  if (interactionController) {
@@ -4341,11 +4587,17 @@ var RunHandler = class {
4341
4587
  const discardOnAbort = toolExecutionMode === "restore" || !!interactionController;
4342
4588
  try {
4343
4589
  if (tool) {
4344
- if (await this.executeSpecificTool(tool, toolCall, message, agent, agentId, executionSignal, discardOnAbort, toolExecutionMode === "restore")) needsFollowUp = true;
4590
+ if (await this.executeSpecificTool(tool, toolCall, message, agent, agentId, executionSignal, discardOnAbort, toolExecutionMode === "restore")) {
4591
+ ownsHandlerFollowUp ||= !!tool.handler;
4592
+ needsFollowUp = true;
4593
+ }
4345
4594
  } else {
4346
4595
  const fallbackTool = getWildcardTool();
4347
4596
  if (fallbackTool) {
4348
- if (await this.executeWildcardTool(fallbackTool, toolCall, message, agent, agentId, executionSignal, discardOnAbort, toolExecutionMode === "restore")) needsFollowUp = true;
4597
+ if (await this.executeWildcardTool(fallbackTool, toolCall, message, agent, agentId, executionSignal, discardOnAbort, toolExecutionMode === "restore")) {
4598
+ ownsHandlerFollowUp ||= !!fallbackTool.handler;
4599
+ needsFollowUp = true;
4600
+ }
4349
4601
  }
4350
4602
  }
4351
4603
  } finally {
@@ -4362,11 +4614,24 @@ var RunHandler = class {
4362
4614
  if (needsFollowUp && agent.threadId === threadId && !signal?.aborted) if ((this._runDepths.get(agent) ?? 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.`);
4363
4615
  else {
4364
4616
  await this._internal.waitForPendingFrameworkUpdates();
4617
+ if (signal?.aborted || agent.threadId !== threadId || this._runGenerations.get(agent) !== runGeneration || connectionGeneration && !ownsHandlerFollowUp && this._connectionGenerations.get(agent) !== connectionGeneration || interruptState && ɵgetAgentInterruptState(agent) !== interruptState) return runAgentResult;
4365
4618
  if (toolExecutionMode === "restore" && !messagesToProcess.some((message) => this.isInLatestUserTurn(agent.messages, message.id))) return runAgentResult;
4619
+ let resume;
4620
+ if (agent.pendingInterrupts?.length) {
4621
+ const decision = ɵgetAgentInterruptState(agent).resumeWithToolResults(agent.messages);
4622
+ if (decision.kind !== "resume") return runAgentResult;
4623
+ resume = decision.resume;
4624
+ for (const result of decision.toolResults) agent.addMessage({
4625
+ id: (0, _copilotkit_shared.randomUUID)(),
4626
+ role: "tool",
4627
+ ...result
4628
+ });
4629
+ }
4366
4630
  const continuationHandoff = this._internal.stateManager.markNextRunAsContinuation(agent, runId);
4367
4631
  return await this.runAgent({
4368
4632
  agent,
4369
- ...runId !== void 0 ? { runId } : {}
4633
+ ...runId !== void 0 ? { runId } : {},
4634
+ ...resume ? { resume } : {}
4370
4635
  }, continuationHandoff, runController);
4371
4636
  }
4372
4637
  this._internal.suggestionEngine.reloadSuggestions(agentId);
@@ -8192,7 +8457,7 @@ let ToolCallStatus = /* @__PURE__ */ function(ToolCallStatus) {
8192
8457
  }({});
8193
8458
 
8194
8459
  //#endregion
8195
- //#region src/utils/markdown.ts
8460
+ //#region src/utils/markdown/complete-partial-markdown.ts
8196
8461
  function completePartialMarkdown(input) {
8197
8462
  let s = input;
8198
8463
  const fenceMatches = Array.from(s.matchAll(/^(\s*)(`{3,}|~{3,})/gm));
@@ -8359,6 +8624,23 @@ function completePartialMarkdown(input) {
8359
8624
  return result;
8360
8625
  }
8361
8626
 
8627
+ //#endregion
8628
+ //#region src/utils/markdown/parse.ts
8629
+ /**
8630
+ * Parse a markdown string into a framework-agnostic token tree.
8631
+ *
8632
+ * Uses `marked`'s lexer (GFM enabled) so the result is DOM-free and can be
8633
+ * walked into React, Vue, or React Native elements by each framework's
8634
+ * built-in renderer.
8635
+ */
8636
+ function parseMarkdown(content, options = {}) {
8637
+ const src = !content ? "" : options.complete === false ? content : completePartialMarkdown(content);
8638
+ return marked.marked.lexer(src, {
8639
+ gfm: true,
8640
+ breaks: true
8641
+ });
8642
+ }
8643
+
8362
8644
  //#endregion
8363
8645
  //#region src/threads.ts
8364
8646
  const THREADS_CHANNEL_EVENT = "thread_metadata";
@@ -9125,111 +9407,6 @@ function ɵisCopilotKitFeature(name) {
9125
9407
  return FEATURE_SET.has(name);
9126
9408
  }
9127
9409
 
9128
- //#endregion
9129
- //#region src/interrupt-state.ts
9130
- function toolResultContent(response) {
9131
- if (response.status === "cancelled") return JSON.stringify({ status: "cancelled" });
9132
- return JSON.stringify(response.payload ?? { status: "resolved" });
9133
- }
9134
- /**
9135
- * @internal Framework-neutral interrupt response state shared by framework
9136
- * adapters. Application authors must not depend on this API.
9137
- */
9138
- var ɵInterruptState = class {
9139
- #responses = {};
9140
- #pending = null;
9141
- #sealed = false;
9142
- /** Return the active normalized interrupt without exposing mutable state. */
9143
- get pending() {
9144
- const pending = this.#pending;
9145
- if (pending?.kind === "standard") return {
9146
- kind: "standard",
9147
- interrupts: [...pending.interrupts]
9148
- };
9149
- return pending;
9150
- }
9151
- /** Replace the current interrupt with a legacy custom-event interrupt. */
9152
- setLegacy(event) {
9153
- this.#replace({
9154
- kind: "legacy",
9155
- event
9156
- });
9157
- }
9158
- /** Replace the current interrupt with an AG-UI standard interrupt set. */
9159
- setStandard(interrupts) {
9160
- this.#replace({
9161
- kind: "standard",
9162
- interrupts: [...interrupts]
9163
- });
9164
- }
9165
- /** Clear all pending interrupt data and accumulated responses. */
9166
- clear() {
9167
- this.#pending = null;
9168
- this.#sealed = false;
9169
- for (const id of Object.keys(this.#responses)) delete this.#responses[id];
9170
- }
9171
- /** Record a resolved response and return the next framework action. */
9172
- resolve(payload, interruptId) {
9173
- const pending = this.#pending;
9174
- if (!pending || this.#sealed) return { kind: "ignored" };
9175
- if (pending.kind === "legacy") {
9176
- this.#sealed = true;
9177
- return {
9178
- kind: "legacy-resume",
9179
- payload,
9180
- interruptValue: pending.event.value
9181
- };
9182
- }
9183
- return this.#respond(pending.interrupts, interruptId, {
9184
- status: "resolved",
9185
- payload
9186
- });
9187
- }
9188
- /** Record a cancelled response and return the next framework action. */
9189
- cancel(interruptId) {
9190
- const pending = this.#pending;
9191
- if (!pending || this.#sealed) return { kind: "ignored" };
9192
- if (pending.kind === "legacy") {
9193
- this.#sealed = true;
9194
- return { kind: "dismiss" };
9195
- }
9196
- return this.#respond(pending.interrupts, interruptId, { status: "cancelled" });
9197
- }
9198
- #replace(pending) {
9199
- this.clear();
9200
- this.#pending = pending;
9201
- }
9202
- #respond(interrupts, interruptId, response) {
9203
- const id = interruptId ?? interrupts[0]?.id;
9204
- if (!id || !interrupts.some((interrupt) => interrupt.id === id)) return { kind: "ignored" };
9205
- this.#responses[id] = response;
9206
- if (!interrupts.every((interrupt) => this.#responses[interrupt.id])) return { kind: "waiting" };
9207
- const expired = interrupts.find((interrupt) => (0, _ag_ui_client.isInterruptExpired)(interrupt));
9208
- if (expired) {
9209
- this.#sealed = true;
9210
- return {
9211
- kind: "expired",
9212
- interrupt: expired
9213
- };
9214
- }
9215
- const mutableInterrupts = [...interrupts];
9216
- const resume = (0, _ag_ui_client.buildResumeArray)(mutableInterrupts, this.#responses);
9217
- const toolResults = mutableInterrupts.flatMap((interrupt) => {
9218
- if (!interrupt.toolCallId || interrupt.reason !== "tool_call") return [];
9219
- return [{
9220
- toolCallId: interrupt.toolCallId,
9221
- content: toolResultContent(this.#responses[interrupt.id])
9222
- }];
9223
- });
9224
- this.#sealed = true;
9225
- return {
9226
- kind: "resume",
9227
- resume,
9228
- toolResults
9229
- };
9230
- }
9231
- };
9232
-
9233
9410
  //#endregion
9234
9411
  //#region src/inspector-thread-bridge.ts
9235
9412
  const INSPECTOR_THREAD_BRIDGE_PLUGIN_ID = "cpk-inspector-thread";
@@ -10642,6 +10819,7 @@ exports.onInspectorActiveThread = onInspectorActiveThread;
10642
10819
  exports.onInspectorStopViewing = onInspectorStopViewing;
10643
10820
  exports.onInspectorViewThread = onInspectorViewThread;
10644
10821
  exports.onInspectorViewThreadResult = onInspectorViewThreadResult;
10822
+ exports.parseMarkdown = parseMarkdown;
10645
10823
  exports.parseToolArguments = parseToolArguments;
10646
10824
  exports.prepareSurfaceOperations = prepareSurfaceOperations;
10647
10825
  exports.props = props;
@@ -10653,9 +10831,11 @@ exports.ɵInterruptState = ɵInterruptState;
10653
10831
  exports.ɵMAX_SOCKET_RETRIES = ɵMAX_SOCKET_RETRIES;
10654
10832
  exports.ɵRUNTIME_PROBE_TIMEOUT_MS = ɵRUNTIME_PROBE_TIMEOUT_MS;
10655
10833
  exports.ɵTHREAD_REQUEST_TIMEOUT_MS = ɵTHREAD_REQUEST_TIMEOUT_MS;
10834
+ exports.ɵclearAgentInterruptState = ɵclearAgentInterruptState;
10656
10835
  exports.ɵcreateMemoryStore = createMemoryStore;
10657
10836
  exports.ɵcreateThreadSelectors = ɵcreateThreadSelectors;
10658
10837
  exports.ɵcreateThreadStore = createThreadStore;
10838
+ exports.ɵgetAgentInterruptState = ɵgetAgentInterruptState;
10659
10839
  exports.ɵisCopilotKitFeature = ɵisCopilotKitFeature;
10660
10840
  exports.ɵisHttpAgent = ɵisHttpAgent;
10661
10841
  exports.ɵisRetryableMemoryStatus = isRetryableStatus;