@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.umd.js CHANGED
@@ -1,8 +1,8 @@
1
1
  (function(global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@tanstack/pacer'), require('@ag-ui/client'), require('@copilotkit/shared'), require('rxjs'), require('rxjs/operators'), require('phoenix'), require('zod-to-json-schema'), require('@copilotkit/learning'), require('marked')) :
3
- typeof define === 'function' && define.amd ? define(['exports', '@tanstack/pacer', '@ag-ui/client', '@copilotkit/shared', 'rxjs', 'rxjs/operators', 'phoenix', 'zod-to-json-schema', '@copilotkit/learning', 'marked'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.CopilotKitCore = {}), global._tanstack_pacer,global.AgUIClient,global.CopilotKitShared,global.rxjs,global.rxjs.operators,global.phoenix,global.zodToJsonSchema,global._copilotkit_learning,global.marked));
5
- })(this, function(exports, _tanstack_pacer, _ag_ui_client, _copilotkit_shared, rxjs, rxjs_operators, phoenix, zod_to_json_schema, _copilotkit_learning, marked) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@tanstack/pacer'), require('@ag-ui/client'), require('@copilotkit/shared'), require('rxjs'), require('rxjs/operators'), require('phoenix'), require('zod-to-json-schema'), require('@copilotkit/learning')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', '@tanstack/pacer', '@ag-ui/client', '@copilotkit/shared', 'rxjs', 'rxjs/operators', 'phoenix', 'zod-to-json-schema', '@copilotkit/learning'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.CopilotKitCore = {}), global._tanstack_pacer,global.AgUIClient,global.CopilotKitShared,global.rxjs,global.rxjs.operators,global.phoenix,global.zodToJsonSchema,global._copilotkit_learning));
5
+ })(this, function(exports, _tanstack_pacer, _ag_ui_client, _copilotkit_shared, rxjs, rxjs_operators, phoenix, zod_to_json_schema, _copilotkit_learning) {
6
6
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
7
7
 
8
8
  //#region src/utils/http-agent.ts
@@ -1882,6 +1882,20 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
1882
1882
  return typeof message === "string" && ABORT_MESSAGES.has(message);
1883
1883
  }
1884
1884
 
1885
+ //#endregion
1886
+ //#region src/utils/shallow-equal.ts
1887
+ /**
1888
+ * True when both records have the same own keys and each key holds the same
1889
+ * value (compared with `Object.is`). Key order does not matter. Nested
1890
+ * objects are compared by reference, not by content.
1891
+ */
1892
+ function shallowEqualRecord(a, b) {
1893
+ if (a === b) return true;
1894
+ const aKeys = Object.keys(a);
1895
+ if (aKeys.length !== Object.keys(b).length) return false;
1896
+ return aKeys.every((key) => Object.prototype.hasOwnProperty.call(b, key) && Object.is(a[key], b[key]));
1897
+ }
1898
+
1885
1899
  //#endregion
1886
1900
  //#region src/utils/runtime-request.ts
1887
1901
  const RUNTIME_REQUEST_WATCHDOG_MS = 1e4;
@@ -1986,13 +2000,6 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
1986
2000
  function normalizeHeaders(headers) {
1987
2001
  return Object.fromEntries(Object.entries(headers).filter((entry) => entry[1] != null));
1988
2002
  }
1989
- /** Same keys, same values (order-independent). */
1990
- function shallowEqualRecord(a, b) {
1991
- const aKeys = Object.keys(a);
1992
- const bKeys = Object.keys(b);
1993
- if (aKeys.length !== bKeys.length) return false;
1994
- return aKeys.every((key) => a[key] === b[key]);
1995
- }
1996
2003
  function isHeaderRecordInput(value) {
1997
2004
  return typeof value === "object" && value !== null && !Array.isArray(value);
1998
2005
  }
@@ -2165,6 +2172,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2165
2172
  this.core = core;
2166
2173
  _defineProperty(this, "_agents", {});
2167
2174
  _defineProperty(this, "localAgents", {});
2175
+ _defineProperty(this, "agentsPublished", false);
2168
2176
  _defineProperty(this, "remoteAgents", {});
2169
2177
  _defineProperty(this, "mintedThreadIds", /* @__PURE__ */ new WeakMap());
2170
2178
  _defineProperty(this, "_runtimeUrl", void 0);
@@ -2209,6 +2217,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2209
2217
  _defineProperty(this, "runtimeRecoveryRunning", false);
2210
2218
  _defineProperty(this, "runtimeRecoveryPending", false);
2211
2219
  _defineProperty(this, "runtimeHealthGeneration", 0);
2220
+ _defineProperty(this, "disposeController", new AbortController());
2212
2221
  _defineProperty(this, "agentOwnHeaders", /* @__PURE__ */ new WeakMap());
2213
2222
  }
2214
2223
  /**
@@ -2277,6 +2286,28 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2277
2286
  return this._telemetryDisabled;
2278
2287
  }
2279
2288
  /**
2289
+ * Stop runtime work this registry owns: the entitlement retry timer, the
2290
+ * inspector metadata request, runtime probes and recovery fetches with
2291
+ * their timeouts, and request watchdogs. In-flight `/info` connections are
2292
+ * detached so their late results change nothing. Called by
2293
+ * `CopilotKitCore.dispose`.
2294
+ */
2295
+ dispose() {
2296
+ var _this$inspectorMetada;
2297
+ if (this.disposeController.signal.aborted) return;
2298
+ this.disposeController.abort();
2299
+ this._activeRuntimeConnectionAttempt = void 0;
2300
+ this._connectionInFlight = void 0;
2301
+ this.resetRuntimeEntitlementRetry();
2302
+ this.inspectorMetadataGeneration += 1;
2303
+ (_this$inspectorMetada = this.inspectorMetadataAbortController) === null || _this$inspectorMetada === void 0 || _this$inspectorMetada.abort();
2304
+ this.inspectorMetadataAbortController = void 0;
2305
+ this.abandonRuntimeHealthProbe();
2306
+ }
2307
+ get isDisposed() {
2308
+ return this.disposeController.signal.aborted;
2309
+ }
2310
+ /**
2280
2311
  * Initialize agents from configuration
2281
2312
  */
2282
2313
  initialize(agents) {
@@ -2363,9 +2394,12 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2363
2394
  this.runtimeProbeAbortController = void 0;
2364
2395
  }
2365
2396
  /**
2366
- * Set all agents at once (for development use)
2397
+ * Set all agents at once (for development use). Same ids mapped to the
2398
+ * same instances as the current local agents is a no-op once the agents
2399
+ * have been announced.
2367
2400
  */
2368
2401
  setAgents__unsafe_dev_only(agents) {
2402
+ if (this.agentsPublished && shallowEqualRecord(agents, this.localAgents)) return;
2369
2403
  Object.entries(agents).forEach(([id, agent]) => {
2370
2404
  if (agent) this.validateAndAssignAgentId(id, agent);
2371
2405
  });
@@ -2635,11 +2669,17 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2635
2669
  checked: () => false
2636
2670
  };
2637
2671
  let checked = false;
2672
+ const disposeSignal = this.disposeController.signal;
2638
2673
  const timeoutId = setTimeout(() => {
2639
2674
  checked = this.handleRuntimeRequestOutcome("failed");
2640
2675
  }, RUNTIME_REQUEST_WATCHDOG_MS);
2676
+ const clear = () => {
2677
+ clearTimeout(timeoutId);
2678
+ disposeSignal.removeEventListener("abort", clear);
2679
+ };
2680
+ disposeSignal.addEventListener("abort", clear, { once: true });
2641
2681
  return {
2642
- clear: () => clearTimeout(timeoutId),
2682
+ clear,
2643
2683
  checked: () => checked
2644
2684
  };
2645
2685
  }
@@ -2669,9 +2709,9 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2669
2709
  * runtime connection state.
2670
2710
  */
2671
2711
  async refreshInspectorMetadata() {
2672
- var _this$inspectorMetada;
2712
+ var _this$inspectorMetada2;
2673
2713
  const generation = ++this.inspectorMetadataGeneration;
2674
- (_this$inspectorMetada = this.inspectorMetadataAbortController) === null || _this$inspectorMetada === void 0 || _this$inspectorMetada.abort();
2714
+ (_this$inspectorMetada2 = this.inspectorMetadataAbortController) === null || _this$inspectorMetada2 === void 0 || _this$inspectorMetada2.abort();
2675
2715
  this.inspectorMetadataAbortController = void 0;
2676
2716
  if (!this._inspectorMetadataSupported || !this.inspectorMetadataRefreshReady || !this.runtimeUrl || this._runtimeConnectionStatus !== CopilotKitCoreRuntimeConnectionStatus.Connected) {
2677
2717
  this.setInspectorMetadata(void 0);
@@ -2774,13 +2814,13 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2774
2814
  return (allowAbortedSignal || !signal.aborted) && generation === this.inspectorMetadataGeneration && runtimeUrl === this.runtimeUrl && requestedTransport === this._requestedTransport && resolvedTransport === this._runtimeTransport && headersGeneration === this.inspectorMetadataHeadersGeneration && credentialsGeneration === this.inspectorMetadataCredentialsGeneration && this._inspectorMetadataSupported && this.inspectorMetadataRefreshReady && this._runtimeConnectionStatus === CopilotKitCoreRuntimeConnectionStatus.Connected;
2775
2815
  }
2776
2816
  invalidateInspectorMetadataConnection() {
2777
- var _this$inspectorMetada2;
2817
+ var _this$inspectorMetada3;
2778
2818
  this._inspectorMetadataSupported = false;
2779
2819
  this._inspectorLearning = false;
2780
2820
  this.inspectorMetadataRefreshReady = false;
2781
2821
  this.inspectorMetadataConnectionGeneration += 1;
2782
2822
  this.inspectorMetadataGeneration += 1;
2783
- (_this$inspectorMetada2 = this.inspectorMetadataAbortController) === null || _this$inspectorMetada2 === void 0 || _this$inspectorMetada2.abort();
2823
+ (_this$inspectorMetada3 = this.inspectorMetadataAbortController) === null || _this$inspectorMetada3 === void 0 || _this$inspectorMetada3.abort();
2784
2824
  this.inspectorMetadataAbortController = void 0;
2785
2825
  this.setInspectorMetadata(void 0);
2786
2826
  }
@@ -2802,7 +2842,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2802
2842
  this.runtimeHealthGeneration += 1;
2803
2843
  }
2804
2844
  handleRuntimeRequestOutcome(outcome, alreadyChecked = () => false) {
2805
- if (outcome === "aborted" || outcome === "ignored") return false;
2845
+ if (outcome === "aborted" || outcome === "ignored" || this.isDisposed) return false;
2806
2846
  if (outcome === "failed" && alreadyChecked()) return false;
2807
2847
  if (typeof window === "undefined") return false;
2808
2848
  if (!this._runtimeUrl) return false;
@@ -2822,16 +2862,32 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2822
2862
  let timeoutId;
2823
2863
  const request = this.fetchRuntimeInfo(runtimeUrl, runtimeTransport, abortController.signal);
2824
2864
  request.catch(() => {});
2865
+ const disposeSignal = this.disposeController.signal;
2866
+ let rejectOnAbort;
2867
+ const abortOnDispose = () => abortController.abort();
2825
2868
  try {
2826
2869
  const timedOut = new Promise((_resolve, reject) => {
2827
2870
  timeoutId = setTimeout(() => {
2828
- abortController.abort();
2829
2871
  reject(/* @__PURE__ */ new Error(`Runtime did not answer within ${ɵRUNTIME_PROBE_TIMEOUT_MS}ms`));
2872
+ abortController.abort();
2830
2873
  }, ɵRUNTIME_PROBE_TIMEOUT_MS);
2831
2874
  });
2832
- return await Promise.race([request, timedOut]);
2875
+ const aborted = new Promise((_resolve, reject) => {
2876
+ rejectOnAbort = () => reject(/* @__PURE__ */ new Error("Runtime request aborted"));
2877
+ abortController.signal.addEventListener("abort", rejectOnAbort, { once: true });
2878
+ });
2879
+ aborted.catch(() => {});
2880
+ disposeSignal.addEventListener("abort", abortOnDispose, { once: true });
2881
+ if (disposeSignal.aborted) abortController.abort();
2882
+ return await Promise.race([
2883
+ request,
2884
+ timedOut,
2885
+ aborted
2886
+ ]);
2833
2887
  } finally {
2834
2888
  if (timeoutId !== void 0) clearTimeout(timeoutId);
2889
+ if (rejectOnAbort) abortController.signal.removeEventListener("abort", rejectOnAbort);
2890
+ disposeSignal.removeEventListener("abort", abortOnDispose);
2835
2891
  }
2836
2892
  }
2837
2893
  async probeRuntimeReachability() {
@@ -2892,7 +2948,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2892
2948
  * Update runtime connection and fetch remote agents
2893
2949
  */
2894
2950
  async updateRuntimeConnection(options) {
2895
- if (typeof window === "undefined") return;
2951
+ if (typeof window === "undefined" || this.isDisposed) return;
2896
2952
  const key = this.runtimeConnectionKey();
2897
2953
  const inFlight = this._connectionInFlight;
2898
2954
  if (inFlight && inFlight.attempt.key === key && this.isCurrentRuntimeConnection(inFlight.attempt)) return inFlight.promise;
@@ -2957,6 +3013,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2957
3013
  }
2958
3014
  this._runtimeEntitlementRetryAttemptedKey = key;
2959
3015
  this._runtimeEntitlementRetryPendingKey = key;
3016
+ if (this.isDisposed) return;
2960
3017
  this._runtimeEntitlementRetryTimer = setTimeout(() => {
2961
3018
  this._runtimeEntitlementRetryTimer = void 0;
2962
3019
  this.executeRuntimeEntitlementRetry(attempt).catch((error) => {
@@ -3216,6 +3273,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3216
3273
  * Notify subscribers of agent changes
3217
3274
  */
3218
3275
  async notifyAgentsChanged() {
3276
+ this.agentsPublished = true;
3219
3277
  await this.core.notifySubscribers((subscriber) => {
3220
3278
  var _subscriber$onAgentsC;
3221
3279
  return (_subscriber$onAgentsC = subscriber.onAgentsChanged) === null || _subscriber$onAgentsC === void 0 ? void 0 : _subscriber$onAgentsC.call(subscriber, {
@@ -3322,6 +3380,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3322
3380
  _defineProperty(this, "_suggestionsConfig", {});
3323
3381
  _defineProperty(this, "_suggestions", {});
3324
3382
  _defineProperty(this, "_runningSuggestions", {});
3383
+ _defineProperty(this, "_snapshots", /* @__PURE__ */ new Map());
3325
3384
  }
3326
3385
  /**
3327
3386
  * Initialize with suggestion configs
@@ -3383,14 +3442,30 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3383
3442
  this.notifySuggestionsChanged(agentId, []);
3384
3443
  }
3385
3444
  /**
3386
- * Get current suggestions for an agent
3445
+ * Get current suggestions for an agent. Returns the same object until the
3446
+ * agent's suggestions or loading state change.
3387
3447
  */
3388
3448
  getSuggestions(agentId) {
3389
3449
  var _this$_suggestions$ag, _this$_runningSuggest, _this$_runningSuggest2;
3390
- return {
3391
- suggestions: Object.values((_this$_suggestions$ag = this._suggestions[agentId]) !== null && _this$_suggestions$ag !== void 0 ? _this$_suggestions$ag : {}).flat(),
3392
- isLoading: ((_this$_runningSuggest = (_this$_runningSuggest2 = this._runningSuggestions[agentId]) === null || _this$_runningSuggest2 === void 0 ? void 0 : _this$_runningSuggest2.length) !== null && _this$_runningSuggest !== void 0 ? _this$_runningSuggest : 0) > 0
3450
+ const parts = Object.values((_this$_suggestions$ag = this._suggestions[agentId]) !== null && _this$_suggestions$ag !== void 0 ? _this$_suggestions$ag : {});
3451
+ const isLoading = ((_this$_runningSuggest = (_this$_runningSuggest2 = this._runningSuggestions[agentId]) === null || _this$_runningSuggest2 === void 0 ? void 0 : _this$_runningSuggest2.length) !== null && _this$_runningSuggest !== void 0 ? _this$_runningSuggest : 0) > 0;
3452
+ const cached = this._snapshots.get(agentId);
3453
+ if (cached !== void 0 && cached.result.isLoading === isLoading && cached.parts.length === parts.length && parts.every((part, index) => part === cached.parts[index])) return cached.result;
3454
+ const result = {
3455
+ suggestions: parts.flat(),
3456
+ isLoading
3393
3457
  };
3458
+ this._snapshots.set(agentId, {
3459
+ parts,
3460
+ result
3461
+ });
3462
+ return result;
3463
+ }
3464
+ /** Abort every running suggestion generation. Called by `CopilotKitCore.dispose`. */
3465
+ dispose() {
3466
+ const runs = Object.values(this._runningSuggestions).flat();
3467
+ this._runningSuggestions = {};
3468
+ for (const run of runs) run.abortRun();
3394
3469
  }
3395
3470
  /**
3396
3471
  * Generate suggestions by running a provider agent and extracting the
@@ -3846,14 +3921,14 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3846
3921
  _classPrivateFieldInitSpec(this, _pending, null);
3847
3922
  _classPrivateFieldInitSpec(this, _sealed, false);
3848
3923
  }
3849
- /** Return the active normalized interrupt without exposing mutable state. */
3924
+ /**
3925
+ * Return the active normalized interrupt. A standard interrupt set is a
3926
+ * frozen snapshot, and every read returns the same object until the
3927
+ * interrupt is replaced or cleared, so a framework can compare it by
3928
+ * reference.
3929
+ */
3850
3930
  get pending() {
3851
- const pending = _classPrivateFieldGet2(_pending, this);
3852
- if ((pending === null || pending === void 0 ? void 0 : pending.kind) === "standard") return {
3853
- kind: "standard",
3854
- interrupts: [...pending.interrupts]
3855
- };
3856
- return pending;
3931
+ return _classPrivateFieldGet2(_pending, this);
3857
3932
  }
3858
3933
  /** Replace the current interrupt with a legacy custom-event interrupt. */
3859
3934
  setLegacy(event) {
@@ -3874,10 +3949,10 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3874
3949
  callIds.add(interrupt.toolCallId);
3875
3950
  }
3876
3951
  }
3877
- _assertClassBrand(_ɵInterruptState_brand, this, _replace).call(this, {
3952
+ _assertClassBrand(_ɵInterruptState_brand, this, _replace).call(this, Object.freeze({
3878
3953
  kind: "standard",
3879
- interrupts: [...interrupts]
3880
- });
3954
+ interrupts: Object.freeze([...interrupts])
3955
+ }));
3881
3956
  }
3882
3957
  /** Clear all pending interrupt data and accumulated responses. */
3883
3958
  clear() {
@@ -4206,6 +4281,8 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4206
4281
  _defineProperty(this, "_warnedMissingToolParameters", /* @__PURE__ */ new Set());
4207
4282
  _defineProperty(this, "_runAbortControllers", /* @__PURE__ */ new WeakMap());
4208
4283
  _defineProperty(this, "_runDepths", /* @__PURE__ */ new WeakMap());
4284
+ _defineProperty(this, "_runningAgents", /* @__PURE__ */ new Set());
4285
+ _defineProperty(this, "_disposed", false);
4209
4286
  _defineProperty(this, "_originalAbortRuns", /* @__PURE__ */ new WeakMap());
4210
4287
  _defineProperty(this, "_activeRequestIds", /* @__PURE__ */ new WeakMap());
4211
4288
  _defineProperty(this, "_requestIdByRun", /* @__PURE__ */ new Map());
@@ -4217,7 +4294,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4217
4294
  _defineProperty(this, "_executingToolCalls", /* @__PURE__ */ new WeakMap());
4218
4295
  _defineProperty(this, "_connectionGenerations", /* @__PURE__ */ new WeakMap());
4219
4296
  _defineProperty(this, "_runGenerations", /* @__PURE__ */ new WeakMap());
4220
- _defineProperty(this, "_interactionAbortControllers", /* @__PURE__ */ new WeakMap());
4297
+ _defineProperty(this, "_interactionAbortControllers", /* @__PURE__ */ new Map());
4221
4298
  }
4222
4299
  /**
4223
4300
  * Abort the current run. Called by `CopilotKitCore.stopAgent()` to signal
@@ -4233,6 +4310,30 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4233
4310
  this._executingToolCalls.delete(agent);
4234
4311
  }
4235
4312
  }
4313
+ /**
4314
+ * Stop every run chain and tool interaction this handler tracks, and every
4315
+ * agent in `agents` that reports a run in flight, the same way `stopAgent`
4316
+ * does. Then unregister all WebMCP tools. Called by `CopilotKitCore.dispose`.
4317
+ */
4318
+ dispose(agents) {
4319
+ this._disposed = true;
4320
+ const candidates = new Set([
4321
+ ...agents,
4322
+ ...this._runningAgents,
4323
+ ...this._interactionAbortControllers.keys()
4324
+ ]);
4325
+ for (const agent of candidates) {
4326
+ const hasActiveRun = agent.isRunning || this._runningAgents.has(agent);
4327
+ try {
4328
+ this.abortCurrentRun(agent);
4329
+ if (hasActiveRun) agent.abortRun();
4330
+ } catch (error) {
4331
+ var _agent$agentId;
4332
+ _copilotkit_shared.logger.error(`Failed to stop agent '${(_agent$agentId = agent.agentId) !== null && _agent$agentId !== void 0 ? _agent$agentId : "(unknown agent)"}' on dispose:`, error);
4333
+ }
4334
+ }
4335
+ this._webmcpRegistry.sync(/* @__PURE__ */ new Map());
4336
+ }
4236
4337
  abortAgentRuns(agent) {
4237
4338
  var _this$_runAbortContro;
4238
4339
  for (const controller of (_this$_runAbortContro = this._runAbortControllers.get(agent)) !== null && _this$_runAbortContro !== void 0 ? _this$_runAbortContro : []) controller.abort();
@@ -4275,7 +4376,10 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4275
4376
  if (this._cachedMergedTools) return this._cachedMergedTools;
4276
4377
  const merged = /* @__PURE__ */ new Map();
4277
4378
  for (const tool of this._propTools) merged.set(this.capabilityKey(tool.name, tool.agentId), tool);
4278
- for (const [key, tool] of this._hookTools) merged.set(key, tool);
4379
+ for (const [key, stack] of this._hookTools) {
4380
+ const active = stack[stack.length - 1];
4381
+ if (active) merged.set(key, active.tool);
4382
+ }
4279
4383
  this._cachedMergedTools = Array.from(merged.values());
4280
4384
  return this._cachedMergedTools;
4281
4385
  }
@@ -4291,17 +4395,35 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4291
4395
  /**
4292
4396
  * Add a tool to the registry. Survives provider re-syncs ({@link setTools}),
4293
4397
  * and shadows a provider tool of the same name + agentId.
4398
+ *
4399
+ * Registrations of the same name + agentId stack: the most recent one is
4400
+ * active. Call the returned function to remove exactly this registration;
4401
+ * the previous registration (or the provider tool) becomes active again.
4402
+ * Calling it more than once does nothing.
4294
4403
  */
4295
4404
  addTool(tool) {
4296
4405
  const key = this.capabilityKey(tool.name, tool.agentId);
4297
- if (this._hookTools.has(key)) {
4298
- _copilotkit_shared.logger.warn(`Tool already exists: '${tool.name}' for agent '${tool.agentId || "global"}', skipping.`);
4299
- return;
4300
- }
4301
- this._hookTools.set(key, tool);
4406
+ const registration = { tool };
4407
+ const stack = this._hookTools.get(key);
4408
+ if (stack) {
4409
+ 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.`);
4410
+ stack.push(registration);
4411
+ } else this._hookTools.set(key, [registration]);
4302
4412
  this._cachedMergedTools = null;
4303
4413
  this.warnOnMissingToolParameters([tool]);
4304
4414
  this.syncWebMCP();
4415
+ return () => this.unregisterHookTool(key, registration);
4416
+ }
4417
+ /** Remove one `addTool` registration. Unknown registrations are ignored. */
4418
+ unregisterHookTool(key, registration) {
4419
+ var _stack$indexOf;
4420
+ const stack = this._hookTools.get(key);
4421
+ const index = (_stack$indexOf = stack === null || stack === void 0 ? void 0 : stack.indexOf(registration)) !== null && _stack$indexOf !== void 0 ? _stack$indexOf : -1;
4422
+ if (!stack || index === -1) return;
4423
+ stack.splice(index, 1);
4424
+ if (stack.length === 0) this._hookTools.delete(key);
4425
+ this._cachedMergedTools = null;
4426
+ this.syncWebMCP();
4305
4427
  }
4306
4428
  /**
4307
4429
  * Report, once per tool and at development time only, a tool registered with
@@ -4333,7 +4455,10 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4333
4455
  }
4334
4456
  }
4335
4457
  /**
4336
- * Remove a tool by name and optionally by agentId
4458
+ * Remove a tool by name and optionally by agentId: every `addTool`
4459
+ * registration of that key and the provider tool of that key. Without an
4460
+ * agentId only global tools are removed. To remove one `addTool`
4461
+ * registration and keep the others, call the function `addTool` returned.
4337
4462
  */
4338
4463
  removeTool(id, agentId) {
4339
4464
  this._hookTools.delete(this.capabilityKey(id, agentId));
@@ -4538,6 +4663,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4538
4663
  this._runAbortControllers.set(agent, controllers);
4539
4664
  }
4540
4665
  if (depth === 0) {
4666
+ this._runningAgents.add(agent);
4541
4667
  const originalAbortRun = agent.abortRun;
4542
4668
  this._originalAbortRuns.set(agent, originalAbortRun);
4543
4669
  agent.abortRun = () => {
@@ -4615,6 +4741,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4615
4741
  if ((controllers === null || controllers === void 0 ? void 0 : controllers.size) === 0) this._runAbortControllers.delete(agent);
4616
4742
  }
4617
4743
  if (remainingDepth === 0) {
4744
+ this._runningAgents.delete(agent);
4618
4745
  const originalAbortRun = this._originalAbortRuns.get(agent);
4619
4746
  if (originalAbortRun) {
4620
4747
  agent.abortRun = originalAbortRun;
@@ -5146,6 +5273,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5146
5273
  * agentId — a name collision across agentIds keeps the first registration.
5147
5274
  */
5148
5275
  syncWebMCP() {
5276
+ if (this._disposed) return;
5149
5277
  const desired = /* @__PURE__ */ new Map();
5150
5278
  const warnedCollisions = /* @__PURE__ */ new Set();
5151
5279
  for (const tool of this.tools) {
@@ -5502,6 +5630,11 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5502
5630
  }
5503
5631
  this.rawEventByMessage.delete(agentId);
5504
5632
  }
5633
+ /** Unsubscribe from every agent. Called by `CopilotKitCore.dispose`. */
5634
+ dispose() {
5635
+ const agentIds = [...this.agentSubscriptions.keys()];
5636
+ for (const agentId of agentIds) this.unsubscribeFromAgent(agentId);
5637
+ }
5505
5638
  /**
5506
5639
  * Get state for a specific run
5507
5640
  * Returns a deep copy to prevent external mutations
@@ -7718,7 +7851,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
7718
7851
  return CopilotKitCoreRuntimeConnectionStatus;
7719
7852
  }({});
7720
7853
  var CopilotKitCore = class {
7721
- constructor({ runtimeUrl, runtimeTransport = "auto", deferInitialConnection = false, headers = {}, credentials, messageFilter, properties = {}, agents__unsafe_dev_only = {}, tools = [], suggestionsConfig = [], debug, learning }) {
7854
+ constructor({ runtimeUrl, runtimeTransport = "auto", deferInitialConnection = false, headers = {}, credentials, messageFilter, properties = {}, agents__unsafe_dev_only = {}, tools = [], suggestionsConfig = [], debug, learning, ɵwaitForFrameworkUpdates }) {
7722
7855
  _defineProperty(this, "headerSource", void 0);
7723
7856
  _defineProperty(this, "_credentials", void 0);
7724
7857
  _defineProperty(this, "_messageFilter", void 0);
@@ -7727,6 +7860,8 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
7727
7860
  _defineProperty(this, "_defaultThrottleMs", void 0);
7728
7861
  _defineProperty(this, "_debug", void 0);
7729
7862
  _defineProperty(this, "subscribers", /* @__PURE__ */ new Set());
7863
+ _defineProperty(this, "_disposed", false);
7864
+ _defineProperty(this, "waitForFrameworkUpdates", void 0);
7730
7865
  _defineProperty(this, "agentRegistry", void 0);
7731
7866
  _defineProperty(this, "contextStore", void 0);
7732
7867
  _defineProperty(this, "suggestionEngine", void 0);
@@ -7740,6 +7875,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
7740
7875
  _defineProperty(this, "generativeUIDebugListeners", /* @__PURE__ */ new Set());
7741
7876
  _defineProperty(this, "_memoryStore", void 0);
7742
7877
  _defineProperty(this, "previousAgentIds", /* @__PURE__ */ new Set());
7878
+ this.waitForFrameworkUpdates = ɵwaitForFrameworkUpdates;
7743
7879
  this.headerSource = new HeaderSourceResolver((error) => {
7744
7880
  this.emitError({
7745
7881
  error,
@@ -7793,6 +7929,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
7793
7929
  * Internal method used by delegate classes and subclasses to notify subscribers
7794
7930
  */
7795
7931
  async notifySubscribers(handler, errorMessage) {
7932
+ if (this._disposed) return;
7796
7933
  await Promise.all(Array.from(this.subscribers).map(async (subscriber) => {
7797
7934
  try {
7798
7935
  await handler(subscriber);
@@ -8048,7 +8185,12 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
8048
8185
  });
8049
8186
  }, "Subscriber onHeadersChanged error:");
8050
8187
  }
8188
+ /**
8189
+ * Set the credentials mode for runtime requests (for example `"include"`
8190
+ * to send HTTP-only cookies). Passing the current value does nothing.
8191
+ */
8051
8192
  setCredentials(credentials) {
8193
+ if (credentials === this._credentials) return;
8052
8194
  this._credentials = credentials;
8053
8195
  this.agentRegistry.applyCredentialsToAgents(this.agentRegistry.agents);
8054
8196
  this.agentRegistry.handleCredentialsChanged();
@@ -8058,9 +8200,11 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
8058
8200
  *
8059
8201
  * Applies to agents already discovered as well as ones discovered later, so
8060
8202
  * a filter set before `/info` lands is not lost. Pass `undefined` to go back
8061
- * to sending the full thread.
8203
+ * to sending the full thread. Passing the current filter function again
8204
+ * does nothing.
8062
8205
  */
8063
8206
  setMessageFilter(messageFilter) {
8207
+ if (messageFilter === this._messageFilter) return;
8064
8208
  this._messageFilter = messageFilter;
8065
8209
  this.agentRegistry.applyMessageFilterToAgents(this.agentRegistry.agents);
8066
8210
  }
@@ -8117,7 +8261,14 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
8117
8261
  }
8118
8262
  return merged;
8119
8263
  }
8264
+ /**
8265
+ * Replace the properties sent as `forwardedProps` with every run, and
8266
+ * notify `onPropertiesChanged`. Passing an object with the same keys and
8267
+ * values as the current one does nothing, so a fresh object literal on
8268
+ * every render is safe.
8269
+ */
8120
8270
  setProperties(properties) {
8271
+ if (shallowEqualRecord(properties, this._properties)) return;
8121
8272
  this._properties = properties;
8122
8273
  this.notifySubscribers((subscriber) => {
8123
8274
  var _subscriber$onPropert;
@@ -8128,7 +8279,10 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
8128
8279
  }, "Subscriber onPropertiesChanged error:");
8129
8280
  }
8130
8281
  /**
8131
- * Agent management (delegated to AgentRegistry)
8282
+ * Agent management (delegated to AgentRegistry).
8283
+ *
8284
+ * Replace the local (development) agents. Passing the same ids mapped to
8285
+ * the same agent instances does nothing.
8132
8286
  */
8133
8287
  setAgents__unsafe_dev_only(agents) {
8134
8288
  this.agentRegistry.setAgents__unsafe_dev_only(agents);
@@ -8411,11 +8565,34 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
8411
8565
  return this.suggestionEngine.getSuggestions(agentId);
8412
8566
  }
8413
8567
  /**
8414
- * Tool management (delegated to RunHandler)
8568
+ * Register a frontend tool. It shadows a provider tool (from the `tools`
8569
+ * config or `setTools`) with the same name and agentId.
8570
+ *
8571
+ * A second registration with the same name and agentId shadows the first.
8572
+ * Call the returned function to remove only this registration: the tool it
8573
+ * shadowed becomes active again. Calling it more than once does nothing.
8574
+ *
8575
+ * @param tool - The tool to register.
8576
+ * @returns A function that removes this registration.
8577
+ *
8578
+ * @example
8579
+ * const unregister = copilotkit.addTool({
8580
+ * name: "showWeather",
8581
+ * handler: async ({ city }) => `Sunny in ${city}`,
8582
+ * });
8583
+ * // later
8584
+ * unregister();
8415
8585
  */
8416
8586
  addTool(tool) {
8417
- this.runHandler.addTool(tool);
8587
+ return this.runHandler.addTool(tool);
8418
8588
  }
8589
+ /**
8590
+ * Remove a tool by name, and by agentId when given. This removes every
8591
+ * `addTool` registration with that name and agentId, and the provider tool
8592
+ * with that name and agentId. Without an agentId, only global tools are
8593
+ * removed. To remove one registration, call the function `addTool`
8594
+ * returned.
8595
+ */
8419
8596
  removeTool(id, agentId) {
8420
8597
  this.runHandler.removeTool(id, agentId);
8421
8598
  }
@@ -8666,11 +8843,54 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
8666
8843
  * synchronously while the deferred updates are still pending, producing stale
8667
8844
  * context for the next agent turn.
8668
8845
  *
8669
- * Override in framework-specific subclasses to yield to the framework
8670
- * scheduler before the follow-up run. The base implementation is a no-op
8671
- * because non-React environments have no deferred state to flush.
8846
+ * Awaits the `ɵwaitForFrameworkUpdates` config option when one is given.
8847
+ * Without it there is nothing to wait for, because a plain JavaScript
8848
+ * environment has no deferred state to flush. Framework subclasses that
8849
+ * still override this method keep working.
8672
8850
  */
8673
- async waitForPendingFrameworkUpdates() {}
8851
+ async waitForPendingFrameworkUpdates() {
8852
+ var _this$waitForFramewor;
8853
+ await ((_this$waitForFramewor = this.waitForFrameworkUpdates) === null || _this$waitForFramewor === void 0 ? void 0 : _this$waitForFramewor.call(this));
8854
+ }
8855
+ /**
8856
+ * Stop everything this core started, so it can be dropped without leaks.
8857
+ *
8858
+ * Call it when you created a `CopilotKitCore` yourself and are done with it
8859
+ * (for example when a page or test tears down). Framework providers call it
8860
+ * for you.
8861
+ *
8862
+ * It does this, in order:
8863
+ *
8864
+ * - removes every subscriber, so no callback runs after this call;
8865
+ * - stops agent runs in flight and aborts running frontend tools;
8866
+ * - aborts suggestion generation;
8867
+ * - clears runtime timers and aborts runtime requests it can cancel;
8868
+ * - removes agent subscriptions, WebMCP tools, and the learning capture;
8869
+ * - stops the memory store and every registered thread store.
8870
+ *
8871
+ * Calling it again does nothing. Do not use the core after this call.
8872
+ *
8873
+ * @example
8874
+ * const copilotkit = new CopilotKitCore({ runtimeUrl: "/api/copilotkit" });
8875
+ * // ... use it ...
8876
+ * copilotkit.dispose();
8877
+ */
8878
+ dispose() {
8879
+ var _this$_memoryStore;
8880
+ if (this._disposed) return;
8881
+ this._disposed = true;
8882
+ this.subscribers.clear();
8883
+ this.learningConfiguredListeners.clear();
8884
+ this.generativeUIDebugListeners.clear();
8885
+ this.runHandler.dispose(Object.values(this.agentRegistry.agents));
8886
+ this.suggestionEngine.dispose();
8887
+ this.agentRegistry.dispose();
8888
+ this.stateManager.dispose();
8889
+ this.stopTrajectory();
8890
+ (_this$_memoryStore = this._memoryStore) === null || _this$_memoryStore === void 0 || _this$_memoryStore.stop();
8891
+ const threadStores = Object.values(this.threadStoreRegistry.getAll());
8892
+ for (const store of threadStores) store.stop();
8893
+ }
8674
8894
  };
8675
8895
 
8676
8896
  //#endregion
@@ -8853,23 +9073,6 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
8853
9073
  return result;
8854
9074
  }
8855
9075
 
8856
- //#endregion
8857
- //#region src/utils/markdown/parse.ts
8858
- /**
8859
- * Parse a markdown string into a framework-agnostic token tree.
8860
- *
8861
- * Uses `marked`'s lexer (GFM enabled) so the result is DOM-free and can be
8862
- * walked into React, Vue, or React Native elements by each framework's
8863
- * built-in renderer.
8864
- */
8865
- function parseMarkdown(content, options = {}) {
8866
- const src = !content ? "" : options.complete === false ? content : completePartialMarkdown(content);
8867
- return marked.marked.lexer(src, {
8868
- gfm: true,
8869
- breaks: true
8870
- });
8871
- }
8872
-
8873
9076
  //#endregion
8874
9077
  //#region src/threads.ts
8875
9078
  const THREADS_CHANNEL_EVENT = "thread_metadata";
@@ -11030,16 +11233,1446 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
11030
11233
  });
11031
11234
  }
11032
11235
 
11236
+ //#endregion
11237
+ //#region src/chat/labels.ts
11238
+ /**
11239
+ * The default English text for every word the chat UI shows. React, Vue and
11240
+ * Angular all read their chat text from this one set.
11241
+ *
11242
+ * To change or translate the text, pass a partial set to your framework's chat
11243
+ * configuration. Keys you leave out keep their default:
11244
+ *
11245
+ * ```ts
11246
+ * const labels = { ...CopilotChatDefaultLabels, chatInputPlaceholder: "Ask me" };
11247
+ * ```
11248
+ *
11249
+ * Some values are templates with `{name}` placeholders, such as
11250
+ * `"Thought for {duration}"`. Keep the placeholders when you translate them.
11251
+ *
11252
+ * Counts use two keys: `...One` for a count of 1, and `...Other` for any other
11253
+ * count.
11254
+ */
11255
+ const CopilotChatDefaultLabels = Object.freeze({
11256
+ chatInputPlaceholder: "Type a message...",
11257
+ chatInputToolbarStartTranscribeButtonLabel: "Transcribe",
11258
+ chatInputToolbarCancelTranscribeButtonLabel: "Cancel",
11259
+ chatInputToolbarFinishTranscribeButtonLabel: "Finish",
11260
+ chatInputToolbarAddButtonLabel: "Add attachments",
11261
+ chatInputToolbarToolsButtonLabel: "Tools",
11262
+ chatInputToolbarSendButtonLabel: "Send message",
11263
+ chatInputToolbarStopButtonLabel: "Stop",
11264
+ assistantMessageToolbarCopyCodeLabel: "Copy",
11265
+ assistantMessageToolbarCopyCodeCopiedLabel: "Copied",
11266
+ assistantMessageToolbarCopyMessageLabel: "Copy",
11267
+ assistantMessageToolbarInspectorLabel: "View in Inspector",
11268
+ assistantMessageToolbarInspectorDescription: "Open this message in the Inspector",
11269
+ assistantMessageToolbarInspectorLocalOnlyLabel: "Local only",
11270
+ assistantMessageToolbarInspectorLocalOnlyDescription: "Only visible on localhost or loopback hosts in development. Never shown in production.",
11271
+ assistantMessageToolbarInspectorTitle: "CopilotKit Inspector",
11272
+ assistantMessageToolbarInspectorHideLabel: "Hide this icon",
11273
+ assistantMessageToolbarInspectorHideDescription: "Until you reload this page",
11274
+ assistantMessageToolbarThumbsUpLabel: "Good response",
11275
+ assistantMessageToolbarThumbsDownLabel: "Bad response",
11276
+ assistantMessageFeedbackCommentPlaceholder: "Add a comment (optional)",
11277
+ assistantMessageFeedbackCommentSubmitLabel: "Send comment",
11278
+ assistantMessageToolbarReadAloudLabel: "Read aloud",
11279
+ assistantMessageToolbarRegenerateLabel: "Regenerate",
11280
+ userMessageToolbarCopyMessageLabel: "Copy",
11281
+ userMessageToolbarEditMessageLabel: "Edit",
11282
+ userMessageToolbarPreviousBranchLabel: "Previous branch",
11283
+ userMessageToolbarNextBranchLabel: "Next branch",
11284
+ chatDisclaimerText: "AI can make mistakes. Please verify important information.",
11285
+ chatToggleOpenLabel: "Open chat",
11286
+ chatToggleCloseLabel: "Close chat",
11287
+ chatScrollToBottomLabel: "Scroll to bottom",
11288
+ modalHeaderTitle: "CopilotKit Chat",
11289
+ welcomeMessageText: "How can I help you today?",
11290
+ reasoningMessageThinkingLabel: "Thinking…",
11291
+ chatInputSlashMenuLabel: "Slash commands",
11292
+ chatInputSlashMenuEmptyText: "No commands found",
11293
+ attachmentRemoveButtonLabel: "Remove attachment",
11294
+ attachmentPlayVideoButtonLabel: "Play video",
11295
+ attachmentPreviewCloseButtonLabel: "Close preview",
11296
+ modalHeaderCloseButtonLabel: "Close",
11297
+ modalHeaderThreadsButtonLabel: "Open threads",
11298
+ sidebarLabel: "Copilot chat sidebar",
11299
+ chatDropFilesLabel: "Drop files here",
11300
+ threadLoadErrorText: "Could not load saved conversation. Reopen the thread and try again.",
11301
+ reasoningMessageThoughtForLabel: "Thought for {duration}",
11302
+ reasoningMessageDurationFewSeconds: "a few seconds",
11303
+ reasoningMessageDurationSeconds: "{count} seconds",
11304
+ reasoningMessageDurationMinutesOne: "{count} minute",
11305
+ reasoningMessageDurationMinutesOther: "{count} minutes",
11306
+ reasoningMessageDurationMinutesSeconds: "{minutes}m {seconds}s",
11307
+ toolCallStatusRunningLabel: "Running",
11308
+ toolCallStatusDoneLabel: "Done",
11309
+ toolCallStatusFailedLabel: "Failed",
11310
+ toolCallStatusStoppedLabel: "Stopped",
11311
+ toolCallRunningLabel: "Running {name}",
11312
+ toolCallFailedCountLabel: "{count} failed",
11313
+ toolCallDoneCountLabel: "{count} done",
11314
+ toolCallArgumentsLabel: "Arguments",
11315
+ toolCallResultLabel: "Result",
11316
+ toolCallCollapseLabel: "Collapse",
11317
+ toolCallUsedToolsOne: "Used {count} tool",
11318
+ toolCallUsedToolsOther: "Used {count} tools",
11319
+ toolCallToolCountOne: "{count} tool",
11320
+ toolCallToolCountOther: "{count} tools",
11321
+ toolCallToolCallCountOne: "{count} tool call",
11322
+ toolCallToolCallCountOther: "{count} tool calls",
11323
+ toolCallCallCountOne: "{count} call",
11324
+ toolCallCallCountOther: "{count} calls",
11325
+ workSummaryWorkingLabel: "Working",
11326
+ workSummaryWorkedForLabel: "Worked for {duration}",
11327
+ attachmentImageLoadErrorText: "Failed to load image",
11328
+ attachmentImageAltText: "Image attachment",
11329
+ attachmentUnknownTypeText: "Unknown type",
11330
+ attachmentDocumentLabel: "Document",
11331
+ attachmentDocumentAltText: "Document attachment",
11332
+ attachmentNoPreviewText: "No preview available for this file type",
11333
+ chatAttachmentsUploadingText: "Cannot send while attachments are uploading.",
11334
+ transcriptionErrorRateLimitedText: "Too many requests. Please wait a moment.",
11335
+ transcriptionErrorAuthFailedText: "Authentication error. Please check your configuration.",
11336
+ transcriptionErrorAudioTooLongText: "Recording is too long. Please try a shorter recording.",
11337
+ transcriptionErrorAudioTooShortText: "Recording is too short. Please try again.",
11338
+ transcriptionErrorInvalidAudioFormatText: "Audio format not supported.",
11339
+ transcriptionErrorServiceNotConfiguredText: "Transcription service is not available.",
11340
+ transcriptionErrorNetworkText: "Network error. Please check your connection.",
11341
+ transcriptionErrorGenericText: "Transcription failed. Please try again.",
11342
+ licensePoweredByText: "Powered by CopilotKit",
11343
+ licenseGetLicenseLabel: "Get a license",
11344
+ licenseFeatureUnlicensedText: "⚠ The \"{feature}\" feature requires a CopilotKit license.",
11345
+ licenseExpiringText: "Your CopilotKit license expires soon. Please renew.",
11346
+ licenseExpiringInDaysOne: "Your CopilotKit license expires in {days} day. Please renew.",
11347
+ licenseExpiringInDaysOther: "Your CopilotKit license expires in {days} days. Please renew.",
11348
+ licenseExpiredText: "Your CopilotKit license expired. Please renew at copilotkit.ai/pricing",
11349
+ licenseExpiredOnDateText: "Your CopilotKit license expired on {date}. Please renew at copilotkit.ai/pricing",
11350
+ licenseInvalidText: "Invalid CopilotKit license token. Please check your configuration.",
11351
+ licenseRenewLabel: "Renew",
11352
+ licenseRenewNowLabel: "Renew now"
11353
+ });
11354
+ /**
11355
+ * Puts values into a label template. Each `{name}` in the template is replaced
11356
+ * by `values[name]`. A placeholder with no value stays in the text as is.
11357
+ *
11358
+ * @param template - A label value, such as `"Running {name}"`.
11359
+ * @param values - The value for each placeholder.
11360
+ *
11361
+ * ```ts
11362
+ * ɵformatLabel(labels.toolCallRunningLabel, { name: "read_file" });
11363
+ * // "Running read_file"
11364
+ * ```
11365
+ */
11366
+ function ɵformatLabel(template, values) {
11367
+ return template.replace(/\{(\w+)\}/g, (placeholder, name) => Object.hasOwn(values, name) ? String(values[name]) : placeholder);
11368
+ }
11369
+ /**
11370
+ * Fills a counted label pair: the `one` template for a count of 1, the
11371
+ * `other` template for any other count. Both templates take `{count}`.
11372
+ *
11373
+ * @param count - The number to show.
11374
+ * @param templates - The `...One` and `...Other` label templates.
11375
+ *
11376
+ * ```ts
11377
+ * ɵformatCountLabel(3, {
11378
+ * one: labels.toolCallToolCountOne,
11379
+ * other: labels.toolCallToolCountOther,
11380
+ * }); // "3 tools"
11381
+ * ```
11382
+ */
11383
+ function ɵformatCountLabel(count, templates) {
11384
+ return ɵformatLabel(count === 1 ? templates.one : templates.other, { count });
11385
+ }
11386
+
11387
+ //#endregion
11388
+ //#region src/chat/renderers.ts
11389
+ /** Name or activity type that matches anything. */
11390
+ const WILDCARD = "*";
11391
+ /**
11392
+ * Find the renderer that draws a tool call.
11393
+ *
11394
+ * The first rule that matches wins:
11395
+ *
11396
+ * 1. A renderer for `toolName` with `agentId` equal to the current agent.
11397
+ * 2. A renderer for `toolName` with no `agentId`.
11398
+ * 3. The first renderer for `toolName` from any other agent.
11399
+ * 4. The first `"*"` renderer, from any agent.
11400
+ *
11401
+ * Inside each rule, the earlier renderer in the list wins.
11402
+ *
11403
+ * @param renderers - Registered renderers in registration order. If you
11404
+ * build tiers (for example app renderers before built-in ones), flatten
11405
+ * them into one ordered list first.
11406
+ * @param toolName - Name of the tool the agent called.
11407
+ * @param agentId - The agent that owns the chat. The caller picks the
11408
+ * default: React and Vue pass `DEFAULT_AGENT_ID` when the chat has no
11409
+ * agent. With `undefined`, rule 1 matches the same renderers as rule 2.
11410
+ * @returns The renderer, or `null` when no renderer matches. Draw nothing
11411
+ * for `null`.
11412
+ *
11413
+ * @example
11414
+ * ```ts
11415
+ * const renderer = ɵresolveToolCallRenderer(
11416
+ * core.renderToolCalls,
11417
+ * toolCall.function.name,
11418
+ * chatAgentId ?? DEFAULT_AGENT_ID,
11419
+ * );
11420
+ * ```
11421
+ */
11422
+ function ɵresolveToolCallRenderer(renderers, toolName, agentId) {
11423
+ var _ref, _ref2, _ref3, _named$find;
11424
+ const named = renderers.filter((renderer) => renderer.name === toolName);
11425
+ return (_ref = (_ref2 = (_ref3 = (_named$find = named.find((renderer) => renderer.agentId === agentId)) !== null && _named$find !== void 0 ? _named$find : named.find((renderer) => !renderer.agentId)) !== null && _ref3 !== void 0 ? _ref3 : named[0]) !== null && _ref2 !== void 0 ? _ref2 : renderers.find((renderer) => renderer.name === WILDCARD)) !== null && _ref !== void 0 ? _ref : null;
11426
+ }
11427
+ /**
11428
+ * Find the renderer that draws an activity message, and validate the
11429
+ * message content with that renderer's `content` schema.
11430
+ *
11431
+ * The first rule that matches picks the renderer:
11432
+ *
11433
+ * 1. A renderer for `activityType` with `agentId` equal to the current agent.
11434
+ * 2. A renderer for `activityType` with no `agentId`.
11435
+ * 3. The first `"*"` renderer, from any agent.
11436
+ *
11437
+ * A renderer for `activityType` that belongs to a different agent never
11438
+ * matches. Inside each rule, the earlier renderer in the list wins.
11439
+ *
11440
+ * Only the picked renderer validates the content. When validation fails, or
11441
+ * the schema validates asynchronously, the result is `null`. The function
11442
+ * does not try the next renderer.
11443
+ *
11444
+ * @param renderers - Registered renderers in registration order.
11445
+ * @param query - The activity type, the current agent, and the raw content.
11446
+ * @returns `{ renderer, content }`, where `content` is the value the schema
11447
+ * returned. Pass that value to `render`, not the raw content. Returns
11448
+ * `null` when no renderer matches or validation does not pass.
11449
+ *
11450
+ * @example
11451
+ * ```ts
11452
+ * const match = ɵresolveActivityRenderer(core.renderActivityMessages, {
11453
+ * activityType: message.activityType,
11454
+ * agentId,
11455
+ * content: message.content,
11456
+ * });
11457
+ * if (match) draw(match.renderer.render, match.content);
11458
+ * ```
11459
+ */
11460
+ function ɵresolveActivityRenderer(renderers, query) {
11461
+ var _ref4, _sameType$find;
11462
+ const { activityType, agentId, content } = query;
11463
+ const sameType = renderers.filter((renderer) => renderer.activityType === activityType);
11464
+ const renderer = (_ref4 = (_sameType$find = sameType.find((candidate) => candidate.agentId === agentId)) !== null && _sameType$find !== void 0 ? _sameType$find : sameType.find((candidate) => candidate.agentId === void 0)) !== null && _ref4 !== void 0 ? _ref4 : renderers.find((candidate) => candidate.activityType === WILDCARD);
11465
+ if (renderer === void 0) return null;
11466
+ const result = renderer.content["~standard"].validate(content);
11467
+ if (result instanceof Promise) return null;
11468
+ if (result.issues) return null;
11469
+ return {
11470
+ renderer,
11471
+ content: result.value
11472
+ };
11473
+ }
11474
+ /**
11475
+ * List the custom message renderers that apply to an agent, in the order to
11476
+ * try them.
11477
+ *
11478
+ * The list keeps renderers with no `agentId` and renderers for `agentId`.
11479
+ * Renderers for `agentId` come first. Inside each group, registration order
11480
+ * stays the same.
11481
+ *
11482
+ * The framework tries each renderer in this order and shows the first one
11483
+ * that draws something (a non-null result).
11484
+ *
11485
+ * @param renderers - Registered renderers in registration order.
11486
+ * @param agentId - The agent that owns the chat.
11487
+ * @returns A new array. Empty when no renderer applies.
11488
+ *
11489
+ * @example
11490
+ * ```ts
11491
+ * const candidates = ɵresolveCustomMessageRenderers(
11492
+ * core.renderCustomMessages,
11493
+ * agentId,
11494
+ * );
11495
+ * ```
11496
+ */
11497
+ function ɵresolveCustomMessageRenderers(renderers, agentId) {
11498
+ const scoped = renderers.filter((renderer) => renderer.agentId === agentId);
11499
+ const unscoped = renderers.filter((renderer) => renderer.agentId === void 0);
11500
+ return [...scoped, ...unscoped];
11501
+ }
11502
+
11503
+ //#endregion
11504
+ //#region src/chat/interrupt-types.ts
11505
+ /** Name of the legacy custom event agents emit to signal an interrupt. */
11506
+ const INTERRUPT_EVENT_NAME = "on_interrupt";
11507
+
11508
+ //#endregion
11509
+ //#region src/chat/tool-call-layout.ts
11510
+ function contentLength(content) {
11511
+ return typeof content === "string" ? content.length : JSON.stringify(content !== null && content !== void 0 ? content : "").length;
11512
+ }
11513
+ const entrySignature = ({ toolCall, toolMessage }) => [
11514
+ toolCall.id,
11515
+ toolCall.function.name,
11516
+ toolCall.function.arguments.length,
11517
+ toolMessage ? `${contentLength(toolMessage.content)}${toolMessage.error ? "!" : ""}` : "-"
11518
+ ].join(":");
11519
+ function signatureOf(segments) {
11520
+ return segments.map((segment) => segment.kind === "call" ? `c(${entrySignature(segment.call)})` : `g${segment.trailing ? "*" : ""}(${segment.calls.map(entrySignature).join(",")})`).join("|");
11521
+ }
11522
+ /**
11523
+ * Indexes tool results by the id of the call they answer.
11524
+ *
11525
+ * @param messages - The messages to search. Only `role: "tool"` messages count.
11526
+ */
11527
+ function getToolResults(messages) {
11528
+ const results = /* @__PURE__ */ new Map();
11529
+ for (const message of messages) if (message.role === "tool") results.set(message.toolCallId, message);
11530
+ return results;
11531
+ }
11532
+ /**
11533
+ * Lays out the tool calls of every assistant message in `rendered`.
11534
+ *
11535
+ * Calls drawn by a renderer that opted into grouping join the group that is
11536
+ * open. Anything else that shows between them closes it: assistant text, a
11537
+ * user, reasoning or activity message, or a call drawn by any other renderer.
11538
+ * A group belongs to the message where it starts, so later messages whose
11539
+ * calls joined it render no tool calls themselves.
11540
+ *
11541
+ * @param rendered - The messages as the chat renders them, in order.
11542
+ * @param all - Every message, for finding tool results (a transform may hide them).
11543
+ * @param renderers - The registered renderers, from `getToolCallRendererNames`.
11544
+ * @returns A map from assistant message id to its layout.
11545
+ *
11546
+ * @example
11547
+ * ```ts
11548
+ * const names = getToolCallRendererNames(core.renderToolCalls);
11549
+ * const layouts = getToolCallLayouts(renderedMessages, messages, names);
11550
+ * layouts.get(message.id)?.segments;
11551
+ * ```
11552
+ */
11553
+ function getToolCallLayouts(rendered, all, renderers) {
11554
+ const results = getToolResults(all);
11555
+ const layouts = /* @__PURE__ */ new Map();
11556
+ let open;
11557
+ for (const message of rendered) {
11558
+ var _message$toolCalls;
11559
+ if (message.role === "tool") continue;
11560
+ if (message.role !== "assistant") {
11561
+ open = void 0;
11562
+ continue;
11563
+ }
11564
+ if (typeof message.content === "string" && message.content.trim() !== "") open = void 0;
11565
+ const segments = [];
11566
+ layouts.set(message.id, segments);
11567
+ const toolCalls = /* @__PURE__ */ new Map();
11568
+ const messageToolCalls = (_message$toolCalls = message.toolCalls) !== null && _message$toolCalls !== void 0 ? _message$toolCalls : [];
11569
+ for (const toolCall of messageToolCalls) toolCalls.set(toolCall.id, toolCall);
11570
+ const uniqueToolCalls = toolCalls.values();
11571
+ for (const toolCall of uniqueToolCalls) {
11572
+ const entry = {
11573
+ toolCall,
11574
+ toolMessage: results.get(toolCall.id)
11575
+ };
11576
+ const name = toolCall.function.name;
11577
+ const named = renderers.named.has(name);
11578
+ const isRendered = named || renderers.wildcard;
11579
+ const groups = named ? renderers.groupedNames.has(name) : renderers.wildcardGroups;
11580
+ if (!isRendered || !groups) {
11581
+ if (isRendered) open = void 0;
11582
+ segments.push({
11583
+ kind: "call",
11584
+ id: toolCall.id,
11585
+ call: entry,
11586
+ rendered: isRendered
11587
+ });
11588
+ } else if (open) open.calls.push(entry);
11589
+ else {
11590
+ open = {
11591
+ kind: "group",
11592
+ id: toolCall.id,
11593
+ calls: [entry],
11594
+ trailing: false
11595
+ };
11596
+ segments.push(open);
11597
+ }
11598
+ }
11599
+ }
11600
+ if (open) open.trailing = true;
11601
+ const layout = /* @__PURE__ */ new Map();
11602
+ for (const [id, segments] of layouts) layout.set(id, {
11603
+ segments,
11604
+ signature: signatureOf(segments)
11605
+ });
11606
+ return layout;
11607
+ }
11608
+ const TOOL_CALL_SLOT_PREFIX = "tool-call-";
11609
+ const WILDCARD_TOOL_CALL_SLOT = "tool-call";
11610
+ /**
11611
+ * Works out which tool calls have a renderer and which of those group, for
11612
+ * `getToolCallLayouts`.
11613
+ *
11614
+ * @param renderers - The registered renderers. A renderer named `"*"` is the
11615
+ * wildcard. `group: true` opts the renderer into grouping.
11616
+ * @param options - Slots, extra named tools, and a built-in wildcard card.
11617
+ * See `ToolCallRendererNamesOptions`.
11618
+ *
11619
+ * @example
11620
+ * ```ts
11621
+ * // React: only registered renderers.
11622
+ * getToolCallRendererNames(core.renderToolCalls);
11623
+ * // Vue: the view's slots count too.
11624
+ * getToolCallRendererNames(core.renderToolCalls, { slotNames: Object.keys(slots) });
11625
+ * // Angular: client and human-in-the-loop renderers, and the built-in card.
11626
+ * getToolCallRendererNames(appRenderers, {
11627
+ * extraNamed: [...clientNames, ...hitlNames],
11628
+ * builtInWildcard: { enabled: defaultToolRenderingEnabled, groups: true },
11629
+ * });
11630
+ * ```
11631
+ */
11632
+ function getToolCallRendererNames(renderers, options = {}) {
11633
+ var _builtInWildcard$enab, _builtInWildcard$grou;
11634
+ const { slotNames = [], extraNamed = [], builtInWildcard } = options;
11635
+ const hasWildcardSlot = slotNames.includes(WILDCARD_TOOL_CALL_SLOT);
11636
+ const slotTools = slotNames.filter((name) => name.startsWith(TOOL_CALL_SLOT_PREFIX)).map((name) => name.slice(10));
11637
+ const named = renderers.filter((renderer) => renderer.name !== "*");
11638
+ const wildcards = renderers.filter((renderer) => renderer.name === "*");
11639
+ const hasAppWildcard = wildcards.length > 0;
11640
+ const isBuiltInEnabled = (_builtInWildcard$enab = builtInWildcard === null || builtInWildcard === void 0 ? void 0 : builtInWildcard.enabled) !== null && _builtInWildcard$enab !== void 0 ? _builtInWildcard$enab : false;
11641
+ const builtInGroups = isBuiltInEnabled && ((_builtInWildcard$grou = builtInWildcard === null || builtInWildcard === void 0 ? void 0 : builtInWildcard.groups) !== null && _builtInWildcard$grou !== void 0 ? _builtInWildcard$grou : false);
11642
+ const groupedNames = hasWildcardSlot ? [] : named.filter((renderer) => renderer.group && !slotTools.includes(renderer.name)).map((renderer) => renderer.name);
11643
+ const appWildcardGroups = wildcards.some((renderer) => renderer.group);
11644
+ return {
11645
+ named: new Set([
11646
+ ...named.map((renderer) => renderer.name),
11647
+ ...slotTools,
11648
+ ...extraNamed
11649
+ ]),
11650
+ groupedNames: new Set(groupedNames),
11651
+ wildcard: hasAppWildcard || hasWildcardSlot || isBuiltInEnabled,
11652
+ wildcardGroups: !hasWildcardSlot && (hasAppWildcard ? appWildcardGroups : builtInGroups)
11653
+ };
11654
+ }
11655
+ /** The turn key of a reply that no user message starts. */
11656
+ const FIRST_TURN_KEY = "start";
11657
+ /**
11658
+ * Finds the working phase of every reply in `rendered`: its messages up to the
11659
+ * last one that calls a tool. Text in there was narration. What follows is the
11660
+ * reply itself. Replies that called no tools are left out, except the latest,
11661
+ * which may be about to.
11662
+ *
11663
+ * @param rendered - The messages as the chat renders them, in order.
11664
+ * @param layouts - The layouts from `getToolCallLayouts` for the same messages.
11665
+ * @returns A map from turn key (see `TurnWork.key`) to the turn's work.
11666
+ */
11667
+ function getTurnWork(rendered, layouts) {
11668
+ const turns = /* @__PURE__ */ new Map();
11669
+ let start = 0;
11670
+ while (start < rendered.length) {
11671
+ let end = start;
11672
+ while (end < rendered.length && rendered[end].role !== "user") end++;
11673
+ const key = start > 0 ? rendered[start - 1].id : FIRST_TURN_KEY;
11674
+ const visible = rendered.slice(start, end).filter((message) => message.role !== "tool");
11675
+ const isLatest = end === rendered.length;
11676
+ const calls = [];
11677
+ for (const message of visible) {
11678
+ var _layouts$get$segments, _layouts$get;
11679
+ const segments = (_layouts$get$segments = (_layouts$get = layouts.get(message.id)) === null || _layouts$get === void 0 ? void 0 : _layouts$get.segments) !== null && _layouts$get$segments !== void 0 ? _layouts$get$segments : [];
11680
+ for (const segment of segments) if (segment.kind === "group") calls.push(...segment.calls);
11681
+ else if (segment.rendered) calls.push(segment.call);
11682
+ }
11683
+ const shown = new Set(calls.map((entry) => entry.toolCall.id));
11684
+ let lastWork = -1;
11685
+ visible.forEach((message, index) => {
11686
+ var _message$toolCalls2;
11687
+ if (message.role === "assistant" && ((_message$toolCalls2 = message.toolCalls) === null || _message$toolCalls2 === void 0 ? void 0 : _message$toolCalls2.some((call) => shown.has(call.id)))) lastWork = index;
11688
+ });
11689
+ const first = visible[0];
11690
+ if (first && (calls.length > 0 || isLatest)) {
11691
+ var _visible$lastAssistan;
11692
+ let lastAssistant = -1;
11693
+ visible.forEach((message, index) => {
11694
+ if (message.role === "assistant") lastAssistant = index;
11695
+ });
11696
+ const replyText = (_visible$lastAssistan = visible[lastAssistant]) === null || _visible$lastAssistan === void 0 ? void 0 : _visible$lastAssistan.content;
11697
+ const endsWithWork = lastAssistant >= 0 && lastAssistant <= lastWork && typeof replyText === "string" && replyText.trim().length > 0;
11698
+ turns.set(key, {
11699
+ key,
11700
+ firstMessageId: first.id,
11701
+ workMessageIds: new Set(visible.slice(0, lastWork + 1).map((message) => message.id)),
11702
+ replyTextMessageId: endsWithWork ? visible[lastAssistant].id : void 0,
11703
+ calls,
11704
+ isLatest
11705
+ });
11706
+ }
11707
+ start = end + 1;
11708
+ }
11709
+ return turns;
11710
+ }
11711
+ /**
11712
+ * The key of the latest reply (see `TurnWork.key`): the id of the last user
11713
+ * message, or `"start"` when there is none.
11714
+ *
11715
+ * @param rendered - The messages as the chat renders them, in order.
11716
+ */
11717
+ function getLatestTurnKey(rendered) {
11718
+ for (let i = rendered.length - 1; i >= 0; i--) {
11719
+ const message = rendered[i];
11720
+ if (message.role === "user") return message.id;
11721
+ }
11722
+ return FIRST_TURN_KEY;
11723
+ }
11724
+ /**
11725
+ * Whether the agent is working on this reply now: it is the latest one and a
11726
+ * run is going.
11727
+ *
11728
+ * @param turnKey - The reply's `TurnWork.key`.
11729
+ * @param state - The run state and the latest turn key.
11730
+ */
11731
+ function isTurnWorking(turnKey, state) {
11732
+ return state.isRunning && turnKey === state.latestTurnKey;
11733
+ }
11734
+ /**
11735
+ * Whether a reply's work shows. It shows while the agent works on the reply
11736
+ * and folds once the reply is done, unless the user opened or closed it.
11737
+ *
11738
+ * @param turnKey - The reply's `TurnWork.key`.
11739
+ * @param state - The user's toggles, the run state, and the latest turn key.
11740
+ */
11741
+ function isTurnWorkOpen(turnKey, state) {
11742
+ var _state$toggledTurns$g;
11743
+ return (_state$toggledTurns$g = state.toggledTurns.get(turnKey)) !== null && _state$toggledTurns$g !== void 0 ? _state$toggledTurns$g : isTurnWorking(turnKey, state);
11744
+ }
11745
+ /**
11746
+ * For each message in a reply's working phase, whether its work and its text
11747
+ * show. Text that ends the reply stays out of `workTextOpen` even when its
11748
+ * message also calls a tool, because it is the answer.
11749
+ *
11750
+ * @param turns - The turns from `getTurnWork`.
11751
+ * @param state - The user's toggles, the run state, and the latest turn key.
11752
+ * @returns The `workOpen` and `workTextOpen` maps of `ToolCallDisplayContextValue`.
11753
+ */
11754
+ function getWorkOpenState(turns, state) {
11755
+ const workOpen = /* @__PURE__ */ new Map();
11756
+ const workTextOpen = /* @__PURE__ */ new Map();
11757
+ for (const turn of turns) {
11758
+ const turnOpen = isTurnWorkOpen(turn.key, state);
11759
+ for (const id of turn.workMessageIds) {
11760
+ workOpen.set(id, turnOpen);
11761
+ if (id !== turn.replyTextMessageId) workTextOpen.set(id, turnOpen);
11762
+ }
11763
+ }
11764
+ return {
11765
+ workOpen,
11766
+ workTextOpen
11767
+ };
11768
+ }
11769
+ /**
11770
+ * Records run starts and ends in `workTimes`, for "Worked for 9s". Time spent
11771
+ * between runs (say, waiting for an approval) does not count. A reply is only
11772
+ * timed when this client saw it start from the user's message, so a restored
11773
+ * thread gets no entry. Calling it again with the same state changes nothing.
11774
+ *
11775
+ * @param workTimes - The times by turn key. This function updates it in place.
11776
+ * @param state - The run state now.
11777
+ * @param state.lastMessageRole - The role of the last rendered message.
11778
+ * @param state.now - The current time, in epoch ms.
11779
+ */
11780
+ function recordWorkTime(workTimes, state) {
11781
+ const { isRunning, latestTurnKey, lastMessageRole, now } = state;
11782
+ if (isRunning) {
11783
+ var _times$workingSince;
11784
+ const times = workTimes.get(latestTurnKey);
11785
+ if (times) (_times$workingSince = times.workingSince) !== null && _times$workingSince !== void 0 || (times.workingSince = now);
11786
+ else if (lastMessageRole === "user") workTimes.set(latestTurnKey, {
11787
+ elapsedMs: 0,
11788
+ workingSince: now
11789
+ });
11790
+ return;
11791
+ }
11792
+ const allTimes = workTimes.values();
11793
+ for (const times of allTimes) {
11794
+ if (times.workingSince === void 0) continue;
11795
+ times.elapsedMs += now - times.workingSince;
11796
+ times.workingSince = void 0;
11797
+ }
11798
+ }
11799
+ /**
11800
+ * The status of one call in a group. A call without a result is running only
11801
+ * while the group is active: once the run has moved on or ended, its result
11802
+ * is never coming.
11803
+ *
11804
+ * @param entry - The call and its result, if any.
11805
+ * @param active - The agent may still finish the group's calls.
11806
+ */
11807
+ function getToolCallRowStatus(entry, active) {
11808
+ const { toolMessage } = entry;
11809
+ let status;
11810
+ if (toolMessage) status = toolMessage.error ? "failed" : "done";
11811
+ else status = active ? "running" : "stopped";
11812
+ return status;
11813
+ }
11814
+ /**
11815
+ * The first non-empty string argument, with runs of whitespace collapsed to
11816
+ * one space. This is usually a command, path or query.
11817
+ *
11818
+ * @param parameters - The call's parsed arguments.
11819
+ * @returns The preview, or `undefined` when no argument is a non-empty string.
11820
+ */
11821
+ function getArgumentPreview(parameters) {
11822
+ if (!parameters || typeof parameters !== "object") return void 0;
11823
+ const value = Object.values(parameters).find((v) => typeof v === "string" && v.trim().length > 0);
11824
+ return value === null || value === void 0 ? void 0 : value.replace(/\s+/g, " ");
11825
+ }
11826
+ /**
11827
+ * `getArgumentPreview` for a call whose arguments may still be streaming in
11828
+ * as partial JSON.
11829
+ *
11830
+ * @param entry - The call.
11831
+ */
11832
+ function getToolCallPreview(entry) {
11833
+ return getArgumentPreview((0, _copilotkit_shared.partialJSONParse)(entry.toolCall.function.arguments));
11834
+ }
11835
+ /**
11836
+ * The names of the tools the calls used, in first-use order, with a count
11837
+ * for repeats: `"run_command ×2, read_file"`.
11838
+ *
11839
+ * @param calls - The calls to name.
11840
+ */
11841
+ function formatToolNames(calls) {
11842
+ const counts = /* @__PURE__ */ new Map();
11843
+ for (const { toolCall } of calls) {
11844
+ var _counts$get;
11845
+ const name = toolCall.function.name;
11846
+ counts.set(name, ((_counts$get = counts.get(name)) !== null && _counts$get !== void 0 ? _counts$get : 0) + 1);
11847
+ }
11848
+ return [...counts].map(([name, count]) => count > 1 ? `${name} ×${count}` : name).join(", ");
11849
+ }
11850
+ /**
11851
+ * How many of the calls finished with an error.
11852
+ *
11853
+ * @param calls - The calls to count.
11854
+ */
11855
+ function countFailedToolCalls(calls) {
11856
+ return calls.filter((call) => {
11857
+ var _call$toolMessage;
11858
+ return (_call$toolMessage = call.toolMessage) === null || _call$toolMessage === void 0 ? void 0 : _call$toolMessage.error;
11859
+ }).length;
11860
+ }
11861
+ /**
11862
+ * A count followed by the word that fits it: `"1 tool"`, `"3 tools"`.
11863
+ *
11864
+ * @param count - The number to show.
11865
+ * @param words - The word for exactly one (`one`) and for any other count (`other`).
11866
+ *
11867
+ * @example
11868
+ * ```ts
11869
+ * pluralize(3, { one: "tool", other: "tools" }); // "3 tools"
11870
+ * ```
11871
+ */
11872
+ function pluralize(count, words) {
11873
+ return `${count} ${count === 1 ? words.one : words.other}`;
11874
+ }
11875
+ /**
11876
+ * A tool call's arguments or result as display text. Strings pass through.
11877
+ * Other values are pretty-printed JSON. A value JSON cannot encode (say, a
11878
+ * circular reference) falls back to `String(value)`, then to
11879
+ * `"[unserializable]"`, so it never throws during a render.
11880
+ *
11881
+ * @param value - The arguments or the result.
11882
+ */
11883
+ function stringifyToolCallPayload(value) {
11884
+ if (typeof value === "string") return value;
11885
+ try {
11886
+ return JSON.stringify(value, null, 2);
11887
+ } catch (err) {
11888
+ console.warn("[CopilotKit] Failed to JSON.stringify tool-call payload; falling back to String():", err);
11889
+ try {
11890
+ return String(value);
11891
+ } catch (_unused) {
11892
+ return "[unserializable]";
11893
+ }
11894
+ }
11895
+ }
11896
+ /**
11897
+ * How long a `"turn"` reply worked, as short text: `"45s"`, `"1m 5s"`, `"2m"`.
11898
+ * Used for the live timer and the final duration. Partial seconds round down,
11899
+ * and a negative time reads `"0s"`.
11900
+ *
11901
+ * @param ms - The time in milliseconds.
11902
+ */
11903
+ function formatWorkDuration(ms) {
11904
+ const seconds = Math.max(0, Math.floor(ms / 1e3));
11905
+ if (seconds < 60) return `${seconds}s`;
11906
+ const minutes = Math.floor(seconds / 60);
11907
+ const rest = seconds % 60;
11908
+ return rest ? `${minutes}m ${rest}s` : `${minutes}m`;
11909
+ }
11910
+ /**
11911
+ * Splits a reasoning time into the unit and counts the "Thought for ..."
11912
+ * header shows. See `ReasoningDuration` for the text each unit maps to.
11913
+ *
11914
+ * - Under 1 second: `fewSeconds`.
11915
+ * - Under 60 seconds: `seconds`, rounded to the nearest second.
11916
+ * - Whole minutes after rounding the seconds: `minutes`.
11917
+ * - Otherwise: `minutesSeconds`.
11918
+ *
11919
+ * @param seconds - The elapsed time in seconds. It may have a fraction.
11920
+ */
11921
+ function formatReasoningDuration(seconds) {
11922
+ if (seconds < 1) return { unit: "fewSeconds" };
11923
+ if (seconds < 60) return {
11924
+ unit: "seconds",
11925
+ seconds: Math.round(seconds)
11926
+ };
11927
+ const minutes = Math.floor(seconds / 60);
11928
+ const rest = Math.round(seconds % 60);
11929
+ if (rest === 0) return {
11930
+ unit: "minutes",
11931
+ minutes
11932
+ };
11933
+ return {
11934
+ unit: "minutesSeconds",
11935
+ minutes,
11936
+ seconds: rest
11937
+ };
11938
+ }
11939
+
11940
+ //#endregion
11941
+ //#region src/chat/messages.ts
11942
+ /**
11943
+ * Collapses tool calls that share an id, keeping first-seen order.
11944
+ *
11945
+ * AG-UI's TOOL_CALL_START handler appends to the parent message's `toolCalls`
11946
+ * without checking whether that id is already present. When a start event is
11947
+ * applied twice (the human-in-the-loop flow does this when the run syncs after
11948
+ * `respond()`), the message carries the same call twice. The second copy has
11949
+ * empty `arguments`, because a start event carries none. The args arrive later
11950
+ * as TOOL_CALL_ARGS deltas addressed to the first copy.
11951
+ *
11952
+ * Left alone, the same tool call renders twice: once populated and once blank.
11953
+ * The blank copy is the redundant one, so the copy that carries arguments wins,
11954
+ * whatever order the two arrive in.
11955
+ *
11956
+ * @param toolCalls - The tool calls of one assistant message.
11957
+ * @returns The same array when no id repeats, so memoized consumers keep a
11958
+ * stable reference. Otherwise a new array with one entry per id.
11959
+ */
11960
+ function dedupeToolCalls(toolCalls) {
11961
+ const byId = /* @__PURE__ */ new Map();
11962
+ for (const toolCall of toolCalls) {
11963
+ var _existing$function, _toolCall$function;
11964
+ const existing = byId.get(toolCall.id);
11965
+ if (!existing) {
11966
+ byId.set(toolCall.id, toolCall);
11967
+ continue;
11968
+ }
11969
+ if (!((_existing$function = existing.function) === null || _existing$function === void 0 ? void 0 : _existing$function.arguments) && Boolean((_toolCall$function = toolCall.function) === null || _toolCall$function === void 0 ? void 0 : _toolCall$function.arguments)) byId.set(toolCall.id, toolCall);
11970
+ }
11971
+ return byId.size === toolCalls.length ? toolCalls : [...byId.values()];
11972
+ }
11973
+ /**
11974
+ * Merges two snapshots of the same assistant message.
11975
+ *
11976
+ * - Empty `content` means a streaming update cleared the field, so the earlier
11977
+ * non-empty content is kept.
11978
+ * - `toolCalls: undefined` means the later chunk had no tool-call activity, so
11979
+ * the earlier tool calls are kept. An explicit `[]` is kept as-is.
11980
+ * - Fields that only the earlier snapshot has are kept.
11981
+ */
11982
+ function mergeAssistantMessages(existing, message) {
11983
+ var _message$toolCalls;
11984
+ const content = message.content || existing.content;
11985
+ const toolCalls = (_message$toolCalls = message.toolCalls) !== null && _message$toolCalls !== void 0 ? _message$toolCalls : existing.toolCalls;
11986
+ return {
11987
+ ...existing,
11988
+ ...message,
11989
+ content,
11990
+ toolCalls: toolCalls ? dedupeToolCalls(toolCalls) : toolCalls
11991
+ };
11992
+ }
11993
+ /**
11994
+ * Returns the assistant message with repeated tool-call ids collapsed. Returns
11995
+ * the same object when nothing collapsed.
11996
+ */
11997
+ function withDedupedToolCalls(message) {
11998
+ if (!message.toolCalls) return message;
11999
+ const toolCalls = dedupeToolCalls(message.toolCalls);
12000
+ return toolCalls === message.toolCalls ? message : {
12001
+ ...message,
12002
+ toolCalls
12003
+ };
12004
+ }
12005
+ /**
12006
+ * De-duplicates chat messages by id, for rendering.
12007
+ *
12008
+ * A message list from an agent can hold the same message id more than once
12009
+ * while it streams. This keeps one entry per id, at the position the id first
12010
+ * appears:
12011
+ *
12012
+ * - **Assistant messages** are merged. Later fields win, but empty `content`
12013
+ * falls back to earlier non-empty content, and `toolCalls: undefined` falls
12014
+ * back to earlier tool calls (an explicit `[]` is kept).
12015
+ * - **Tool calls** on an assistant message are de-duplicated by id, also
12016
+ * when the message itself is not repeated. The copy that has arguments
12017
+ * wins, and the first-seen order is kept.
12018
+ * - **Other roles** keep the last copy.
12019
+ *
12020
+ * @param messages - The agent's messages, in order.
12021
+ * @returns A new array. A message that needed no change is returned as the
12022
+ * same object.
12023
+ *
12024
+ * @example
12025
+ * ```ts
12026
+ * const visible = ɵdeduplicateMessages(agent.messages);
12027
+ * ```
12028
+ */
12029
+ function ɵdeduplicateMessages(messages) {
12030
+ const byId = /* @__PURE__ */ new Map();
12031
+ for (const message of messages) {
12032
+ if (message.role !== "assistant") {
12033
+ byId.set(message.id, message);
12034
+ continue;
12035
+ }
12036
+ const existing = byId.get(message.id);
12037
+ const merged = (existing === null || existing === void 0 ? void 0 : existing.role) === "assistant" ? mergeAssistantMessages(existing, message) : withDedupedToolCalls(message);
12038
+ byId.set(message.id, merged);
12039
+ }
12040
+ return [...byId.values()];
12041
+ }
12042
+ /**
12043
+ * Serializes object content for {@link ɵmessagesFingerprint}.
12044
+ *
12045
+ * `JSON.stringify` throws on a circular structure (and on a `BigInt`). The
12046
+ * fingerprint runs on every render, so a throw would take the chat down. A
12047
+ * value that cannot be serialized gets a constant key instead: it does not
12048
+ * trigger a change on its own, but every other part of the fingerprint still
12049
+ * does.
12050
+ */
12051
+ function objectContentKey(content) {
12052
+ try {
12053
+ var _JSON$stringify;
12054
+ return (_JSON$stringify = JSON.stringify(content)) !== null && _JSON$stringify !== void 0 ? _JSON$stringify : "";
12055
+ } catch (_unused) {
12056
+ return "[unserializable]";
12057
+ }
12058
+ }
12059
+ /**
12060
+ * Gives the part of the fingerprint that tracks a message's content:
12061
+ * - string content: its length, so streamed text changes it.
12062
+ * - array content: the part count, so an added attachment changes it. The
12063
+ * parts are not serialized, which keeps base64 uploads out of the key.
12064
+ * - object content (activity messages): its JSON, so a snapshot that replaces
12065
+ * the content under the same message id changes it.
12066
+ */
12067
+ function contentKey(content) {
12068
+ if (typeof content === "string" || Array.isArray(content)) return String(content.length);
12069
+ if (content !== null && typeof content === "object") return objectContentKey(content);
12070
+ return "0";
12071
+ }
12072
+ /**
12073
+ * Builds a string that changes whenever a render of the message list could
12074
+ * change. Use it as a cheap memo key in place of a deep comparison.
12075
+ *
12076
+ * The key covers, per message:
12077
+ * - the id and the role.
12078
+ * - the content: text length, part count, or the JSON of object content.
12079
+ * - the `toolCallId` of a tool message.
12080
+ * - each tool call's id and the length of its arguments, so streamed
12081
+ * arguments change the key.
12082
+ *
12083
+ * It never throws. Object content that cannot be serialized (for example a
12084
+ * circular tool result) gets a constant key.
12085
+ *
12086
+ * @param messages - The agent's messages, in order.
12087
+ * @returns The fingerprint string.
12088
+ *
12089
+ * @example
12090
+ * ```ts
12091
+ * const key = ɵmessagesFingerprint(agent.messages);
12092
+ * if (key !== previousKey) rerender();
12093
+ * ```
12094
+ */
12095
+ function ɵmessagesFingerprint(messages) {
12096
+ return messages.map((message) => {
12097
+ const toolCallId = "toolCallId" in message ? message.toolCallId : "";
12098
+ const toolCallsKey = ("toolCalls" in message && Array.isArray(message.toolCalls) ? message.toolCalls : []).map((tc) => {
12099
+ var _tc$function$argument, _tc$function;
12100
+ return `${tc.id}:${(_tc$function$argument = (_tc$function = tc.function) === null || _tc$function === void 0 || (_tc$function = _tc$function.arguments) === null || _tc$function === void 0 ? void 0 : _tc$function.length) !== null && _tc$function$argument !== void 0 ? _tc$function$argument : 0}`;
12101
+ }).join(";");
12102
+ return `${message.id}:${message.role}:${contentKey(message.content)}:${toolCallId}:${toolCallsKey}`;
12103
+ }).join(",");
12104
+ }
12105
+
12106
+ //#endregion
12107
+ //#region src/chat/composer.ts
12108
+ /**
12109
+ * Get the state of the send/stop button in the chat input.
12110
+ *
12111
+ * @param input - The current state of the chat input.
12112
+ * @returns
12113
+ * - `isProcessing`: the agent runs and the input does not record audio.
12114
+ * - `canSend`: the text is not empty and nothing blocks a send.
12115
+ * - `action`: `"stop"` when the button stops the run, else `"send"`.
12116
+ * Use it for the icon, the label, and the click.
12117
+ * - `disabled`: `true` when a click does nothing.
12118
+ *
12119
+ * @example
12120
+ * ```ts
12121
+ * const button = ɵcomposerButtonState({
12122
+ * mode: "input",
12123
+ * isRunning: agent.isRunning,
12124
+ * value: text,
12125
+ * canSubmit: true,
12126
+ * canStop: true,
12127
+ * });
12128
+ * // On click:
12129
+ * if (button.action === "stop") stopRun();
12130
+ * else if (button.canSend) sendMessage(text.trim());
12131
+ * ```
12132
+ */
12133
+ function ɵcomposerButtonState(input) {
12134
+ const isProcessing = input.mode !== "transcribe" && input.isRunning;
12135
+ const isSendBlocked = input.disabled === true || input.attachmentsUploading === true;
12136
+ const canSend = input.canSubmit && !isSendBlocked && input.value.trim().length > 0;
12137
+ return {
12138
+ isProcessing,
12139
+ canSend,
12140
+ action: isProcessing && input.canStop ? "stop" : "send",
12141
+ disabled: isProcessing ? !input.canStop : !canSend
12142
+ };
12143
+ }
12144
+ /**
12145
+ * Decide what a key press in the chat input does.
12146
+ *
12147
+ * This handles Enter only. Keys for the slash-command menu stay in each
12148
+ * framework, and the framework handles them before it calls this function.
12149
+ *
12150
+ * Results:
12151
+ * - `"send"`: send the trimmed text.
12152
+ * - `"stop"`: stop the run. This happens for Enter in an empty input while
12153
+ * the agent runs. Text in the input always means send, not stop.
12154
+ * - `"newline"`: Shift+Enter. Let the browser add the line break.
12155
+ * - `"none"`: do nothing. Returned during IME composition, while the input
12156
+ * is disabled, for keys other than Enter, and for an Enter that has
12157
+ * nothing to send or stop.
12158
+ *
12159
+ * Call `preventDefault()` for every Enter without Shift that is not part of
12160
+ * IME composition, including when the result is `"none"`. This stops Enter
12161
+ * from adding a line break that the user cannot send.
12162
+ *
12163
+ * @param event - The keyboard event, or an object with the same fields.
12164
+ * @param input - The current state of the chat input.
12165
+ *
12166
+ * @example
12167
+ * ```ts
12168
+ * function onKeyDown(event: KeyboardEvent) {
12169
+ * if (event.isComposing || event.keyCode === 229) return;
12170
+ * // ...slash-command menu keys...
12171
+ * const result = ɵresolveComposerKey(event, composerInput);
12172
+ * if (event.key === "Enter" && !event.shiftKey) event.preventDefault();
12173
+ * if (result === "send") sendMessage(composerInput.value.trim());
12174
+ * if (result === "stop") stopRun();
12175
+ * }
12176
+ * ```
12177
+ */
12178
+ function ɵresolveComposerKey(event, input) {
12179
+ if (event.isComposing || event.keyCode === 229 || input.disabled === true || event.key !== "Enter") return "none";
12180
+ if (event.shiftKey) return "newline";
12181
+ const button = ɵcomposerButtonState(input);
12182
+ const isEmpty = input.value.trim().length === 0;
12183
+ if (button.isProcessing && isEmpty) return input.canStop ? "stop" : "none";
12184
+ return button.canSend ? "send" : "none";
12185
+ }
12186
+
12187
+ //#endregion
12188
+ //#region src/chat/transcription.ts
12189
+ /**
12190
+ * The error `ɵtranscribeAudio` throws. Read `error.info.code` to pick a
12191
+ * message for the user, or pass `error.info` to
12192
+ * `ɵtranscriptionErrorMessageKey`.
12193
+ */
12194
+ var TranscriptionError = class extends Error {
12195
+ constructor(info) {
12196
+ super(info.message);
12197
+ _defineProperty(this, "info", void 0);
12198
+ this.name = "TranscriptionError";
12199
+ this.info = info;
12200
+ }
12201
+ };
12202
+ /**
12203
+ * Send a recording to the CopilotKit runtime and get its text back.
12204
+ *
12205
+ * The request follows the transport set on the core:
12206
+ * - `"single"`: one JSON POST to `runtimeUrl`, with the audio as base64.
12207
+ * - any other transport: a multipart POST to `${runtimeUrl}/transcribe`.
12208
+ *
12209
+ * Headers are resolved on each call. The core's `credentials` are sent when
12210
+ * they are set, the same as for agent requests.
12211
+ *
12212
+ * @param core - The `CopilotKitCore` (or a framework subclass) to send through.
12213
+ * @param audioBlob - The recorded audio.
12214
+ * @param filename - The file name the runtime sees. Defaults to `"recording.webm"`.
12215
+ * @returns The transcription result, with the text in `result.text`.
12216
+ * @throws {TranscriptionError} When the runtime URL is not set, the request
12217
+ * fails, or the runtime returns an error. `error.info` has the code.
12218
+ *
12219
+ * @example
12220
+ * ```ts
12221
+ * try {
12222
+ * const { text } = await ɵtranscribeAudio(core, blob);
12223
+ * } catch (error) {
12224
+ * if (error instanceof TranscriptionError) {
12225
+ * const key = ɵtranscriptionErrorMessageKey(error.info);
12226
+ * showError(key ? labels[key] : error.info.message);
12227
+ * }
12228
+ * }
12229
+ * ```
12230
+ */
12231
+ async function ɵtranscribeAudio(core, audioBlob, filename = "recording.webm") {
12232
+ const { runtimeUrl, credentials } = core;
12233
+ if (!runtimeUrl) throw new TranscriptionError({
12234
+ code: _copilotkit_shared.TranscriptionErrorCode.INVALID_REQUEST,
12235
+ message: "Runtime URL is not configured",
12236
+ retryable: false
12237
+ });
12238
+ const resolvedHeaders = await core.resolveHeaders();
12239
+ const credentialsInit = credentials ? { credentials } : {};
12240
+ let response;
12241
+ try {
12242
+ response = core.runtimeTransport === "single" ? await fetch(runtimeUrl, {
12243
+ method: "POST",
12244
+ headers: {
12245
+ ...omitContentType(resolvedHeaders),
12246
+ "Content-Type": "application/json"
12247
+ },
12248
+ body: JSON.stringify({
12249
+ method: "transcribe",
12250
+ body: {
12251
+ audio: await blobToBase64(audioBlob),
12252
+ mimeType: audioBlob.type || "audio/webm",
12253
+ filename
12254
+ }
12255
+ }),
12256
+ ...credentialsInit
12257
+ }) : await fetch(`${runtimeUrl}/transcribe`, {
12258
+ method: "POST",
12259
+ headers: omitContentType(resolvedHeaders),
12260
+ body: toFormData(audioBlob, filename),
12261
+ ...credentialsInit
12262
+ });
12263
+ } catch (error) {
12264
+ throw new TranscriptionError({
12265
+ code: _copilotkit_shared.TranscriptionErrorCode.NETWORK_ERROR,
12266
+ message: error instanceof Error ? error.message : "Network request failed",
12267
+ retryable: true
12268
+ });
12269
+ }
12270
+ if (!response.ok) throw await toTranscriptionError(response);
12271
+ return await response.json();
12272
+ }
12273
+ /**
12274
+ * Pick the chat label to show the user for a transcription error.
12275
+ *
12276
+ * @param error - The `info` of a `TranscriptionError`.
12277
+ * @returns A key of the chat labels, or `null`. `null` means no label fits:
12278
+ * show `error.message` instead.
12279
+ *
12280
+ * @example
12281
+ * ```ts
12282
+ * const key = ɵtranscriptionErrorMessageKey(error.info);
12283
+ * const text = key ? labels[key] : error.info.message;
12284
+ * ```
12285
+ */
12286
+ function ɵtranscriptionErrorMessageKey(error) {
12287
+ switch (error.code) {
12288
+ case _copilotkit_shared.TranscriptionErrorCode.RATE_LIMITED: return "transcriptionErrorRateLimitedText";
12289
+ case _copilotkit_shared.TranscriptionErrorCode.AUTH_FAILED: return "transcriptionErrorAuthFailedText";
12290
+ case _copilotkit_shared.TranscriptionErrorCode.AUDIO_TOO_LONG: return "transcriptionErrorAudioTooLongText";
12291
+ case _copilotkit_shared.TranscriptionErrorCode.AUDIO_TOO_SHORT: return "transcriptionErrorAudioTooShortText";
12292
+ case _copilotkit_shared.TranscriptionErrorCode.INVALID_AUDIO_FORMAT: return "transcriptionErrorInvalidAudioFormatText";
12293
+ case _copilotkit_shared.TranscriptionErrorCode.SERVICE_NOT_CONFIGURED: return "transcriptionErrorServiceNotConfiguredText";
12294
+ case _copilotkit_shared.TranscriptionErrorCode.NETWORK_ERROR: return "transcriptionErrorNetworkText";
12295
+ default: return error.retryable ? "transcriptionErrorGenericText" : null;
12296
+ }
12297
+ }
12298
+ function toFormData(audioBlob, filename) {
12299
+ const formData = new FormData();
12300
+ formData.append("audio", audioBlob, filename);
12301
+ return formData;
12302
+ }
12303
+ function omitContentType(headers) {
12304
+ const entries = Object.entries(headers);
12305
+ return Object.fromEntries(entries.filter(([name]) => name.toLowerCase() !== "content-type"));
12306
+ }
12307
+ async function blobToBase64(blob) {
12308
+ const bytes = new Uint8Array(await blob.arrayBuffer());
12309
+ const chunkSize = 32768;
12310
+ let binary = "";
12311
+ for (let offset = 0; offset < bytes.length; offset += chunkSize) binary += String.fromCharCode(...bytes.subarray(offset, offset + chunkSize));
12312
+ return btoa(binary);
12313
+ }
12314
+ /** Build a typed error from a non-OK transcription response. */
12315
+ async function toTranscriptionError(response) {
12316
+ const retryable = response.status >= 500;
12317
+ let data;
12318
+ try {
12319
+ data = await response.json();
12320
+ } catch (_unused) {
12321
+ return new TranscriptionError({
12322
+ code: _copilotkit_shared.TranscriptionErrorCode.PROVIDER_ERROR,
12323
+ message: `HTTP ${response.status}: ${response.statusText}`,
12324
+ retryable
12325
+ });
12326
+ }
12327
+ if (isTranscriptionErrorResponse(data)) {
12328
+ var _data$retryable;
12329
+ return new TranscriptionError({
12330
+ code: data.error,
12331
+ message: data.message,
12332
+ retryable: (_data$retryable = data.retryable) !== null && _data$retryable !== void 0 ? _data$retryable : false
12333
+ });
12334
+ }
12335
+ const message = typeof data === "object" && data !== null && "message" in data ? String(data.message) : "Transcription failed";
12336
+ return new TranscriptionError({
12337
+ code: _copilotkit_shared.TranscriptionErrorCode.PROVIDER_ERROR,
12338
+ message,
12339
+ retryable
12340
+ });
12341
+ }
12342
+ function isTranscriptionErrorResponse(data) {
12343
+ return typeof data === "object" && data !== null && "error" in data && "message" in data && typeof data.error === "string" && typeof data.message === "string";
12344
+ }
12345
+
12346
+ //#endregion
12347
+ //#region src/chat/license.ts
12348
+ /**
12349
+ * Resolves the license context and the license banner from the runtime
12350
+ * license authority. React, Vue, and Angular call it with the values core
12351
+ * reports, then show the banner and provide the context.
12352
+ *
12353
+ * Rules:
12354
+ *
12355
+ * - A retryable entitlement failure that core is still retrying hides the
12356
+ * status, so no banner shows until the retry ends. A `valid` or `expiring`
12357
+ * legacy status stays in use during the retry.
12358
+ * - A terminal entitlement failure (not retryable, no `valid` or `expiring`
12359
+ * legacy status) keeps the reported status, but `checkFeature` returns
12360
+ * `false` and `getLimit` returns `null` for every feature.
12361
+ * - The `no_license` banner shows only when the status is `none` and no
12362
+ * public key is set.
12363
+ *
12364
+ * The banner text has no day count. No data source gives the days left.
12365
+ *
12366
+ * @param input - The runtime license values and the public key. See
12367
+ * {@link LicenseStateInput}.
12368
+ * @returns `context` for the license context, `warningStatus` (the status the
12369
+ * banner is based on, `undefined` while a retry runs), and `bannerType`
12370
+ * (`null` when no banner shows).
12371
+ *
12372
+ * @example
12373
+ * ```ts
12374
+ * const { context, bannerType } = ɵresolveLicenseState({
12375
+ * status: core.licenseStatus,
12376
+ * entitlements: core.runtimeEntitlements,
12377
+ * retryPending: core.runtimeEntitlementRetryPending,
12378
+ * publicKey,
12379
+ * });
12380
+ * ```
12381
+ */
12382
+ function ɵresolveLicenseState({ status, entitlements, retryPending, publicKey }) {
12383
+ var _context$status;
12384
+ const isRetryableFailure = (entitlements === null || entitlements === void 0 ? void 0 : entitlements.status) !== "ready" && (entitlements === null || entitlements === void 0 ? void 0 : entitlements.error.retryable) === true;
12385
+ const isNonReady = entitlements !== void 0 && entitlements.status !== "ready";
12386
+ const hasLegacyFallback = status === "valid" || status === "expiring";
12387
+ const isRetrying = isRetryableFailure && retryPending && !hasLegacyFallback;
12388
+ const isTerminalFailure = isNonReady && !isRetryableFailure && !hasLegacyFallback;
12389
+ const runtimeContext = (0, _copilotkit_shared.createLicenseContextValue)(isRetrying ? void 0 : status, entitlements);
12390
+ const context = isTerminalFailure ? {
12391
+ ...runtimeContext,
12392
+ checkFeature: () => false,
12393
+ getLimit: () => null
12394
+ } : runtimeContext;
12395
+ const warningStatus = isRetrying ? void 0 : (_context$status = context.status) !== null && _context$status !== void 0 ? _context$status : void 0;
12396
+ return {
12397
+ context,
12398
+ warningStatus,
12399
+ bannerType: resolveLicenseBannerType(warningStatus, publicKey)
12400
+ };
12401
+ }
12402
+ function resolveLicenseBannerType(warningStatus, publicKey) {
12403
+ switch (warningStatus) {
12404
+ case "none": return publicKey ? null : "no_license";
12405
+ case "expired":
12406
+ case "invalid":
12407
+ case "expiring": return warningStatus;
12408
+ case "valid":
12409
+ case "unknown":
12410
+ case void 0: return null;
12411
+ }
12412
+ }
12413
+ /**
12414
+ * Resolves whether the threads drawer can load its thread list.
12415
+ *
12416
+ * - `licensed` is `true` when the status is `unknown` (an entitlement lookup
12417
+ * that did not recover, so the threads endpoint decides), or when the
12418
+ * status is `valid` or `expiring` and `checkFeature("threads")` is `true`.
12419
+ * - `licensePending` is `true` while the status is `null` (the runtime has
12420
+ * not reported yet). Show the loading state then, not the locked view.
12421
+ *
12422
+ * @param context - The license context from {@link ɵresolveLicenseState}.
12423
+ *
12424
+ * @example
12425
+ * ```ts
12426
+ * const { licensed, licensePending } = ɵresolveThreadsLicense(context);
12427
+ * ```
12428
+ */
12429
+ function ɵresolveThreadsLicense(context) {
12430
+ const { status } = context;
12431
+ return {
12432
+ licensed: status === "unknown" || (status === "valid" || status === "expiring") && context.checkFeature("threads"),
12433
+ licensePending: status === null
12434
+ };
12435
+ }
12436
+
12437
+ //#endregion
12438
+ //#region src/chat/icons.ts
12439
+ /*! @license
12440
+ * The icon data below is copied from Lucide v0.525.0 (https://lucide.dev).
12441
+ * The Lucide license follows. A copy is in LUCIDE-LICENSE.md next to this file.
12442
+ * This comment sits right above runtime code so the bundler keeps it in dist.
12443
+ *
12444
+ * ISC License
12445
+ *
12446
+ * 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.
12447
+ *
12448
+ * Permission to use, copy, modify, and/or distribute this software for any
12449
+ * purpose with or without fee is hereby granted, provided that the above
12450
+ * copyright notice and this permission notice appear in all copies.
12451
+ *
12452
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12453
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12454
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12455
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12456
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
12457
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
12458
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
12459
+ */
12460
+ function path(d) {
12461
+ return {
12462
+ tag: "path",
12463
+ attributes: { d }
12464
+ };
12465
+ }
12466
+ const icons = {
12467
+ ArrowUp: {
12468
+ name: "arrow-up",
12469
+ nodes: [path("m5 12 7-7 7 7"), path("M12 19V5")]
12470
+ },
12471
+ Check: {
12472
+ name: "check",
12473
+ nodes: [path("M20 6 9 17l-5-5")]
12474
+ },
12475
+ ChevronDown: {
12476
+ name: "chevron-down",
12477
+ nodes: [path("m6 9 6 6 6-6")]
12478
+ },
12479
+ ChevronLeft: {
12480
+ name: "chevron-left",
12481
+ nodes: [path("m15 18-6-6 6-6")]
12482
+ },
12483
+ ChevronRight: {
12484
+ name: "chevron-right",
12485
+ nodes: [path("m9 18 6-6-6-6")]
12486
+ },
12487
+ Circle: {
12488
+ name: "circle",
12489
+ nodes: [{
12490
+ tag: "circle",
12491
+ attributes: {
12492
+ cx: "12",
12493
+ cy: "12",
12494
+ r: "10"
12495
+ }
12496
+ }]
12497
+ },
12498
+ Copy: {
12499
+ name: "copy",
12500
+ nodes: [{
12501
+ tag: "rect",
12502
+ attributes: {
12503
+ width: "14",
12504
+ height: "14",
12505
+ x: "8",
12506
+ y: "8",
12507
+ rx: "2",
12508
+ ry: "2"
12509
+ }
12510
+ }, path("M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2")]
12511
+ },
12512
+ Edit: {
12513
+ name: "square-pen",
12514
+ 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")]
12515
+ },
12516
+ EyeOff: {
12517
+ name: "eye-off",
12518
+ nodes: [
12519
+ 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"),
12520
+ path("M14.084 14.158a3 3 0 0 1-4.242-4.242"),
12521
+ 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"),
12522
+ path("m2 2 20 20")
12523
+ ]
12524
+ },
12525
+ Loader2: {
12526
+ name: "loader-circle",
12527
+ nodes: [path("M21 12a9 9 0 1 1-6.219-8.56")]
12528
+ },
12529
+ MessageCircle: {
12530
+ name: "message-circle",
12531
+ nodes: [path("M7.9 20A9 9 0 1 0 4 16.1L2 22Z")]
12532
+ },
12533
+ Mic: {
12534
+ name: "mic",
12535
+ nodes: [
12536
+ path("M12 19v3"),
12537
+ path("M19 10v2a7 7 0 0 1-14 0v-2"),
12538
+ {
12539
+ tag: "rect",
12540
+ attributes: {
12541
+ x: "9",
12542
+ y: "2",
12543
+ width: "6",
12544
+ height: "13",
12545
+ rx: "3"
12546
+ }
12547
+ }
12548
+ ]
12549
+ },
12550
+ PanelLeftOpen: {
12551
+ name: "panel-left-open",
12552
+ nodes: [
12553
+ {
12554
+ tag: "rect",
12555
+ attributes: {
12556
+ width: "18",
12557
+ height: "18",
12558
+ x: "3",
12559
+ y: "3",
12560
+ rx: "2"
12561
+ }
12562
+ },
12563
+ path("M9 3v18"),
12564
+ path("m14 9 3 3-3 3")
12565
+ ]
12566
+ },
12567
+ Play: {
12568
+ name: "play",
12569
+ nodes: [{
12570
+ tag: "polygon",
12571
+ attributes: { points: "6 3 20 12 6 21 6 3" }
12572
+ }]
12573
+ },
12574
+ Plus: {
12575
+ name: "plus",
12576
+ nodes: [path("M5 12h14"), path("M12 5v14")]
12577
+ },
12578
+ RefreshCw: {
12579
+ name: "refresh-cw",
12580
+ nodes: [
12581
+ path("M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"),
12582
+ path("M21 3v5h-5"),
12583
+ path("M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"),
12584
+ path("M8 16H3v5")
12585
+ ]
12586
+ },
12587
+ Square: {
12588
+ name: "square",
12589
+ nodes: [{
12590
+ tag: "rect",
12591
+ attributes: {
12592
+ width: "18",
12593
+ height: "18",
12594
+ x: "3",
12595
+ y: "3",
12596
+ rx: "2"
12597
+ }
12598
+ }]
12599
+ },
12600
+ ThumbsDown: {
12601
+ name: "thumbs-down",
12602
+ 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")]
12603
+ },
12604
+ ThumbsUp: {
12605
+ name: "thumbs-up",
12606
+ 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")]
12607
+ },
12608
+ Upload: {
12609
+ name: "upload",
12610
+ nodes: [
12611
+ path("M12 3v12"),
12612
+ path("m17 8-5-5-5 5"),
12613
+ path("M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4")
12614
+ ]
12615
+ },
12616
+ Volume2: {
12617
+ name: "volume-2",
12618
+ nodes: [
12619
+ 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"),
12620
+ path("M16 9a5 5 0 0 1 0 6"),
12621
+ path("M19.364 18.364a9 9 0 0 0 0-12.728")
12622
+ ]
12623
+ },
12624
+ Wrench: {
12625
+ name: "wrench",
12626
+ 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")]
12627
+ },
12628
+ X: {
12629
+ name: "x",
12630
+ nodes: [path("M18 6 6 18"), path("m6 6 12 12")]
12631
+ }
12632
+ };
12633
+ /**
12634
+ * Internal. The SVG data for every icon the chat components draw.
12635
+ *
12636
+ * Each framework's `CopilotIcon` component reads an entry and draws it:
12637
+ *
12638
+ * ```ts
12639
+ * const { name, nodes } = ɵcopilotIcons.ArrowUp;
12640
+ * // <svg {...ɵcopilotIconSvgAttributes} class="lucide lucide-arrow-up">
12641
+ * // one child element per node: <{node.tag} {...node.attributes} />
12642
+ * // </svg>
12643
+ * ```
12644
+ */
12645
+ const ɵcopilotIcons = icons;
12646
+ /**
12647
+ * Internal. The attributes to put on the `<svg>` of every chat icon.
12648
+ *
12649
+ * These are Lucide's default attributes, so a drawn icon matches the Lucide
12650
+ * icon. Set `width` and `height` to change the size.
12651
+ */
12652
+ const ɵcopilotIconSvgAttributes = {
12653
+ xmlns: "http://www.w3.org/2000/svg",
12654
+ width: "24",
12655
+ height: "24",
12656
+ viewBox: "0 0 24 24",
12657
+ fill: "none",
12658
+ stroke: "currentColor",
12659
+ "stroke-width": "2",
12660
+ "stroke-linecap": "round",
12661
+ "stroke-linejoin": "round"
12662
+ };
12663
+
11033
12664
  //#endregion
11034
12665
  exports.A2UI_FENCE_LANGUAGE = A2UI_FENCE_LANGUAGE;
11035
12666
  exports.AgentRegistry = AgentRegistry;
11036
12667
  exports.AgentThreadLockedError = AgentThreadLockedError;
11037
12668
  exports.ContextStore = ContextStore;
12669
+ exports.CopilotChatDefaultLabels = CopilotChatDefaultLabels;
11038
12670
  exports.CopilotKitCore = CopilotKitCore;
11039
12671
  exports.CopilotKitCoreErrorCode = CopilotKitCoreErrorCode;
11040
12672
  exports.CopilotKitCoreRuntimeConnectionStatus = CopilotKitCoreRuntimeConnectionStatus;
11041
12673
  exports.CopilotKitHeaderResolutionError = CopilotKitHeaderResolutionError;
11042
12674
  exports.INSPECTOR_THREAD_BRIDGE_PLUGIN_ID = INSPECTOR_THREAD_BRIDGE_PLUGIN_ID;
12675
+ exports.INTERRUPT_EVENT_NAME = INTERRUPT_EVENT_NAME;
11043
12676
  exports.IntelligenceAgent = IntelligenceAgent;
11044
12677
  exports.MEMORY_ERROR_REGISTRY = MEMORY_ERROR_REGISTRY;
11045
12678
  exports.MemoryError = MemoryError;
@@ -11048,6 +12681,8 @@ exports.RunHandler = RunHandler;
11048
12681
  exports.StateManager = StateManager;
11049
12682
  exports.SuggestionEngine = SuggestionEngine;
11050
12683
  exports.ToolCallStatus = ToolCallStatus;
12684
+ exports.TranscriptionError = TranscriptionError;
12685
+ exports.TranscriptionErrorCode = _copilotkit_shared.TranscriptionErrorCode;
11051
12686
  exports.WebMCPRegistry = WebMCPRegistry;
11052
12687
  exports.classifySurfaceCards = classifySurfaceCards;
11053
12688
  exports.completePartialMarkdown = completePartialMarkdown;
@@ -11078,7 +12713,6 @@ exports.onInspectorActiveThread = onInspectorActiveThread;
11078
12713
  exports.onInspectorStopViewing = onInspectorStopViewing;
11079
12714
  exports.onInspectorViewThread = onInspectorViewThread;
11080
12715
  exports.onInspectorViewThreadResult = onInspectorViewThreadResult;
11081
- exports.parseMarkdown = parseMarkdown;
11082
12716
  exports.parseToolArguments = parseToolArguments;
11083
12717
  exports.prepareSurfaceOperations = prepareSurfaceOperations;
11084
12718
  exports.props = props;
@@ -11091,25 +12725,55 @@ exports.ɵMAX_SOCKET_RETRIES = ɵMAX_SOCKET_RETRIES;
11091
12725
  exports.ɵRUNTIME_PROBE_TIMEOUT_MS = ɵRUNTIME_PROBE_TIMEOUT_MS;
11092
12726
  exports.ɵTHREAD_REQUEST_TIMEOUT_MS = ɵTHREAD_REQUEST_TIMEOUT_MS;
11093
12727
  exports.ɵclearAgentInterruptState = ɵclearAgentInterruptState;
12728
+ exports.ɵcomposerButtonState = ɵcomposerButtonState;
12729
+ exports.ɵcopilotIconSvgAttributes = ɵcopilotIconSvgAttributes;
12730
+ exports.ɵcopilotIcons = ɵcopilotIcons;
12731
+ exports.ɵcountFailedToolCalls = countFailedToolCalls;
11094
12732
  exports.ɵcreateMemoryStore = createMemoryStore;
11095
12733
  exports.ɵcreateThreadSelectors = ɵcreateThreadSelectors;
11096
12734
  exports.ɵcreateThreadStore = createThreadStore;
12735
+ exports.ɵdeduplicateMessages = ɵdeduplicateMessages;
12736
+ exports.ɵformatCountLabel = ɵformatCountLabel;
12737
+ exports.ɵformatLabel = ɵformatLabel;
12738
+ exports.ɵformatReasoningDuration = formatReasoningDuration;
12739
+ exports.ɵformatToolNames = formatToolNames;
12740
+ exports.ɵformatWorkDuration = formatWorkDuration;
11097
12741
  exports.ɵgetAgentInterruptState = ɵgetAgentInterruptState;
12742
+ exports.ɵgetArgumentPreview = getArgumentPreview;
12743
+ exports.ɵgetLatestTurnKey = getLatestTurnKey;
12744
+ exports.ɵgetToolCallLayouts = getToolCallLayouts;
12745
+ exports.ɵgetToolCallPreview = getToolCallPreview;
12746
+ exports.ɵgetToolCallRendererNames = getToolCallRendererNames;
12747
+ exports.ɵgetToolCallRowStatus = getToolCallRowStatus;
12748
+ exports.ɵgetToolResults = getToolResults;
12749
+ exports.ɵgetTurnWork = getTurnWork;
12750
+ exports.ɵgetWorkOpenState = getWorkOpenState;
11098
12751
  exports.ɵisCopilotKitFeature = ɵisCopilotKitFeature;
11099
12752
  exports.ɵisHttpAgent = ɵisHttpAgent;
11100
12753
  exports.ɵisRetryableMemoryStatus = isRetryableStatus;
12754
+ exports.ɵisTurnWorkOpen = isTurnWorkOpen;
12755
+ exports.ɵisTurnWorking = isTurnWorking;
11101
12756
  exports.ɵjoinPhoenixChannel$ = ɵjoinPhoenixChannel$;
11102
12757
  exports.ɵmapMemoryMetadataEvent = ɵmapMemoryMetadataEvent;
11103
12758
  exports.ɵmemoryAdapterEvents = ɵmemoryAdapterEvents;
11104
12759
  exports.ɵmemoryDomainEvents = ɵmemoryDomainEvents;
11105
12760
  exports.ɵmemoryReducer = ɵmemoryReducer;
11106
12761
  exports.ɵmemoryRestEvents = ɵmemoryRestEvents;
12762
+ exports.ɵmessagesFingerprint = ɵmessagesFingerprint;
11107
12763
  exports.ɵobservePhoenixEvent$ = ɵobservePhoenixEvent$;
11108
12764
  exports.ɵobservePhoenixJoinOutcome$ = ɵobservePhoenixJoinOutcome$;
11109
12765
  exports.ɵobservePhoenixSocketHealth$ = ɵobservePhoenixSocketHealth$;
11110
12766
  exports.ɵobservePhoenixSocketSignals$ = ɵobservePhoenixSocketSignals$;
11111
12767
  exports.ɵphoenixChannel$ = ɵphoenixChannel$;
11112
12768
  exports.ɵphoenixSocket$ = ɵphoenixSocket$;
12769
+ exports.ɵpluralize = pluralize;
12770
+ exports.ɵrecordWorkTime = recordWorkTime;
12771
+ exports.ɵresolveActivityRenderer = ɵresolveActivityRenderer;
12772
+ exports.ɵresolveComposerKey = ɵresolveComposerKey;
12773
+ exports.ɵresolveCustomMessageRenderers = ɵresolveCustomMessageRenderers;
12774
+ exports.ɵresolveLicenseState = ɵresolveLicenseState;
12775
+ exports.ɵresolveThreadsLicense = ɵresolveThreadsLicense;
12776
+ exports.ɵresolveToolCallRenderer = ɵresolveToolCallRenderer;
11113
12777
  exports.ɵselectFetchMoreError = ɵselectFetchMoreError;
11114
12778
  exports.ɵselectHasNextPage = ɵselectHasNextPage;
11115
12779
  exports.ɵselectIsFetchingNextPage = ɵselectIsFetchingNextPage;
@@ -11123,7 +12787,10 @@ exports.ɵselectMemoriesRealtimeStatus = ɵselectMemoriesRealtimeStatus;
11123
12787
  exports.ɵselectThreads = ɵselectThreads;
11124
12788
  exports.ɵselectThreadsError = ɵselectThreadsError;
11125
12789
  exports.ɵselectThreadsIsLoading = ɵselectThreadsIsLoading;
12790
+ exports.ɵstringifyToolCallPayload = stringifyToolCallPayload;
11126
12791
  exports.ɵthreadAdapterEvents = ɵthreadAdapterEvents;
12792
+ exports.ɵtranscribeAudio = ɵtranscribeAudio;
12793
+ exports.ɵtranscriptionErrorMessageKey = ɵtranscriptionErrorMessageKey;
11127
12794
  exports.ɵwithHeaderDefaults = ɵwithHeaderDefaults;
11128
12795
  });
11129
12796
  //# sourceMappingURL=index.umd.js.map