@copilotkit/core 1.83.0 → 1.84.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.mjs CHANGED
@@ -6,6 +6,7 @@ import { catchError, concatMap, concatWith, delay, distinctUntilChanged, endWith
6
6
  import { Socket } from "phoenix";
7
7
  import { zodToJsonSchema } from "zod-to-json-schema";
8
8
  import { createCollector, createTrajectoryCollector } from "@copilotkit/learning";
9
+ import { jsonrepair } from "jsonrepair";
9
10
 
10
11
  //#region src/utils/http-agent.ts
11
12
  /**
@@ -801,10 +802,23 @@ function isRuntimeInfoRequestError(error) {
801
802
 
802
803
  //#endregion
803
804
  //#region src/core/message-filter.ts
805
+ /**
806
+ * The string ids of a message's tool calls.
807
+ *
808
+ * Malformed entries are ignored rather than thrown on, matching
809
+ * {@link ɵkeepToolResultsWithCalls}: a null or primitive entry, or an entry
810
+ * without a string `id`, opens no pair instead of failing the repair.
811
+ */
804
812
  function toolCallIdsOf(message) {
805
813
  const calls = message.toolCalls;
806
814
  if (!Array.isArray(calls)) return [];
807
- return calls.map((call) => call.id).filter((id) => Boolean(id));
815
+ const ids = [];
816
+ for (const call of calls) {
817
+ if (typeof call !== "object" || call === null) continue;
818
+ const id = call.id;
819
+ if (typeof id === "string" && id) ids.push(id);
820
+ }
821
+ return ids;
808
822
  }
809
823
  function resultCallIdOf(message) {
810
824
  if (message.role !== "tool") return void 0;
@@ -845,12 +859,24 @@ function resultCallIdOf(message) {
845
859
  * untouched.
846
860
  */
847
861
  function ɵrepairToolCallPairs(kept, full) {
848
- const callIdToIssuer = /* @__PURE__ */ new Map();
849
- const callIdToResult = /* @__PURE__ */ new Map();
862
+ const pendingIssuersByCallId = /* @__PURE__ */ new Map();
863
+ const issuerIdToResultsByCallId = /* @__PURE__ */ new Map();
864
+ const resultIdToIssuer = /* @__PURE__ */ new Map();
850
865
  for (const message of full) {
851
- for (const callId of toolCallIdsOf(message)) callIdToIssuer.set(callId, message);
866
+ for (const callId of toolCallIdsOf(message)) push(pendingIssuersByCallId, callId, message);
852
867
  const resultCallId = resultCallIdOf(message);
853
- if (resultCallId !== void 0) callIdToResult.set(resultCallId, message);
868
+ if (resultCallId !== void 0) {
869
+ const issuer = pendingIssuersByCallId.get(resultCallId)?.pop();
870
+ if (issuer) {
871
+ resultIdToIssuer.set(message.id, issuer);
872
+ let resultsByCallId = issuerIdToResultsByCallId.get(issuer.id);
873
+ if (!resultsByCallId) {
874
+ resultsByCallId = /* @__PURE__ */ new Map();
875
+ issuerIdToResultsByCallId.set(issuer.id, resultsByCallId);
876
+ }
877
+ push(resultsByCallId, resultCallId, message);
878
+ }
879
+ }
854
880
  }
855
881
  const repaired = [];
856
882
  const emitted = /* @__PURE__ */ new Set();
@@ -865,18 +891,15 @@ function ɵrepairToolCallPairs(kept, full) {
865
891
  emit(message);
866
892
  if (expandedMessages.has(message)) return;
867
893
  expandedMessages.add(message);
868
- for (const callId of toolCallIdsOf(message)) {
869
- const result = callIdToResult.get(callId);
870
- if (result) emit(result);
871
- }
894
+ const resultsByCallId = issuerIdToResultsByCallId.get(message.id);
895
+ for (const callId of toolCallIdsOf(message)) for (const result of resultsByCallId?.get(callId) ?? []) emit(result);
872
896
  };
873
897
  for (const message of kept) {
874
- const resultCallId = resultCallIdOf(message);
875
- if (resultCallId === void 0) {
898
+ if (resultCallIdOf(message) === void 0) {
876
899
  emitWithResults(message);
877
900
  continue;
878
901
  }
879
- const issuer = callIdToIssuer.get(resultCallId);
902
+ const issuer = resultIdToIssuer.get(message.id);
880
903
  if (issuer) {
881
904
  emitWithResults(issuer);
882
905
  continue;
@@ -3622,6 +3645,216 @@ function stripAdditionalProperties(schema) {
3622
3645
  for (const value of Object.values(record)) stripAdditionalProperties(value);
3623
3646
  }
3624
3647
 
3648
+ //#endregion
3649
+ //#region src/interrupt-state.ts
3650
+ /** Serialize a newly answered frontend call for the canonical message history. */
3651
+ function toolResultContent(response) {
3652
+ if (response.status === "cancelled") return JSON.stringify({ status: "cancelled" });
3653
+ return JSON.stringify(response.payload ?? { status: "resolved" });
3654
+ }
3655
+ /**
3656
+ * @internal Framework-neutral interrupt response state shared by framework
3657
+ * adapters. Application authors must not depend on this API.
3658
+ */
3659
+ var ɵInterruptState = class {
3660
+ #responses = Object.create(null);
3661
+ #adoptedContent = /* @__PURE__ */ new Map();
3662
+ #pending = null;
3663
+ #sealed = false;
3664
+ /** Return the active normalized interrupt without exposing mutable state. */
3665
+ get pending() {
3666
+ const pending = this.#pending;
3667
+ if (pending?.kind === "standard") return {
3668
+ kind: "standard",
3669
+ interrupts: [...pending.interrupts]
3670
+ };
3671
+ return pending;
3672
+ }
3673
+ /** Replace the current interrupt with a legacy custom-event interrupt. */
3674
+ setLegacy(event) {
3675
+ this.#replace({
3676
+ kind: "legacy",
3677
+ event
3678
+ });
3679
+ }
3680
+ /** Replace the current interrupt with an AG-UI standard interrupt set. */
3681
+ setStandard(interrupts) {
3682
+ const ids = /* @__PURE__ */ new Set();
3683
+ const callIds = /* @__PURE__ */ new Set();
3684
+ for (const interrupt of interrupts) {
3685
+ if (ids.has(interrupt.id)) throw new Error(`Duplicate interrupt id: ${interrupt.id}`);
3686
+ ids.add(interrupt.id);
3687
+ if (interrupt.reason === "tool_call" && interrupt.toolCallId) {
3688
+ if (callIds.has(interrupt.toolCallId)) throw new Error(`Duplicate interrupt tool call: ${interrupt.toolCallId}`);
3689
+ callIds.add(interrupt.toolCallId);
3690
+ }
3691
+ }
3692
+ this.#replace({
3693
+ kind: "standard",
3694
+ interrupts: [...interrupts]
3695
+ });
3696
+ }
3697
+ /** Clear all pending interrupt data and accumulated responses. */
3698
+ clear() {
3699
+ this.#pending = null;
3700
+ this.#sealed = false;
3701
+ this.#adoptedContent.clear();
3702
+ for (const id of Object.keys(this.#responses)) delete this.#responses[id];
3703
+ }
3704
+ /** Record a resolved response and return the next framework action. */
3705
+ resolve(payload, interruptId, messages = []) {
3706
+ const pending = this.#pending;
3707
+ if (!pending || this.#sealed) return { kind: "ignored" };
3708
+ if (pending.kind === "legacy") {
3709
+ this.#sealed = true;
3710
+ return {
3711
+ kind: "legacy-resume",
3712
+ payload,
3713
+ interruptValue: pending.event.value
3714
+ };
3715
+ }
3716
+ return this.#respond(pending.interrupts, interruptId, {
3717
+ status: "resolved",
3718
+ payload
3719
+ }, messages);
3720
+ }
3721
+ /** Record a cancelled response and return the next framework action. */
3722
+ cancel(interruptId, messages = []) {
3723
+ const pending = this.#pending;
3724
+ if (!pending || this.#sealed) return { kind: "ignored" };
3725
+ if (pending.kind === "legacy") {
3726
+ this.#sealed = true;
3727
+ return { kind: "dismiss" };
3728
+ }
3729
+ return this.#respond(pending.interrupts, interruptId, { status: "cancelled" }, messages);
3730
+ }
3731
+ /** Reject ambiguous assistant definitions before executing or answering a call. */
3732
+ validateToolCalls(messages) {
3733
+ if (this.#pending?.kind !== "standard") return;
3734
+ const pendingCalls = new Set(this.#pending.interrupts.filter((interrupt) => interrupt.reason === "tool_call").map((interrupt) => interrupt.toolCallId));
3735
+ const seen = /* @__PURE__ */ new Set();
3736
+ for (const message of messages) {
3737
+ if (message.role !== "assistant") continue;
3738
+ for (const call of message.toolCalls ?? []) {
3739
+ if (!pendingCalls.has(call.id)) continue;
3740
+ if (seen.has(call.id)) throw new Error(`Duplicate tool call definition: ${call.id}`);
3741
+ seen.add(call.id);
3742
+ }
3743
+ }
3744
+ }
3745
+ /** Let UI adapters ignore answers for exactly one successful frontend result. */
3746
+ isCompletedToolCall(interruptId, messages) {
3747
+ const pending = this.#pending;
3748
+ if (pending?.kind !== "standard") return false;
3749
+ const id = interruptId ?? pending.interrupts[0]?.id;
3750
+ const interrupt = pending.interrupts.find((entry) => entry.id === id);
3751
+ if (interrupt?.reason !== "tool_call" || !interrupt.toolCallId) return false;
3752
+ const results = messages.filter((message) => message.role === "tool" && message.toolCallId === interrupt.toolCallId && !isForwardedToClientPlaceholder(message.content));
3753
+ const result = results[0];
3754
+ return results.length === 1 && result?.role === "tool" && result.error === void 0;
3755
+ }
3756
+ /** Resume only when saved frontend results answer every pending interrupt. */
3757
+ resumeWithToolResults(messages) {
3758
+ const pending = this.#pending;
3759
+ if (pending?.kind !== "standard" || this.#sealed) return { kind: "ignored" };
3760
+ return this.#decide(pending.interrupts, { ...this.#responses }, messages);
3761
+ }
3762
+ /** Start a new batch with no decisions retained from the preceding run. */
3763
+ #replace(pending) {
3764
+ this.clear();
3765
+ this.#pending = pending;
3766
+ }
3767
+ /** Record one explicit answer and reconcile it with saved frontend results. */
3768
+ #respond(interrupts, interruptId, response, messages) {
3769
+ const id = interruptId ?? interrupts[0]?.id;
3770
+ if (!id || !interrupts.some((interrupt) => interrupt.id === id)) return { kind: "ignored" };
3771
+ return this.#decide(interrupts, {
3772
+ ...this.#responses,
3773
+ [id]: response
3774
+ }, messages);
3775
+ }
3776
+ /** Claim a complete batch once, preserving saved results and partial answers. */
3777
+ #decide(interrupts, responses, messages) {
3778
+ this.validateToolCalls(messages);
3779
+ const completed = /* @__PURE__ */ new Set();
3780
+ const adoptedContent = new Map(this.#adoptedContent);
3781
+ for (const interrupt of interrupts) {
3782
+ if (interrupt.reason !== "tool_call" || !interrupt.toolCallId) continue;
3783
+ const results = messages.filter((message) => message.role === "tool" && message.toolCallId === interrupt.toolCallId && !isForwardedToClientPlaceholder(message.content));
3784
+ if (results.length > 1) throw new Error(`Duplicate tool results for ${interrupt.toolCallId}`);
3785
+ const result = results[0];
3786
+ if (!result && !adoptedContent.has(interrupt.id)) continue;
3787
+ const response = Object.prototype.hasOwnProperty.call(responses, interrupt.id) ? responses[interrupt.id] : void 0;
3788
+ if (result?.role === "tool" && result.error !== void 0) {
3789
+ adoptedContent.delete(interrupt.id);
3790
+ completed.add(interrupt.id);
3791
+ continue;
3792
+ }
3793
+ const content = result ? result.content : adoptedContent.get(interrupt.id);
3794
+ 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}`);
3795
+ responses[interrupt.id] = {
3796
+ status: "resolved",
3797
+ payload: content
3798
+ };
3799
+ adoptedContent.set(interrupt.id, content);
3800
+ if (result) completed.add(interrupt.id);
3801
+ }
3802
+ Object.assign(this.#responses, responses);
3803
+ this.#adoptedContent = adoptedContent;
3804
+ if (!interrupts.every((interrupt) => Object.prototype.hasOwnProperty.call(responses, interrupt.id))) return { kind: "waiting" };
3805
+ const expired = interrupts.find((interrupt) => responses[interrupt.id]?.status !== "cancelled" && isInterruptExpired(interrupt));
3806
+ if (expired) {
3807
+ this.#sealed = true;
3808
+ return {
3809
+ kind: "expired",
3810
+ interrupt: expired
3811
+ };
3812
+ }
3813
+ const mutableInterrupts = [...interrupts];
3814
+ const resume = buildResumeArray(mutableInterrupts, responses);
3815
+ const toolResults = mutableInterrupts.flatMap((interrupt) => {
3816
+ if (!interrupt.toolCallId || interrupt.reason !== "tool_call" || completed.has(interrupt.id)) return [];
3817
+ return [{
3818
+ toolCallId: interrupt.toolCallId,
3819
+ content: adoptedContent.has(interrupt.id) ? adoptedContent.get(interrupt.id) : toolResultContent(responses[interrupt.id])
3820
+ }];
3821
+ });
3822
+ this.#sealed = true;
3823
+ return {
3824
+ kind: "resume",
3825
+ resume,
3826
+ toolResults
3827
+ };
3828
+ }
3829
+ };
3830
+ /** Compare JSON protocol values without depending on object key insertion order. */
3831
+ function sameValue(left, right) {
3832
+ if (left === right) return true;
3833
+ if (!left || !right || typeof left !== "object" || typeof right !== "object") return false;
3834
+ 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]));
3835
+ const a = left;
3836
+ const b = right;
3837
+ 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]));
3838
+ }
3839
+ const agentInterruptStates = /* @__PURE__ */ new WeakMap();
3840
+ /** @internal Share decisions and the single resume claim for an agent's pending batch. */
3841
+ function ɵgetAgentInterruptState(agent, interrupts = agent.pendingInterrupts) {
3842
+ const current = agentInterruptStates.get(agent);
3843
+ if (current && current.threadId === agent.threadId && current.state.pending && sameValue(current.interrupts, interrupts)) return current.state;
3844
+ const state = new ɵInterruptState();
3845
+ state.setStandard(interrupts);
3846
+ agentInterruptStates.set(agent, {
3847
+ threadId: agent.threadId,
3848
+ interrupts: structuredClone(interrupts),
3849
+ state
3850
+ });
3851
+ return state;
3852
+ }
3853
+ /** @internal A new run owns a new batch, even if the server reuses interrupt IDs. */
3854
+ function ɵclearAgentInterruptState(agent) {
3855
+ agentInterruptStates.delete(agent);
3856
+ }
3857
+
3625
3858
  //#endregion
3626
3859
  //#region src/core/webmcp.ts
3627
3860
  /**
@@ -3878,6 +4111,7 @@ var RunHandler = class {
3878
4111
  /** Prevent reconnects from starting an interaction already executing locally. */
3879
4112
  _executingToolCalls = /* @__PURE__ */ new WeakMap();
3880
4113
  _connectionGenerations = /* @__PURE__ */ new WeakMap();
4114
+ _runGenerations = /* @__PURE__ */ new WeakMap();
3881
4115
  _interactionAbortControllers = /* @__PURE__ */ new WeakMap();
3882
4116
  constructor(core) {
3883
4117
  this.core = core;
@@ -4116,6 +4350,7 @@ var RunHandler = class {
4116
4350
  runAgentResult,
4117
4351
  agent,
4118
4352
  toolExecutionMode: "restore",
4353
+ connectionGeneration: connection,
4119
4354
  signal: controller.signal
4120
4355
  }).catch(async (error) => {
4121
4356
  await this._internal.emitError({
@@ -4153,6 +4388,9 @@ var RunHandler = class {
4153
4388
  * Run an agent
4154
4389
  */
4155
4390
  async runAgent({ agent, forwardedProps, resume, runId }, continuationHandoff, followUpOf) {
4391
+ this._connectionGenerations.set(agent, {});
4392
+ this._runGenerations.set(agent, {});
4393
+ ɵclearAgentInterruptState(agent);
4156
4394
  if (agent.agentId) this._internal.suggestionEngine.clearSuggestions(agent.agentId);
4157
4395
  try {
4158
4396
  const headersApplied = this._internal.prepareAgentHeadersForRun(agent);
@@ -4282,11 +4520,15 @@ var RunHandler = class {
4282
4520
  /**
4283
4521
  * Process agent result and execute tools
4284
4522
  */
4285
- async processAgentResult({ runAgentResult, agent, runId, toolExecutionMode = "all", runController, signal = runController?.signal }) {
4523
+ async processAgentResult({ runAgentResult, agent, runId, toolExecutionMode = "all", runController, signal = runController?.signal, connectionGeneration }) {
4286
4524
  const { newMessages } = runAgentResult;
4287
4525
  const agentId = agent.agentId;
4288
4526
  let needsFollowUp = false;
4527
+ let ownsHandlerFollowUp = false;
4528
+ const runGeneration = this._runGenerations.get(agent);
4289
4529
  const threadId = agent.threadId;
4530
+ const interruptState = agent.pendingInterrupts?.length ? ɵgetAgentInterruptState(agent) : void 0;
4531
+ interruptState?.validateToolCalls(agent.messages);
4290
4532
  const executing = this._executingToolCalls.get(agent) ?? /* @__PURE__ */ new Set();
4291
4533
  this._executingToolCalls.set(agent, executing);
4292
4534
  const messagesToProcess = toolExecutionMode === "restore" ? agent.messages.filter((message) => message.role === "assistant" && this.isInLatestUserTurn(agent.messages, message.id)) : newMessages;
@@ -4306,11 +4548,15 @@ var RunHandler = class {
4306
4548
  return wildcardTool;
4307
4549
  };
4308
4550
  const executableTool = tool ?? getWildcardTool();
4309
- if (toolExecutionMode === "restore" && (!executableTool || executableTool.handler && executableTool.type !== "human-in-the-loop" && executableTool.reconnectBehavior !== "resume-pending")) continue;
4310
4551
  const executionKey = JSON.stringify([threadId, toolCall.id]);
4311
4552
  if (signal?.aborted || agent.threadId !== threadId || toolExecutionMode === "restore" && !this.isInLatestUserTurn(agent.messages, message.id) || executing.has(executionKey)) continue;
4312
4553
  const existingResultIndex = newMessages.findIndex((m) => m.role === "tool" && m.toolCallId === toolCall.id);
4313
4554
  let existingResult = agent.messages.find((m) => m.role === "tool" && m.toolCallId === toolCall.id) ?? newMessages[existingResultIndex];
4555
+ if (existingResult && !this.isFrontendPlaceholderResult(existingResult)) {
4556
+ if (executableTool && executableTool.followUp !== false && agent.pendingInterrupts?.some((interrupt) => interrupt.reason === "tool_call" && interrupt.toolCallId === toolCall.id)) needsFollowUp = true;
4557
+ continue;
4558
+ }
4559
+ if (toolExecutionMode === "restore" && (!executableTool || executableTool.handler && executableTool.type !== "human-in-the-loop" && executableTool.reconnectBehavior !== "resume-pending")) continue;
4314
4560
  if (existingResult && this.isFrontendPlaceholderResult(existingResult) && (toolExecutionMode === "restore" || executableTool?.handler)) {
4315
4561
  if (existingResultIndex !== -1) newMessages.splice(existingResultIndex, 1);
4316
4562
  existingResult = void 0;
@@ -4326,8 +4572,8 @@ var RunHandler = class {
4326
4572
  };
4327
4573
  const abortInteraction = () => {
4328
4574
  if (!interactionController) return;
4329
- const connectionGeneration = this._connectionGenerations.get(agent);
4330
- liveHITLStops.set(interactionController.signal, () => this._connectionGenerations.get(agent) === connectionGeneration && agent.threadId === threadId);
4575
+ const stopConnectionGeneration = this._connectionGenerations.get(agent);
4576
+ liveHITLStops.set(interactionController.signal, () => this._connectionGenerations.get(agent) === stopConnectionGeneration && agent.threadId === threadId);
4331
4577
  interactionController.abort();
4332
4578
  };
4333
4579
  if (interactionController) {
@@ -4340,11 +4586,17 @@ var RunHandler = class {
4340
4586
  const discardOnAbort = toolExecutionMode === "restore" || !!interactionController;
4341
4587
  try {
4342
4588
  if (tool) {
4343
- if (await this.executeSpecificTool(tool, toolCall, message, agent, agentId, executionSignal, discardOnAbort, toolExecutionMode === "restore")) needsFollowUp = true;
4589
+ if (await this.executeSpecificTool(tool, toolCall, message, agent, agentId, executionSignal, discardOnAbort, toolExecutionMode === "restore")) {
4590
+ ownsHandlerFollowUp ||= !!tool.handler;
4591
+ needsFollowUp = true;
4592
+ }
4344
4593
  } else {
4345
4594
  const fallbackTool = getWildcardTool();
4346
4595
  if (fallbackTool) {
4347
- if (await this.executeWildcardTool(fallbackTool, toolCall, message, agent, agentId, executionSignal, discardOnAbort, toolExecutionMode === "restore")) needsFollowUp = true;
4596
+ if (await this.executeWildcardTool(fallbackTool, toolCall, message, agent, agentId, executionSignal, discardOnAbort, toolExecutionMode === "restore")) {
4597
+ ownsHandlerFollowUp ||= !!fallbackTool.handler;
4598
+ needsFollowUp = true;
4599
+ }
4348
4600
  }
4349
4601
  }
4350
4602
  } finally {
@@ -4361,11 +4613,24 @@ var RunHandler = class {
4361
4613
  if (needsFollowUp && agent.threadId === threadId && !signal?.aborted) if ((this._runDepths.get(agent) ?? 0) >= MAX_FOLLOW_UP_DEPTH) 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.`);
4362
4614
  else {
4363
4615
  await this._internal.waitForPendingFrameworkUpdates();
4616
+ if (signal?.aborted || agent.threadId !== threadId || this._runGenerations.get(agent) !== runGeneration || connectionGeneration && !ownsHandlerFollowUp && this._connectionGenerations.get(agent) !== connectionGeneration || interruptState && ɵgetAgentInterruptState(agent) !== interruptState) return runAgentResult;
4364
4617
  if (toolExecutionMode === "restore" && !messagesToProcess.some((message) => this.isInLatestUserTurn(agent.messages, message.id))) return runAgentResult;
4618
+ let resume;
4619
+ if (agent.pendingInterrupts?.length) {
4620
+ const decision = ɵgetAgentInterruptState(agent).resumeWithToolResults(agent.messages);
4621
+ if (decision.kind !== "resume") return runAgentResult;
4622
+ resume = decision.resume;
4623
+ for (const result of decision.toolResults) agent.addMessage({
4624
+ id: randomUUID$1(),
4625
+ role: "tool",
4626
+ ...result
4627
+ });
4628
+ }
4365
4629
  const continuationHandoff = this._internal.stateManager.markNextRunAsContinuation(agent, runId);
4366
4630
  return await this.runAgent({
4367
4631
  agent,
4368
- ...runId !== void 0 ? { runId } : {}
4632
+ ...runId !== void 0 ? { runId } : {},
4633
+ ...resume ? { resume } : {}
4369
4634
  }, continuationHandoff, runController);
4370
4635
  }
4371
4636
  this._internal.suggestionEngine.reloadSuggestions(agentId);
@@ -9124,111 +9389,6 @@ function ɵisCopilotKitFeature(name) {
9124
9389
  return FEATURE_SET.has(name);
9125
9390
  }
9126
9391
 
9127
- //#endregion
9128
- //#region src/interrupt-state.ts
9129
- function toolResultContent(response) {
9130
- if (response.status === "cancelled") return JSON.stringify({ status: "cancelled" });
9131
- return JSON.stringify(response.payload ?? { status: "resolved" });
9132
- }
9133
- /**
9134
- * @internal Framework-neutral interrupt response state shared by framework
9135
- * adapters. Application authors must not depend on this API.
9136
- */
9137
- var ɵInterruptState = class {
9138
- #responses = {};
9139
- #pending = null;
9140
- #sealed = false;
9141
- /** Return the active normalized interrupt without exposing mutable state. */
9142
- get pending() {
9143
- const pending = this.#pending;
9144
- if (pending?.kind === "standard") return {
9145
- kind: "standard",
9146
- interrupts: [...pending.interrupts]
9147
- };
9148
- return pending;
9149
- }
9150
- /** Replace the current interrupt with a legacy custom-event interrupt. */
9151
- setLegacy(event) {
9152
- this.#replace({
9153
- kind: "legacy",
9154
- event
9155
- });
9156
- }
9157
- /** Replace the current interrupt with an AG-UI standard interrupt set. */
9158
- setStandard(interrupts) {
9159
- this.#replace({
9160
- kind: "standard",
9161
- interrupts: [...interrupts]
9162
- });
9163
- }
9164
- /** Clear all pending interrupt data and accumulated responses. */
9165
- clear() {
9166
- this.#pending = null;
9167
- this.#sealed = false;
9168
- for (const id of Object.keys(this.#responses)) delete this.#responses[id];
9169
- }
9170
- /** Record a resolved response and return the next framework action. */
9171
- resolve(payload, interruptId) {
9172
- const pending = this.#pending;
9173
- if (!pending || this.#sealed) return { kind: "ignored" };
9174
- if (pending.kind === "legacy") {
9175
- this.#sealed = true;
9176
- return {
9177
- kind: "legacy-resume",
9178
- payload,
9179
- interruptValue: pending.event.value
9180
- };
9181
- }
9182
- return this.#respond(pending.interrupts, interruptId, {
9183
- status: "resolved",
9184
- payload
9185
- });
9186
- }
9187
- /** Record a cancelled response and return the next framework action. */
9188
- cancel(interruptId) {
9189
- const pending = this.#pending;
9190
- if (!pending || this.#sealed) return { kind: "ignored" };
9191
- if (pending.kind === "legacy") {
9192
- this.#sealed = true;
9193
- return { kind: "dismiss" };
9194
- }
9195
- return this.#respond(pending.interrupts, interruptId, { status: "cancelled" });
9196
- }
9197
- #replace(pending) {
9198
- this.clear();
9199
- this.#pending = pending;
9200
- }
9201
- #respond(interrupts, interruptId, response) {
9202
- const id = interruptId ?? interrupts[0]?.id;
9203
- if (!id || !interrupts.some((interrupt) => interrupt.id === id)) return { kind: "ignored" };
9204
- this.#responses[id] = response;
9205
- if (!interrupts.every((interrupt) => this.#responses[interrupt.id])) return { kind: "waiting" };
9206
- const expired = interrupts.find((interrupt) => isInterruptExpired(interrupt));
9207
- if (expired) {
9208
- this.#sealed = true;
9209
- return {
9210
- kind: "expired",
9211
- interrupt: expired
9212
- };
9213
- }
9214
- const mutableInterrupts = [...interrupts];
9215
- const resume = buildResumeArray(mutableInterrupts, this.#responses);
9216
- const toolResults = mutableInterrupts.flatMap((interrupt) => {
9217
- if (!interrupt.toolCallId || interrupt.reason !== "tool_call") return [];
9218
- return [{
9219
- toolCallId: interrupt.toolCallId,
9220
- content: toolResultContent(this.#responses[interrupt.id])
9221
- }];
9222
- });
9223
- this.#sealed = true;
9224
- return {
9225
- kind: "resume",
9226
- resume,
9227
- toolResults
9228
- };
9229
- }
9230
- };
9231
-
9232
9392
  //#endregion
9233
9393
  //#region src/inspector-thread-bridge.ts
9234
9394
  const INSPECTOR_THREAD_BRIDGE_PLUGIN_ID = "cpk-inspector-thread";
@@ -9957,11 +10117,11 @@ function partialOperation(line) {
9957
10117
  return null;
9958
10118
  }
9959
10119
  /**
9960
- * A line that opens a new top-level operation: `{"version":"v…` or
10120
+ * A line that opens a new top-level operation: `{"version":"1…` or
9961
10121
  * `{"<operation>":{`. Seen at the start of a line while an earlier object is
9962
10122
  * still unbalanced, it means that object is malformed and has ended.
9963
10123
  */
9964
- const OPERATION_START = new RegExp(`^\\{\\s*"(?:version"\\s*:\\s*"v\\d|(?:${OP_KEYS.join("|")})"\\s*:\\s*\\{)`);
10124
+ const OPERATION_START = new RegExp(`^\\{\\s*"(?:version"\\s*:\\s*"\\d|(?:${OP_KEYS.join("|")})"\\s*:\\s*\\{)`);
9965
10125
  /**
9966
10126
  * Scan the top-level object whose "{" is at `start`. Returns the index just
9967
10127
  * past it and whether it balanced. An unbalanced object ends early (at the
@@ -10003,6 +10163,91 @@ function scanTopLevelObject(s, start) {
10003
10163
  balanced: false
10004
10164
  };
10005
10165
  }
10166
+ const OPERATION_NAMES = [
10167
+ "createSurface",
10168
+ "updateComponents",
10169
+ "updateDataModel",
10170
+ "deleteSurface",
10171
+ "callRendererFunction"
10172
+ ];
10173
+ /** Whether a value is shaped like one A2UI operation, with named components. */
10174
+ function isOperationShape(value) {
10175
+ if (!isRecord(value) || value.version !== A2UI_VERSION) return false;
10176
+ const names = OPERATION_NAMES.filter((name) => name in value);
10177
+ if (names.length !== 1 || Object.keys(value).length !== 2) return false;
10178
+ const body = value[names[0]];
10179
+ if (!isRecord(body)) return false;
10180
+ if (names[0] === "callRendererFunction") return true;
10181
+ if (typeof body.surfaceId !== "string") return false;
10182
+ const components = body.components;
10183
+ return components === void 0 || Array.isArray(components) && components.every((c) => isRecord(c) && typeof c.id === "string" && typeof c.component === "string");
10184
+ }
10185
+ /** Openers minus closers ({ and [ against } and ]) outside strings. */
10186
+ function closerImbalance(line) {
10187
+ let depth = 0;
10188
+ let inString = false;
10189
+ for (let i = 0; i < line.length; i++) {
10190
+ const c = line[i];
10191
+ if (inString) {
10192
+ if (c === "\\") i++;
10193
+ else if (c === "\"") inString = false;
10194
+ } else if (c === "\"") inString = true;
10195
+ else if (c === "{" || c === "[") depth++;
10196
+ else if (c === "}" || c === "]") depth--;
10197
+ }
10198
+ return depth;
10199
+ }
10200
+ /** The text with closers and whitespace removed, to compare a repair. */
10201
+ function withoutClosers(text) {
10202
+ return text.replace(/[\]}\s]/g, "");
10203
+ }
10204
+ /**
10205
+ * Whether a component of the operation holds a structural key (`id`,
10206
+ * `component`, `child`, `children`) in a nested object: a closer added at
10207
+ * the end instead of where it was dropped. The scan below repairs those.
10208
+ */
10209
+ function nestsStructuralKey(value) {
10210
+ const nests = (v) => isRecord(v) && Object.entries(v).some(([k, x]) => STRUCTURAL_KEYS.has(k) || nests(x));
10211
+ const components = (isRecord(value) ? Object.values(value).find(isRecord) : void 0)?.components;
10212
+ return Array.isArray(components) && components.some((c) => isRecord(c) && Object.values(c).some((prop) => nests(prop)));
10213
+ }
10214
+ /**
10215
+ * Repairs the complete lines of a fence that are not valid JSON (a missing
10216
+ * or extra brace) with jsonrepair, when the repair only adds or removes
10217
+ * closers and the result is shaped like an operation. A line still streaming in (no newline yet) is left alone.
10218
+ */
10219
+ function repairFenceLines(fenceText) {
10220
+ const repaired = [];
10221
+ const lines = fenceText.split("\n");
10222
+ if (fenceText.trimStart().startsWith("[")) return {
10223
+ text: fenceText,
10224
+ repaired
10225
+ };
10226
+ for (let n = 0; n < lines.length - 1; n++) {
10227
+ const line = lines[n];
10228
+ if (!line.trim().startsWith("{")) continue;
10229
+ try {
10230
+ JSON.parse(line);
10231
+ continue;
10232
+ } catch {}
10233
+ const imbalance = closerImbalance(line);
10234
+ if (Math.abs(imbalance) !== 1) continue;
10235
+ const next = lines.slice(n + 1).find((l) => l.trim() !== "");
10236
+ if (imbalance > 0 && next !== void 0 && !next.trim().startsWith("{")) continue;
10237
+ try {
10238
+ const fixed = jsonrepair(line);
10239
+ const value = JSON.parse(fixed);
10240
+ if (withoutClosers(fixed) === withoutClosers(line) && isOperationShape(value) && !nestsStructuralKey(value) && !(isRecord(value) && "callRendererFunction" in value)) {
10241
+ repaired.push(line.trim());
10242
+ lines[n] = JSON.stringify(value);
10243
+ }
10244
+ } catch {}
10245
+ }
10246
+ return {
10247
+ text: lines.join("\n"),
10248
+ repaired
10249
+ };
10250
+ }
10006
10251
  /**
10007
10252
  * Parse the body of an a2ui fence as a stream of top-level JSON values, so
10008
10253
  * operations may be one per line (the documented format), several per line,
@@ -10032,7 +10277,7 @@ function scanTopLevelObject(s, start) {
10032
10277
  * ```
10033
10278
  */
10034
10279
  function extractFenceOperations(fenceText) {
10035
- const s = fenceText;
10280
+ const { text: s, repaired: repairedLines } = repairFenceLines(fenceText);
10036
10281
  const operations = [];
10037
10282
  const invalidLines = [];
10038
10283
  const recovered = [];
@@ -10086,7 +10331,8 @@ function extractFenceOperations(fenceText) {
10086
10331
  partialObject,
10087
10332
  partialLine: partialObject,
10088
10333
  invalidLines,
10089
- recovered
10334
+ recovered,
10335
+ repairedLines
10090
10336
  };
10091
10337
  }
10092
10338
  /**
@@ -10594,5 +10840,5 @@ function segmentSurfaceProse(components, options = {}) {
10594
10840
  }
10595
10841
 
10596
10842
  //#endregion
10597
- export { A2UI_FENCE_LANGUAGE, AgentRegistry, AgentThreadLockedError, ContextStore, CopilotKitCore, CopilotKitCoreErrorCode, CopilotKitCoreRuntimeConnectionStatus, CopilotKitHeaderResolutionError, INSPECTOR_THREAD_BRIDGE_PLUGIN_ID, IntelligenceAgent, MEMORY_ERROR_REGISTRY, MemoryError, ProxiedCopilotRuntimeAgent, RunHandler, StateManager, SuggestionEngine, ToolCallStatus, WebMCPRegistry, classifySurfaceCards, completePartialMarkdown, createActionGroup, createEffect, createInspectorThreadRequestId, createReducer, createSelector, createStore, emitInspectorActiveThread, emitInspectorStopViewing, emitInspectorViewThread, emitInspectorViewThreadResult, empty, ensureObjectArgs, extractCompleteArrayItems, extractFenceOperations, extractStringField, flattenInformationalCards, getMarkdownOperationSurfaceId, getWebMCPModelContext, isAbortError, isInspectorThreadBridgeEnabled, isRunCompletionAware, ofType, on, onInspectorActiveThread, onInspectorStopViewing, onInspectorViewThread, onInspectorViewThreadResult, parseToolArguments, prepareSurfaceOperations, props, segmentSurfaceProse, select, splitA2UIMarkdown, ɵ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 };
10843
+ export { A2UI_FENCE_LANGUAGE, AgentRegistry, AgentThreadLockedError, ContextStore, CopilotKitCore, CopilotKitCoreErrorCode, CopilotKitCoreRuntimeConnectionStatus, CopilotKitHeaderResolutionError, INSPECTOR_THREAD_BRIDGE_PLUGIN_ID, IntelligenceAgent, MEMORY_ERROR_REGISTRY, MemoryError, ProxiedCopilotRuntimeAgent, RunHandler, StateManager, SuggestionEngine, ToolCallStatus, WebMCPRegistry, classifySurfaceCards, completePartialMarkdown, createActionGroup, createEffect, createInspectorThreadRequestId, createReducer, createSelector, createStore, emitInspectorActiveThread, emitInspectorStopViewing, emitInspectorViewThread, emitInspectorViewThreadResult, empty, ensureObjectArgs, extractCompleteArrayItems, extractFenceOperations, extractStringField, flattenInformationalCards, getMarkdownOperationSurfaceId, getWebMCPModelContext, isAbortError, isInspectorThreadBridgeEnabled, isRunCompletionAware, ofType, on, onInspectorActiveThread, onInspectorStopViewing, onInspectorViewThread, onInspectorViewThreadResult, parseToolArguments, prepareSurfaceOperations, props, segmentSurfaceProse, select, splitA2UIMarkdown, ɵCOPILOTKIT_FEATURES, ɵInterruptState, ɵMAX_SOCKET_RETRIES, ɵRUNTIME_PROBE_TIMEOUT_MS, ɵTHREAD_REQUEST_TIMEOUT_MS, ɵclearAgentInterruptState, createMemoryStore as ɵcreateMemoryStore, ɵcreateThreadSelectors, createThreadStore as ɵcreateThreadStore, ɵgetAgentInterruptState, ɵ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 };
10598
10844
  //# sourceMappingURL=index.mjs.map