@copilotkit/core 2.0.0-rc.7 → 2.0.0-rc.8

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,7 +7,6 @@ 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");
11
10
 
12
11
  //#region src/utils/http-agent.ts
13
12
  /**
@@ -1765,6 +1764,20 @@ function isAbortError$1(error) {
1765
1764
  return typeof message === "string" && ABORT_MESSAGES.has(message);
1766
1765
  }
1767
1766
 
1767
+ //#endregion
1768
+ //#region src/utils/shallow-equal.ts
1769
+ /**
1770
+ * True when both records have the same own keys and each key holds the same
1771
+ * value (compared with `Object.is`). Key order does not matter. Nested
1772
+ * objects are compared by reference, not by content.
1773
+ */
1774
+ function shallowEqualRecord(a, b) {
1775
+ if (a === b) return true;
1776
+ const aKeys = Object.keys(a);
1777
+ if (aKeys.length !== Object.keys(b).length) return false;
1778
+ return aKeys.every((key) => Object.prototype.hasOwnProperty.call(b, key) && Object.is(a[key], b[key]));
1779
+ }
1780
+
1768
1781
  //#endregion
1769
1782
  //#region src/utils/runtime-request.ts
1770
1783
  const RUNTIME_REQUEST_WATCHDOG_MS = 1e4;
@@ -1867,13 +1880,6 @@ function isPromiseLike(value) {
1867
1880
  function normalizeHeaders(headers) {
1868
1881
  return Object.fromEntries(Object.entries(headers).filter((entry) => entry[1] != null));
1869
1882
  }
1870
- /** Same keys, same values (order-independent). */
1871
- function shallowEqualRecord(a, b) {
1872
- const aKeys = Object.keys(a);
1873
- const bKeys = Object.keys(b);
1874
- if (aKeys.length !== bKeys.length) return false;
1875
- return aKeys.every((key) => a[key] === b[key]);
1876
- }
1877
1883
  function isHeaderRecordInput(value) {
1878
1884
  return typeof value === "object" && value !== null && !Array.isArray(value);
1879
1885
  }
@@ -2042,6 +2048,13 @@ const RUNTIME_ENTITLEMENT_RETRY_DELAY_MS = 5e3;
2042
2048
  var AgentRegistry = class {
2043
2049
  _agents = {};
2044
2050
  localAgents = {};
2051
+ /**
2052
+ * Whether `onAgentsChanged` has run since {@link initialize}. Constructor
2053
+ * agents are not announced, so the first `setAgents__unsafe_dev_only` with
2054
+ * the same agents must still announce them (core subscribes to agents on
2055
+ * that notification).
2056
+ */
2057
+ agentsPublished = false;
2045
2058
  remoteAgents = {};
2046
2059
  mintedThreadIds = /* @__PURE__ */ new WeakMap();
2047
2060
  _runtimeUrl;
@@ -2088,6 +2101,12 @@ var AgentRegistry = class {
2088
2101
  runtimeRecoveryPending = false;
2089
2102
  runtimeHealthGeneration = 0;
2090
2103
  /**
2104
+ * Aborted by {@link dispose}. Runtime probes, recovery fetches and request
2105
+ * watchdogs listen to it so a disposed core leaves no timer or request
2106
+ * behind.
2107
+ */
2108
+ disposeController = new AbortController();
2109
+ /**
2091
2110
  * The headers each HttpAgent was constructed with, captured on the first
2092
2111
  * `applyHeadersToAgent` call for that agent (which, for agents the registry
2093
2112
  * owns, happens at registration before any core headers are applied). Core
@@ -2167,6 +2186,27 @@ var AgentRegistry = class {
2167
2186
  return this._telemetryDisabled;
2168
2187
  }
2169
2188
  /**
2189
+ * Stop runtime work this registry owns: the entitlement retry timer, the
2190
+ * inspector metadata request, runtime probes and recovery fetches with
2191
+ * their timeouts, and request watchdogs. In-flight `/info` connections are
2192
+ * detached so their late results change nothing. Called by
2193
+ * `CopilotKitCore.dispose`.
2194
+ */
2195
+ dispose() {
2196
+ if (this.disposeController.signal.aborted) return;
2197
+ this.disposeController.abort();
2198
+ this._activeRuntimeConnectionAttempt = void 0;
2199
+ this._connectionInFlight = void 0;
2200
+ this.resetRuntimeEntitlementRetry();
2201
+ this.inspectorMetadataGeneration += 1;
2202
+ this.inspectorMetadataAbortController?.abort();
2203
+ this.inspectorMetadataAbortController = void 0;
2204
+ this.abandonRuntimeHealthProbe();
2205
+ }
2206
+ get isDisposed() {
2207
+ return this.disposeController.signal.aborted;
2208
+ }
2209
+ /**
2170
2210
  * Initialize agents from configuration
2171
2211
  */
2172
2212
  initialize(agents) {
@@ -2252,9 +2292,12 @@ var AgentRegistry = class {
2252
2292
  this.runtimeProbeAbortController = void 0;
2253
2293
  }
2254
2294
  /**
2255
- * Set all agents at once (for development use)
2295
+ * Set all agents at once (for development use). Same ids mapped to the
2296
+ * same instances as the current local agents is a no-op once the agents
2297
+ * have been announced.
2256
2298
  */
2257
2299
  setAgents__unsafe_dev_only(agents) {
2300
+ if (this.agentsPublished && shallowEqualRecord(agents, this.localAgents)) return;
2258
2301
  Object.entries(agents).forEach(([id, agent]) => {
2259
2302
  if (agent) this.validateAndAssignAgentId(id, agent);
2260
2303
  });
@@ -2518,11 +2561,17 @@ var AgentRegistry = class {
2518
2561
  checked: () => false
2519
2562
  };
2520
2563
  let checked = false;
2564
+ const disposeSignal = this.disposeController.signal;
2521
2565
  const timeoutId = setTimeout(() => {
2522
2566
  checked = this.handleRuntimeRequestOutcome("failed");
2523
2567
  }, RUNTIME_REQUEST_WATCHDOG_MS);
2568
+ const clear = () => {
2569
+ clearTimeout(timeoutId);
2570
+ disposeSignal.removeEventListener("abort", clear);
2571
+ };
2572
+ disposeSignal.addEventListener("abort", clear, { once: true });
2524
2573
  return {
2525
- clear: () => clearTimeout(timeoutId),
2574
+ clear,
2526
2575
  checked: () => checked
2527
2576
  };
2528
2577
  }
@@ -2683,7 +2732,7 @@ var AgentRegistry = class {
2683
2732
  this.runtimeHealthGeneration += 1;
2684
2733
  }
2685
2734
  handleRuntimeRequestOutcome(outcome, alreadyChecked = () => false) {
2686
- if (outcome === "aborted" || outcome === "ignored") return false;
2735
+ if (outcome === "aborted" || outcome === "ignored" || this.isDisposed) return false;
2687
2736
  if (outcome === "failed" && alreadyChecked()) return false;
2688
2737
  if (typeof window === "undefined") return false;
2689
2738
  if (!this._runtimeUrl) return false;
@@ -2703,16 +2752,32 @@ var AgentRegistry = class {
2703
2752
  let timeoutId;
2704
2753
  const request = this.fetchRuntimeInfo(runtimeUrl, runtimeTransport, abortController.signal);
2705
2754
  request.catch(() => {});
2755
+ const disposeSignal = this.disposeController.signal;
2756
+ let rejectOnAbort;
2757
+ const abortOnDispose = () => abortController.abort();
2706
2758
  try {
2707
2759
  const timedOut = new Promise((_resolve, reject) => {
2708
2760
  timeoutId = setTimeout(() => {
2709
- abortController.abort();
2710
2761
  reject(/* @__PURE__ */ new Error(`Runtime did not answer within ${ɵRUNTIME_PROBE_TIMEOUT_MS}ms`));
2762
+ abortController.abort();
2711
2763
  }, ɵRUNTIME_PROBE_TIMEOUT_MS);
2712
2764
  });
2713
- return await Promise.race([request, timedOut]);
2765
+ const aborted = new Promise((_resolve, reject) => {
2766
+ rejectOnAbort = () => reject(/* @__PURE__ */ new Error("Runtime request aborted"));
2767
+ abortController.signal.addEventListener("abort", rejectOnAbort, { once: true });
2768
+ });
2769
+ aborted.catch(() => {});
2770
+ disposeSignal.addEventListener("abort", abortOnDispose, { once: true });
2771
+ if (disposeSignal.aborted) abortController.abort();
2772
+ return await Promise.race([
2773
+ request,
2774
+ timedOut,
2775
+ aborted
2776
+ ]);
2714
2777
  } finally {
2715
2778
  if (timeoutId !== void 0) clearTimeout(timeoutId);
2779
+ if (rejectOnAbort) abortController.signal.removeEventListener("abort", rejectOnAbort);
2780
+ disposeSignal.removeEventListener("abort", abortOnDispose);
2716
2781
  }
2717
2782
  }
2718
2783
  async probeRuntimeReachability() {
@@ -2773,7 +2838,7 @@ var AgentRegistry = class {
2773
2838
  * Update runtime connection and fetch remote agents
2774
2839
  */
2775
2840
  async updateRuntimeConnection(options) {
2776
- if (typeof window === "undefined") return;
2841
+ if (typeof window === "undefined" || this.isDisposed) return;
2777
2842
  const key = this.runtimeConnectionKey();
2778
2843
  const inFlight = this._connectionInFlight;
2779
2844
  if (inFlight && inFlight.attempt.key === key && this.isCurrentRuntimeConnection(inFlight.attempt)) return inFlight.promise;
@@ -2835,6 +2900,7 @@ var AgentRegistry = class {
2835
2900
  }
2836
2901
  this._runtimeEntitlementRetryAttemptedKey = key;
2837
2902
  this._runtimeEntitlementRetryPendingKey = key;
2903
+ if (this.isDisposed) return;
2838
2904
  this._runtimeEntitlementRetryTimer = setTimeout(() => {
2839
2905
  this._runtimeEntitlementRetryTimer = void 0;
2840
2906
  this.executeRuntimeEntitlementRetry(attempt).catch((error) => {
@@ -3089,6 +3155,7 @@ var AgentRegistry = class {
3089
3155
  * Notify subscribers of agent changes
3090
3156
  */
3091
3157
  async notifyAgentsChanged() {
3158
+ this.agentsPublished = true;
3092
3159
  await this.core.notifySubscribers((subscriber) => subscriber.onAgentsChanged?.({
3093
3160
  copilotkit: this.core,
3094
3161
  agents: this._agents
@@ -3184,6 +3251,13 @@ var SuggestionEngine = class {
3184
3251
  _suggestionsConfig = {};
3185
3252
  _suggestions = {};
3186
3253
  _runningSuggestions = {};
3254
+ /**
3255
+ * The last `getSuggestions` result per agent, with the per-generation
3256
+ * arrays it was built from. Each generation's array is replaced (never
3257
+ * mutated) on change, so comparing those references tells whether the
3258
+ * cached result is still current.
3259
+ */
3260
+ _snapshots = /* @__PURE__ */ new Map();
3187
3261
  constructor(core) {
3188
3262
  this.core = core;
3189
3263
  }
@@ -3246,13 +3320,29 @@ var SuggestionEngine = class {
3246
3320
  this.notifySuggestionsChanged(agentId, []);
3247
3321
  }
3248
3322
  /**
3249
- * Get current suggestions for an agent
3323
+ * Get current suggestions for an agent. Returns the same object until the
3324
+ * agent's suggestions or loading state change.
3250
3325
  */
3251
3326
  getSuggestions(agentId) {
3252
- return {
3253
- suggestions: Object.values(this._suggestions[agentId] ?? {}).flat(),
3254
- isLoading: (this._runningSuggestions[agentId]?.length ?? 0) > 0
3327
+ const parts = Object.values(this._suggestions[agentId] ?? {});
3328
+ const isLoading = (this._runningSuggestions[agentId]?.length ?? 0) > 0;
3329
+ const cached = this._snapshots.get(agentId);
3330
+ if (cached !== void 0 && cached.result.isLoading === isLoading && cached.parts.length === parts.length && parts.every((part, index) => part === cached.parts[index])) return cached.result;
3331
+ const result = {
3332
+ suggestions: parts.flat(),
3333
+ isLoading
3255
3334
  };
3335
+ this._snapshots.set(agentId, {
3336
+ parts,
3337
+ result
3338
+ });
3339
+ return result;
3340
+ }
3341
+ /** Abort every running suggestion generation. Called by `CopilotKitCore.dispose`. */
3342
+ dispose() {
3343
+ const runs = Object.values(this._runningSuggestions).flat();
3344
+ this._runningSuggestions = {};
3345
+ for (const run of runs) run.abortRun();
3256
3346
  }
3257
3347
  /**
3258
3348
  * Generate suggestions by running a provider agent and extracting the
@@ -3662,14 +3752,14 @@ var ɵInterruptState = class {
3662
3752
  #adoptedContent = /* @__PURE__ */ new Map();
3663
3753
  #pending = null;
3664
3754
  #sealed = false;
3665
- /** Return the active normalized interrupt without exposing mutable state. */
3755
+ /**
3756
+ * Return the active normalized interrupt. A standard interrupt set is a
3757
+ * frozen snapshot, and every read returns the same object until the
3758
+ * interrupt is replaced or cleared, so a framework can compare it by
3759
+ * reference.
3760
+ */
3666
3761
  get pending() {
3667
- const pending = this.#pending;
3668
- if (pending?.kind === "standard") return {
3669
- kind: "standard",
3670
- interrupts: [...pending.interrupts]
3671
- };
3672
- return pending;
3762
+ return this.#pending;
3673
3763
  }
3674
3764
  /** Replace the current interrupt with a legacy custom-event interrupt. */
3675
3765
  setLegacy(event) {
@@ -3690,10 +3780,10 @@ var ɵInterruptState = class {
3690
3780
  callIds.add(interrupt.toolCallId);
3691
3781
  }
3692
3782
  }
3693
- this.#replace({
3783
+ this.#replace(Object.freeze({
3694
3784
  kind: "standard",
3695
- interrupts: [...interrupts]
3696
- });
3785
+ interrupts: Object.freeze([...interrupts])
3786
+ }));
3697
3787
  }
3698
3788
  /** Clear all pending interrupt data and accumulated responses. */
3699
3789
  clear() {
@@ -4012,6 +4102,12 @@ var RunHandler = class {
4012
4102
  * one array before, so the `/info` response flipping `openGenerativeUI` (or
4013
4103
  * any other provider-prop change) silently dropped every hook-registered
4014
4104
  * tool (#4952). Key = `capabilityKey(name, agentId)`.
4105
+ *
4106
+ * Each key holds a stack of registrations. The last one is the active tool;
4107
+ * removing it (via the function `addTool` returns) brings back the one
4108
+ * below, and an empty stack lets the provider tool of that key show again.
4109
+ * A registration is its own object, so removing one never removes another
4110
+ * registration of the same tool object.
4015
4111
  */
4016
4112
  _hookTools = /* @__PURE__ */ new Map();
4017
4113
  /**
@@ -4068,6 +4164,13 @@ var RunHandler = class {
4068
4164
  */
4069
4165
  _runDepths = /* @__PURE__ */ new WeakMap();
4070
4166
  /**
4167
+ * Agents with at least one run in flight (depth above 0), so
4168
+ * {@link dispose} can stop them. Removed when the last run ends.
4169
+ */
4170
+ _runningAgents = /* @__PURE__ */ new Set();
4171
+ /** Set by {@link dispose}. Stops WebMCP from registering tools again. */
4172
+ _disposed = false;
4173
+ /**
4071
4174
  * Each agent's own `abortRun`, saved while RunHandler's intercept is
4072
4175
  * installed. Restored only once none of the agent's runs is in flight, so an
4073
4176
  * overlapping run keeps the intercept after an earlier run finishes.
@@ -4113,7 +4216,7 @@ var RunHandler = class {
4113
4216
  _executingToolCalls = /* @__PURE__ */ new WeakMap();
4114
4217
  _connectionGenerations = /* @__PURE__ */ new WeakMap();
4115
4218
  _runGenerations = /* @__PURE__ */ new WeakMap();
4116
- _interactionAbortControllers = /* @__PURE__ */ new WeakMap();
4219
+ _interactionAbortControllers = /* @__PURE__ */ new Map();
4117
4220
  constructor(core) {
4118
4221
  this.core = core;
4119
4222
  }
@@ -4131,6 +4234,29 @@ var RunHandler = class {
4131
4234
  this._executingToolCalls.delete(agent);
4132
4235
  }
4133
4236
  }
4237
+ /**
4238
+ * Stop every run chain and tool interaction this handler tracks, and every
4239
+ * agent in `agents` that reports a run in flight, the same way `stopAgent`
4240
+ * does. Then unregister all WebMCP tools. Called by `CopilotKitCore.dispose`.
4241
+ */
4242
+ dispose(agents) {
4243
+ this._disposed = true;
4244
+ const candidates = new Set([
4245
+ ...agents,
4246
+ ...this._runningAgents,
4247
+ ...this._interactionAbortControllers.keys()
4248
+ ]);
4249
+ for (const agent of candidates) {
4250
+ const hasActiveRun = agent.isRunning || this._runningAgents.has(agent);
4251
+ try {
4252
+ this.abortCurrentRun(agent);
4253
+ if (hasActiveRun) agent.abortRun();
4254
+ } catch (error) {
4255
+ _copilotkit_shared.logger.error(`Failed to stop agent '${agent.agentId ?? "(unknown agent)"}' on dispose:`, error);
4256
+ }
4257
+ }
4258
+ this._webmcpRegistry.sync(/* @__PURE__ */ new Map());
4259
+ }
4134
4260
  abortAgentRuns(agent) {
4135
4261
  for (const controller of this._runAbortControllers.get(agent) ?? []) controller.abort();
4136
4262
  }
@@ -4171,7 +4297,10 @@ var RunHandler = class {
4171
4297
  if (this._cachedMergedTools) return this._cachedMergedTools;
4172
4298
  const merged = /* @__PURE__ */ new Map();
4173
4299
  for (const tool of this._propTools) merged.set(this.capabilityKey(tool.name, tool.agentId), tool);
4174
- for (const [key, tool] of this._hookTools) merged.set(key, tool);
4300
+ for (const [key, stack] of this._hookTools) {
4301
+ const active = stack[stack.length - 1];
4302
+ if (active) merged.set(key, active.tool);
4303
+ }
4175
4304
  this._cachedMergedTools = Array.from(merged.values());
4176
4305
  return this._cachedMergedTools;
4177
4306
  }
@@ -4187,17 +4316,34 @@ var RunHandler = class {
4187
4316
  /**
4188
4317
  * Add a tool to the registry. Survives provider re-syncs ({@link setTools}),
4189
4318
  * and shadows a provider tool of the same name + agentId.
4319
+ *
4320
+ * Registrations of the same name + agentId stack: the most recent one is
4321
+ * active. Call the returned function to remove exactly this registration;
4322
+ * the previous registration (or the provider tool) becomes active again.
4323
+ * Calling it more than once does nothing.
4190
4324
  */
4191
4325
  addTool(tool) {
4192
4326
  const key = this.capabilityKey(tool.name, tool.agentId);
4193
- if (this._hookTools.has(key)) {
4194
- _copilotkit_shared.logger.warn(`Tool already exists: '${tool.name}' for agent '${tool.agentId || "global"}', skipping.`);
4195
- return;
4196
- }
4197
- this._hookTools.set(key, tool);
4327
+ const registration = { tool };
4328
+ const stack = this._hookTools.get(key);
4329
+ if (stack) {
4330
+ if (process.env.NODE_ENV !== "production") _copilotkit_shared.logger.warn(`Tool already exists: '${tool.name}' for agent '${tool.agentId || "global"}'. The new registration shadows it until the new one is removed.`);
4331
+ stack.push(registration);
4332
+ } else this._hookTools.set(key, [registration]);
4198
4333
  this._cachedMergedTools = null;
4199
4334
  this.warnOnMissingToolParameters([tool]);
4200
4335
  this.syncWebMCP();
4336
+ return () => this.unregisterHookTool(key, registration);
4337
+ }
4338
+ /** Remove one `addTool` registration. Unknown registrations are ignored. */
4339
+ unregisterHookTool(key, registration) {
4340
+ const stack = this._hookTools.get(key);
4341
+ const index = stack?.indexOf(registration) ?? -1;
4342
+ if (!stack || index === -1) return;
4343
+ stack.splice(index, 1);
4344
+ if (stack.length === 0) this._hookTools.delete(key);
4345
+ this._cachedMergedTools = null;
4346
+ this.syncWebMCP();
4201
4347
  }
4202
4348
  /**
4203
4349
  * Report, once per tool and at development time only, a tool registered with
@@ -4229,7 +4375,10 @@ var RunHandler = class {
4229
4375
  }
4230
4376
  }
4231
4377
  /**
4232
- * Remove a tool by name and optionally by agentId
4378
+ * Remove a tool by name and optionally by agentId: every `addTool`
4379
+ * registration of that key and the provider tool of that key. Without an
4380
+ * agentId only global tools are removed. To remove one `addTool`
4381
+ * registration and keep the others, call the function `addTool` returned.
4233
4382
  */
4234
4383
  removeTool(id, agentId) {
4235
4384
  this._hookTools.delete(this.capabilityKey(id, agentId));
@@ -4427,6 +4576,7 @@ var RunHandler = class {
4427
4576
  this._runAbortControllers.set(agent, controllers);
4428
4577
  }
4429
4578
  if (depth === 0) {
4579
+ this._runningAgents.add(agent);
4430
4580
  const originalAbortRun = agent.abortRun;
4431
4581
  this._originalAbortRuns.set(agent, originalAbortRun);
4432
4582
  agent.abortRun = () => {
@@ -4500,6 +4650,7 @@ var RunHandler = class {
4500
4650
  if (controllers?.size === 0) this._runAbortControllers.delete(agent);
4501
4651
  }
4502
4652
  if (remainingDepth === 0) {
4653
+ this._runningAgents.delete(agent);
4503
4654
  const originalAbortRun = this._originalAbortRuns.get(agent);
4504
4655
  if (originalAbortRun) {
4505
4656
  agent.abortRun = originalAbortRun;
@@ -5004,6 +5155,7 @@ var RunHandler = class {
5004
5155
  * agentId — a name collision across agentIds keeps the first registration.
5005
5156
  */
5006
5157
  syncWebMCP() {
5158
+ if (this._disposed) return;
5007
5159
  const desired = /* @__PURE__ */ new Map();
5008
5160
  const warnedCollisions = /* @__PURE__ */ new Set();
5009
5161
  for (const tool of this.tools) {
@@ -5333,6 +5485,11 @@ var StateManager = class {
5333
5485
  }
5334
5486
  this.rawEventByMessage.delete(agentId);
5335
5487
  }
5488
+ /** Unsubscribe from every agent. Called by `CopilotKitCore.dispose`. */
5489
+ dispose() {
5490
+ const agentIds = [...this.agentSubscriptions.keys()];
5491
+ for (const agentId of agentIds) this.unsubscribeFromAgent(agentId);
5492
+ }
5336
5493
  /**
5337
5494
  * Get state for a specific run
5338
5495
  * Returns a deep copy to prevent external mutations
@@ -7505,6 +7662,8 @@ var CopilotKitCore = class {
7505
7662
  _defaultThrottleMs;
7506
7663
  _debug;
7507
7664
  subscribers = /* @__PURE__ */ new Set();
7665
+ _disposed = false;
7666
+ waitForFrameworkUpdates;
7508
7667
  agentRegistry;
7509
7668
  contextStore;
7510
7669
  suggestionEngine;
@@ -7530,7 +7689,8 @@ var CopilotKitCore = class {
7530
7689
  * store that was registered prior to that initial notification.
7531
7690
  */
7532
7691
  previousAgentIds = /* @__PURE__ */ new Set();
7533
- constructor({ runtimeUrl, runtimeTransport = "auto", deferInitialConnection = false, headers = {}, credentials, messageFilter, properties = {}, agents__unsafe_dev_only = {}, tools = [], suggestionsConfig = [], debug, learning }) {
7692
+ constructor({ runtimeUrl, runtimeTransport = "auto", deferInitialConnection = false, headers = {}, credentials, messageFilter, properties = {}, agents__unsafe_dev_only = {}, tools = [], suggestionsConfig = [], debug, learning, ɵwaitForFrameworkUpdates }) {
7693
+ this.waitForFrameworkUpdates = ɵwaitForFrameworkUpdates;
7534
7694
  this.headerSource = new HeaderSourceResolver((error) => {
7535
7695
  this.emitError({
7536
7696
  error,
@@ -7584,6 +7744,7 @@ var CopilotKitCore = class {
7584
7744
  * Internal method used by delegate classes and subclasses to notify subscribers
7585
7745
  */
7586
7746
  async notifySubscribers(handler, errorMessage) {
7747
+ if (this._disposed) return;
7587
7748
  await Promise.all(Array.from(this.subscribers).map(async (subscriber) => {
7588
7749
  try {
7589
7750
  await handler(subscriber);
@@ -7833,7 +7994,12 @@ var CopilotKitCore = class {
7833
7994
  headers: this.headers
7834
7995
  }), "Subscriber onHeadersChanged error:");
7835
7996
  }
7997
+ /**
7998
+ * Set the credentials mode for runtime requests (for example `"include"`
7999
+ * to send HTTP-only cookies). Passing the current value does nothing.
8000
+ */
7836
8001
  setCredentials(credentials) {
8002
+ if (credentials === this._credentials) return;
7837
8003
  this._credentials = credentials;
7838
8004
  this.agentRegistry.applyCredentialsToAgents(this.agentRegistry.agents);
7839
8005
  this.agentRegistry.handleCredentialsChanged();
@@ -7843,9 +8009,11 @@ var CopilotKitCore = class {
7843
8009
  *
7844
8010
  * Applies to agents already discovered as well as ones discovered later, so
7845
8011
  * a filter set before `/info` lands is not lost. Pass `undefined` to go back
7846
- * to sending the full thread.
8012
+ * to sending the full thread. Passing the current filter function again
8013
+ * does nothing.
7847
8014
  */
7848
8015
  setMessageFilter(messageFilter) {
8016
+ if (messageFilter === this._messageFilter) return;
7849
8017
  this._messageFilter = messageFilter;
7850
8018
  this.agentRegistry.applyMessageFilterToAgents(this.agentRegistry.agents);
7851
8019
  }
@@ -7902,7 +8070,14 @@ var CopilotKitCore = class {
7902
8070
  }
7903
8071
  return merged;
7904
8072
  }
8073
+ /**
8074
+ * Replace the properties sent as `forwardedProps` with every run, and
8075
+ * notify `onPropertiesChanged`. Passing an object with the same keys and
8076
+ * values as the current one does nothing, so a fresh object literal on
8077
+ * every render is safe.
8078
+ */
7905
8079
  setProperties(properties) {
8080
+ if (shallowEqualRecord(properties, this._properties)) return;
7906
8081
  this._properties = properties;
7907
8082
  this.notifySubscribers((subscriber) => subscriber.onPropertiesChanged?.({
7908
8083
  copilotkit: this,
@@ -7910,7 +8085,10 @@ var CopilotKitCore = class {
7910
8085
  }), "Subscriber onPropertiesChanged error:");
7911
8086
  }
7912
8087
  /**
7913
- * Agent management (delegated to AgentRegistry)
8088
+ * Agent management (delegated to AgentRegistry).
8089
+ *
8090
+ * Replace the local (development) agents. Passing the same ids mapped to
8091
+ * the same agent instances does nothing.
7914
8092
  */
7915
8093
  setAgents__unsafe_dev_only(agents) {
7916
8094
  this.agentRegistry.setAgents__unsafe_dev_only(agents);
@@ -8189,11 +8367,34 @@ var CopilotKitCore = class {
8189
8367
  return this.suggestionEngine.getSuggestions(agentId);
8190
8368
  }
8191
8369
  /**
8192
- * Tool management (delegated to RunHandler)
8370
+ * Register a frontend tool. It shadows a provider tool (from the `tools`
8371
+ * config or `setTools`) with the same name and agentId.
8372
+ *
8373
+ * A second registration with the same name and agentId shadows the first.
8374
+ * Call the returned function to remove only this registration: the tool it
8375
+ * shadowed becomes active again. Calling it more than once does nothing.
8376
+ *
8377
+ * @param tool - The tool to register.
8378
+ * @returns A function that removes this registration.
8379
+ *
8380
+ * @example
8381
+ * const unregister = copilotkit.addTool({
8382
+ * name: "showWeather",
8383
+ * handler: async ({ city }) => `Sunny in ${city}`,
8384
+ * });
8385
+ * // later
8386
+ * unregister();
8193
8387
  */
8194
8388
  addTool(tool) {
8195
- this.runHandler.addTool(tool);
8389
+ return this.runHandler.addTool(tool);
8196
8390
  }
8391
+ /**
8392
+ * Remove a tool by name, and by agentId when given. This removes every
8393
+ * `addTool` registration with that name and agentId, and the provider tool
8394
+ * with that name and agentId. Without an agentId, only global tools are
8395
+ * removed. To remove one registration, call the function `addTool`
8396
+ * returned.
8397
+ */
8197
8398
  removeTool(id, agentId) {
8198
8399
  this.runHandler.removeTool(id, agentId);
8199
8400
  }
@@ -8437,11 +8638,52 @@ var CopilotKitCore = class {
8437
8638
  * synchronously while the deferred updates are still pending, producing stale
8438
8639
  * context for the next agent turn.
8439
8640
  *
8440
- * Override in framework-specific subclasses to yield to the framework
8441
- * scheduler before the follow-up run. The base implementation is a no-op
8442
- * because non-React environments have no deferred state to flush.
8641
+ * Awaits the `ɵwaitForFrameworkUpdates` config option when one is given.
8642
+ * Without it there is nothing to wait for, because a plain JavaScript
8643
+ * environment has no deferred state to flush. Framework subclasses that
8644
+ * still override this method keep working.
8443
8645
  */
8444
- async waitForPendingFrameworkUpdates() {}
8646
+ async waitForPendingFrameworkUpdates() {
8647
+ await this.waitForFrameworkUpdates?.();
8648
+ }
8649
+ /**
8650
+ * Stop everything this core started, so it can be dropped without leaks.
8651
+ *
8652
+ * Call it when you created a `CopilotKitCore` yourself and are done with it
8653
+ * (for example when a page or test tears down). Framework providers call it
8654
+ * for you.
8655
+ *
8656
+ * It does this, in order:
8657
+ *
8658
+ * - removes every subscriber, so no callback runs after this call;
8659
+ * - stops agent runs in flight and aborts running frontend tools;
8660
+ * - aborts suggestion generation;
8661
+ * - clears runtime timers and aborts runtime requests it can cancel;
8662
+ * - removes agent subscriptions, WebMCP tools, and the learning capture;
8663
+ * - stops the memory store and every registered thread store.
8664
+ *
8665
+ * Calling it again does nothing. Do not use the core after this call.
8666
+ *
8667
+ * @example
8668
+ * const copilotkit = new CopilotKitCore({ runtimeUrl: "/api/copilotkit" });
8669
+ * // ... use it ...
8670
+ * copilotkit.dispose();
8671
+ */
8672
+ dispose() {
8673
+ if (this._disposed) return;
8674
+ this._disposed = true;
8675
+ this.subscribers.clear();
8676
+ this.learningConfiguredListeners.clear();
8677
+ this.generativeUIDebugListeners.clear();
8678
+ this.runHandler.dispose(Object.values(this.agentRegistry.agents));
8679
+ this.suggestionEngine.dispose();
8680
+ this.agentRegistry.dispose();
8681
+ this.stateManager.dispose();
8682
+ this.stopTrajectory();
8683
+ this._memoryStore?.stop();
8684
+ const threadStores = Object.values(this.threadStoreRegistry.getAll());
8685
+ for (const store of threadStores) store.stop();
8686
+ }
8445
8687
  };
8446
8688
 
8447
8689
  //#endregion
@@ -8624,23 +8866,6 @@ function completePartialMarkdown(input) {
8624
8866
  return result;
8625
8867
  }
8626
8868
 
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
-
8644
8869
  //#endregion
8645
8870
  //#region src/threads.ts
8646
8871
  const THREADS_CHANNEL_EVENT = "thread_metadata";
@@ -10771,16 +10996,1422 @@ function segmentSurfaceProse(components, options = {}) {
10771
10996
  });
10772
10997
  }
10773
10998
 
10999
+ //#endregion
11000
+ //#region src/chat/labels.ts
11001
+ /**
11002
+ * The default English text for every word the chat UI shows. React, Vue and
11003
+ * Angular all read their chat text from this one set.
11004
+ *
11005
+ * To change or translate the text, pass a partial set to your framework's chat
11006
+ * configuration. Keys you leave out keep their default:
11007
+ *
11008
+ * ```ts
11009
+ * const labels = { ...CopilotChatDefaultLabels, chatInputPlaceholder: "Ask me" };
11010
+ * ```
11011
+ *
11012
+ * Some values are templates with `{name}` placeholders, such as
11013
+ * `"Thought for {duration}"`. Keep the placeholders when you translate them.
11014
+ *
11015
+ * Counts use two keys: `...One` for a count of 1, and `...Other` for any other
11016
+ * count.
11017
+ */
11018
+ const CopilotChatDefaultLabels = Object.freeze({
11019
+ chatInputPlaceholder: "Type a message...",
11020
+ chatInputToolbarStartTranscribeButtonLabel: "Transcribe",
11021
+ chatInputToolbarCancelTranscribeButtonLabel: "Cancel",
11022
+ chatInputToolbarFinishTranscribeButtonLabel: "Finish",
11023
+ chatInputToolbarAddButtonLabel: "Add attachments",
11024
+ chatInputToolbarToolsButtonLabel: "Tools",
11025
+ chatInputToolbarSendButtonLabel: "Send message",
11026
+ chatInputToolbarStopButtonLabel: "Stop",
11027
+ assistantMessageToolbarCopyCodeLabel: "Copy",
11028
+ assistantMessageToolbarCopyCodeCopiedLabel: "Copied",
11029
+ assistantMessageToolbarCopyMessageLabel: "Copy",
11030
+ assistantMessageToolbarInspectorLabel: "View in Inspector",
11031
+ assistantMessageToolbarInspectorDescription: "Open this message in the Inspector",
11032
+ assistantMessageToolbarInspectorLocalOnlyLabel: "Local only",
11033
+ assistantMessageToolbarInspectorLocalOnlyDescription: "Only visible on localhost or loopback hosts in development. Never shown in production.",
11034
+ assistantMessageToolbarInspectorTitle: "CopilotKit Inspector",
11035
+ assistantMessageToolbarInspectorHideLabel: "Hide this icon",
11036
+ assistantMessageToolbarInspectorHideDescription: "Until you reload this page",
11037
+ assistantMessageToolbarThumbsUpLabel: "Good response",
11038
+ assistantMessageToolbarThumbsDownLabel: "Bad response",
11039
+ assistantMessageFeedbackCommentPlaceholder: "Add a comment (optional)",
11040
+ assistantMessageFeedbackCommentSubmitLabel: "Send comment",
11041
+ assistantMessageToolbarReadAloudLabel: "Read aloud",
11042
+ assistantMessageToolbarRegenerateLabel: "Regenerate",
11043
+ userMessageToolbarCopyMessageLabel: "Copy",
11044
+ userMessageToolbarEditMessageLabel: "Edit",
11045
+ userMessageToolbarPreviousBranchLabel: "Previous branch",
11046
+ userMessageToolbarNextBranchLabel: "Next branch",
11047
+ chatDisclaimerText: "AI can make mistakes. Please verify important information.",
11048
+ chatToggleOpenLabel: "Open chat",
11049
+ chatToggleCloseLabel: "Close chat",
11050
+ chatScrollToBottomLabel: "Scroll to bottom",
11051
+ modalHeaderTitle: "CopilotKit Chat",
11052
+ welcomeMessageText: "How can I help you today?",
11053
+ reasoningMessageThinkingLabel: "Thinking…",
11054
+ chatInputSlashMenuLabel: "Slash commands",
11055
+ chatInputSlashMenuEmptyText: "No commands found",
11056
+ attachmentRemoveButtonLabel: "Remove attachment",
11057
+ attachmentPlayVideoButtonLabel: "Play video",
11058
+ attachmentPreviewCloseButtonLabel: "Close preview",
11059
+ modalHeaderCloseButtonLabel: "Close",
11060
+ modalHeaderThreadsButtonLabel: "Open threads",
11061
+ sidebarLabel: "Copilot chat sidebar",
11062
+ chatDropFilesLabel: "Drop files here",
11063
+ threadLoadErrorText: "Could not load saved conversation. Reopen the thread and try again.",
11064
+ reasoningMessageThoughtForLabel: "Thought for {duration}",
11065
+ reasoningMessageDurationFewSeconds: "a few seconds",
11066
+ reasoningMessageDurationSeconds: "{count} seconds",
11067
+ reasoningMessageDurationMinutesOne: "{count} minute",
11068
+ reasoningMessageDurationMinutesOther: "{count} minutes",
11069
+ reasoningMessageDurationMinutesSeconds: "{minutes}m {seconds}s",
11070
+ toolCallStatusRunningLabel: "Running",
11071
+ toolCallStatusDoneLabel: "Done",
11072
+ toolCallStatusFailedLabel: "Failed",
11073
+ toolCallStatusStoppedLabel: "Stopped",
11074
+ toolCallRunningLabel: "Running {name}",
11075
+ toolCallFailedCountLabel: "{count} failed",
11076
+ toolCallDoneCountLabel: "{count} done",
11077
+ toolCallArgumentsLabel: "Arguments",
11078
+ toolCallResultLabel: "Result",
11079
+ toolCallCollapseLabel: "Collapse",
11080
+ toolCallUsedToolsOne: "Used {count} tool",
11081
+ toolCallUsedToolsOther: "Used {count} tools",
11082
+ toolCallToolCountOne: "{count} tool",
11083
+ toolCallToolCountOther: "{count} tools",
11084
+ toolCallToolCallCountOne: "{count} tool call",
11085
+ toolCallToolCallCountOther: "{count} tool calls",
11086
+ toolCallCallCountOne: "{count} call",
11087
+ toolCallCallCountOther: "{count} calls",
11088
+ workSummaryWorkingLabel: "Working",
11089
+ workSummaryWorkedForLabel: "Worked for {duration}",
11090
+ attachmentImageLoadErrorText: "Failed to load image",
11091
+ attachmentImageAltText: "Image attachment",
11092
+ attachmentUnknownTypeText: "Unknown type",
11093
+ attachmentDocumentLabel: "Document",
11094
+ attachmentDocumentAltText: "Document attachment",
11095
+ attachmentNoPreviewText: "No preview available for this file type",
11096
+ chatAttachmentsUploadingText: "Cannot send while attachments are uploading.",
11097
+ transcriptionErrorRateLimitedText: "Too many requests. Please wait a moment.",
11098
+ transcriptionErrorAuthFailedText: "Authentication error. Please check your configuration.",
11099
+ transcriptionErrorAudioTooLongText: "Recording is too long. Please try a shorter recording.",
11100
+ transcriptionErrorAudioTooShortText: "Recording is too short. Please try again.",
11101
+ transcriptionErrorInvalidAudioFormatText: "Audio format not supported.",
11102
+ transcriptionErrorServiceNotConfiguredText: "Transcription service is not available.",
11103
+ transcriptionErrorNetworkText: "Network error. Please check your connection.",
11104
+ transcriptionErrorGenericText: "Transcription failed. Please try again.",
11105
+ licensePoweredByText: "Powered by CopilotKit",
11106
+ licenseGetLicenseLabel: "Get a license",
11107
+ licenseFeatureUnlicensedText: "⚠ The \"{feature}\" feature requires a CopilotKit license.",
11108
+ licenseExpiringText: "Your CopilotKit license expires soon. Please renew.",
11109
+ licenseExpiringInDaysOne: "Your CopilotKit license expires in {days} day. Please renew.",
11110
+ licenseExpiringInDaysOther: "Your CopilotKit license expires in {days} days. Please renew.",
11111
+ licenseExpiredText: "Your CopilotKit license expired. Please renew at copilotkit.ai/pricing",
11112
+ licenseExpiredOnDateText: "Your CopilotKit license expired on {date}. Please renew at copilotkit.ai/pricing",
11113
+ licenseInvalidText: "Invalid CopilotKit license token. Please check your configuration.",
11114
+ licenseRenewLabel: "Renew",
11115
+ licenseRenewNowLabel: "Renew now"
11116
+ });
11117
+ /**
11118
+ * Puts values into a label template. Each `{name}` in the template is replaced
11119
+ * by `values[name]`. A placeholder with no value stays in the text as is.
11120
+ *
11121
+ * @param template - A label value, such as `"Running {name}"`.
11122
+ * @param values - The value for each placeholder.
11123
+ *
11124
+ * ```ts
11125
+ * ɵformatLabel(labels.toolCallRunningLabel, { name: "read_file" });
11126
+ * // "Running read_file"
11127
+ * ```
11128
+ */
11129
+ function ɵformatLabel(template, values) {
11130
+ return template.replace(/\{(\w+)\}/g, (placeholder, name) => Object.hasOwn(values, name) ? String(values[name]) : placeholder);
11131
+ }
11132
+ /**
11133
+ * Fills a counted label pair: the `one` template for a count of 1, the
11134
+ * `other` template for any other count. Both templates take `{count}`.
11135
+ *
11136
+ * @param count - The number to show.
11137
+ * @param templates - The `...One` and `...Other` label templates.
11138
+ *
11139
+ * ```ts
11140
+ * ɵformatCountLabel(3, {
11141
+ * one: labels.toolCallToolCountOne,
11142
+ * other: labels.toolCallToolCountOther,
11143
+ * }); // "3 tools"
11144
+ * ```
11145
+ */
11146
+ function ɵformatCountLabel(count, templates) {
11147
+ return ɵformatLabel(count === 1 ? templates.one : templates.other, { count });
11148
+ }
11149
+
11150
+ //#endregion
11151
+ //#region src/chat/renderers.ts
11152
+ /** Name or activity type that matches anything. */
11153
+ const WILDCARD = "*";
11154
+ /**
11155
+ * Find the renderer that draws a tool call.
11156
+ *
11157
+ * The first rule that matches wins:
11158
+ *
11159
+ * 1. A renderer for `toolName` with `agentId` equal to the current agent.
11160
+ * 2. A renderer for `toolName` with no `agentId`.
11161
+ * 3. The first renderer for `toolName` from any other agent.
11162
+ * 4. The first `"*"` renderer, from any agent.
11163
+ *
11164
+ * Inside each rule, the earlier renderer in the list wins.
11165
+ *
11166
+ * @param renderers - Registered renderers in registration order. If you
11167
+ * build tiers (for example app renderers before built-in ones), flatten
11168
+ * them into one ordered list first.
11169
+ * @param toolName - Name of the tool the agent called.
11170
+ * @param agentId - The agent that owns the chat. The caller picks the
11171
+ * default: React and Vue pass `DEFAULT_AGENT_ID` when the chat has no
11172
+ * agent. With `undefined`, rule 1 matches the same renderers as rule 2.
11173
+ * @returns The renderer, or `null` when no renderer matches. Draw nothing
11174
+ * for `null`.
11175
+ *
11176
+ * @example
11177
+ * ```ts
11178
+ * const renderer = ɵresolveToolCallRenderer(
11179
+ * core.renderToolCalls,
11180
+ * toolCall.function.name,
11181
+ * chatAgentId ?? DEFAULT_AGENT_ID,
11182
+ * );
11183
+ * ```
11184
+ */
11185
+ function ɵresolveToolCallRenderer(renderers, toolName, agentId) {
11186
+ const named = renderers.filter((renderer) => renderer.name === toolName);
11187
+ return named.find((renderer) => renderer.agentId === agentId) ?? named.find((renderer) => !renderer.agentId) ?? named[0] ?? renderers.find((renderer) => renderer.name === WILDCARD) ?? null;
11188
+ }
11189
+ /**
11190
+ * Find the renderer that draws an activity message, and validate the
11191
+ * message content with that renderer's `content` schema.
11192
+ *
11193
+ * The first rule that matches picks the renderer:
11194
+ *
11195
+ * 1. A renderer for `activityType` with `agentId` equal to the current agent.
11196
+ * 2. A renderer for `activityType` with no `agentId`.
11197
+ * 3. The first `"*"` renderer, from any agent.
11198
+ *
11199
+ * A renderer for `activityType` that belongs to a different agent never
11200
+ * matches. Inside each rule, the earlier renderer in the list wins.
11201
+ *
11202
+ * Only the picked renderer validates the content. When validation fails, or
11203
+ * the schema validates asynchronously, the result is `null`. The function
11204
+ * does not try the next renderer.
11205
+ *
11206
+ * @param renderers - Registered renderers in registration order.
11207
+ * @param query - The activity type, the current agent, and the raw content.
11208
+ * @returns `{ renderer, content }`, where `content` is the value the schema
11209
+ * returned. Pass that value to `render`, not the raw content. Returns
11210
+ * `null` when no renderer matches or validation does not pass.
11211
+ *
11212
+ * @example
11213
+ * ```ts
11214
+ * const match = ɵresolveActivityRenderer(core.renderActivityMessages, {
11215
+ * activityType: message.activityType,
11216
+ * agentId,
11217
+ * content: message.content,
11218
+ * });
11219
+ * if (match) draw(match.renderer.render, match.content);
11220
+ * ```
11221
+ */
11222
+ function ɵresolveActivityRenderer(renderers, query) {
11223
+ const { activityType, agentId, content } = query;
11224
+ const sameType = renderers.filter((renderer) => renderer.activityType === activityType);
11225
+ const renderer = sameType.find((candidate) => candidate.agentId === agentId) ?? sameType.find((candidate) => candidate.agentId === void 0) ?? renderers.find((candidate) => candidate.activityType === WILDCARD);
11226
+ if (renderer === void 0) return null;
11227
+ const result = renderer.content["~standard"].validate(content);
11228
+ if (result instanceof Promise) return null;
11229
+ if (result.issues) return null;
11230
+ return {
11231
+ renderer,
11232
+ content: result.value
11233
+ };
11234
+ }
11235
+ /**
11236
+ * List the custom message renderers that apply to an agent, in the order to
11237
+ * try them.
11238
+ *
11239
+ * The list keeps renderers with no `agentId` and renderers for `agentId`.
11240
+ * Renderers for `agentId` come first. Inside each group, registration order
11241
+ * stays the same.
11242
+ *
11243
+ * The framework tries each renderer in this order and shows the first one
11244
+ * that draws something (a non-null result).
11245
+ *
11246
+ * @param renderers - Registered renderers in registration order.
11247
+ * @param agentId - The agent that owns the chat.
11248
+ * @returns A new array. Empty when no renderer applies.
11249
+ *
11250
+ * @example
11251
+ * ```ts
11252
+ * const candidates = ɵresolveCustomMessageRenderers(
11253
+ * core.renderCustomMessages,
11254
+ * agentId,
11255
+ * );
11256
+ * ```
11257
+ */
11258
+ function ɵresolveCustomMessageRenderers(renderers, agentId) {
11259
+ const scoped = renderers.filter((renderer) => renderer.agentId === agentId);
11260
+ const unscoped = renderers.filter((renderer) => renderer.agentId === void 0);
11261
+ return [...scoped, ...unscoped];
11262
+ }
11263
+
11264
+ //#endregion
11265
+ //#region src/chat/interrupt-types.ts
11266
+ /** Name of the legacy custom event agents emit to signal an interrupt. */
11267
+ const INTERRUPT_EVENT_NAME = "on_interrupt";
11268
+
11269
+ //#endregion
11270
+ //#region src/chat/tool-call-layout.ts
11271
+ function contentLength(content) {
11272
+ return typeof content === "string" ? content.length : JSON.stringify(content ?? "").length;
11273
+ }
11274
+ const entrySignature = ({ toolCall, toolMessage }) => [
11275
+ toolCall.id,
11276
+ toolCall.function.name,
11277
+ toolCall.function.arguments.length,
11278
+ toolMessage ? `${contentLength(toolMessage.content)}${toolMessage.error ? "!" : ""}` : "-"
11279
+ ].join(":");
11280
+ function signatureOf(segments) {
11281
+ return segments.map((segment) => segment.kind === "call" ? `c(${entrySignature(segment.call)})` : `g${segment.trailing ? "*" : ""}(${segment.calls.map(entrySignature).join(",")})`).join("|");
11282
+ }
11283
+ /**
11284
+ * Indexes tool results by the id of the call they answer.
11285
+ *
11286
+ * @param messages - The messages to search. Only `role: "tool"` messages count.
11287
+ */
11288
+ function getToolResults(messages) {
11289
+ const results = /* @__PURE__ */ new Map();
11290
+ for (const message of messages) if (message.role === "tool") results.set(message.toolCallId, message);
11291
+ return results;
11292
+ }
11293
+ /**
11294
+ * Lays out the tool calls of every assistant message in `rendered`.
11295
+ *
11296
+ * Calls drawn by a renderer that opted into grouping join the group that is
11297
+ * open. Anything else that shows between them closes it: assistant text, a
11298
+ * user, reasoning or activity message, or a call drawn by any other renderer.
11299
+ * A group belongs to the message where it starts, so later messages whose
11300
+ * calls joined it render no tool calls themselves.
11301
+ *
11302
+ * @param rendered - The messages as the chat renders them, in order.
11303
+ * @param all - Every message, for finding tool results (a transform may hide them).
11304
+ * @param renderers - The registered renderers, from `getToolCallRendererNames`.
11305
+ * @returns A map from assistant message id to its layout.
11306
+ *
11307
+ * @example
11308
+ * ```ts
11309
+ * const names = getToolCallRendererNames(core.renderToolCalls);
11310
+ * const layouts = getToolCallLayouts(renderedMessages, messages, names);
11311
+ * layouts.get(message.id)?.segments;
11312
+ * ```
11313
+ */
11314
+ function getToolCallLayouts(rendered, all, renderers) {
11315
+ const results = getToolResults(all);
11316
+ const layouts = /* @__PURE__ */ new Map();
11317
+ let open;
11318
+ for (const message of rendered) {
11319
+ if (message.role === "tool") continue;
11320
+ if (message.role !== "assistant") {
11321
+ open = void 0;
11322
+ continue;
11323
+ }
11324
+ if (typeof message.content === "string" && message.content.trim() !== "") open = void 0;
11325
+ const segments = [];
11326
+ layouts.set(message.id, segments);
11327
+ const toolCalls = /* @__PURE__ */ new Map();
11328
+ const messageToolCalls = message.toolCalls ?? [];
11329
+ for (const toolCall of messageToolCalls) toolCalls.set(toolCall.id, toolCall);
11330
+ const uniqueToolCalls = toolCalls.values();
11331
+ for (const toolCall of uniqueToolCalls) {
11332
+ const entry = {
11333
+ toolCall,
11334
+ toolMessage: results.get(toolCall.id)
11335
+ };
11336
+ const name = toolCall.function.name;
11337
+ const named = renderers.named.has(name);
11338
+ const isRendered = named || renderers.wildcard;
11339
+ const groups = named ? renderers.groupedNames.has(name) : renderers.wildcardGroups;
11340
+ if (!isRendered || !groups) {
11341
+ if (isRendered) open = void 0;
11342
+ segments.push({
11343
+ kind: "call",
11344
+ id: toolCall.id,
11345
+ call: entry,
11346
+ rendered: isRendered
11347
+ });
11348
+ } else if (open) open.calls.push(entry);
11349
+ else {
11350
+ open = {
11351
+ kind: "group",
11352
+ id: toolCall.id,
11353
+ calls: [entry],
11354
+ trailing: false
11355
+ };
11356
+ segments.push(open);
11357
+ }
11358
+ }
11359
+ }
11360
+ if (open) open.trailing = true;
11361
+ const layout = /* @__PURE__ */ new Map();
11362
+ for (const [id, segments] of layouts) layout.set(id, {
11363
+ segments,
11364
+ signature: signatureOf(segments)
11365
+ });
11366
+ return layout;
11367
+ }
11368
+ const TOOL_CALL_SLOT_PREFIX = "tool-call-";
11369
+ const WILDCARD_TOOL_CALL_SLOT = "tool-call";
11370
+ /**
11371
+ * Works out which tool calls have a renderer and which of those group, for
11372
+ * `getToolCallLayouts`.
11373
+ *
11374
+ * @param renderers - The registered renderers. A renderer named `"*"` is the
11375
+ * wildcard. `group: true` opts the renderer into grouping.
11376
+ * @param options - Slots, extra named tools, and a built-in wildcard card.
11377
+ * See `ToolCallRendererNamesOptions`.
11378
+ *
11379
+ * @example
11380
+ * ```ts
11381
+ * // React: only registered renderers.
11382
+ * getToolCallRendererNames(core.renderToolCalls);
11383
+ * // Vue: the view's slots count too.
11384
+ * getToolCallRendererNames(core.renderToolCalls, { slotNames: Object.keys(slots) });
11385
+ * // Angular: client and human-in-the-loop renderers, and the built-in card.
11386
+ * getToolCallRendererNames(appRenderers, {
11387
+ * extraNamed: [...clientNames, ...hitlNames],
11388
+ * builtInWildcard: { enabled: defaultToolRenderingEnabled, groups: true },
11389
+ * });
11390
+ * ```
11391
+ */
11392
+ function getToolCallRendererNames(renderers, options = {}) {
11393
+ const { slotNames = [], extraNamed = [], builtInWildcard } = options;
11394
+ const hasWildcardSlot = slotNames.includes(WILDCARD_TOOL_CALL_SLOT);
11395
+ const slotTools = slotNames.filter((name) => name.startsWith(TOOL_CALL_SLOT_PREFIX)).map((name) => name.slice(10));
11396
+ const named = renderers.filter((renderer) => renderer.name !== "*");
11397
+ const wildcards = renderers.filter((renderer) => renderer.name === "*");
11398
+ const hasAppWildcard = wildcards.length > 0;
11399
+ const isBuiltInEnabled = builtInWildcard?.enabled ?? false;
11400
+ const builtInGroups = isBuiltInEnabled && (builtInWildcard?.groups ?? false);
11401
+ const groupedNames = hasWildcardSlot ? [] : named.filter((renderer) => renderer.group && !slotTools.includes(renderer.name)).map((renderer) => renderer.name);
11402
+ const appWildcardGroups = wildcards.some((renderer) => renderer.group);
11403
+ return {
11404
+ named: new Set([
11405
+ ...named.map((renderer) => renderer.name),
11406
+ ...slotTools,
11407
+ ...extraNamed
11408
+ ]),
11409
+ groupedNames: new Set(groupedNames),
11410
+ wildcard: hasAppWildcard || hasWildcardSlot || isBuiltInEnabled,
11411
+ wildcardGroups: !hasWildcardSlot && (hasAppWildcard ? appWildcardGroups : builtInGroups)
11412
+ };
11413
+ }
11414
+ /** The turn key of a reply that no user message starts. */
11415
+ const FIRST_TURN_KEY = "start";
11416
+ /**
11417
+ * Finds the working phase of every reply in `rendered`: its messages up to the
11418
+ * last one that calls a tool. Text in there was narration. What follows is the
11419
+ * reply itself. Replies that called no tools are left out, except the latest,
11420
+ * which may be about to.
11421
+ *
11422
+ * @param rendered - The messages as the chat renders them, in order.
11423
+ * @param layouts - The layouts from `getToolCallLayouts` for the same messages.
11424
+ * @returns A map from turn key (see `TurnWork.key`) to the turn's work.
11425
+ */
11426
+ function getTurnWork(rendered, layouts) {
11427
+ const turns = /* @__PURE__ */ new Map();
11428
+ let start = 0;
11429
+ while (start < rendered.length) {
11430
+ let end = start;
11431
+ while (end < rendered.length && rendered[end].role !== "user") end++;
11432
+ const key = start > 0 ? rendered[start - 1].id : FIRST_TURN_KEY;
11433
+ const visible = rendered.slice(start, end).filter((message) => message.role !== "tool");
11434
+ const isLatest = end === rendered.length;
11435
+ const calls = [];
11436
+ for (const message of visible) {
11437
+ const segments = layouts.get(message.id)?.segments ?? [];
11438
+ for (const segment of segments) if (segment.kind === "group") calls.push(...segment.calls);
11439
+ else if (segment.rendered) calls.push(segment.call);
11440
+ }
11441
+ const shown = new Set(calls.map((entry) => entry.toolCall.id));
11442
+ let lastWork = -1;
11443
+ visible.forEach((message, index) => {
11444
+ if (message.role === "assistant" && message.toolCalls?.some((call) => shown.has(call.id))) lastWork = index;
11445
+ });
11446
+ const first = visible[0];
11447
+ if (first && (calls.length > 0 || isLatest)) {
11448
+ let lastAssistant = -1;
11449
+ visible.forEach((message, index) => {
11450
+ if (message.role === "assistant") lastAssistant = index;
11451
+ });
11452
+ const replyText = visible[lastAssistant]?.content;
11453
+ const endsWithWork = lastAssistant >= 0 && lastAssistant <= lastWork && typeof replyText === "string" && replyText.trim().length > 0;
11454
+ turns.set(key, {
11455
+ key,
11456
+ firstMessageId: first.id,
11457
+ workMessageIds: new Set(visible.slice(0, lastWork + 1).map((message) => message.id)),
11458
+ replyTextMessageId: endsWithWork ? visible[lastAssistant].id : void 0,
11459
+ calls,
11460
+ isLatest
11461
+ });
11462
+ }
11463
+ start = end + 1;
11464
+ }
11465
+ return turns;
11466
+ }
11467
+ /**
11468
+ * The key of the latest reply (see `TurnWork.key`): the id of the last user
11469
+ * message, or `"start"` when there is none.
11470
+ *
11471
+ * @param rendered - The messages as the chat renders them, in order.
11472
+ */
11473
+ function getLatestTurnKey(rendered) {
11474
+ for (let i = rendered.length - 1; i >= 0; i--) {
11475
+ const message = rendered[i];
11476
+ if (message.role === "user") return message.id;
11477
+ }
11478
+ return FIRST_TURN_KEY;
11479
+ }
11480
+ /**
11481
+ * Whether the agent is working on this reply now: it is the latest one and a
11482
+ * run is going.
11483
+ *
11484
+ * @param turnKey - The reply's `TurnWork.key`.
11485
+ * @param state - The run state and the latest turn key.
11486
+ */
11487
+ function isTurnWorking(turnKey, state) {
11488
+ return state.isRunning && turnKey === state.latestTurnKey;
11489
+ }
11490
+ /**
11491
+ * Whether a reply's work shows. It shows while the agent works on the reply
11492
+ * and folds once the reply is done, unless the user opened or closed it.
11493
+ *
11494
+ * @param turnKey - The reply's `TurnWork.key`.
11495
+ * @param state - The user's toggles, the run state, and the latest turn key.
11496
+ */
11497
+ function isTurnWorkOpen(turnKey, state) {
11498
+ return state.toggledTurns.get(turnKey) ?? isTurnWorking(turnKey, state);
11499
+ }
11500
+ /**
11501
+ * For each message in a reply's working phase, whether its work and its text
11502
+ * show. Text that ends the reply stays out of `workTextOpen` even when its
11503
+ * message also calls a tool, because it is the answer.
11504
+ *
11505
+ * @param turns - The turns from `getTurnWork`.
11506
+ * @param state - The user's toggles, the run state, and the latest turn key.
11507
+ * @returns The `workOpen` and `workTextOpen` maps of `ToolCallDisplayContextValue`.
11508
+ */
11509
+ function getWorkOpenState(turns, state) {
11510
+ const workOpen = /* @__PURE__ */ new Map();
11511
+ const workTextOpen = /* @__PURE__ */ new Map();
11512
+ for (const turn of turns) {
11513
+ const turnOpen = isTurnWorkOpen(turn.key, state);
11514
+ for (const id of turn.workMessageIds) {
11515
+ workOpen.set(id, turnOpen);
11516
+ if (id !== turn.replyTextMessageId) workTextOpen.set(id, turnOpen);
11517
+ }
11518
+ }
11519
+ return {
11520
+ workOpen,
11521
+ workTextOpen
11522
+ };
11523
+ }
11524
+ /**
11525
+ * Records run starts and ends in `workTimes`, for "Worked for 9s". Time spent
11526
+ * between runs (say, waiting for an approval) does not count. A reply is only
11527
+ * timed when this client saw it start from the user's message, so a restored
11528
+ * thread gets no entry. Calling it again with the same state changes nothing.
11529
+ *
11530
+ * @param workTimes - The times by turn key. This function updates it in place.
11531
+ * @param state - The run state now.
11532
+ * @param state.lastMessageRole - The role of the last rendered message.
11533
+ * @param state.now - The current time, in epoch ms.
11534
+ */
11535
+ function recordWorkTime(workTimes, state) {
11536
+ const { isRunning, latestTurnKey, lastMessageRole, now } = state;
11537
+ if (isRunning) {
11538
+ const times = workTimes.get(latestTurnKey);
11539
+ if (times) times.workingSince ??= now;
11540
+ else if (lastMessageRole === "user") workTimes.set(latestTurnKey, {
11541
+ elapsedMs: 0,
11542
+ workingSince: now
11543
+ });
11544
+ return;
11545
+ }
11546
+ const allTimes = workTimes.values();
11547
+ for (const times of allTimes) {
11548
+ if (times.workingSince === void 0) continue;
11549
+ times.elapsedMs += now - times.workingSince;
11550
+ times.workingSince = void 0;
11551
+ }
11552
+ }
11553
+ /**
11554
+ * The status of one call in a group. A call without a result is running only
11555
+ * while the group is active: once the run has moved on or ended, its result
11556
+ * is never coming.
11557
+ *
11558
+ * @param entry - The call and its result, if any.
11559
+ * @param active - The agent may still finish the group's calls.
11560
+ */
11561
+ function getToolCallRowStatus(entry, active) {
11562
+ const { toolMessage } = entry;
11563
+ let status;
11564
+ if (toolMessage) status = toolMessage.error ? "failed" : "done";
11565
+ else status = active ? "running" : "stopped";
11566
+ return status;
11567
+ }
11568
+ /**
11569
+ * The first non-empty string argument, with runs of whitespace collapsed to
11570
+ * one space. This is usually a command, path or query.
11571
+ *
11572
+ * @param parameters - The call's parsed arguments.
11573
+ * @returns The preview, or `undefined` when no argument is a non-empty string.
11574
+ */
11575
+ function getArgumentPreview(parameters) {
11576
+ if (!parameters || typeof parameters !== "object") return void 0;
11577
+ return Object.values(parameters).find((v) => typeof v === "string" && v.trim().length > 0)?.replace(/\s+/g, " ");
11578
+ }
11579
+ /**
11580
+ * `getArgumentPreview` for a call whose arguments may still be streaming in
11581
+ * as partial JSON.
11582
+ *
11583
+ * @param entry - The call.
11584
+ */
11585
+ function getToolCallPreview(entry) {
11586
+ return getArgumentPreview((0, _copilotkit_shared.partialJSONParse)(entry.toolCall.function.arguments));
11587
+ }
11588
+ /**
11589
+ * The names of the tools the calls used, in first-use order, with a count
11590
+ * for repeats: `"run_command ×2, read_file"`.
11591
+ *
11592
+ * @param calls - The calls to name.
11593
+ */
11594
+ function formatToolNames(calls) {
11595
+ const counts = /* @__PURE__ */ new Map();
11596
+ for (const { toolCall } of calls) {
11597
+ const name = toolCall.function.name;
11598
+ counts.set(name, (counts.get(name) ?? 0) + 1);
11599
+ }
11600
+ return [...counts].map(([name, count]) => count > 1 ? `${name} ×${count}` : name).join(", ");
11601
+ }
11602
+ /**
11603
+ * How many of the calls finished with an error.
11604
+ *
11605
+ * @param calls - The calls to count.
11606
+ */
11607
+ function countFailedToolCalls(calls) {
11608
+ return calls.filter((call) => call.toolMessage?.error).length;
11609
+ }
11610
+ /**
11611
+ * A count followed by the word that fits it: `"1 tool"`, `"3 tools"`.
11612
+ *
11613
+ * @param count - The number to show.
11614
+ * @param words - The word for exactly one (`one`) and for any other count (`other`).
11615
+ *
11616
+ * @example
11617
+ * ```ts
11618
+ * pluralize(3, { one: "tool", other: "tools" }); // "3 tools"
11619
+ * ```
11620
+ */
11621
+ function pluralize(count, words) {
11622
+ return `${count} ${count === 1 ? words.one : words.other}`;
11623
+ }
11624
+ /**
11625
+ * A tool call's arguments or result as display text. Strings pass through.
11626
+ * Other values are pretty-printed JSON. A value JSON cannot encode (say, a
11627
+ * circular reference) falls back to `String(value)`, then to
11628
+ * `"[unserializable]"`, so it never throws during a render.
11629
+ *
11630
+ * @param value - The arguments or the result.
11631
+ */
11632
+ function stringifyToolCallPayload(value) {
11633
+ if (typeof value === "string") return value;
11634
+ try {
11635
+ return JSON.stringify(value, null, 2);
11636
+ } catch (err) {
11637
+ console.warn("[CopilotKit] Failed to JSON.stringify tool-call payload; falling back to String():", err);
11638
+ try {
11639
+ return String(value);
11640
+ } catch {
11641
+ return "[unserializable]";
11642
+ }
11643
+ }
11644
+ }
11645
+ /**
11646
+ * How long a `"turn"` reply worked, as short text: `"45s"`, `"1m 5s"`, `"2m"`.
11647
+ * Used for the live timer and the final duration. Partial seconds round down,
11648
+ * and a negative time reads `"0s"`.
11649
+ *
11650
+ * @param ms - The time in milliseconds.
11651
+ */
11652
+ function formatWorkDuration(ms) {
11653
+ const seconds = Math.max(0, Math.floor(ms / 1e3));
11654
+ if (seconds < 60) return `${seconds}s`;
11655
+ const minutes = Math.floor(seconds / 60);
11656
+ const rest = seconds % 60;
11657
+ return rest ? `${minutes}m ${rest}s` : `${minutes}m`;
11658
+ }
11659
+ /**
11660
+ * Splits a reasoning time into the unit and counts the "Thought for ..."
11661
+ * header shows. See `ReasoningDuration` for the text each unit maps to.
11662
+ *
11663
+ * - Under 1 second: `fewSeconds`.
11664
+ * - Under 60 seconds: `seconds`, rounded to the nearest second.
11665
+ * - Whole minutes after rounding the seconds: `minutes`.
11666
+ * - Otherwise: `minutesSeconds`.
11667
+ *
11668
+ * @param seconds - The elapsed time in seconds. It may have a fraction.
11669
+ */
11670
+ function formatReasoningDuration(seconds) {
11671
+ if (seconds < 1) return { unit: "fewSeconds" };
11672
+ if (seconds < 60) return {
11673
+ unit: "seconds",
11674
+ seconds: Math.round(seconds)
11675
+ };
11676
+ const minutes = Math.floor(seconds / 60);
11677
+ const rest = Math.round(seconds % 60);
11678
+ if (rest === 0) return {
11679
+ unit: "minutes",
11680
+ minutes
11681
+ };
11682
+ return {
11683
+ unit: "minutesSeconds",
11684
+ minutes,
11685
+ seconds: rest
11686
+ };
11687
+ }
11688
+
11689
+ //#endregion
11690
+ //#region src/chat/messages.ts
11691
+ /**
11692
+ * Collapses tool calls that share an id, keeping first-seen order.
11693
+ *
11694
+ * AG-UI's TOOL_CALL_START handler appends to the parent message's `toolCalls`
11695
+ * without checking whether that id is already present. When a start event is
11696
+ * applied twice (the human-in-the-loop flow does this when the run syncs after
11697
+ * `respond()`), the message carries the same call twice. The second copy has
11698
+ * empty `arguments`, because a start event carries none. The args arrive later
11699
+ * as TOOL_CALL_ARGS deltas addressed to the first copy.
11700
+ *
11701
+ * Left alone, the same tool call renders twice: once populated and once blank.
11702
+ * The blank copy is the redundant one, so the copy that carries arguments wins,
11703
+ * whatever order the two arrive in.
11704
+ *
11705
+ * @param toolCalls - The tool calls of one assistant message.
11706
+ * @returns The same array when no id repeats, so memoized consumers keep a
11707
+ * stable reference. Otherwise a new array with one entry per id.
11708
+ */
11709
+ function dedupeToolCalls(toolCalls) {
11710
+ const byId = /* @__PURE__ */ new Map();
11711
+ for (const toolCall of toolCalls) {
11712
+ const existing = byId.get(toolCall.id);
11713
+ if (!existing) {
11714
+ byId.set(toolCall.id, toolCall);
11715
+ continue;
11716
+ }
11717
+ if (!existing.function?.arguments && Boolean(toolCall.function?.arguments)) byId.set(toolCall.id, toolCall);
11718
+ }
11719
+ return byId.size === toolCalls.length ? toolCalls : [...byId.values()];
11720
+ }
11721
+ /**
11722
+ * Merges two snapshots of the same assistant message.
11723
+ *
11724
+ * - Empty `content` means a streaming update cleared the field, so the earlier
11725
+ * non-empty content is kept.
11726
+ * - `toolCalls: undefined` means the later chunk had no tool-call activity, so
11727
+ * the earlier tool calls are kept. An explicit `[]` is kept as-is.
11728
+ * - Fields that only the earlier snapshot has are kept.
11729
+ */
11730
+ function mergeAssistantMessages(existing, message) {
11731
+ const content = message.content || existing.content;
11732
+ const toolCalls = message.toolCalls ?? existing.toolCalls;
11733
+ return {
11734
+ ...existing,
11735
+ ...message,
11736
+ content,
11737
+ toolCalls: toolCalls ? dedupeToolCalls(toolCalls) : toolCalls
11738
+ };
11739
+ }
11740
+ /**
11741
+ * Returns the assistant message with repeated tool-call ids collapsed. Returns
11742
+ * the same object when nothing collapsed.
11743
+ */
11744
+ function withDedupedToolCalls(message) {
11745
+ if (!message.toolCalls) return message;
11746
+ const toolCalls = dedupeToolCalls(message.toolCalls);
11747
+ return toolCalls === message.toolCalls ? message : {
11748
+ ...message,
11749
+ toolCalls
11750
+ };
11751
+ }
11752
+ /**
11753
+ * De-duplicates chat messages by id, for rendering.
11754
+ *
11755
+ * A message list from an agent can hold the same message id more than once
11756
+ * while it streams. This keeps one entry per id, at the position the id first
11757
+ * appears:
11758
+ *
11759
+ * - **Assistant messages** are merged. Later fields win, but empty `content`
11760
+ * falls back to earlier non-empty content, and `toolCalls: undefined` falls
11761
+ * back to earlier tool calls (an explicit `[]` is kept).
11762
+ * - **Tool calls** on an assistant message are de-duplicated by id, also
11763
+ * when the message itself is not repeated. The copy that has arguments
11764
+ * wins, and the first-seen order is kept.
11765
+ * - **Other roles** keep the last copy.
11766
+ *
11767
+ * @param messages - The agent's messages, in order.
11768
+ * @returns A new array. A message that needed no change is returned as the
11769
+ * same object.
11770
+ *
11771
+ * @example
11772
+ * ```ts
11773
+ * const visible = ɵdeduplicateMessages(agent.messages);
11774
+ * ```
11775
+ */
11776
+ function ɵdeduplicateMessages(messages) {
11777
+ const byId = /* @__PURE__ */ new Map();
11778
+ for (const message of messages) {
11779
+ if (message.role !== "assistant") {
11780
+ byId.set(message.id, message);
11781
+ continue;
11782
+ }
11783
+ const existing = byId.get(message.id);
11784
+ const merged = existing?.role === "assistant" ? mergeAssistantMessages(existing, message) : withDedupedToolCalls(message);
11785
+ byId.set(message.id, merged);
11786
+ }
11787
+ return [...byId.values()];
11788
+ }
11789
+ /**
11790
+ * Serializes object content for {@link ɵmessagesFingerprint}.
11791
+ *
11792
+ * `JSON.stringify` throws on a circular structure (and on a `BigInt`). The
11793
+ * fingerprint runs on every render, so a throw would take the chat down. A
11794
+ * value that cannot be serialized gets a constant key instead: it does not
11795
+ * trigger a change on its own, but every other part of the fingerprint still
11796
+ * does.
11797
+ */
11798
+ function objectContentKey(content) {
11799
+ try {
11800
+ return JSON.stringify(content) ?? "";
11801
+ } catch {
11802
+ return "[unserializable]";
11803
+ }
11804
+ }
11805
+ /**
11806
+ * Gives the part of the fingerprint that tracks a message's content:
11807
+ * - string content: its length, so streamed text changes it.
11808
+ * - array content: the part count, so an added attachment changes it. The
11809
+ * parts are not serialized, which keeps base64 uploads out of the key.
11810
+ * - object content (activity messages): its JSON, so a snapshot that replaces
11811
+ * the content under the same message id changes it.
11812
+ */
11813
+ function contentKey(content) {
11814
+ if (typeof content === "string" || Array.isArray(content)) return String(content.length);
11815
+ if (content !== null && typeof content === "object") return objectContentKey(content);
11816
+ return "0";
11817
+ }
11818
+ /**
11819
+ * Builds a string that changes whenever a render of the message list could
11820
+ * change. Use it as a cheap memo key in place of a deep comparison.
11821
+ *
11822
+ * The key covers, per message:
11823
+ * - the id and the role.
11824
+ * - the content: text length, part count, or the JSON of object content.
11825
+ * - the `toolCallId` of a tool message.
11826
+ * - each tool call's id and the length of its arguments, so streamed
11827
+ * arguments change the key.
11828
+ *
11829
+ * It never throws. Object content that cannot be serialized (for example a
11830
+ * circular tool result) gets a constant key.
11831
+ *
11832
+ * @param messages - The agent's messages, in order.
11833
+ * @returns The fingerprint string.
11834
+ *
11835
+ * @example
11836
+ * ```ts
11837
+ * const key = ɵmessagesFingerprint(agent.messages);
11838
+ * if (key !== previousKey) rerender();
11839
+ * ```
11840
+ */
11841
+ function ɵmessagesFingerprint(messages) {
11842
+ return messages.map((message) => {
11843
+ const toolCallId = "toolCallId" in message ? message.toolCallId : "";
11844
+ const toolCallsKey = ("toolCalls" in message && Array.isArray(message.toolCalls) ? message.toolCalls : []).map((tc) => `${tc.id}:${tc.function?.arguments?.length ?? 0}`).join(";");
11845
+ return `${message.id}:${message.role}:${contentKey(message.content)}:${toolCallId}:${toolCallsKey}`;
11846
+ }).join(",");
11847
+ }
11848
+
11849
+ //#endregion
11850
+ //#region src/chat/composer.ts
11851
+ /**
11852
+ * Get the state of the send/stop button in the chat input.
11853
+ *
11854
+ * @param input - The current state of the chat input.
11855
+ * @returns
11856
+ * - `isProcessing`: the agent runs and the input does not record audio.
11857
+ * - `canSend`: the text is not empty and nothing blocks a send.
11858
+ * - `action`: `"stop"` when the button stops the run, else `"send"`.
11859
+ * Use it for the icon, the label, and the click.
11860
+ * - `disabled`: `true` when a click does nothing.
11861
+ *
11862
+ * @example
11863
+ * ```ts
11864
+ * const button = ɵcomposerButtonState({
11865
+ * mode: "input",
11866
+ * isRunning: agent.isRunning,
11867
+ * value: text,
11868
+ * canSubmit: true,
11869
+ * canStop: true,
11870
+ * });
11871
+ * // On click:
11872
+ * if (button.action === "stop") stopRun();
11873
+ * else if (button.canSend) sendMessage(text.trim());
11874
+ * ```
11875
+ */
11876
+ function ɵcomposerButtonState(input) {
11877
+ const isProcessing = input.mode !== "transcribe" && input.isRunning;
11878
+ const isSendBlocked = input.disabled === true || input.attachmentsUploading === true;
11879
+ const canSend = input.canSubmit && !isSendBlocked && input.value.trim().length > 0;
11880
+ return {
11881
+ isProcessing,
11882
+ canSend,
11883
+ action: isProcessing && input.canStop ? "stop" : "send",
11884
+ disabled: isProcessing ? !input.canStop : !canSend
11885
+ };
11886
+ }
11887
+ /**
11888
+ * Decide what a key press in the chat input does.
11889
+ *
11890
+ * This handles Enter only. Keys for the slash-command menu stay in each
11891
+ * framework, and the framework handles them before it calls this function.
11892
+ *
11893
+ * Results:
11894
+ * - `"send"`: send the trimmed text.
11895
+ * - `"stop"`: stop the run. This happens for Enter in an empty input while
11896
+ * the agent runs. Text in the input always means send, not stop.
11897
+ * - `"newline"`: Shift+Enter. Let the browser add the line break.
11898
+ * - `"none"`: do nothing. Returned during IME composition, while the input
11899
+ * is disabled, for keys other than Enter, and for an Enter that has
11900
+ * nothing to send or stop.
11901
+ *
11902
+ * Call `preventDefault()` for every Enter without Shift that is not part of
11903
+ * IME composition, including when the result is `"none"`. This stops Enter
11904
+ * from adding a line break that the user cannot send.
11905
+ *
11906
+ * @param event - The keyboard event, or an object with the same fields.
11907
+ * @param input - The current state of the chat input.
11908
+ *
11909
+ * @example
11910
+ * ```ts
11911
+ * function onKeyDown(event: KeyboardEvent) {
11912
+ * if (event.isComposing || event.keyCode === 229) return;
11913
+ * // ...slash-command menu keys...
11914
+ * const result = ɵresolveComposerKey(event, composerInput);
11915
+ * if (event.key === "Enter" && !event.shiftKey) event.preventDefault();
11916
+ * if (result === "send") sendMessage(composerInput.value.trim());
11917
+ * if (result === "stop") stopRun();
11918
+ * }
11919
+ * ```
11920
+ */
11921
+ function ɵresolveComposerKey(event, input) {
11922
+ if (event.isComposing || event.keyCode === 229 || input.disabled === true || event.key !== "Enter") return "none";
11923
+ if (event.shiftKey) return "newline";
11924
+ const button = ɵcomposerButtonState(input);
11925
+ const isEmpty = input.value.trim().length === 0;
11926
+ if (button.isProcessing && isEmpty) return input.canStop ? "stop" : "none";
11927
+ return button.canSend ? "send" : "none";
11928
+ }
11929
+
11930
+ //#endregion
11931
+ //#region src/chat/transcription.ts
11932
+ /**
11933
+ * The error `ɵtranscribeAudio` throws. Read `error.info.code` to pick a
11934
+ * message for the user, or pass `error.info` to
11935
+ * `ɵtranscriptionErrorMessageKey`.
11936
+ */
11937
+ var TranscriptionError = class extends Error {
11938
+ info;
11939
+ constructor(info) {
11940
+ super(info.message);
11941
+ this.name = "TranscriptionError";
11942
+ this.info = info;
11943
+ }
11944
+ };
11945
+ /**
11946
+ * Send a recording to the CopilotKit runtime and get its text back.
11947
+ *
11948
+ * The request follows the transport set on the core:
11949
+ * - `"single"`: one JSON POST to `runtimeUrl`, with the audio as base64.
11950
+ * - any other transport: a multipart POST to `${runtimeUrl}/transcribe`.
11951
+ *
11952
+ * Headers are resolved on each call. The core's `credentials` are sent when
11953
+ * they are set, the same as for agent requests.
11954
+ *
11955
+ * @param core - The `CopilotKitCore` (or a framework subclass) to send through.
11956
+ * @param audioBlob - The recorded audio.
11957
+ * @param filename - The file name the runtime sees. Defaults to `"recording.webm"`.
11958
+ * @returns The transcription result, with the text in `result.text`.
11959
+ * @throws {TranscriptionError} When the runtime URL is not set, the request
11960
+ * fails, or the runtime returns an error. `error.info` has the code.
11961
+ *
11962
+ * @example
11963
+ * ```ts
11964
+ * try {
11965
+ * const { text } = await ɵtranscribeAudio(core, blob);
11966
+ * } catch (error) {
11967
+ * if (error instanceof TranscriptionError) {
11968
+ * const key = ɵtranscriptionErrorMessageKey(error.info);
11969
+ * showError(key ? labels[key] : error.info.message);
11970
+ * }
11971
+ * }
11972
+ * ```
11973
+ */
11974
+ async function ɵtranscribeAudio(core, audioBlob, filename = "recording.webm") {
11975
+ const { runtimeUrl, credentials } = core;
11976
+ if (!runtimeUrl) throw new TranscriptionError({
11977
+ code: _copilotkit_shared.TranscriptionErrorCode.INVALID_REQUEST,
11978
+ message: "Runtime URL is not configured",
11979
+ retryable: false
11980
+ });
11981
+ const resolvedHeaders = await core.resolveHeaders();
11982
+ const credentialsInit = credentials ? { credentials } : {};
11983
+ let response;
11984
+ try {
11985
+ response = core.runtimeTransport === "single" ? await fetch(runtimeUrl, {
11986
+ method: "POST",
11987
+ headers: {
11988
+ ...omitContentType(resolvedHeaders),
11989
+ "Content-Type": "application/json"
11990
+ },
11991
+ body: JSON.stringify({
11992
+ method: "transcribe",
11993
+ body: {
11994
+ audio: await blobToBase64(audioBlob),
11995
+ mimeType: audioBlob.type || "audio/webm",
11996
+ filename
11997
+ }
11998
+ }),
11999
+ ...credentialsInit
12000
+ }) : await fetch(`${runtimeUrl}/transcribe`, {
12001
+ method: "POST",
12002
+ headers: omitContentType(resolvedHeaders),
12003
+ body: toFormData(audioBlob, filename),
12004
+ ...credentialsInit
12005
+ });
12006
+ } catch (error) {
12007
+ throw new TranscriptionError({
12008
+ code: _copilotkit_shared.TranscriptionErrorCode.NETWORK_ERROR,
12009
+ message: error instanceof Error ? error.message : "Network request failed",
12010
+ retryable: true
12011
+ });
12012
+ }
12013
+ if (!response.ok) throw await toTranscriptionError(response);
12014
+ return await response.json();
12015
+ }
12016
+ /**
12017
+ * Pick the chat label to show the user for a transcription error.
12018
+ *
12019
+ * @param error - The `info` of a `TranscriptionError`.
12020
+ * @returns A key of the chat labels, or `null`. `null` means no label fits:
12021
+ * show `error.message` instead.
12022
+ *
12023
+ * @example
12024
+ * ```ts
12025
+ * const key = ɵtranscriptionErrorMessageKey(error.info);
12026
+ * const text = key ? labels[key] : error.info.message;
12027
+ * ```
12028
+ */
12029
+ function ɵtranscriptionErrorMessageKey(error) {
12030
+ switch (error.code) {
12031
+ case _copilotkit_shared.TranscriptionErrorCode.RATE_LIMITED: return "transcriptionErrorRateLimitedText";
12032
+ case _copilotkit_shared.TranscriptionErrorCode.AUTH_FAILED: return "transcriptionErrorAuthFailedText";
12033
+ case _copilotkit_shared.TranscriptionErrorCode.AUDIO_TOO_LONG: return "transcriptionErrorAudioTooLongText";
12034
+ case _copilotkit_shared.TranscriptionErrorCode.AUDIO_TOO_SHORT: return "transcriptionErrorAudioTooShortText";
12035
+ case _copilotkit_shared.TranscriptionErrorCode.INVALID_AUDIO_FORMAT: return "transcriptionErrorInvalidAudioFormatText";
12036
+ case _copilotkit_shared.TranscriptionErrorCode.SERVICE_NOT_CONFIGURED: return "transcriptionErrorServiceNotConfiguredText";
12037
+ case _copilotkit_shared.TranscriptionErrorCode.NETWORK_ERROR: return "transcriptionErrorNetworkText";
12038
+ default: return error.retryable ? "transcriptionErrorGenericText" : null;
12039
+ }
12040
+ }
12041
+ function toFormData(audioBlob, filename) {
12042
+ const formData = new FormData();
12043
+ formData.append("audio", audioBlob, filename);
12044
+ return formData;
12045
+ }
12046
+ function omitContentType(headers) {
12047
+ const entries = Object.entries(headers);
12048
+ return Object.fromEntries(entries.filter(([name]) => name.toLowerCase() !== "content-type"));
12049
+ }
12050
+ async function blobToBase64(blob) {
12051
+ const bytes = new Uint8Array(await blob.arrayBuffer());
12052
+ const chunkSize = 32768;
12053
+ let binary = "";
12054
+ for (let offset = 0; offset < bytes.length; offset += chunkSize) binary += String.fromCharCode(...bytes.subarray(offset, offset + chunkSize));
12055
+ return btoa(binary);
12056
+ }
12057
+ /** Build a typed error from a non-OK transcription response. */
12058
+ async function toTranscriptionError(response) {
12059
+ const retryable = response.status >= 500;
12060
+ let data;
12061
+ try {
12062
+ data = await response.json();
12063
+ } catch {
12064
+ return new TranscriptionError({
12065
+ code: _copilotkit_shared.TranscriptionErrorCode.PROVIDER_ERROR,
12066
+ message: `HTTP ${response.status}: ${response.statusText}`,
12067
+ retryable
12068
+ });
12069
+ }
12070
+ if (isTranscriptionErrorResponse(data)) return new TranscriptionError({
12071
+ code: data.error,
12072
+ message: data.message,
12073
+ retryable: data.retryable ?? false
12074
+ });
12075
+ const message = typeof data === "object" && data !== null && "message" in data ? String(data.message) : "Transcription failed";
12076
+ return new TranscriptionError({
12077
+ code: _copilotkit_shared.TranscriptionErrorCode.PROVIDER_ERROR,
12078
+ message,
12079
+ retryable
12080
+ });
12081
+ }
12082
+ function isTranscriptionErrorResponse(data) {
12083
+ return typeof data === "object" && data !== null && "error" in data && "message" in data && typeof data.error === "string" && typeof data.message === "string";
12084
+ }
12085
+
12086
+ //#endregion
12087
+ //#region src/chat/license.ts
12088
+ /**
12089
+ * Resolves the license context and the license banner from the runtime
12090
+ * license authority. React, Vue, and Angular call it with the values core
12091
+ * reports, then show the banner and provide the context.
12092
+ *
12093
+ * Rules:
12094
+ *
12095
+ * - A retryable entitlement failure that core is still retrying hides the
12096
+ * status, so no banner shows until the retry ends. A `valid` or `expiring`
12097
+ * legacy status stays in use during the retry.
12098
+ * - A terminal entitlement failure (not retryable, no `valid` or `expiring`
12099
+ * legacy status) keeps the reported status, but `checkFeature` returns
12100
+ * `false` and `getLimit` returns `null` for every feature.
12101
+ * - The `no_license` banner shows only when the status is `none` and no
12102
+ * public key is set.
12103
+ *
12104
+ * The banner text has no day count. No data source gives the days left.
12105
+ *
12106
+ * @param input - The runtime license values and the public key. See
12107
+ * {@link LicenseStateInput}.
12108
+ * @returns `context` for the license context, `warningStatus` (the status the
12109
+ * banner is based on, `undefined` while a retry runs), and `bannerType`
12110
+ * (`null` when no banner shows).
12111
+ *
12112
+ * @example
12113
+ * ```ts
12114
+ * const { context, bannerType } = ɵresolveLicenseState({
12115
+ * status: core.licenseStatus,
12116
+ * entitlements: core.runtimeEntitlements,
12117
+ * retryPending: core.runtimeEntitlementRetryPending,
12118
+ * publicKey,
12119
+ * });
12120
+ * ```
12121
+ */
12122
+ function ɵresolveLicenseState({ status, entitlements, retryPending, publicKey }) {
12123
+ const isRetryableFailure = entitlements?.status !== "ready" && entitlements?.error.retryable === true;
12124
+ const isNonReady = entitlements !== void 0 && entitlements.status !== "ready";
12125
+ const hasLegacyFallback = status === "valid" || status === "expiring";
12126
+ const isRetrying = isRetryableFailure && retryPending && !hasLegacyFallback;
12127
+ const isTerminalFailure = isNonReady && !isRetryableFailure && !hasLegacyFallback;
12128
+ const runtimeContext = (0, _copilotkit_shared.createLicenseContextValue)(isRetrying ? void 0 : status, entitlements);
12129
+ const context = isTerminalFailure ? {
12130
+ ...runtimeContext,
12131
+ checkFeature: () => false,
12132
+ getLimit: () => null
12133
+ } : runtimeContext;
12134
+ const warningStatus = isRetrying ? void 0 : context.status ?? void 0;
12135
+ return {
12136
+ context,
12137
+ warningStatus,
12138
+ bannerType: resolveLicenseBannerType(warningStatus, publicKey)
12139
+ };
12140
+ }
12141
+ function resolveLicenseBannerType(warningStatus, publicKey) {
12142
+ switch (warningStatus) {
12143
+ case "none": return publicKey ? null : "no_license";
12144
+ case "expired":
12145
+ case "invalid":
12146
+ case "expiring": return warningStatus;
12147
+ case "valid":
12148
+ case "unknown":
12149
+ case void 0: return null;
12150
+ }
12151
+ }
12152
+ /**
12153
+ * Resolves whether the threads drawer can load its thread list.
12154
+ *
12155
+ * - `licensed` is `true` when the status is `unknown` (an entitlement lookup
12156
+ * that did not recover, so the threads endpoint decides), or when the
12157
+ * status is `valid` or `expiring` and `checkFeature("threads")` is `true`.
12158
+ * - `licensePending` is `true` while the status is `null` (the runtime has
12159
+ * not reported yet). Show the loading state then, not the locked view.
12160
+ *
12161
+ * @param context - The license context from {@link ɵresolveLicenseState}.
12162
+ *
12163
+ * @example
12164
+ * ```ts
12165
+ * const { licensed, licensePending } = ɵresolveThreadsLicense(context);
12166
+ * ```
12167
+ */
12168
+ function ɵresolveThreadsLicense(context) {
12169
+ const { status } = context;
12170
+ return {
12171
+ licensed: status === "unknown" || (status === "valid" || status === "expiring") && context.checkFeature("threads"),
12172
+ licensePending: status === null
12173
+ };
12174
+ }
12175
+
12176
+ //#endregion
12177
+ //#region src/chat/icons.ts
12178
+ /*! @license
12179
+ * The icon data below is copied from Lucide v0.525.0 (https://lucide.dev).
12180
+ * The Lucide license follows. A copy is in LUCIDE-LICENSE.md next to this file.
12181
+ * This comment sits right above runtime code so the bundler keeps it in dist.
12182
+ *
12183
+ * ISC License
12184
+ *
12185
+ * Copyright (c) for portions of Lucide are held by Cole Bemis 2013-2022 as part of Feather (MIT). All other copyright (c) for Lucide are held by Lucide Contributors 2022.
12186
+ *
12187
+ * Permission to use, copy, modify, and/or distribute this software for any
12188
+ * purpose with or without fee is hereby granted, provided that the above
12189
+ * copyright notice and this permission notice appear in all copies.
12190
+ *
12191
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12192
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12193
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12194
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12195
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
12196
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
12197
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
12198
+ */
12199
+ function path(d) {
12200
+ return {
12201
+ tag: "path",
12202
+ attributes: { d }
12203
+ };
12204
+ }
12205
+ const icons = {
12206
+ ArrowUp: {
12207
+ name: "arrow-up",
12208
+ nodes: [path("m5 12 7-7 7 7"), path("M12 19V5")]
12209
+ },
12210
+ Check: {
12211
+ name: "check",
12212
+ nodes: [path("M20 6 9 17l-5-5")]
12213
+ },
12214
+ ChevronDown: {
12215
+ name: "chevron-down",
12216
+ nodes: [path("m6 9 6 6 6-6")]
12217
+ },
12218
+ ChevronLeft: {
12219
+ name: "chevron-left",
12220
+ nodes: [path("m15 18-6-6 6-6")]
12221
+ },
12222
+ ChevronRight: {
12223
+ name: "chevron-right",
12224
+ nodes: [path("m9 18 6-6-6-6")]
12225
+ },
12226
+ Circle: {
12227
+ name: "circle",
12228
+ nodes: [{
12229
+ tag: "circle",
12230
+ attributes: {
12231
+ cx: "12",
12232
+ cy: "12",
12233
+ r: "10"
12234
+ }
12235
+ }]
12236
+ },
12237
+ Copy: {
12238
+ name: "copy",
12239
+ nodes: [{
12240
+ tag: "rect",
12241
+ attributes: {
12242
+ width: "14",
12243
+ height: "14",
12244
+ x: "8",
12245
+ y: "8",
12246
+ rx: "2",
12247
+ ry: "2"
12248
+ }
12249
+ }, path("M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2")]
12250
+ },
12251
+ Edit: {
12252
+ name: "square-pen",
12253
+ nodes: [path("M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"), path("M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z")]
12254
+ },
12255
+ EyeOff: {
12256
+ name: "eye-off",
12257
+ nodes: [
12258
+ path("M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49"),
12259
+ path("M14.084 14.158a3 3 0 0 1-4.242-4.242"),
12260
+ path("M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143"),
12261
+ path("m2 2 20 20")
12262
+ ]
12263
+ },
12264
+ Loader2: {
12265
+ name: "loader-circle",
12266
+ nodes: [path("M21 12a9 9 0 1 1-6.219-8.56")]
12267
+ },
12268
+ MessageCircle: {
12269
+ name: "message-circle",
12270
+ nodes: [path("M7.9 20A9 9 0 1 0 4 16.1L2 22Z")]
12271
+ },
12272
+ Mic: {
12273
+ name: "mic",
12274
+ nodes: [
12275
+ path("M12 19v3"),
12276
+ path("M19 10v2a7 7 0 0 1-14 0v-2"),
12277
+ {
12278
+ tag: "rect",
12279
+ attributes: {
12280
+ x: "9",
12281
+ y: "2",
12282
+ width: "6",
12283
+ height: "13",
12284
+ rx: "3"
12285
+ }
12286
+ }
12287
+ ]
12288
+ },
12289
+ PanelLeftOpen: {
12290
+ name: "panel-left-open",
12291
+ nodes: [
12292
+ {
12293
+ tag: "rect",
12294
+ attributes: {
12295
+ width: "18",
12296
+ height: "18",
12297
+ x: "3",
12298
+ y: "3",
12299
+ rx: "2"
12300
+ }
12301
+ },
12302
+ path("M9 3v18"),
12303
+ path("m14 9 3 3-3 3")
12304
+ ]
12305
+ },
12306
+ Play: {
12307
+ name: "play",
12308
+ nodes: [{
12309
+ tag: "polygon",
12310
+ attributes: { points: "6 3 20 12 6 21 6 3" }
12311
+ }]
12312
+ },
12313
+ Plus: {
12314
+ name: "plus",
12315
+ nodes: [path("M5 12h14"), path("M12 5v14")]
12316
+ },
12317
+ RefreshCw: {
12318
+ name: "refresh-cw",
12319
+ nodes: [
12320
+ path("M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"),
12321
+ path("M21 3v5h-5"),
12322
+ path("M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"),
12323
+ path("M8 16H3v5")
12324
+ ]
12325
+ },
12326
+ Square: {
12327
+ name: "square",
12328
+ nodes: [{
12329
+ tag: "rect",
12330
+ attributes: {
12331
+ width: "18",
12332
+ height: "18",
12333
+ x: "3",
12334
+ y: "3",
12335
+ rx: "2"
12336
+ }
12337
+ }]
12338
+ },
12339
+ ThumbsDown: {
12340
+ name: "thumbs-down",
12341
+ nodes: [path("M17 14V2"), path("M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z")]
12342
+ },
12343
+ ThumbsUp: {
12344
+ name: "thumbs-up",
12345
+ nodes: [path("M7 10v12"), path("M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z")]
12346
+ },
12347
+ Upload: {
12348
+ name: "upload",
12349
+ nodes: [
12350
+ path("M12 3v12"),
12351
+ path("m17 8-5-5-5 5"),
12352
+ path("M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4")
12353
+ ]
12354
+ },
12355
+ Volume2: {
12356
+ name: "volume-2",
12357
+ nodes: [
12358
+ path("M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"),
12359
+ path("M16 9a5 5 0 0 1 0 6"),
12360
+ path("M19.364 18.364a9 9 0 0 0 0-12.728")
12361
+ ]
12362
+ },
12363
+ Wrench: {
12364
+ name: "wrench",
12365
+ nodes: [path("M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z")]
12366
+ },
12367
+ X: {
12368
+ name: "x",
12369
+ nodes: [path("M18 6 6 18"), path("m6 6 12 12")]
12370
+ }
12371
+ };
12372
+ /**
12373
+ * Internal. The SVG data for every icon the chat components draw.
12374
+ *
12375
+ * Each framework's `CopilotIcon` component reads an entry and draws it:
12376
+ *
12377
+ * ```ts
12378
+ * const { name, nodes } = ɵcopilotIcons.ArrowUp;
12379
+ * // <svg {...ɵcopilotIconSvgAttributes} class="lucide lucide-arrow-up">
12380
+ * // one child element per node: <{node.tag} {...node.attributes} />
12381
+ * // </svg>
12382
+ * ```
12383
+ */
12384
+ const ɵcopilotIcons = icons;
12385
+ /**
12386
+ * Internal. The attributes to put on the `<svg>` of every chat icon.
12387
+ *
12388
+ * These are Lucide's default attributes, so a drawn icon matches the Lucide
12389
+ * icon. Set `width` and `height` to change the size.
12390
+ */
12391
+ const ɵcopilotIconSvgAttributes = {
12392
+ xmlns: "http://www.w3.org/2000/svg",
12393
+ width: "24",
12394
+ height: "24",
12395
+ viewBox: "0 0 24 24",
12396
+ fill: "none",
12397
+ stroke: "currentColor",
12398
+ "stroke-width": "2",
12399
+ "stroke-linecap": "round",
12400
+ "stroke-linejoin": "round"
12401
+ };
12402
+
10774
12403
  //#endregion
10775
12404
  exports.A2UI_FENCE_LANGUAGE = A2UI_FENCE_LANGUAGE;
10776
12405
  exports.AgentRegistry = AgentRegistry;
10777
12406
  exports.AgentThreadLockedError = AgentThreadLockedError;
10778
12407
  exports.ContextStore = ContextStore;
12408
+ exports.CopilotChatDefaultLabels = CopilotChatDefaultLabels;
10779
12409
  exports.CopilotKitCore = CopilotKitCore;
10780
12410
  exports.CopilotKitCoreErrorCode = CopilotKitCoreErrorCode;
10781
12411
  exports.CopilotKitCoreRuntimeConnectionStatus = CopilotKitCoreRuntimeConnectionStatus;
10782
12412
  exports.CopilotKitHeaderResolutionError = CopilotKitHeaderResolutionError;
10783
12413
  exports.INSPECTOR_THREAD_BRIDGE_PLUGIN_ID = INSPECTOR_THREAD_BRIDGE_PLUGIN_ID;
12414
+ exports.INTERRUPT_EVENT_NAME = INTERRUPT_EVENT_NAME;
10784
12415
  exports.IntelligenceAgent = IntelligenceAgent;
10785
12416
  exports.MEMORY_ERROR_REGISTRY = MEMORY_ERROR_REGISTRY;
10786
12417
  exports.MemoryError = MemoryError;
@@ -10789,6 +12420,8 @@ exports.RunHandler = RunHandler;
10789
12420
  exports.StateManager = StateManager;
10790
12421
  exports.SuggestionEngine = SuggestionEngine;
10791
12422
  exports.ToolCallStatus = ToolCallStatus;
12423
+ exports.TranscriptionError = TranscriptionError;
12424
+ exports.TranscriptionErrorCode = _copilotkit_shared.TranscriptionErrorCode;
10792
12425
  exports.WebMCPRegistry = WebMCPRegistry;
10793
12426
  exports.classifySurfaceCards = classifySurfaceCards;
10794
12427
  exports.completePartialMarkdown = completePartialMarkdown;
@@ -10819,7 +12452,6 @@ exports.onInspectorActiveThread = onInspectorActiveThread;
10819
12452
  exports.onInspectorStopViewing = onInspectorStopViewing;
10820
12453
  exports.onInspectorViewThread = onInspectorViewThread;
10821
12454
  exports.onInspectorViewThreadResult = onInspectorViewThreadResult;
10822
- exports.parseMarkdown = parseMarkdown;
10823
12455
  exports.parseToolArguments = parseToolArguments;
10824
12456
  exports.prepareSurfaceOperations = prepareSurfaceOperations;
10825
12457
  exports.props = props;
@@ -10832,25 +12464,55 @@ exports.ɵMAX_SOCKET_RETRIES = ɵMAX_SOCKET_RETRIES;
10832
12464
  exports.ɵRUNTIME_PROBE_TIMEOUT_MS = ɵRUNTIME_PROBE_TIMEOUT_MS;
10833
12465
  exports.ɵTHREAD_REQUEST_TIMEOUT_MS = ɵTHREAD_REQUEST_TIMEOUT_MS;
10834
12466
  exports.ɵclearAgentInterruptState = ɵclearAgentInterruptState;
12467
+ exports.ɵcomposerButtonState = ɵcomposerButtonState;
12468
+ exports.ɵcopilotIconSvgAttributes = ɵcopilotIconSvgAttributes;
12469
+ exports.ɵcopilotIcons = ɵcopilotIcons;
12470
+ exports.ɵcountFailedToolCalls = countFailedToolCalls;
10835
12471
  exports.ɵcreateMemoryStore = createMemoryStore;
10836
12472
  exports.ɵcreateThreadSelectors = ɵcreateThreadSelectors;
10837
12473
  exports.ɵcreateThreadStore = createThreadStore;
12474
+ exports.ɵdeduplicateMessages = ɵdeduplicateMessages;
12475
+ exports.ɵformatCountLabel = ɵformatCountLabel;
12476
+ exports.ɵformatLabel = ɵformatLabel;
12477
+ exports.ɵformatReasoningDuration = formatReasoningDuration;
12478
+ exports.ɵformatToolNames = formatToolNames;
12479
+ exports.ɵformatWorkDuration = formatWorkDuration;
10838
12480
  exports.ɵgetAgentInterruptState = ɵgetAgentInterruptState;
12481
+ exports.ɵgetArgumentPreview = getArgumentPreview;
12482
+ exports.ɵgetLatestTurnKey = getLatestTurnKey;
12483
+ exports.ɵgetToolCallLayouts = getToolCallLayouts;
12484
+ exports.ɵgetToolCallPreview = getToolCallPreview;
12485
+ exports.ɵgetToolCallRendererNames = getToolCallRendererNames;
12486
+ exports.ɵgetToolCallRowStatus = getToolCallRowStatus;
12487
+ exports.ɵgetToolResults = getToolResults;
12488
+ exports.ɵgetTurnWork = getTurnWork;
12489
+ exports.ɵgetWorkOpenState = getWorkOpenState;
10839
12490
  exports.ɵisCopilotKitFeature = ɵisCopilotKitFeature;
10840
12491
  exports.ɵisHttpAgent = ɵisHttpAgent;
10841
12492
  exports.ɵisRetryableMemoryStatus = isRetryableStatus;
12493
+ exports.ɵisTurnWorkOpen = isTurnWorkOpen;
12494
+ exports.ɵisTurnWorking = isTurnWorking;
10842
12495
  exports.ɵjoinPhoenixChannel$ = ɵjoinPhoenixChannel$;
10843
12496
  exports.ɵmapMemoryMetadataEvent = ɵmapMemoryMetadataEvent;
10844
12497
  exports.ɵmemoryAdapterEvents = ɵmemoryAdapterEvents;
10845
12498
  exports.ɵmemoryDomainEvents = ɵmemoryDomainEvents;
10846
12499
  exports.ɵmemoryReducer = ɵmemoryReducer;
10847
12500
  exports.ɵmemoryRestEvents = ɵmemoryRestEvents;
12501
+ exports.ɵmessagesFingerprint = ɵmessagesFingerprint;
10848
12502
  exports.ɵobservePhoenixEvent$ = ɵobservePhoenixEvent$;
10849
12503
  exports.ɵobservePhoenixJoinOutcome$ = ɵobservePhoenixJoinOutcome$;
10850
12504
  exports.ɵobservePhoenixSocketHealth$ = ɵobservePhoenixSocketHealth$;
10851
12505
  exports.ɵobservePhoenixSocketSignals$ = ɵobservePhoenixSocketSignals$;
10852
12506
  exports.ɵphoenixChannel$ = ɵphoenixChannel$;
10853
12507
  exports.ɵphoenixSocket$ = ɵphoenixSocket$;
12508
+ exports.ɵpluralize = pluralize;
12509
+ exports.ɵrecordWorkTime = recordWorkTime;
12510
+ exports.ɵresolveActivityRenderer = ɵresolveActivityRenderer;
12511
+ exports.ɵresolveComposerKey = ɵresolveComposerKey;
12512
+ exports.ɵresolveCustomMessageRenderers = ɵresolveCustomMessageRenderers;
12513
+ exports.ɵresolveLicenseState = ɵresolveLicenseState;
12514
+ exports.ɵresolveThreadsLicense = ɵresolveThreadsLicense;
12515
+ exports.ɵresolveToolCallRenderer = ɵresolveToolCallRenderer;
10854
12516
  exports.ɵselectFetchMoreError = ɵselectFetchMoreError;
10855
12517
  exports.ɵselectHasNextPage = ɵselectHasNextPage;
10856
12518
  exports.ɵselectIsFetchingNextPage = ɵselectIsFetchingNextPage;
@@ -10864,6 +12526,9 @@ exports.ɵselectMemoriesRealtimeStatus = ɵselectMemoriesRealtimeStatus;
10864
12526
  exports.ɵselectThreads = ɵselectThreads;
10865
12527
  exports.ɵselectThreadsError = ɵselectThreadsError;
10866
12528
  exports.ɵselectThreadsIsLoading = ɵselectThreadsIsLoading;
12529
+ exports.ɵstringifyToolCallPayload = stringifyToolCallPayload;
10867
12530
  exports.ɵthreadAdapterEvents = ɵthreadAdapterEvents;
12531
+ exports.ɵtranscribeAudio = ɵtranscribeAudio;
12532
+ exports.ɵtranscriptionErrorMessageKey = ɵtranscriptionErrorMessageKey;
10868
12533
  exports.ɵwithHeaderDefaults = ɵwithHeaderDefaults;
10869
12534
  //# sourceMappingURL=index.cjs.map