@copilotkit/core 2.0.0-rc.2 → 2.0.0-rc.20

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,9 +1,37 @@
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('@copilotkit/learning'), require('jsonrepair')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', '@tanstack/pacer', '@ag-ui/client', '@copilotkit/shared', 'rxjs', 'rxjs/operators', 'phoenix', '@copilotkit/learning', 'jsonrepair'], 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._copilotkit_learning,global.jsonrepair));
5
+ })(this, function(exports, _tanstack_pacer, _ag_ui_client, _copilotkit_shared, rxjs, rxjs_operators, phoenix, _copilotkit_learning, jsonrepair) {
6
6
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
7
+ //#region \0rolldown/runtime.js
8
+ var __create = Object.create;
9
+ var __defProp = Object.defineProperty;
10
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
11
+ var __getOwnPropNames = Object.getOwnPropertyNames;
12
+ var __getProtoOf = Object.getPrototypeOf;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
15
+ var __copyProps = (to, from, except, desc) => {
16
+ if (from && typeof from === "object" || typeof from === "function") {
17
+ for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
18
+ key = keys[i];
19
+ if (!__hasOwnProp.call(to, key) && key !== except) {
20
+ __defProp(to, key, {
21
+ get: ((k) => from[k]).bind(null, key),
22
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
23
+ });
24
+ }
25
+ }
26
+ }
27
+ return to;
28
+ };
29
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
30
+ value: mod,
31
+ enumerable: true
32
+ }) : target, mod));
33
+
34
+ //#endregion
7
35
 
8
36
  //#region src/utils/http-agent.ts
9
37
  /**
@@ -1882,6 +1910,20 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
1882
1910
  return typeof message === "string" && ABORT_MESSAGES.has(message);
1883
1911
  }
1884
1912
 
1913
+ //#endregion
1914
+ //#region src/utils/shallow-equal.ts
1915
+ /**
1916
+ * True when both records have the same own keys and each key holds the same
1917
+ * value (compared with `Object.is`). Key order does not matter. Nested
1918
+ * objects are compared by reference, not by content.
1919
+ */
1920
+ function shallowEqualRecord(a, b) {
1921
+ if (a === b) return true;
1922
+ const aKeys = Object.keys(a);
1923
+ if (aKeys.length !== Object.keys(b).length) return false;
1924
+ return aKeys.every((key) => Object.prototype.hasOwnProperty.call(b, key) && Object.is(a[key], b[key]));
1925
+ }
1926
+
1885
1927
  //#endregion
1886
1928
  //#region src/utils/runtime-request.ts
1887
1929
  const RUNTIME_REQUEST_WATCHDOG_MS = 1e4;
@@ -1986,13 +2028,6 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
1986
2028
  function normalizeHeaders(headers) {
1987
2029
  return Object.fromEntries(Object.entries(headers).filter((entry) => entry[1] != null));
1988
2030
  }
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
2031
  function isHeaderRecordInput(value) {
1997
2032
  return typeof value === "object" && value !== null && !Array.isArray(value);
1998
2033
  }
@@ -2165,6 +2200,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2165
2200
  this.core = core;
2166
2201
  _defineProperty(this, "_agents", {});
2167
2202
  _defineProperty(this, "localAgents", {});
2203
+ _defineProperty(this, "agentsPublished", false);
2168
2204
  _defineProperty(this, "remoteAgents", {});
2169
2205
  _defineProperty(this, "mintedThreadIds", /* @__PURE__ */ new WeakMap());
2170
2206
  _defineProperty(this, "_runtimeUrl", void 0);
@@ -2209,6 +2245,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2209
2245
  _defineProperty(this, "runtimeRecoveryRunning", false);
2210
2246
  _defineProperty(this, "runtimeRecoveryPending", false);
2211
2247
  _defineProperty(this, "runtimeHealthGeneration", 0);
2248
+ _defineProperty(this, "disposeController", new AbortController());
2212
2249
  _defineProperty(this, "agentOwnHeaders", /* @__PURE__ */ new WeakMap());
2213
2250
  }
2214
2251
  /**
@@ -2277,6 +2314,28 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2277
2314
  return this._telemetryDisabled;
2278
2315
  }
2279
2316
  /**
2317
+ * Stop runtime work this registry owns: the entitlement retry timer, the
2318
+ * inspector metadata request, runtime probes and recovery fetches with
2319
+ * their timeouts, and request watchdogs. In-flight `/info` connections are
2320
+ * detached so their late results change nothing. Called by
2321
+ * `CopilotKitCore.dispose`.
2322
+ */
2323
+ dispose() {
2324
+ var _this$inspectorMetada;
2325
+ if (this.disposeController.signal.aborted) return;
2326
+ this.disposeController.abort();
2327
+ this._activeRuntimeConnectionAttempt = void 0;
2328
+ this._connectionInFlight = void 0;
2329
+ this.resetRuntimeEntitlementRetry();
2330
+ this.inspectorMetadataGeneration += 1;
2331
+ (_this$inspectorMetada = this.inspectorMetadataAbortController) === null || _this$inspectorMetada === void 0 || _this$inspectorMetada.abort();
2332
+ this.inspectorMetadataAbortController = void 0;
2333
+ this.abandonRuntimeHealthProbe();
2334
+ }
2335
+ get isDisposed() {
2336
+ return this.disposeController.signal.aborted;
2337
+ }
2338
+ /**
2280
2339
  * Initialize agents from configuration
2281
2340
  */
2282
2341
  initialize(agents) {
@@ -2363,9 +2422,12 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2363
2422
  this.runtimeProbeAbortController = void 0;
2364
2423
  }
2365
2424
  /**
2366
- * Set all agents at once (for development use)
2425
+ * Set all agents at once (for development use). Same ids mapped to the
2426
+ * same instances as the current local agents is a no-op once the agents
2427
+ * have been announced.
2367
2428
  */
2368
2429
  setAgents__unsafe_dev_only(agents) {
2430
+ if (this.agentsPublished && shallowEqualRecord(agents, this.localAgents)) return;
2369
2431
  Object.entries(agents).forEach(([id, agent]) => {
2370
2432
  if (agent) this.validateAndAssignAgentId(id, agent);
2371
2433
  });
@@ -2635,11 +2697,17 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2635
2697
  checked: () => false
2636
2698
  };
2637
2699
  let checked = false;
2700
+ const disposeSignal = this.disposeController.signal;
2638
2701
  const timeoutId = setTimeout(() => {
2639
2702
  checked = this.handleRuntimeRequestOutcome("failed");
2640
2703
  }, RUNTIME_REQUEST_WATCHDOG_MS);
2704
+ const clear = () => {
2705
+ clearTimeout(timeoutId);
2706
+ disposeSignal.removeEventListener("abort", clear);
2707
+ };
2708
+ disposeSignal.addEventListener("abort", clear, { once: true });
2641
2709
  return {
2642
- clear: () => clearTimeout(timeoutId),
2710
+ clear,
2643
2711
  checked: () => checked
2644
2712
  };
2645
2713
  }
@@ -2669,9 +2737,9 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2669
2737
  * runtime connection state.
2670
2738
  */
2671
2739
  async refreshInspectorMetadata() {
2672
- var _this$inspectorMetada;
2740
+ var _this$inspectorMetada2;
2673
2741
  const generation = ++this.inspectorMetadataGeneration;
2674
- (_this$inspectorMetada = this.inspectorMetadataAbortController) === null || _this$inspectorMetada === void 0 || _this$inspectorMetada.abort();
2742
+ (_this$inspectorMetada2 = this.inspectorMetadataAbortController) === null || _this$inspectorMetada2 === void 0 || _this$inspectorMetada2.abort();
2675
2743
  this.inspectorMetadataAbortController = void 0;
2676
2744
  if (!this._inspectorMetadataSupported || !this.inspectorMetadataRefreshReady || !this.runtimeUrl || this._runtimeConnectionStatus !== CopilotKitCoreRuntimeConnectionStatus.Connected) {
2677
2745
  this.setInspectorMetadata(void 0);
@@ -2774,13 +2842,13 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2774
2842
  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
2843
  }
2776
2844
  invalidateInspectorMetadataConnection() {
2777
- var _this$inspectorMetada2;
2845
+ var _this$inspectorMetada3;
2778
2846
  this._inspectorMetadataSupported = false;
2779
2847
  this._inspectorLearning = false;
2780
2848
  this.inspectorMetadataRefreshReady = false;
2781
2849
  this.inspectorMetadataConnectionGeneration += 1;
2782
2850
  this.inspectorMetadataGeneration += 1;
2783
- (_this$inspectorMetada2 = this.inspectorMetadataAbortController) === null || _this$inspectorMetada2 === void 0 || _this$inspectorMetada2.abort();
2851
+ (_this$inspectorMetada3 = this.inspectorMetadataAbortController) === null || _this$inspectorMetada3 === void 0 || _this$inspectorMetada3.abort();
2784
2852
  this.inspectorMetadataAbortController = void 0;
2785
2853
  this.setInspectorMetadata(void 0);
2786
2854
  }
@@ -2802,7 +2870,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2802
2870
  this.runtimeHealthGeneration += 1;
2803
2871
  }
2804
2872
  handleRuntimeRequestOutcome(outcome, alreadyChecked = () => false) {
2805
- if (outcome === "aborted" || outcome === "ignored") return false;
2873
+ if (outcome === "aborted" || outcome === "ignored" || this.isDisposed) return false;
2806
2874
  if (outcome === "failed" && alreadyChecked()) return false;
2807
2875
  if (typeof window === "undefined") return false;
2808
2876
  if (!this._runtimeUrl) return false;
@@ -2822,16 +2890,32 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2822
2890
  let timeoutId;
2823
2891
  const request = this.fetchRuntimeInfo(runtimeUrl, runtimeTransport, abortController.signal);
2824
2892
  request.catch(() => {});
2893
+ const disposeSignal = this.disposeController.signal;
2894
+ let rejectOnAbort;
2895
+ const abortOnDispose = () => abortController.abort();
2825
2896
  try {
2826
2897
  const timedOut = new Promise((_resolve, reject) => {
2827
2898
  timeoutId = setTimeout(() => {
2828
- abortController.abort();
2829
2899
  reject(/* @__PURE__ */ new Error(`Runtime did not answer within ${ɵRUNTIME_PROBE_TIMEOUT_MS}ms`));
2900
+ abortController.abort();
2830
2901
  }, ɵRUNTIME_PROBE_TIMEOUT_MS);
2831
2902
  });
2832
- return await Promise.race([request, timedOut]);
2903
+ const aborted = new Promise((_resolve, reject) => {
2904
+ rejectOnAbort = () => reject(/* @__PURE__ */ new Error("Runtime request aborted"));
2905
+ abortController.signal.addEventListener("abort", rejectOnAbort, { once: true });
2906
+ });
2907
+ aborted.catch(() => {});
2908
+ disposeSignal.addEventListener("abort", abortOnDispose, { once: true });
2909
+ if (disposeSignal.aborted) abortController.abort();
2910
+ return await Promise.race([
2911
+ request,
2912
+ timedOut,
2913
+ aborted
2914
+ ]);
2833
2915
  } finally {
2834
2916
  if (timeoutId !== void 0) clearTimeout(timeoutId);
2917
+ if (rejectOnAbort) abortController.signal.removeEventListener("abort", rejectOnAbort);
2918
+ disposeSignal.removeEventListener("abort", abortOnDispose);
2835
2919
  }
2836
2920
  }
2837
2921
  async probeRuntimeReachability() {
@@ -2892,7 +2976,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2892
2976
  * Update runtime connection and fetch remote agents
2893
2977
  */
2894
2978
  async updateRuntimeConnection(options) {
2895
- if (typeof window === "undefined") return;
2979
+ if (typeof window === "undefined" || this.isDisposed) return;
2896
2980
  const key = this.runtimeConnectionKey();
2897
2981
  const inFlight = this._connectionInFlight;
2898
2982
  if (inFlight && inFlight.attempt.key === key && this.isCurrentRuntimeConnection(inFlight.attempt)) return inFlight.promise;
@@ -2957,6 +3041,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2957
3041
  }
2958
3042
  this._runtimeEntitlementRetryAttemptedKey = key;
2959
3043
  this._runtimeEntitlementRetryPendingKey = key;
3044
+ if (this.isDisposed) return;
2960
3045
  this._runtimeEntitlementRetryTimer = setTimeout(() => {
2961
3046
  this._runtimeEntitlementRetryTimer = void 0;
2962
3047
  this.executeRuntimeEntitlementRetry(attempt).catch((error) => {
@@ -3216,6 +3301,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3216
3301
  * Notify subscribers of agent changes
3217
3302
  */
3218
3303
  async notifyAgentsChanged() {
3304
+ this.agentsPublished = true;
3219
3305
  await this.core.notifySubscribers((subscriber) => {
3220
3306
  var _subscriber$onAgentsC;
3221
3307
  return (_subscriber$onAgentsC = subscriber.onAgentsChanged) === null || _subscriber$onAgentsC === void 0 ? void 0 : _subscriber$onAgentsC.call(subscriber, {
@@ -3322,6 +3408,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3322
3408
  _defineProperty(this, "_suggestionsConfig", {});
3323
3409
  _defineProperty(this, "_suggestions", {});
3324
3410
  _defineProperty(this, "_runningSuggestions", {});
3411
+ _defineProperty(this, "_snapshots", /* @__PURE__ */ new Map());
3325
3412
  }
3326
3413
  /**
3327
3414
  * Initialize with suggestion configs
@@ -3383,14 +3470,30 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3383
3470
  this.notifySuggestionsChanged(agentId, []);
3384
3471
  }
3385
3472
  /**
3386
- * Get current suggestions for an agent
3473
+ * Get current suggestions for an agent. Returns the same object until the
3474
+ * agent's suggestions or loading state change.
3387
3475
  */
3388
3476
  getSuggestions(agentId) {
3389
3477
  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
3478
+ const parts = Object.values((_this$_suggestions$ag = this._suggestions[agentId]) !== null && _this$_suggestions$ag !== void 0 ? _this$_suggestions$ag : {});
3479
+ 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;
3480
+ const cached = this._snapshots.get(agentId);
3481
+ if (cached !== void 0 && cached.result.isLoading === isLoading && cached.parts.length === parts.length && parts.every((part, index) => part === cached.parts[index])) return cached.result;
3482
+ const result = {
3483
+ suggestions: parts.flat(),
3484
+ isLoading
3393
3485
  };
3486
+ this._snapshots.set(agentId, {
3487
+ parts,
3488
+ result
3489
+ });
3490
+ return result;
3491
+ }
3492
+ /** Abort every running suggestion generation. Called by `CopilotKitCore.dispose`. */
3493
+ dispose() {
3494
+ const runs = Object.values(this._runningSuggestions).flat();
3495
+ this._runningSuggestions = {};
3496
+ for (const run of runs) run.abortRun();
3394
3497
  }
3395
3498
  /**
3396
3499
  * Generate suggestions by running a provider agent and extracting the
@@ -3780,7 +3883,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3780
3883
  */
3781
3884
  function createToolSchema(tool) {
3782
3885
  if (!tool.parameters) return { ...EMPTY_TOOL_SCHEMA };
3783
- const rawSchema = (0, _copilotkit_shared.schemaToJsonSchema)(tool.parameters, { zodToJsonSchema: (schema, options) => (0, zod_to_json_schema.zodToJsonSchema)(schema, options) });
3886
+ const rawSchema = (0, _copilotkit_shared.schemaToJsonSchema)(tool.parameters);
3784
3887
  if (!rawSchema || typeof rawSchema !== "object") return { ...EMPTY_TOOL_SCHEMA };
3785
3888
  const { $schema: _$schema, ...schema } = rawSchema;
3786
3889
  if (typeof schema.type !== "string") schema.type = "object";
@@ -3846,14 +3949,14 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3846
3949
  _classPrivateFieldInitSpec(this, _pending, null);
3847
3950
  _classPrivateFieldInitSpec(this, _sealed, false);
3848
3951
  }
3849
- /** Return the active normalized interrupt without exposing mutable state. */
3952
+ /**
3953
+ * Return the active normalized interrupt. A standard interrupt set is a
3954
+ * frozen snapshot, and every read returns the same object until the
3955
+ * interrupt is replaced or cleared, so a framework can compare it by
3956
+ * reference.
3957
+ */
3850
3958
  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;
3959
+ return _classPrivateFieldGet2(_pending, this);
3857
3960
  }
3858
3961
  /** Replace the current interrupt with a legacy custom-event interrupt. */
3859
3962
  setLegacy(event) {
@@ -3874,10 +3977,10 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3874
3977
  callIds.add(interrupt.toolCallId);
3875
3978
  }
3876
3979
  }
3877
- _assertClassBrand(_ɵInterruptState_brand, this, _replace).call(this, {
3980
+ _assertClassBrand(_ɵInterruptState_brand, this, _replace).call(this, Object.freeze({
3878
3981
  kind: "standard",
3879
- interrupts: [...interrupts]
3880
- });
3982
+ interrupts: Object.freeze([...interrupts])
3983
+ }));
3881
3984
  }
3882
3985
  /** Clear all pending interrupt data and accumulated responses. */
3883
3986
  clear() {
@@ -3915,8 +4018,8 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3915
4018
  }
3916
4019
  /** Reject ambiguous assistant definitions before executing or answering a call. */
3917
4020
  validateToolCalls(messages) {
3918
- var _classPrivateFieldGet2$1;
3919
- if (((_classPrivateFieldGet2$1 = _classPrivateFieldGet2(_pending, this)) === null || _classPrivateFieldGet2$1 === void 0 ? void 0 : _classPrivateFieldGet2$1.kind) !== "standard") return;
4021
+ var _classPrivateFieldGet2$3;
4022
+ if (((_classPrivateFieldGet2$3 = _classPrivateFieldGet2(_pending, this)) === null || _classPrivateFieldGet2$3 === void 0 ? void 0 : _classPrivateFieldGet2$3.kind) !== "standard") return;
3920
4023
  const pendingCalls = new Set(_classPrivateFieldGet2(_pending, this).interrupts.filter((interrupt) => interrupt.reason === "tool_call").map((interrupt) => interrupt.toolCallId));
3921
4024
  const seen = /* @__PURE__ */ new Set();
3922
4025
  for (const message of messages) {
@@ -4206,6 +4309,8 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4206
4309
  _defineProperty(this, "_warnedMissingToolParameters", /* @__PURE__ */ new Set());
4207
4310
  _defineProperty(this, "_runAbortControllers", /* @__PURE__ */ new WeakMap());
4208
4311
  _defineProperty(this, "_runDepths", /* @__PURE__ */ new WeakMap());
4312
+ _defineProperty(this, "_runningAgents", /* @__PURE__ */ new Set());
4313
+ _defineProperty(this, "_disposed", false);
4209
4314
  _defineProperty(this, "_originalAbortRuns", /* @__PURE__ */ new WeakMap());
4210
4315
  _defineProperty(this, "_activeRequestIds", /* @__PURE__ */ new WeakMap());
4211
4316
  _defineProperty(this, "_requestIdByRun", /* @__PURE__ */ new Map());
@@ -4217,7 +4322,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4217
4322
  _defineProperty(this, "_executingToolCalls", /* @__PURE__ */ new WeakMap());
4218
4323
  _defineProperty(this, "_connectionGenerations", /* @__PURE__ */ new WeakMap());
4219
4324
  _defineProperty(this, "_runGenerations", /* @__PURE__ */ new WeakMap());
4220
- _defineProperty(this, "_interactionAbortControllers", /* @__PURE__ */ new WeakMap());
4325
+ _defineProperty(this, "_interactionAbortControllers", /* @__PURE__ */ new Map());
4221
4326
  }
4222
4327
  /**
4223
4328
  * Abort the current run. Called by `CopilotKitCore.stopAgent()` to signal
@@ -4233,6 +4338,30 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4233
4338
  this._executingToolCalls.delete(agent);
4234
4339
  }
4235
4340
  }
4341
+ /**
4342
+ * Stop every run chain and tool interaction this handler tracks, and every
4343
+ * agent in `agents` that reports a run in flight, the same way `stopAgent`
4344
+ * does. Then unregister all WebMCP tools. Called by `CopilotKitCore.dispose`.
4345
+ */
4346
+ dispose(agents) {
4347
+ this._disposed = true;
4348
+ const candidates = new Set([
4349
+ ...agents,
4350
+ ...this._runningAgents,
4351
+ ...this._interactionAbortControllers.keys()
4352
+ ]);
4353
+ for (const agent of candidates) {
4354
+ const hasActiveRun = agent.isRunning || this._runningAgents.has(agent);
4355
+ try {
4356
+ this.abortCurrentRun(agent);
4357
+ if (hasActiveRun) agent.abortRun();
4358
+ } catch (error) {
4359
+ var _agent$agentId;
4360
+ _copilotkit_shared.logger.error(`Failed to stop agent '${(_agent$agentId = agent.agentId) !== null && _agent$agentId !== void 0 ? _agent$agentId : "(unknown agent)"}' on dispose:`, error);
4361
+ }
4362
+ }
4363
+ this._webmcpRegistry.sync(/* @__PURE__ */ new Map());
4364
+ }
4236
4365
  abortAgentRuns(agent) {
4237
4366
  var _this$_runAbortContro;
4238
4367
  for (const controller of (_this$_runAbortContro = this._runAbortControllers.get(agent)) !== null && _this$_runAbortContro !== void 0 ? _this$_runAbortContro : []) controller.abort();
@@ -4275,7 +4404,10 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4275
4404
  if (this._cachedMergedTools) return this._cachedMergedTools;
4276
4405
  const merged = /* @__PURE__ */ new Map();
4277
4406
  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);
4407
+ for (const [key, stack] of this._hookTools) {
4408
+ const active = stack[stack.length - 1];
4409
+ if (active) merged.set(key, active.tool);
4410
+ }
4279
4411
  this._cachedMergedTools = Array.from(merged.values());
4280
4412
  return this._cachedMergedTools;
4281
4413
  }
@@ -4291,17 +4423,35 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4291
4423
  /**
4292
4424
  * Add a tool to the registry. Survives provider re-syncs ({@link setTools}),
4293
4425
  * and shadows a provider tool of the same name + agentId.
4426
+ *
4427
+ * Registrations of the same name + agentId stack: the most recent one is
4428
+ * active. Call the returned function to remove exactly this registration;
4429
+ * the previous registration (or the provider tool) becomes active again.
4430
+ * Calling it more than once does nothing.
4294
4431
  */
4295
4432
  addTool(tool) {
4296
4433
  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);
4434
+ const registration = { tool };
4435
+ const stack = this._hookTools.get(key);
4436
+ if (stack) {
4437
+ 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.`);
4438
+ stack.push(registration);
4439
+ } else this._hookTools.set(key, [registration]);
4302
4440
  this._cachedMergedTools = null;
4303
4441
  this.warnOnMissingToolParameters([tool]);
4304
4442
  this.syncWebMCP();
4443
+ return () => this.unregisterHookTool(key, registration);
4444
+ }
4445
+ /** Remove one `addTool` registration. Unknown registrations are ignored. */
4446
+ unregisterHookTool(key, registration) {
4447
+ var _stack$indexOf;
4448
+ const stack = this._hookTools.get(key);
4449
+ const index = (_stack$indexOf = stack === null || stack === void 0 ? void 0 : stack.indexOf(registration)) !== null && _stack$indexOf !== void 0 ? _stack$indexOf : -1;
4450
+ if (!stack || index === -1) return;
4451
+ stack.splice(index, 1);
4452
+ if (stack.length === 0) this._hookTools.delete(key);
4453
+ this._cachedMergedTools = null;
4454
+ this.syncWebMCP();
4305
4455
  }
4306
4456
  /**
4307
4457
  * Report, once per tool and at development time only, a tool registered with
@@ -4333,7 +4483,10 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4333
4483
  }
4334
4484
  }
4335
4485
  /**
4336
- * Remove a tool by name and optionally by agentId
4486
+ * Remove a tool by name and optionally by agentId: every `addTool`
4487
+ * registration of that key and the provider tool of that key. Without an
4488
+ * agentId only global tools are removed. To remove one `addTool`
4489
+ * registration and keep the others, call the function `addTool` returned.
4337
4490
  */
4338
4491
  removeTool(id, agentId) {
4339
4492
  this._hookTools.delete(this.capabilityKey(id, agentId));
@@ -4538,6 +4691,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4538
4691
  this._runAbortControllers.set(agent, controllers);
4539
4692
  }
4540
4693
  if (depth === 0) {
4694
+ this._runningAgents.add(agent);
4541
4695
  const originalAbortRun = agent.abortRun;
4542
4696
  this._originalAbortRuns.set(agent, originalAbortRun);
4543
4697
  agent.abortRun = () => {
@@ -4615,6 +4769,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4615
4769
  if ((controllers === null || controllers === void 0 ? void 0 : controllers.size) === 0) this._runAbortControllers.delete(agent);
4616
4770
  }
4617
4771
  if (remainingDepth === 0) {
4772
+ this._runningAgents.delete(agent);
4618
4773
  const originalAbortRun = this._originalAbortRuns.get(agent);
4619
4774
  if (originalAbortRun) {
4620
4775
  agent.abortRun = originalAbortRun;
@@ -5146,6 +5301,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5146
5301
  * agentId — a name collision across agentIds keeps the first registration.
5147
5302
  */
5148
5303
  syncWebMCP() {
5304
+ if (this._disposed) return;
5149
5305
  const desired = /* @__PURE__ */ new Map();
5150
5306
  const warnedCollisions = /* @__PURE__ */ new Set();
5151
5307
  for (const tool of this.tools) {
@@ -5502,6 +5658,11 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5502
5658
  }
5503
5659
  this.rawEventByMessage.delete(agentId);
5504
5660
  }
5661
+ /** Unsubscribe from every agent. Called by `CopilotKitCore.dispose`. */
5662
+ dispose() {
5663
+ const agentIds = [...this.agentSubscriptions.keys()];
5664
+ for (const agentId of agentIds) this.unsubscribeFromAgent(agentId);
5665
+ }
5505
5666
  /**
5506
5667
  * Get state for a specific run
5507
5668
  * Returns a deep copy to prevent external mutations
@@ -7718,7 +7879,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
7718
7879
  return CopilotKitCoreRuntimeConnectionStatus;
7719
7880
  }({});
7720
7881
  var CopilotKitCore = class {
7721
- constructor({ runtimeUrl, runtimeTransport = "auto", deferInitialConnection = false, headers = {}, credentials, messageFilter, properties = {}, agents__unsafe_dev_only = {}, tools = [], suggestionsConfig = [], debug, learning }) {
7882
+ constructor({ runtimeUrl, runtimeTransport = "auto", deferInitialConnection = false, headers = {}, credentials, messageFilter, properties = {}, agents__unsafe_dev_only = {}, tools = [], suggestionsConfig = [], debug, learning, ɵwaitForFrameworkUpdates }) {
7722
7883
  _defineProperty(this, "headerSource", void 0);
7723
7884
  _defineProperty(this, "_credentials", void 0);
7724
7885
  _defineProperty(this, "_messageFilter", void 0);
@@ -7727,6 +7888,8 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
7727
7888
  _defineProperty(this, "_defaultThrottleMs", void 0);
7728
7889
  _defineProperty(this, "_debug", void 0);
7729
7890
  _defineProperty(this, "subscribers", /* @__PURE__ */ new Set());
7891
+ _defineProperty(this, "_disposed", false);
7892
+ _defineProperty(this, "waitForFrameworkUpdates", void 0);
7730
7893
  _defineProperty(this, "agentRegistry", void 0);
7731
7894
  _defineProperty(this, "contextStore", void 0);
7732
7895
  _defineProperty(this, "suggestionEngine", void 0);
@@ -7740,6 +7903,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
7740
7903
  _defineProperty(this, "generativeUIDebugListeners", /* @__PURE__ */ new Set());
7741
7904
  _defineProperty(this, "_memoryStore", void 0);
7742
7905
  _defineProperty(this, "previousAgentIds", /* @__PURE__ */ new Set());
7906
+ this.waitForFrameworkUpdates = ɵwaitForFrameworkUpdates;
7743
7907
  this.headerSource = new HeaderSourceResolver((error) => {
7744
7908
  this.emitError({
7745
7909
  error,
@@ -7793,6 +7957,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
7793
7957
  * Internal method used by delegate classes and subclasses to notify subscribers
7794
7958
  */
7795
7959
  async notifySubscribers(handler, errorMessage) {
7960
+ if (this._disposed) return;
7796
7961
  await Promise.all(Array.from(this.subscribers).map(async (subscriber) => {
7797
7962
  try {
7798
7963
  await handler(subscriber);
@@ -8048,7 +8213,12 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
8048
8213
  });
8049
8214
  }, "Subscriber onHeadersChanged error:");
8050
8215
  }
8216
+ /**
8217
+ * Set the credentials mode for runtime requests (for example `"include"`
8218
+ * to send HTTP-only cookies). Passing the current value does nothing.
8219
+ */
8051
8220
  setCredentials(credentials) {
8221
+ if (credentials === this._credentials) return;
8052
8222
  this._credentials = credentials;
8053
8223
  this.agentRegistry.applyCredentialsToAgents(this.agentRegistry.agents);
8054
8224
  this.agentRegistry.handleCredentialsChanged();
@@ -8058,9 +8228,11 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
8058
8228
  *
8059
8229
  * Applies to agents already discovered as well as ones discovered later, so
8060
8230
  * a filter set before `/info` lands is not lost. Pass `undefined` to go back
8061
- * to sending the full thread.
8231
+ * to sending the full thread. Passing the current filter function again
8232
+ * does nothing.
8062
8233
  */
8063
8234
  setMessageFilter(messageFilter) {
8235
+ if (messageFilter === this._messageFilter) return;
8064
8236
  this._messageFilter = messageFilter;
8065
8237
  this.agentRegistry.applyMessageFilterToAgents(this.agentRegistry.agents);
8066
8238
  }
@@ -8117,7 +8289,14 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
8117
8289
  }
8118
8290
  return merged;
8119
8291
  }
8292
+ /**
8293
+ * Replace the properties sent as `forwardedProps` with every run, and
8294
+ * notify `onPropertiesChanged`. Passing an object with the same keys and
8295
+ * values as the current one does nothing, so a fresh object literal on
8296
+ * every render is safe.
8297
+ */
8120
8298
  setProperties(properties) {
8299
+ if (shallowEqualRecord(properties, this._properties)) return;
8121
8300
  this._properties = properties;
8122
8301
  this.notifySubscribers((subscriber) => {
8123
8302
  var _subscriber$onPropert;
@@ -8128,7 +8307,10 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
8128
8307
  }, "Subscriber onPropertiesChanged error:");
8129
8308
  }
8130
8309
  /**
8131
- * Agent management (delegated to AgentRegistry)
8310
+ * Agent management (delegated to AgentRegistry).
8311
+ *
8312
+ * Replace the local (development) agents. Passing the same ids mapped to
8313
+ * the same agent instances does nothing.
8132
8314
  */
8133
8315
  setAgents__unsafe_dev_only(agents) {
8134
8316
  this.agentRegistry.setAgents__unsafe_dev_only(agents);
@@ -8411,11 +8593,34 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
8411
8593
  return this.suggestionEngine.getSuggestions(agentId);
8412
8594
  }
8413
8595
  /**
8414
- * Tool management (delegated to RunHandler)
8596
+ * Register a frontend tool. It shadows a provider tool (from the `tools`
8597
+ * config or `setTools`) with the same name and agentId.
8598
+ *
8599
+ * A second registration with the same name and agentId shadows the first.
8600
+ * Call the returned function to remove only this registration: the tool it
8601
+ * shadowed becomes active again. Calling it more than once does nothing.
8602
+ *
8603
+ * @param tool - The tool to register.
8604
+ * @returns A function that removes this registration.
8605
+ *
8606
+ * @example
8607
+ * const unregister = copilotkit.addTool({
8608
+ * name: "showWeather",
8609
+ * handler: async ({ city }) => `Sunny in ${city}`,
8610
+ * });
8611
+ * // later
8612
+ * unregister();
8415
8613
  */
8416
8614
  addTool(tool) {
8417
- this.runHandler.addTool(tool);
8615
+ return this.runHandler.addTool(tool);
8418
8616
  }
8617
+ /**
8618
+ * Remove a tool by name, and by agentId when given. This removes every
8619
+ * `addTool` registration with that name and agentId, and the provider tool
8620
+ * with that name and agentId. Without an agentId, only global tools are
8621
+ * removed. To remove one registration, call the function `addTool`
8622
+ * returned.
8623
+ */
8419
8624
  removeTool(id, agentId) {
8420
8625
  this.runHandler.removeTool(id, agentId);
8421
8626
  }
@@ -8666,11 +8871,54 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
8666
8871
  * synchronously while the deferred updates are still pending, producing stale
8667
8872
  * context for the next agent turn.
8668
8873
  *
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.
8874
+ * Awaits the `ɵwaitForFrameworkUpdates` config option when one is given.
8875
+ * Without it there is nothing to wait for, because a plain JavaScript
8876
+ * environment has no deferred state to flush. Framework subclasses that
8877
+ * still override this method keep working.
8672
8878
  */
8673
- async waitForPendingFrameworkUpdates() {}
8879
+ async waitForPendingFrameworkUpdates() {
8880
+ var _this$waitForFramewor;
8881
+ await ((_this$waitForFramewor = this.waitForFrameworkUpdates) === null || _this$waitForFramewor === void 0 ? void 0 : _this$waitForFramewor.call(this));
8882
+ }
8883
+ /**
8884
+ * Stop everything this core started, so it can be dropped without leaks.
8885
+ *
8886
+ * Call it when you created a `CopilotKitCore` yourself and are done with it
8887
+ * (for example when a page or test tears down). Framework providers call it
8888
+ * for you.
8889
+ *
8890
+ * It does this, in order:
8891
+ *
8892
+ * - removes every subscriber, so no callback runs after this call;
8893
+ * - stops agent runs in flight and aborts running frontend tools;
8894
+ * - aborts suggestion generation;
8895
+ * - clears runtime timers and aborts runtime requests it can cancel;
8896
+ * - removes agent subscriptions, WebMCP tools, and the learning capture;
8897
+ * - stops the memory store and every registered thread store.
8898
+ *
8899
+ * Calling it again does nothing. Do not use the core after this call.
8900
+ *
8901
+ * @example
8902
+ * const copilotkit = new CopilotKitCore({ runtimeUrl: "/api/copilotkit" });
8903
+ * // ... use it ...
8904
+ * copilotkit.dispose();
8905
+ */
8906
+ dispose() {
8907
+ var _this$_memoryStore;
8908
+ if (this._disposed) return;
8909
+ this._disposed = true;
8910
+ this.subscribers.clear();
8911
+ this.learningConfiguredListeners.clear();
8912
+ this.generativeUIDebugListeners.clear();
8913
+ this.runHandler.dispose(Object.values(this.agentRegistry.agents));
8914
+ this.suggestionEngine.dispose();
8915
+ this.agentRegistry.dispose();
8916
+ this.stateManager.dispose();
8917
+ this.stopTrajectory();
8918
+ (_this$_memoryStore = this._memoryStore) === null || _this$_memoryStore === void 0 || _this$_memoryStore.stop();
8919
+ const threadStores = Object.values(this.threadStoreRegistry.getAll());
8920
+ for (const store of threadStores) store.stop();
8921
+ }
8674
8922
  };
8675
8923
 
8676
8924
  //#endregion
@@ -8853,23 +9101,6 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
8853
9101
  return result;
8854
9102
  }
8855
9103
 
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
9104
  //#endregion
8874
9105
  //#region src/threads.ts
8875
9106
  const THREADS_CHANNEL_EVENT = "thread_metadata";
@@ -10386,11 +10617,11 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
10386
10617
  return null;
10387
10618
  }
10388
10619
  /**
10389
- * A line that opens a new top-level operation: `{"version":"v…` or
10620
+ * A line that opens a new top-level operation: `{"version":"1…` or
10390
10621
  * `{"<operation>":{`. Seen at the start of a line while an earlier object is
10391
10622
  * still unbalanced, it means that object is malformed and has ended.
10392
10623
  */
10393
- const OPERATION_START = new RegExp(`^\\{\\s*"(?:version"\\s*:\\s*"v\\d|(?:${OP_KEYS.join("|")})"\\s*:\\s*\\{)`);
10624
+ const OPERATION_START = new RegExp(`^\\{\\s*"(?:version"\\s*:\\s*"\\d|(?:${OP_KEYS.join("|")})"\\s*:\\s*\\{)`);
10394
10625
  /**
10395
10626
  * Scan the top-level object whose "{" is at `start`. Returns the index just
10396
10627
  * past it and whether it balanced. An unbalanced object ends early (at the
@@ -10432,6 +10663,92 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
10432
10663
  balanced: false
10433
10664
  };
10434
10665
  }
10666
+ const OPERATION_NAMES = [
10667
+ "createSurface",
10668
+ "updateComponents",
10669
+ "updateDataModel",
10670
+ "deleteSurface",
10671
+ "callRendererFunction"
10672
+ ];
10673
+ /** Whether a value is shaped like one A2UI operation, with named components. */
10674
+ function isOperationShape(value) {
10675
+ if (!isRecord(value) || value.version !== _copilotkit_shared.A2UI_VERSION) return false;
10676
+ const names = OPERATION_NAMES.filter((name) => name in value);
10677
+ if (names.length !== 1 || Object.keys(value).length !== 2) return false;
10678
+ const body = value[names[0]];
10679
+ if (!isRecord(body)) return false;
10680
+ if (names[0] === "callRendererFunction") return true;
10681
+ if (typeof body.surfaceId !== "string") return false;
10682
+ const components = body.components;
10683
+ return components === void 0 || Array.isArray(components) && components.every((c) => isRecord(c) && typeof c.id === "string" && typeof c.component === "string");
10684
+ }
10685
+ /** Openers minus closers ({ and [ against } and ]) outside strings. */
10686
+ function closerImbalance(line) {
10687
+ let depth = 0;
10688
+ let inString = false;
10689
+ for (let i = 0; i < line.length; i++) {
10690
+ const c = line[i];
10691
+ if (inString) {
10692
+ if (c === "\\") i++;
10693
+ else if (c === "\"") inString = false;
10694
+ } else if (c === "\"") inString = true;
10695
+ else if (c === "{" || c === "[") depth++;
10696
+ else if (c === "}" || c === "]") depth--;
10697
+ }
10698
+ return depth;
10699
+ }
10700
+ /** The text with closers and whitespace removed, to compare a repair. */
10701
+ function withoutClosers(text) {
10702
+ return text.replace(/[\]}\s]/g, "");
10703
+ }
10704
+ /**
10705
+ * Whether a component of the operation holds a structural key (`id`,
10706
+ * `component`, `child`, `children`) in a nested object: a closer added at
10707
+ * the end instead of where it was dropped. The scan below repairs those.
10708
+ */
10709
+ function nestsStructuralKey(value) {
10710
+ const nests = (v) => isRecord(v) && Object.entries(v).some(([k, x]) => STRUCTURAL_KEYS.has(k) || nests(x));
10711
+ const body = isRecord(value) ? Object.values(value).find(isRecord) : void 0;
10712
+ const components = body === null || body === void 0 ? void 0 : body.components;
10713
+ return Array.isArray(components) && components.some((c) => isRecord(c) && Object.values(c).some((prop) => nests(prop)));
10714
+ }
10715
+ /**
10716
+ * Repairs the complete lines of a fence that are not valid JSON (a missing
10717
+ * or extra brace) with jsonrepair, when the repair only adds or removes
10718
+ * closers and the result is shaped like an operation. A line still streaming in (no newline yet) is left alone.
10719
+ */
10720
+ function repairFenceLines(fenceText) {
10721
+ const repaired = [];
10722
+ const lines = fenceText.split("\n");
10723
+ if (fenceText.trimStart().startsWith("[")) return {
10724
+ text: fenceText,
10725
+ repaired
10726
+ };
10727
+ for (let n = 0; n < lines.length - 1; n++) {
10728
+ const line = lines[n];
10729
+ if (!line.trim().startsWith("{")) continue;
10730
+ try {
10731
+ JSON.parse(line);
10732
+ continue;
10733
+ } catch (_unused10) {}
10734
+ const imbalance = closerImbalance(line);
10735
+ if (Math.abs(imbalance) !== 1) continue;
10736
+ const next = lines.slice(n + 1).find((l) => l.trim() !== "");
10737
+ if (imbalance > 0 && next !== void 0 && !next.trim().startsWith("{")) continue;
10738
+ try {
10739
+ const fixed = (0, jsonrepair.jsonrepair)(line);
10740
+ const value = JSON.parse(fixed);
10741
+ if (withoutClosers(fixed) === withoutClosers(line) && isOperationShape(value) && !nestsStructuralKey(value) && !(isRecord(value) && "callRendererFunction" in value)) {
10742
+ repaired.push(line.trim());
10743
+ lines[n] = JSON.stringify(value);
10744
+ }
10745
+ } catch (_unused11) {}
10746
+ }
10747
+ return {
10748
+ text: lines.join("\n"),
10749
+ repaired
10750
+ };
10751
+ }
10435
10752
  /**
10436
10753
  * Parse the body of an a2ui fence as a stream of top-level JSON values, so
10437
10754
  * operations may be one per line (the documented format), several per line,
@@ -10461,7 +10778,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
10461
10778
  * ```
10462
10779
  */
10463
10780
  function extractFenceOperations(fenceText) {
10464
- const s = fenceText;
10781
+ const { text: s, repaired: repairedLines } = repairFenceLines(fenceText);
10465
10782
  const operations = [];
10466
10783
  const invalidLines = [];
10467
10784
  const recovered = [];
@@ -10491,7 +10808,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
10491
10808
  let parsed;
10492
10809
  try {
10493
10810
  parsed = JSON.parse(raw);
10494
- } catch (_unused10) {
10811
+ } catch (_unused12) {
10495
10812
  parsed = void 0;
10496
10813
  }
10497
10814
  if (isRecord(parsed)) operations.push(parsed);
@@ -10515,7 +10832,8 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
10515
10832
  partialObject,
10516
10833
  partialLine: partialObject,
10517
10834
  invalidLines,
10518
- recovered
10835
+ recovered,
10836
+ repairedLines
10519
10837
  };
10520
10838
  }
10521
10839
  /**
@@ -11030,24 +11348,3465 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
11030
11348
  });
11031
11349
  }
11032
11350
 
11351
+ //#endregion
11352
+ //#region src/chat/labels.ts
11353
+ /**
11354
+ * The default English text for every word the chat UI shows. React, Vue and
11355
+ * Angular all read their chat text from this one set.
11356
+ *
11357
+ * To change or translate the text, pass a partial set to your framework's chat
11358
+ * configuration. Keys you leave out keep their default:
11359
+ *
11360
+ * ```ts
11361
+ * const labels = { ...CopilotChatDefaultLabels, chatInputPlaceholder: "Ask me" };
11362
+ * ```
11363
+ *
11364
+ * Some values are templates with `{name}` placeholders, such as
11365
+ * `"Thought for {duration}"`. Keep the placeholders when you translate them.
11366
+ *
11367
+ * Counts use two keys: `...One` for a count of 1, and `...Other` for any other
11368
+ * count.
11369
+ */
11370
+ const CopilotChatDefaultLabels = Object.freeze({
11371
+ chatInputPlaceholder: "Type a message...",
11372
+ chatInputToolbarStartTranscribeButtonLabel: "Transcribe",
11373
+ chatInputToolbarCancelTranscribeButtonLabel: "Cancel",
11374
+ chatInputToolbarFinishTranscribeButtonLabel: "Finish",
11375
+ chatInputToolbarAddButtonLabel: "Add attachments",
11376
+ chatInputToolbarToolsButtonLabel: "Tools",
11377
+ chatInputToolbarSendButtonLabel: "Send message",
11378
+ chatInputToolbarStopButtonLabel: "Stop",
11379
+ assistantMessageToolbarCopyCodeLabel: "Copy",
11380
+ assistantMessageToolbarCopyCodeCopiedLabel: "Copied",
11381
+ assistantMessageToolbarCopyMessageLabel: "Copy",
11382
+ assistantMessageToolbarInspectorLabel: "View in Inspector",
11383
+ assistantMessageToolbarInspectorDescription: "Open this message in the Inspector",
11384
+ assistantMessageToolbarInspectorLocalOnlyLabel: "Local only",
11385
+ assistantMessageToolbarInspectorLocalOnlyDescription: "Only visible on localhost or loopback hosts in development. Never shown in production.",
11386
+ assistantMessageToolbarInspectorTitle: "CopilotKit Inspector",
11387
+ assistantMessageToolbarInspectorHideLabel: "Hide this icon",
11388
+ assistantMessageToolbarInspectorHideDescription: "Until you reload this page",
11389
+ assistantMessageToolbarThumbsUpLabel: "Good response",
11390
+ assistantMessageToolbarThumbsDownLabel: "Bad response",
11391
+ assistantMessageFeedbackCommentPlaceholder: "Add a comment (optional)",
11392
+ assistantMessageFeedbackCommentSubmitLabel: "Send comment",
11393
+ assistantMessageToolbarReadAloudLabel: "Read aloud",
11394
+ assistantMessageToolbarRegenerateLabel: "Regenerate",
11395
+ userMessageToolbarCopyMessageLabel: "Copy",
11396
+ userMessageToolbarEditMessageLabel: "Edit",
11397
+ userMessageToolbarPreviousBranchLabel: "Previous branch",
11398
+ userMessageToolbarNextBranchLabel: "Next branch",
11399
+ chatDisclaimerText: "AI can make mistakes. Please verify important information.",
11400
+ chatToggleOpenLabel: "Open chat",
11401
+ chatToggleCloseLabel: "Close chat",
11402
+ chatScrollToBottomLabel: "Scroll to bottom",
11403
+ chatConnectingLabel: "Loading conversation",
11404
+ modalHeaderTitle: "CopilotKit Chat",
11405
+ welcomeMessageText: "How can I help you today?",
11406
+ reasoningMessageThinkingLabel: "Thinking…",
11407
+ chatInputSlashMenuLabel: "Slash commands",
11408
+ chatInputSlashMenuEmptyText: "No commands found",
11409
+ attachmentRemoveButtonLabel: "Remove attachment",
11410
+ attachmentPlayVideoButtonLabel: "Play video",
11411
+ attachmentPreviewCloseButtonLabel: "Close preview",
11412
+ modalHeaderCloseButtonLabel: "Close",
11413
+ modalHeaderThreadsButtonLabel: "Open threads",
11414
+ sidebarLabel: "Copilot chat sidebar",
11415
+ chatDropFilesLabel: "Drop files here",
11416
+ threadLoadErrorText: "Could not load saved conversation. Reopen the thread and try again.",
11417
+ reasoningMessageThoughtForLabel: "Thought for {duration}",
11418
+ reasoningMessageDurationFewSeconds: "a few seconds",
11419
+ reasoningMessageDurationSeconds: "{count} seconds",
11420
+ reasoningMessageDurationMinutesOne: "{count} minute",
11421
+ reasoningMessageDurationMinutesOther: "{count} minutes",
11422
+ reasoningMessageDurationMinutesSeconds: "{minutes}m {seconds}s",
11423
+ toolCallStatusRunningLabel: "Running",
11424
+ toolCallStatusDoneLabel: "Done",
11425
+ toolCallStatusFailedLabel: "Failed",
11426
+ toolCallStatusStoppedLabel: "Stopped",
11427
+ toolCallRunningLabel: "Running {name}",
11428
+ toolCallFailedCountLabel: "{count} failed",
11429
+ toolCallDoneCountLabel: "{count} done",
11430
+ toolCallArgumentsLabel: "Arguments",
11431
+ toolCallResultLabel: "Result",
11432
+ toolCallCollapseLabel: "Collapse",
11433
+ toolCallUsedToolsOne: "Used {count} tool",
11434
+ toolCallUsedToolsOther: "Used {count} tools",
11435
+ toolCallToolCountOne: "{count} tool",
11436
+ toolCallToolCountOther: "{count} tools",
11437
+ toolCallToolCallCountOne: "{count} tool call",
11438
+ toolCallToolCallCountOther: "{count} tool calls",
11439
+ toolCallCallCountOne: "{count} call",
11440
+ toolCallCallCountOther: "{count} calls",
11441
+ workSummaryWorkingLabel: "Working",
11442
+ workSummaryWorkedForLabel: "Worked for {duration}",
11443
+ attachmentImageLoadErrorText: "Failed to load image",
11444
+ attachmentImageAltText: "Image attachment",
11445
+ attachmentUnknownTypeText: "Unknown type",
11446
+ attachmentDocumentLabel: "Document",
11447
+ attachmentDocumentAltText: "Document attachment",
11448
+ attachmentNoPreviewText: "No preview available for this file type",
11449
+ chatAttachmentsUploadingText: "Cannot send while attachments are uploading.",
11450
+ transcriptionErrorRateLimitedText: "Too many requests. Please wait a moment.",
11451
+ transcriptionErrorAuthFailedText: "Authentication error. Please check your configuration.",
11452
+ transcriptionErrorAudioTooLongText: "Recording is too long. Please try a shorter recording.",
11453
+ transcriptionErrorAudioTooShortText: "Recording is too short. Please try again.",
11454
+ transcriptionErrorInvalidAudioFormatText: "Audio format not supported.",
11455
+ transcriptionErrorServiceNotConfiguredText: "Transcription service is not available.",
11456
+ transcriptionErrorNetworkText: "Network error. Please check your connection.",
11457
+ transcriptionErrorGenericText: "Transcription failed. Please try again.",
11458
+ licensePoweredByText: "Powered by CopilotKit",
11459
+ licenseGetLicenseLabel: "Get a license",
11460
+ licenseFeatureUnlicensedText: "⚠ The \"{feature}\" feature requires a CopilotKit license.",
11461
+ licenseExpiringText: "Your CopilotKit license expires soon. Please renew.",
11462
+ licenseExpiringInDaysOne: "Your CopilotKit license expires in {days} day. Please renew.",
11463
+ licenseExpiringInDaysOther: "Your CopilotKit license expires in {days} days. Please renew.",
11464
+ licenseExpiredText: "Your CopilotKit license expired. Please renew at copilotkit.ai/pricing",
11465
+ licenseExpiredOnDateText: "Your CopilotKit license expired on {date}. Please renew at copilotkit.ai/pricing",
11466
+ licenseInvalidText: "Invalid CopilotKit license token. Please check your configuration.",
11467
+ licenseRenewLabel: "Renew",
11468
+ licenseRenewNowLabel: "Renew now"
11469
+ });
11470
+ /**
11471
+ * Puts values into a label template. Each `{name}` in the template is replaced
11472
+ * by `values[name]`. A placeholder with no value stays in the text as is.
11473
+ *
11474
+ * @param template - A label value, such as `"Running {name}"`.
11475
+ * @param values - The value for each placeholder.
11476
+ *
11477
+ * ```ts
11478
+ * ɵformatLabel(labels.toolCallRunningLabel, { name: "read_file" });
11479
+ * // "Running read_file"
11480
+ * ```
11481
+ */
11482
+ function ɵformatLabel(template, values) {
11483
+ return template.replace(/\{(\w+)\}/g, (placeholder, name) => Object.hasOwn(values, name) ? String(values[name]) : placeholder);
11484
+ }
11485
+ /**
11486
+ * Fills a counted label pair: the `one` template for a count of 1, the
11487
+ * `other` template for any other count. Both templates take `{count}`.
11488
+ *
11489
+ * @param count - The number to show.
11490
+ * @param templates - The `...One` and `...Other` label templates.
11491
+ *
11492
+ * ```ts
11493
+ * ɵformatCountLabel(3, {
11494
+ * one: labels.toolCallToolCountOne,
11495
+ * other: labels.toolCallToolCountOther,
11496
+ * }); // "3 tools"
11497
+ * ```
11498
+ */
11499
+ function ɵformatCountLabel(count, templates) {
11500
+ return ɵformatLabel(count === 1 ? templates.one : templates.other, { count });
11501
+ }
11502
+
11503
+ //#endregion
11504
+ //#region src/chat/renderers.ts
11505
+ /** Name or activity type that matches anything. */
11506
+ const WILDCARD = "*";
11507
+ /**
11508
+ * Find the renderer that draws a tool call.
11509
+ *
11510
+ * The first rule that matches wins:
11511
+ *
11512
+ * 1. A renderer for `toolName` with `agentId` equal to the current agent.
11513
+ * 2. A renderer for `toolName` with no `agentId`.
11514
+ * 3. The first renderer for `toolName` from any other agent.
11515
+ * 4. The first `"*"` renderer, from any agent.
11516
+ *
11517
+ * Inside each rule, the earlier renderer in the list wins.
11518
+ *
11519
+ * @param renderers - Registered renderers in registration order. If you
11520
+ * build tiers (for example app renderers before built-in ones), flatten
11521
+ * them into one ordered list first.
11522
+ * @param toolName - Name of the tool the agent called.
11523
+ * @param agentId - The agent that owns the chat. The caller picks the
11524
+ * default: React and Vue pass `DEFAULT_AGENT_ID` when the chat has no
11525
+ * agent. With `undefined`, rule 1 matches the same renderers as rule 2.
11526
+ * @returns The renderer, or `null` when no renderer matches. Draw nothing
11527
+ * for `null`.
11528
+ *
11529
+ * @example
11530
+ * ```ts
11531
+ * const renderer = ɵresolveToolCallRenderer(
11532
+ * core.renderToolCalls,
11533
+ * toolCall.function.name,
11534
+ * chatAgentId ?? DEFAULT_AGENT_ID,
11535
+ * );
11536
+ * ```
11537
+ */
11538
+ function ɵresolveToolCallRenderer(renderers, toolName, agentId) {
11539
+ var _ref, _ref2, _ref3, _named$find;
11540
+ const named = renderers.filter((renderer) => renderer.name === toolName);
11541
+ 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;
11542
+ }
11543
+ /**
11544
+ * Find the renderer that draws an activity message, and validate the
11545
+ * message content with that renderer's `content` schema.
11546
+ *
11547
+ * The first rule that matches picks the renderer:
11548
+ *
11549
+ * 1. A renderer for `activityType` with `agentId` equal to the current agent.
11550
+ * 2. A renderer for `activityType` with no `agentId`.
11551
+ * 3. The first `"*"` renderer, from any agent.
11552
+ *
11553
+ * A renderer for `activityType` that belongs to a different agent never
11554
+ * matches. Inside each rule, the earlier renderer in the list wins.
11555
+ *
11556
+ * Only the picked renderer validates the content. When validation fails, or
11557
+ * the schema validates asynchronously, the result is `null`. The function
11558
+ * does not try the next renderer.
11559
+ *
11560
+ * @param renderers - Registered renderers in registration order.
11561
+ * @param query - The activity type, the current agent, and the raw content.
11562
+ * @returns `{ renderer, content }`, where `content` is the value the schema
11563
+ * returned. Pass that value to `render`, not the raw content. Returns
11564
+ * `null` when no renderer matches or validation does not pass.
11565
+ *
11566
+ * @example
11567
+ * ```ts
11568
+ * const match = ɵresolveActivityRenderer(core.renderActivityMessages, {
11569
+ * activityType: message.activityType,
11570
+ * agentId,
11571
+ * content: message.content,
11572
+ * });
11573
+ * if (match) draw(match.renderer.render, match.content);
11574
+ * ```
11575
+ */
11576
+ function ɵresolveActivityRenderer(renderers, query) {
11577
+ var _ref4, _sameType$find;
11578
+ const { activityType, agentId, content } = query;
11579
+ const sameType = renderers.filter((renderer) => renderer.activityType === activityType);
11580
+ 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);
11581
+ if (renderer === void 0) return null;
11582
+ const result = renderer.content["~standard"].validate(content);
11583
+ if (result instanceof Promise) return null;
11584
+ if (result.issues) return null;
11585
+ return {
11586
+ renderer,
11587
+ content: result.value
11588
+ };
11589
+ }
11590
+ /**
11591
+ * List the custom message renderers that apply to an agent, in the order to
11592
+ * try them.
11593
+ *
11594
+ * The list keeps renderers with no `agentId` and renderers for `agentId`.
11595
+ * Renderers for `agentId` come first. Inside each group, registration order
11596
+ * stays the same.
11597
+ *
11598
+ * The framework tries each renderer in this order and shows the first one
11599
+ * that draws something (a non-null result).
11600
+ *
11601
+ * @param renderers - Registered renderers in registration order.
11602
+ * @param agentId - The agent that owns the chat.
11603
+ * @returns A new array. Empty when no renderer applies.
11604
+ *
11605
+ * @example
11606
+ * ```ts
11607
+ * const candidates = ɵresolveCustomMessageRenderers(
11608
+ * core.renderCustomMessages,
11609
+ * agentId,
11610
+ * );
11611
+ * ```
11612
+ */
11613
+ function ɵresolveCustomMessageRenderers(renderers, agentId) {
11614
+ const scoped = renderers.filter((renderer) => renderer.agentId === agentId);
11615
+ const unscoped = renderers.filter((renderer) => renderer.agentId === void 0);
11616
+ return [...scoped, ...unscoped];
11617
+ }
11618
+
11619
+ //#endregion
11620
+ //#region src/chat/interrupt-types.ts
11621
+ /** Name of the legacy custom event agents emit to signal an interrupt. */
11622
+ const INTERRUPT_EVENT_NAME = "on_interrupt";
11623
+
11624
+ //#endregion
11625
+ //#region src/chat/tool-call-layout.ts
11626
+ function contentLength(content) {
11627
+ return typeof content === "string" ? content.length : JSON.stringify(content !== null && content !== void 0 ? content : "").length;
11628
+ }
11629
+ const entrySignature = ({ toolCall, toolMessage }) => [
11630
+ toolCall.id,
11631
+ toolCall.function.name,
11632
+ toolCall.function.arguments.length,
11633
+ toolMessage ? `${contentLength(toolMessage.content)}${toolMessage.error ? "!" : ""}` : "-"
11634
+ ].join(":");
11635
+ function signatureOf(segments) {
11636
+ return segments.map((segment) => segment.kind === "call" ? `c(${entrySignature(segment.call)})` : `g${segment.trailing ? "*" : ""}(${segment.calls.map(entrySignature).join(",")})`).join("|");
11637
+ }
11638
+ /**
11639
+ * Indexes tool results by the id of the call they answer.
11640
+ *
11641
+ * @param messages - The messages to search. Only `role: "tool"` messages count.
11642
+ */
11643
+ function getToolResults(messages) {
11644
+ const results = /* @__PURE__ */ new Map();
11645
+ for (const message of messages) if (message.role === "tool") results.set(message.toolCallId, message);
11646
+ return results;
11647
+ }
11648
+ /**
11649
+ * Lays out the tool calls of every assistant message in `rendered`.
11650
+ *
11651
+ * Calls drawn by a renderer that opted into grouping join the group that is
11652
+ * open. Anything else that shows between them closes it: assistant text, a
11653
+ * user, reasoning or activity message, or a call drawn by any other renderer.
11654
+ * A group belongs to the message where it starts, so later messages whose
11655
+ * calls joined it render no tool calls themselves.
11656
+ *
11657
+ * @param rendered - The messages as the chat renders them, in order.
11658
+ * @param all - Every message, for finding tool results (a transform may hide them).
11659
+ * @param renderers - The registered renderers, from `getToolCallRendererNames`.
11660
+ * @returns A map from assistant message id to its layout.
11661
+ *
11662
+ * @example
11663
+ * ```ts
11664
+ * const names = getToolCallRendererNames(core.renderToolCalls);
11665
+ * const layouts = getToolCallLayouts(renderedMessages, messages, names);
11666
+ * layouts.get(message.id)?.segments;
11667
+ * ```
11668
+ */
11669
+ function getToolCallLayouts(rendered, all, renderers) {
11670
+ const results = getToolResults(all);
11671
+ const layouts = /* @__PURE__ */ new Map();
11672
+ let open;
11673
+ for (const message of rendered) {
11674
+ var _message$toolCalls;
11675
+ if (message.role === "tool") continue;
11676
+ if (message.role !== "assistant") {
11677
+ open = void 0;
11678
+ continue;
11679
+ }
11680
+ if (typeof message.content === "string" && message.content.trim() !== "") open = void 0;
11681
+ const segments = [];
11682
+ layouts.set(message.id, segments);
11683
+ const toolCalls = /* @__PURE__ */ new Map();
11684
+ const messageToolCalls = (_message$toolCalls = message.toolCalls) !== null && _message$toolCalls !== void 0 ? _message$toolCalls : [];
11685
+ for (const toolCall of messageToolCalls) toolCalls.set(toolCall.id, toolCall);
11686
+ const uniqueToolCalls = toolCalls.values();
11687
+ for (const toolCall of uniqueToolCalls) {
11688
+ const entry = {
11689
+ toolCall,
11690
+ toolMessage: results.get(toolCall.id)
11691
+ };
11692
+ const name = toolCall.function.name;
11693
+ const named = renderers.named.has(name);
11694
+ const isRendered = named || renderers.wildcard;
11695
+ const groups = named ? renderers.groupedNames.has(name) : renderers.wildcardGroups;
11696
+ if (!isRendered || !groups) {
11697
+ if (isRendered) open = void 0;
11698
+ segments.push({
11699
+ kind: "call",
11700
+ id: toolCall.id,
11701
+ call: entry,
11702
+ rendered: isRendered
11703
+ });
11704
+ } else if (open) open.calls.push(entry);
11705
+ else {
11706
+ open = {
11707
+ kind: "group",
11708
+ id: toolCall.id,
11709
+ calls: [entry],
11710
+ trailing: false
11711
+ };
11712
+ segments.push(open);
11713
+ }
11714
+ }
11715
+ }
11716
+ if (open) open.trailing = true;
11717
+ const layout = /* @__PURE__ */ new Map();
11718
+ for (const [id, segments] of layouts) layout.set(id, {
11719
+ segments,
11720
+ signature: signatureOf(segments)
11721
+ });
11722
+ return layout;
11723
+ }
11724
+ const TOOL_CALL_SLOT_PREFIX = "tool-call-";
11725
+ const WILDCARD_TOOL_CALL_SLOT = "tool-call";
11726
+ /**
11727
+ * Works out which tool calls have a renderer and which of those group, for
11728
+ * `getToolCallLayouts`.
11729
+ *
11730
+ * @param renderers - The registered renderers. A renderer named `"*"` is the
11731
+ * wildcard. `group: true` opts the renderer into grouping.
11732
+ * @param options - Slots, extra named tools, and a built-in wildcard card.
11733
+ * See `ToolCallRendererNamesOptions`.
11734
+ *
11735
+ * @example
11736
+ * ```ts
11737
+ * // React: only registered renderers.
11738
+ * getToolCallRendererNames(core.renderToolCalls);
11739
+ * // Vue: the view's slots count too.
11740
+ * getToolCallRendererNames(core.renderToolCalls, { slotNames: Object.keys(slots) });
11741
+ * // Angular: client and human-in-the-loop renderers, and the built-in card.
11742
+ * getToolCallRendererNames(appRenderers, {
11743
+ * extraNamed: [...clientNames, ...hitlNames],
11744
+ * builtInWildcard: { enabled: defaultToolRenderingEnabled, groups: true },
11745
+ * });
11746
+ * ```
11747
+ */
11748
+ function getToolCallRendererNames(renderers, options = {}) {
11749
+ var _builtInWildcard$enab, _builtInWildcard$grou;
11750
+ const { slotNames = [], extraNamed = [], builtInWildcard } = options;
11751
+ const hasWildcardSlot = slotNames.includes(WILDCARD_TOOL_CALL_SLOT);
11752
+ const slotTools = slotNames.filter((name) => name.startsWith(TOOL_CALL_SLOT_PREFIX)).map((name) => name.slice(10));
11753
+ const named = renderers.filter((renderer) => renderer.name !== "*");
11754
+ const wildcards = renderers.filter((renderer) => renderer.name === "*");
11755
+ const hasAppWildcard = wildcards.length > 0;
11756
+ const isBuiltInEnabled = (_builtInWildcard$enab = builtInWildcard === null || builtInWildcard === void 0 ? void 0 : builtInWildcard.enabled) !== null && _builtInWildcard$enab !== void 0 ? _builtInWildcard$enab : false;
11757
+ const builtInGroups = isBuiltInEnabled && ((_builtInWildcard$grou = builtInWildcard === null || builtInWildcard === void 0 ? void 0 : builtInWildcard.groups) !== null && _builtInWildcard$grou !== void 0 ? _builtInWildcard$grou : false);
11758
+ const groupedNames = hasWildcardSlot ? [] : named.filter((renderer) => renderer.group && !slotTools.includes(renderer.name)).map((renderer) => renderer.name);
11759
+ const appWildcardGroups = wildcards.some((renderer) => renderer.group);
11760
+ return {
11761
+ named: new Set([
11762
+ ...named.map((renderer) => renderer.name),
11763
+ ...slotTools,
11764
+ ...extraNamed
11765
+ ]),
11766
+ groupedNames: new Set(groupedNames),
11767
+ wildcard: hasAppWildcard || hasWildcardSlot || isBuiltInEnabled,
11768
+ wildcardGroups: !hasWildcardSlot && (hasAppWildcard ? appWildcardGroups : builtInGroups)
11769
+ };
11770
+ }
11771
+ /** The turn key of a reply that no user message starts. */
11772
+ const FIRST_TURN_KEY = "start";
11773
+ /**
11774
+ * Finds the working phase of every reply in `rendered`: its messages up to the
11775
+ * last one that calls a tool. Text in there was narration. What follows is the
11776
+ * reply itself. Replies that called no tools are left out, except the latest,
11777
+ * which may be about to.
11778
+ *
11779
+ * @param rendered - The messages as the chat renders them, in order.
11780
+ * @param layouts - The layouts from `getToolCallLayouts` for the same messages.
11781
+ * @returns A map from turn key (see `TurnWork.key`) to the turn's work.
11782
+ */
11783
+ function getTurnWork(rendered, layouts) {
11784
+ const turns = /* @__PURE__ */ new Map();
11785
+ let start = 0;
11786
+ while (start < rendered.length) {
11787
+ let end = start;
11788
+ while (end < rendered.length && rendered[end].role !== "user") end++;
11789
+ const key = start > 0 ? rendered[start - 1].id : FIRST_TURN_KEY;
11790
+ const visible = rendered.slice(start, end).filter((message) => message.role !== "tool");
11791
+ const isLatest = end === rendered.length;
11792
+ const calls = [];
11793
+ for (const message of visible) {
11794
+ var _layouts$get$segments, _layouts$get;
11795
+ 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 : [];
11796
+ for (const segment of segments) if (segment.kind === "group") calls.push(...segment.calls);
11797
+ else if (segment.rendered) calls.push(segment.call);
11798
+ }
11799
+ const shown = new Set(calls.map((entry) => entry.toolCall.id));
11800
+ let lastWork = -1;
11801
+ visible.forEach((message, index) => {
11802
+ var _message$toolCalls2;
11803
+ 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;
11804
+ });
11805
+ const first = visible[0];
11806
+ if (first && (calls.length > 0 || isLatest)) {
11807
+ var _visible$lastAssistan;
11808
+ let lastAssistant = -1;
11809
+ visible.forEach((message, index) => {
11810
+ if (message.role === "assistant") lastAssistant = index;
11811
+ });
11812
+ const replyText = (_visible$lastAssistan = visible[lastAssistant]) === null || _visible$lastAssistan === void 0 ? void 0 : _visible$lastAssistan.content;
11813
+ const endsWithWork = lastAssistant >= 0 && lastAssistant <= lastWork && typeof replyText === "string" && replyText.trim().length > 0;
11814
+ turns.set(key, {
11815
+ key,
11816
+ firstMessageId: first.id,
11817
+ workMessageIds: new Set(visible.slice(0, lastWork + 1).map((message) => message.id)),
11818
+ replyTextMessageId: endsWithWork ? visible[lastAssistant].id : void 0,
11819
+ calls,
11820
+ isLatest
11821
+ });
11822
+ }
11823
+ start = end + 1;
11824
+ }
11825
+ return turns;
11826
+ }
11827
+ /**
11828
+ * The key of the latest reply (see `TurnWork.key`): the id of the last user
11829
+ * message, or `"start"` when there is none.
11830
+ *
11831
+ * @param rendered - The messages as the chat renders them, in order.
11832
+ */
11833
+ function getLatestTurnKey(rendered) {
11834
+ for (let i = rendered.length - 1; i >= 0; i--) {
11835
+ const message = rendered[i];
11836
+ if (message.role === "user") return message.id;
11837
+ }
11838
+ return FIRST_TURN_KEY;
11839
+ }
11840
+ /**
11841
+ * Whether the agent is working on this reply now: it is the latest one and a
11842
+ * run is going.
11843
+ *
11844
+ * @param turnKey - The reply's `TurnWork.key`.
11845
+ * @param state - The run state and the latest turn key.
11846
+ */
11847
+ function isTurnWorking(turnKey, state) {
11848
+ return state.isRunning && turnKey === state.latestTurnKey;
11849
+ }
11850
+ /**
11851
+ * Whether a reply's work shows. It shows while the agent works on the reply
11852
+ * and folds once the reply is done, unless the user opened or closed it.
11853
+ *
11854
+ * @param turnKey - The reply's `TurnWork.key`.
11855
+ * @param state - The user's toggles, the run state, and the latest turn key.
11856
+ */
11857
+ function isTurnWorkOpen(turnKey, state) {
11858
+ var _state$toggledTurns$g;
11859
+ return (_state$toggledTurns$g = state.toggledTurns.get(turnKey)) !== null && _state$toggledTurns$g !== void 0 ? _state$toggledTurns$g : isTurnWorking(turnKey, state);
11860
+ }
11861
+ /**
11862
+ * For each message in a reply's working phase, whether its work and its text
11863
+ * show. Text that ends the reply stays out of `workTextOpen` even when its
11864
+ * message also calls a tool, because it is the answer.
11865
+ *
11866
+ * @param turns - The turns from `getTurnWork`.
11867
+ * @param state - The user's toggles, the run state, and the latest turn key.
11868
+ * @returns The `workOpen` and `workTextOpen` maps of `ToolCallDisplayContextValue`.
11869
+ */
11870
+ function getWorkOpenState(turns, state) {
11871
+ const workOpen = /* @__PURE__ */ new Map();
11872
+ const workTextOpen = /* @__PURE__ */ new Map();
11873
+ for (const turn of turns) {
11874
+ const turnOpen = isTurnWorkOpen(turn.key, state);
11875
+ for (const id of turn.workMessageIds) {
11876
+ workOpen.set(id, turnOpen);
11877
+ if (id !== turn.replyTextMessageId) workTextOpen.set(id, turnOpen);
11878
+ }
11879
+ }
11880
+ return {
11881
+ workOpen,
11882
+ workTextOpen
11883
+ };
11884
+ }
11885
+ /**
11886
+ * Records run starts and ends in `workTimes`, for "Worked for 9s". Time spent
11887
+ * between runs (say, waiting for an approval) does not count. A reply is only
11888
+ * timed when this client saw it start from the user's message, so a restored
11889
+ * thread gets no entry. Calling it again with the same state changes nothing.
11890
+ *
11891
+ * @param workTimes - The times by turn key. This function updates it in place.
11892
+ * @param state - The run state now.
11893
+ * @param state.lastMessageRole - The role of the last rendered message.
11894
+ * @param state.now - The current time, in epoch ms.
11895
+ */
11896
+ function recordWorkTime(workTimes, state) {
11897
+ const { isRunning, latestTurnKey, lastMessageRole, now } = state;
11898
+ if (isRunning) {
11899
+ var _times$workingSince;
11900
+ const times = workTimes.get(latestTurnKey);
11901
+ if (times) (_times$workingSince = times.workingSince) !== null && _times$workingSince !== void 0 || (times.workingSince = now);
11902
+ else if (lastMessageRole === "user") workTimes.set(latestTurnKey, {
11903
+ elapsedMs: 0,
11904
+ workingSince: now
11905
+ });
11906
+ return;
11907
+ }
11908
+ const allTimes = workTimes.values();
11909
+ for (const times of allTimes) {
11910
+ if (times.workingSince === void 0) continue;
11911
+ times.elapsedMs += now - times.workingSince;
11912
+ times.workingSince = void 0;
11913
+ }
11914
+ }
11915
+ /**
11916
+ * The status of one call in a group. A call without a result is running only
11917
+ * while the group is active: once the run has moved on or ended, its result
11918
+ * is never coming.
11919
+ *
11920
+ * @param entry - The call and its result, if any.
11921
+ * @param active - The agent may still finish the group's calls.
11922
+ */
11923
+ function getToolCallRowStatus(entry, active) {
11924
+ const { toolMessage } = entry;
11925
+ let status;
11926
+ if (toolMessage) status = toolMessage.error ? "failed" : "done";
11927
+ else status = active ? "running" : "stopped";
11928
+ return status;
11929
+ }
11930
+ /**
11931
+ * The first non-empty string argument, with runs of whitespace collapsed to
11932
+ * one space. This is usually a command, path or query.
11933
+ *
11934
+ * @param parameters - The call's parsed arguments.
11935
+ * @returns The preview, or `undefined` when no argument is a non-empty string.
11936
+ */
11937
+ function getArgumentPreview(parameters) {
11938
+ if (!parameters || typeof parameters !== "object") return void 0;
11939
+ const value = Object.values(parameters).find((v) => typeof v === "string" && v.trim().length > 0);
11940
+ return value === null || value === void 0 ? void 0 : value.replace(/\s+/g, " ");
11941
+ }
11942
+ /**
11943
+ * `getArgumentPreview` for a call whose arguments may still be streaming in
11944
+ * as partial JSON.
11945
+ *
11946
+ * @param entry - The call.
11947
+ */
11948
+ function getToolCallPreview(entry) {
11949
+ return getArgumentPreview((0, _copilotkit_shared.partialJSONParse)(entry.toolCall.function.arguments));
11950
+ }
11951
+ /**
11952
+ * The names of the tools the calls used, in first-use order, with a count
11953
+ * for repeats: `"run_command ×2, read_file"`.
11954
+ *
11955
+ * @param calls - The calls to name.
11956
+ */
11957
+ function formatToolNames(calls) {
11958
+ const counts = /* @__PURE__ */ new Map();
11959
+ for (const { toolCall } of calls) {
11960
+ var _counts$get;
11961
+ const name = toolCall.function.name;
11962
+ counts.set(name, ((_counts$get = counts.get(name)) !== null && _counts$get !== void 0 ? _counts$get : 0) + 1);
11963
+ }
11964
+ return [...counts].map(([name, count]) => count > 1 ? `${name} ×${count}` : name).join(", ");
11965
+ }
11966
+ /**
11967
+ * How many of the calls finished with an error.
11968
+ *
11969
+ * @param calls - The calls to count.
11970
+ */
11971
+ function countFailedToolCalls(calls) {
11972
+ return calls.filter((call) => {
11973
+ var _call$toolMessage;
11974
+ return (_call$toolMessage = call.toolMessage) === null || _call$toolMessage === void 0 ? void 0 : _call$toolMessage.error;
11975
+ }).length;
11976
+ }
11977
+ /**
11978
+ * A count followed by the word that fits it: `"1 tool"`, `"3 tools"`.
11979
+ *
11980
+ * @param count - The number to show.
11981
+ * @param words - The word for exactly one (`one`) and for any other count (`other`).
11982
+ *
11983
+ * @example
11984
+ * ```ts
11985
+ * pluralize(3, { one: "tool", other: "tools" }); // "3 tools"
11986
+ * ```
11987
+ */
11988
+ function pluralize(count, words) {
11989
+ return `${count} ${count === 1 ? words.one : words.other}`;
11990
+ }
11991
+ /**
11992
+ * A tool call's arguments or result as display text. Strings pass through.
11993
+ * Other values are pretty-printed JSON. A value JSON cannot encode (say, a
11994
+ * circular reference) falls back to `String(value)`, then to
11995
+ * `"[unserializable]"`, so it never throws during a render.
11996
+ *
11997
+ * @param value - The arguments or the result.
11998
+ */
11999
+ function stringifyToolCallPayload(value) {
12000
+ if (typeof value === "string") return value;
12001
+ try {
12002
+ return JSON.stringify(value, null, 2);
12003
+ } catch (err) {
12004
+ console.warn("[CopilotKit] Failed to JSON.stringify tool-call payload; falling back to String():", err);
12005
+ try {
12006
+ return String(value);
12007
+ } catch (_unused) {
12008
+ return "[unserializable]";
12009
+ }
12010
+ }
12011
+ }
12012
+ /**
12013
+ * How long a `"turn"` reply worked, as short text: `"45s"`, `"1m 5s"`, `"2m"`.
12014
+ * Used for the live timer and the final duration. Partial seconds round down,
12015
+ * and a negative time reads `"0s"`.
12016
+ *
12017
+ * @param ms - The time in milliseconds.
12018
+ */
12019
+ function formatWorkDuration(ms) {
12020
+ const seconds = Math.max(0, Math.floor(ms / 1e3));
12021
+ if (seconds < 60) return `${seconds}s`;
12022
+ const minutes = Math.floor(seconds / 60);
12023
+ const rest = seconds % 60;
12024
+ return rest ? `${minutes}m ${rest}s` : `${minutes}m`;
12025
+ }
12026
+ /**
12027
+ * Splits a reasoning time into the unit and counts the "Thought for ..."
12028
+ * header shows. See `ReasoningDuration` for the text each unit maps to.
12029
+ *
12030
+ * - Under 1 second: `fewSeconds`.
12031
+ * - Under 60 seconds: `seconds`, rounded to the nearest second.
12032
+ * - Whole minutes after rounding the seconds: `minutes`.
12033
+ * - Otherwise: `minutesSeconds`.
12034
+ *
12035
+ * @param seconds - The elapsed time in seconds. It may have a fraction.
12036
+ */
12037
+ function formatReasoningDuration(seconds) {
12038
+ if (seconds < 1) return { unit: "fewSeconds" };
12039
+ if (seconds < 60) return {
12040
+ unit: "seconds",
12041
+ seconds: Math.round(seconds)
12042
+ };
12043
+ const minutes = Math.floor(seconds / 60);
12044
+ const rest = Math.round(seconds % 60);
12045
+ if (rest === 0) return {
12046
+ unit: "minutes",
12047
+ minutes
12048
+ };
12049
+ return {
12050
+ unit: "minutesSeconds",
12051
+ minutes,
12052
+ seconds: rest
12053
+ };
12054
+ }
12055
+
12056
+ //#endregion
12057
+ //#region src/chat/messages.ts
12058
+ /**
12059
+ * Collapses tool calls that share an id, keeping first-seen order.
12060
+ *
12061
+ * AG-UI's TOOL_CALL_START handler appends to the parent message's `toolCalls`
12062
+ * without checking whether that id is already present. When a start event is
12063
+ * applied twice (the human-in-the-loop flow does this when the run syncs after
12064
+ * `respond()`), the message carries the same call twice. The second copy has
12065
+ * empty `arguments`, because a start event carries none. The args arrive later
12066
+ * as TOOL_CALL_ARGS deltas addressed to the first copy.
12067
+ *
12068
+ * Left alone, the same tool call renders twice: once populated and once blank.
12069
+ * The blank copy is the redundant one, so the copy that carries arguments wins,
12070
+ * whatever order the two arrive in.
12071
+ *
12072
+ * @param toolCalls - The tool calls of one assistant message.
12073
+ * @returns The same array when no id repeats, so memoized consumers keep a
12074
+ * stable reference. Otherwise a new array with one entry per id.
12075
+ */
12076
+ function dedupeToolCalls(toolCalls) {
12077
+ const byId = /* @__PURE__ */ new Map();
12078
+ for (const toolCall of toolCalls) {
12079
+ var _existing$function, _toolCall$function;
12080
+ const existing = byId.get(toolCall.id);
12081
+ if (!existing) {
12082
+ byId.set(toolCall.id, toolCall);
12083
+ continue;
12084
+ }
12085
+ 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);
12086
+ }
12087
+ return byId.size === toolCalls.length ? toolCalls : [...byId.values()];
12088
+ }
12089
+ /**
12090
+ * Merges two snapshots of the same assistant message.
12091
+ *
12092
+ * - Empty `content` means a streaming update cleared the field, so the earlier
12093
+ * non-empty content is kept.
12094
+ * - `toolCalls: undefined` means the later chunk had no tool-call activity, so
12095
+ * the earlier tool calls are kept. An explicit `[]` is kept as-is.
12096
+ * - Fields that only the earlier snapshot has are kept.
12097
+ */
12098
+ function mergeAssistantMessages(existing, message) {
12099
+ var _message$toolCalls;
12100
+ const content = message.content || existing.content;
12101
+ const toolCalls = (_message$toolCalls = message.toolCalls) !== null && _message$toolCalls !== void 0 ? _message$toolCalls : existing.toolCalls;
12102
+ return {
12103
+ ...existing,
12104
+ ...message,
12105
+ content,
12106
+ toolCalls: toolCalls ? dedupeToolCalls(toolCalls) : toolCalls
12107
+ };
12108
+ }
12109
+ /**
12110
+ * Returns the assistant message with repeated tool-call ids collapsed. Returns
12111
+ * the same object when nothing collapsed.
12112
+ */
12113
+ function withDedupedToolCalls(message) {
12114
+ if (!message.toolCalls) return message;
12115
+ const toolCalls = dedupeToolCalls(message.toolCalls);
12116
+ return toolCalls === message.toolCalls ? message : {
12117
+ ...message,
12118
+ toolCalls
12119
+ };
12120
+ }
12121
+ /**
12122
+ * De-duplicates chat messages by id, for rendering.
12123
+ *
12124
+ * A message list from an agent can hold the same message id more than once
12125
+ * while it streams. This keeps one entry per id, at the position the id first
12126
+ * appears:
12127
+ *
12128
+ * - **Assistant messages** are merged. Later fields win, but empty `content`
12129
+ * falls back to earlier non-empty content, and `toolCalls: undefined` falls
12130
+ * back to earlier tool calls (an explicit `[]` is kept).
12131
+ * - **Tool calls** on an assistant message are de-duplicated by id, also
12132
+ * when the message itself is not repeated. The copy that has arguments
12133
+ * wins, and the first-seen order is kept.
12134
+ * - **Other roles** keep the last copy.
12135
+ *
12136
+ * @param messages - The agent's messages, in order.
12137
+ * @returns A new array. A message that needed no change is returned as the
12138
+ * same object.
12139
+ *
12140
+ * @example
12141
+ * ```ts
12142
+ * const visible = ɵdeduplicateMessages(agent.messages);
12143
+ * ```
12144
+ */
12145
+ function ɵdeduplicateMessages(messages) {
12146
+ const byId = /* @__PURE__ */ new Map();
12147
+ for (const message of messages) {
12148
+ if (message.role !== "assistant") {
12149
+ byId.set(message.id, message);
12150
+ continue;
12151
+ }
12152
+ const existing = byId.get(message.id);
12153
+ const merged = (existing === null || existing === void 0 ? void 0 : existing.role) === "assistant" ? mergeAssistantMessages(existing, message) : withDedupedToolCalls(message);
12154
+ byId.set(message.id, merged);
12155
+ }
12156
+ return [...byId.values()];
12157
+ }
12158
+ /**
12159
+ * Serializes object content for {@link ɵmessagesFingerprint}.
12160
+ *
12161
+ * `JSON.stringify` throws on a circular structure (and on a `BigInt`). The
12162
+ * fingerprint runs on every render, so a throw would take the chat down. A
12163
+ * value that cannot be serialized gets a constant key instead: it does not
12164
+ * trigger a change on its own, but every other part of the fingerprint still
12165
+ * does.
12166
+ */
12167
+ function objectContentKey(content) {
12168
+ try {
12169
+ var _JSON$stringify;
12170
+ return (_JSON$stringify = JSON.stringify(content)) !== null && _JSON$stringify !== void 0 ? _JSON$stringify : "";
12171
+ } catch (_unused) {
12172
+ return "[unserializable]";
12173
+ }
12174
+ }
12175
+ /**
12176
+ * Gives the part of the fingerprint that tracks a message's content:
12177
+ * - string content: its length, so streamed text changes it.
12178
+ * - array content: the part count, so an added attachment changes it. The
12179
+ * parts are not serialized, which keeps base64 uploads out of the key.
12180
+ * - object content (activity messages): its JSON, so a snapshot that replaces
12181
+ * the content under the same message id changes it.
12182
+ */
12183
+ function contentKey(content) {
12184
+ if (typeof content === "string" || Array.isArray(content)) return String(content.length);
12185
+ if (content !== null && typeof content === "object") return objectContentKey(content);
12186
+ return "0";
12187
+ }
12188
+ /**
12189
+ * Builds a string that changes whenever a render of the message list could
12190
+ * change. Use it as a cheap memo key in place of a deep comparison.
12191
+ *
12192
+ * The key covers, per message:
12193
+ * - the id and the role.
12194
+ * - the content: text length, part count, or the JSON of object content.
12195
+ * - the `toolCallId` of a tool message.
12196
+ * - each tool call's id and the length of its arguments, so streamed
12197
+ * arguments change the key.
12198
+ *
12199
+ * It never throws. Object content that cannot be serialized (for example a
12200
+ * circular tool result) gets a constant key.
12201
+ *
12202
+ * @param messages - The agent's messages, in order.
12203
+ * @returns The fingerprint string.
12204
+ *
12205
+ * @example
12206
+ * ```ts
12207
+ * const key = ɵmessagesFingerprint(agent.messages);
12208
+ * if (key !== previousKey) rerender();
12209
+ * ```
12210
+ */
12211
+ function ɵmessagesFingerprint(messages) {
12212
+ return messages.map((message) => {
12213
+ const toolCallId = "toolCallId" in message ? message.toolCallId : "";
12214
+ const toolCallsKey = ("toolCalls" in message && Array.isArray(message.toolCalls) ? message.toolCalls : []).map((tc) => {
12215
+ var _tc$function$argument, _tc$function;
12216
+ 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}`;
12217
+ }).join(";");
12218
+ return `${message.id}:${message.role}:${contentKey(message.content)}:${toolCallId}:${toolCallsKey}`;
12219
+ }).join(",");
12220
+ }
12221
+
12222
+ //#endregion
12223
+ //#region src/chat/composer.ts
12224
+ /**
12225
+ * Get the state of the send/stop button in the chat input.
12226
+ *
12227
+ * @param input - The current state of the chat input.
12228
+ * @returns
12229
+ * - `isProcessing`: the agent runs and the input does not record audio.
12230
+ * - `canSend`: the text is not empty and nothing blocks a send.
12231
+ * - `action`: `"stop"` when the button stops the run, else `"send"`.
12232
+ * Use it for the icon, the label, and the click.
12233
+ * - `disabled`: `true` when a click does nothing.
12234
+ *
12235
+ * @example
12236
+ * ```ts
12237
+ * const button = ɵcomposerButtonState({
12238
+ * mode: "input",
12239
+ * isRunning: agent.isRunning,
12240
+ * value: text,
12241
+ * canSubmit: true,
12242
+ * canStop: true,
12243
+ * });
12244
+ * // On click:
12245
+ * if (button.action === "stop") stopRun();
12246
+ * else if (button.canSend) sendMessage(text.trim());
12247
+ * ```
12248
+ */
12249
+ function ɵcomposerButtonState(input) {
12250
+ const isProcessing = input.mode !== "transcribe" && input.isRunning;
12251
+ const isSendBlocked = input.disabled === true || input.attachmentsUploading === true;
12252
+ const canSend = input.canSubmit && !isSendBlocked && input.value.trim().length > 0;
12253
+ return {
12254
+ isProcessing,
12255
+ canSend,
12256
+ action: isProcessing && input.canStop ? "stop" : "send",
12257
+ disabled: isProcessing ? !input.canStop : !canSend
12258
+ };
12259
+ }
12260
+ /**
12261
+ * Decide what a key press in the chat input does.
12262
+ *
12263
+ * This handles Enter only. Keys for the slash-command menu stay in each
12264
+ * framework, and the framework handles them before it calls this function.
12265
+ *
12266
+ * Results:
12267
+ * - `"send"`: send the trimmed text.
12268
+ * - `"stop"`: stop the run. This happens for Enter in an empty input while
12269
+ * the agent runs. Text in the input always means send, not stop.
12270
+ * - `"newline"`: Shift+Enter. Let the browser add the line break.
12271
+ * - `"none"`: do nothing. Returned during IME composition, while the input
12272
+ * is disabled, for keys other than Enter, and for an Enter that has
12273
+ * nothing to send or stop.
12274
+ *
12275
+ * Call `preventDefault()` for every Enter without Shift that is not part of
12276
+ * IME composition, including when the result is `"none"`. This stops Enter
12277
+ * from adding a line break that the user cannot send.
12278
+ *
12279
+ * @param event - The keyboard event, or an object with the same fields.
12280
+ * @param input - The current state of the chat input.
12281
+ *
12282
+ * @example
12283
+ * ```ts
12284
+ * function onKeyDown(event: KeyboardEvent) {
12285
+ * if (event.isComposing || event.keyCode === 229) return;
12286
+ * // ...slash-command menu keys...
12287
+ * const result = ɵresolveComposerKey(event, composerInput);
12288
+ * if (event.key === "Enter" && !event.shiftKey) event.preventDefault();
12289
+ * if (result === "send") sendMessage(composerInput.value.trim());
12290
+ * if (result === "stop") stopRun();
12291
+ * }
12292
+ * ```
12293
+ */
12294
+ function ɵresolveComposerKey(event, input) {
12295
+ if (event.isComposing || event.keyCode === 229 || input.disabled === true || event.key !== "Enter") return "none";
12296
+ if (event.shiftKey) return "newline";
12297
+ const button = ɵcomposerButtonState(input);
12298
+ const isEmpty = input.value.trim().length === 0;
12299
+ if (button.isProcessing && isEmpty) return input.canStop ? "stop" : "none";
12300
+ return button.canSend ? "send" : "none";
12301
+ }
12302
+
12303
+ //#endregion
12304
+ //#region src/chat/transcription.ts
12305
+ /**
12306
+ * The error `ɵtranscribeAudio` throws. Read `error.info.code` to pick a
12307
+ * message for the user, or pass `error.info` to
12308
+ * `ɵtranscriptionErrorMessageKey`.
12309
+ */
12310
+ var TranscriptionError = class extends Error {
12311
+ constructor(info) {
12312
+ super(info.message);
12313
+ _defineProperty(this, "info", void 0);
12314
+ this.name = "TranscriptionError";
12315
+ this.info = info;
12316
+ }
12317
+ };
12318
+ /**
12319
+ * Send a recording to the CopilotKit runtime and get its text back.
12320
+ *
12321
+ * The request follows the transport set on the core:
12322
+ * - `"single"`: one JSON POST to `runtimeUrl`, with the audio as base64.
12323
+ * - any other transport: a multipart POST to `${runtimeUrl}/transcribe`.
12324
+ *
12325
+ * Headers are resolved on each call. The core's `credentials` are sent when
12326
+ * they are set, the same as for agent requests.
12327
+ *
12328
+ * @param core - The `CopilotKitCore` (or a framework subclass) to send through.
12329
+ * @param audioBlob - The recorded audio.
12330
+ * @param filename - The file name the runtime sees. Defaults to `"recording.webm"`.
12331
+ * @returns The transcription result, with the text in `result.text`.
12332
+ * @throws {TranscriptionError} When the runtime URL is not set, the request
12333
+ * fails, or the runtime returns an error. `error.info` has the code.
12334
+ *
12335
+ * @example
12336
+ * ```ts
12337
+ * try {
12338
+ * const { text } = await ɵtranscribeAudio(core, blob);
12339
+ * } catch (error) {
12340
+ * if (error instanceof TranscriptionError) {
12341
+ * const key = ɵtranscriptionErrorMessageKey(error.info);
12342
+ * showError(key ? labels[key] : error.info.message);
12343
+ * }
12344
+ * }
12345
+ * ```
12346
+ */
12347
+ async function ɵtranscribeAudio(core, audioBlob, filename = "recording.webm") {
12348
+ const { runtimeUrl, credentials } = core;
12349
+ if (!runtimeUrl) throw new TranscriptionError({
12350
+ code: _copilotkit_shared.TranscriptionErrorCode.INVALID_REQUEST,
12351
+ message: "Runtime URL is not configured",
12352
+ retryable: false
12353
+ });
12354
+ const resolvedHeaders = await core.resolveHeaders();
12355
+ const credentialsInit = credentials ? { credentials } : {};
12356
+ let response;
12357
+ try {
12358
+ response = core.runtimeTransport === "single" ? await fetch(runtimeUrl, {
12359
+ method: "POST",
12360
+ headers: {
12361
+ ...omitContentType(resolvedHeaders),
12362
+ "Content-Type": "application/json"
12363
+ },
12364
+ body: JSON.stringify({
12365
+ method: "transcribe",
12366
+ body: {
12367
+ audio: await blobToBase64(audioBlob),
12368
+ mimeType: audioBlob.type || "audio/webm",
12369
+ filename
12370
+ }
12371
+ }),
12372
+ ...credentialsInit
12373
+ }) : await fetch(`${runtimeUrl}/transcribe`, {
12374
+ method: "POST",
12375
+ headers: omitContentType(resolvedHeaders),
12376
+ body: toFormData(audioBlob, filename),
12377
+ ...credentialsInit
12378
+ });
12379
+ } catch (error) {
12380
+ throw new TranscriptionError({
12381
+ code: _copilotkit_shared.TranscriptionErrorCode.NETWORK_ERROR,
12382
+ message: error instanceof Error ? error.message : "Network request failed",
12383
+ retryable: true
12384
+ });
12385
+ }
12386
+ if (!response.ok) throw await toTranscriptionError(response);
12387
+ return await response.json();
12388
+ }
12389
+ /**
12390
+ * Pick the chat label to show the user for a transcription error.
12391
+ *
12392
+ * @param error - The `info` of a `TranscriptionError`.
12393
+ * @returns A key of the chat labels, or `null`. `null` means no label fits:
12394
+ * show `error.message` instead.
12395
+ *
12396
+ * @example
12397
+ * ```ts
12398
+ * const key = ɵtranscriptionErrorMessageKey(error.info);
12399
+ * const text = key ? labels[key] : error.info.message;
12400
+ * ```
12401
+ */
12402
+ function ɵtranscriptionErrorMessageKey(error) {
12403
+ switch (error.code) {
12404
+ case _copilotkit_shared.TranscriptionErrorCode.RATE_LIMITED: return "transcriptionErrorRateLimitedText";
12405
+ case _copilotkit_shared.TranscriptionErrorCode.AUTH_FAILED: return "transcriptionErrorAuthFailedText";
12406
+ case _copilotkit_shared.TranscriptionErrorCode.AUDIO_TOO_LONG: return "transcriptionErrorAudioTooLongText";
12407
+ case _copilotkit_shared.TranscriptionErrorCode.AUDIO_TOO_SHORT: return "transcriptionErrorAudioTooShortText";
12408
+ case _copilotkit_shared.TranscriptionErrorCode.INVALID_AUDIO_FORMAT: return "transcriptionErrorInvalidAudioFormatText";
12409
+ case _copilotkit_shared.TranscriptionErrorCode.SERVICE_NOT_CONFIGURED: return "transcriptionErrorServiceNotConfiguredText";
12410
+ case _copilotkit_shared.TranscriptionErrorCode.NETWORK_ERROR: return "transcriptionErrorNetworkText";
12411
+ case _copilotkit_shared.TranscriptionErrorCode.PROVIDER_ERROR:
12412
+ case _copilotkit_shared.TranscriptionErrorCode.INVALID_REQUEST:
12413
+ default: return error.retryable ? "transcriptionErrorGenericText" : null;
12414
+ }
12415
+ }
12416
+ function toFormData(audioBlob, filename) {
12417
+ const formData = new FormData();
12418
+ formData.append("audio", audioBlob, filename);
12419
+ return formData;
12420
+ }
12421
+ function omitContentType(headers) {
12422
+ const entries = Object.entries(headers);
12423
+ return Object.fromEntries(entries.filter(([name]) => name.toLowerCase() !== "content-type"));
12424
+ }
12425
+ async function blobToBase64(blob) {
12426
+ const bytes = new Uint8Array(await blob.arrayBuffer());
12427
+ const chunkSize = 32768;
12428
+ let binary = "";
12429
+ for (let offset = 0; offset < bytes.length; offset += chunkSize) binary += String.fromCharCode(...bytes.subarray(offset, offset + chunkSize));
12430
+ return btoa(binary);
12431
+ }
12432
+ /** Build a typed error from a non-OK transcription response. */
12433
+ async function toTranscriptionError(response) {
12434
+ const retryable = response.status >= 500;
12435
+ let data;
12436
+ try {
12437
+ data = await response.json();
12438
+ } catch (_unused) {
12439
+ return new TranscriptionError({
12440
+ code: _copilotkit_shared.TranscriptionErrorCode.PROVIDER_ERROR,
12441
+ message: `HTTP ${response.status}: ${response.statusText}`,
12442
+ retryable
12443
+ });
12444
+ }
12445
+ if (isTranscriptionErrorResponse(data)) {
12446
+ var _data$retryable;
12447
+ return new TranscriptionError({
12448
+ code: data.error,
12449
+ message: data.message,
12450
+ retryable: (_data$retryable = data.retryable) !== null && _data$retryable !== void 0 ? _data$retryable : false
12451
+ });
12452
+ }
12453
+ const message = typeof data === "object" && data !== null && "message" in data ? String(data.message) : "Transcription failed";
12454
+ return new TranscriptionError({
12455
+ code: _copilotkit_shared.TranscriptionErrorCode.PROVIDER_ERROR,
12456
+ message,
12457
+ retryable
12458
+ });
12459
+ }
12460
+ function isTranscriptionErrorResponse(data) {
12461
+ return typeof data === "object" && data !== null && "error" in data && "message" in data && typeof data.error === "string" && typeof data.message === "string";
12462
+ }
12463
+
12464
+ //#endregion
12465
+ //#region src/chat/license.ts
12466
+ /**
12467
+ * Resolves the license context and the license banner from the runtime
12468
+ * license authority. React, Vue, and Angular call it with the values core
12469
+ * reports, then show the banner and provide the context.
12470
+ *
12471
+ * Rules:
12472
+ *
12473
+ * - A retryable entitlement failure that core is still retrying hides the
12474
+ * status, so no banner shows until the retry ends. A `valid` or `expiring`
12475
+ * legacy status stays in use during the retry.
12476
+ * - A terminal entitlement failure (not retryable, no `valid` or `expiring`
12477
+ * legacy status) keeps the reported status, but `checkFeature` returns
12478
+ * `false` and `getLimit` returns `null` for every feature.
12479
+ * - The `no_license` banner shows only when the status is `none` and no
12480
+ * public key is set.
12481
+ *
12482
+ * The banner text has no day count. No data source gives the days left.
12483
+ *
12484
+ * @param input - The runtime license values and the public key. See
12485
+ * {@link LicenseStateInput}.
12486
+ * @returns `context` for the license context, `warningStatus` (the status the
12487
+ * banner is based on, `undefined` while a retry runs), and `bannerType`
12488
+ * (`null` when no banner shows).
12489
+ *
12490
+ * @example
12491
+ * ```ts
12492
+ * const { context, bannerType } = ɵresolveLicenseState({
12493
+ * status: core.licenseStatus,
12494
+ * entitlements: core.runtimeEntitlements,
12495
+ * retryPending: core.runtimeEntitlementRetryPending,
12496
+ * publicKey,
12497
+ * });
12498
+ * ```
12499
+ */
12500
+ function ɵresolveLicenseState({ status, entitlements, retryPending, publicKey }) {
12501
+ var _context$status;
12502
+ const isRetryableFailure = (entitlements === null || entitlements === void 0 ? void 0 : entitlements.status) !== "ready" && (entitlements === null || entitlements === void 0 ? void 0 : entitlements.error.retryable) === true;
12503
+ const isNonReady = entitlements !== void 0 && entitlements.status !== "ready";
12504
+ const hasLegacyFallback = status === "valid" || status === "expiring";
12505
+ const isRetrying = isRetryableFailure && retryPending && !hasLegacyFallback;
12506
+ const isTerminalFailure = isNonReady && !isRetryableFailure && !hasLegacyFallback;
12507
+ const runtimeContext = (0, _copilotkit_shared.createLicenseContextValue)(isRetrying ? void 0 : status, entitlements);
12508
+ const context = isTerminalFailure ? {
12509
+ ...runtimeContext,
12510
+ checkFeature: () => false,
12511
+ getLimit: () => null
12512
+ } : runtimeContext;
12513
+ const warningStatus = isRetrying ? void 0 : (_context$status = context.status) !== null && _context$status !== void 0 ? _context$status : void 0;
12514
+ return {
12515
+ context,
12516
+ warningStatus,
12517
+ bannerType: resolveLicenseBannerType(warningStatus, publicKey)
12518
+ };
12519
+ }
12520
+ function resolveLicenseBannerType(warningStatus, publicKey) {
12521
+ switch (warningStatus) {
12522
+ case "none": return publicKey ? null : "no_license";
12523
+ case "expired":
12524
+ case "invalid":
12525
+ case "expiring": return warningStatus;
12526
+ case "valid":
12527
+ case "unknown":
12528
+ case void 0: return null;
12529
+ }
12530
+ }
12531
+ /**
12532
+ * Resolves whether the threads drawer can load its thread list.
12533
+ *
12534
+ * - `licensed` is `true` when the status is `unknown` (an entitlement lookup
12535
+ * that did not recover, so the threads endpoint decides), or when the
12536
+ * status is `valid` or `expiring` and `checkFeature("threads")` is `true`.
12537
+ * - `licensePending` is `true` while the status is `null` (the runtime has
12538
+ * not reported yet). Show the loading state then, not the locked view.
12539
+ *
12540
+ * @param context - The license context from {@link ɵresolveLicenseState}.
12541
+ *
12542
+ * @example
12543
+ * ```ts
12544
+ * const { licensed, licensePending } = ɵresolveThreadsLicense(context);
12545
+ * ```
12546
+ */
12547
+ function ɵresolveThreadsLicense(context) {
12548
+ const { status } = context;
12549
+ return {
12550
+ licensed: status === "unknown" || (status === "valid" || status === "expiring") && context.checkFeature("threads"),
12551
+ licensePending: status === null
12552
+ };
12553
+ }
12554
+ const PRICING_URL = "https://copilotkit.ai/pricing";
12555
+ const DASHBOARD_URL = "https://dashboard.operations.copilotkit.ai";
12556
+ /**
12557
+ * What one license banner shows: its severity, text, and link. React, Vue,
12558
+ * and Angular render it with {@link ɵLICENSE_BANNER_STYLE}.
12559
+ *
12560
+ * @param type - The banner type, for example from
12561
+ * {@link ɵresolveLicenseState}'s `bannerType`.
12562
+ * @param labels - The chat labels in effect, so apps can translate the text.
12563
+ * @param details - The feature name, expiry date, or days left.
12564
+ *
12565
+ * @example
12566
+ * ```ts
12567
+ * const spec = ɵgetLicenseBannerSpec("expiring", labels, { graceRemaining: 3 });
12568
+ * // { severity: "warning", message: "… expires in 3 days …", actionLabel: "Renew", … }
12569
+ * ```
12570
+ */
12571
+ function ɵgetLicenseBannerSpec(type, labels, { featureName, expiryDate, graceRemaining } = {}) {
12572
+ switch (type) {
12573
+ case "no_license": return bannerSpec("info", labels.licensePoweredByText, labels.licenseGetLicenseLabel, PRICING_URL);
12574
+ case "feature_unlicensed": return bannerSpec("warning", ɵformatLabel(labels.licenseFeatureUnlicensedText, { feature: featureName !== null && featureName !== void 0 ? featureName : "" }), labels.licenseGetLicenseLabel, PRICING_URL);
12575
+ case "expiring": return bannerSpec("warning", expiringMessage(labels, graceRemaining), labels.licenseRenewLabel, DASHBOARD_URL);
12576
+ case "expired": return bannerSpec("critical", expiryDate ? ɵformatLabel(labels.licenseExpiredOnDateText, { date: expiryDate }) : labels.licenseExpiredText, labels.licenseRenewNowLabel, PRICING_URL);
12577
+ case "invalid": return bannerSpec("critical", labels.licenseInvalidText, labels.licenseGetLicenseLabel, PRICING_URL);
12578
+ }
12579
+ }
12580
+ const bannerSpec = (severity, message, actionLabel, actionUrl) => ({
12581
+ severity,
12582
+ message,
12583
+ actionLabel,
12584
+ actionUrl
12585
+ });
12586
+ /**
12587
+ * The "expires soon" text. Without a day count it says "soon", never "in
12588
+ * undefined days".
12589
+ */
12590
+ function expiringMessage(labels, graceRemaining) {
12591
+ if (graceRemaining === void 0) return labels.licenseExpiringText;
12592
+ return ɵformatLabel(graceRemaining === 1 ? labels.licenseExpiringInDaysOne : labels.licenseExpiringInDaysOther, { days: graceRemaining });
12593
+ }
12594
+ const FONT_FAMILY = "-apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif";
12595
+ /**
12596
+ * Inline styles of the fixed license banner, in camelCase, for React `style`
12597
+ * and Vue `:style`. `base` is the layout; `severity` holds the colours.
12598
+ */
12599
+ const ɵLICENSE_BANNER_STYLE = {
12600
+ base: {
12601
+ position: "fixed",
12602
+ bottom: "8px",
12603
+ left: "50%",
12604
+ transform: "translateX(-50%)",
12605
+ zIndex: 99999,
12606
+ display: "inline-flex",
12607
+ alignItems: "center",
12608
+ gap: "12px",
12609
+ whiteSpace: "nowrap",
12610
+ padding: "8px 16px",
12611
+ fontSize: "13px",
12612
+ fontFamily: FONT_FAMILY,
12613
+ borderRadius: "6px",
12614
+ boxShadow: "0 2px 8px rgba(0, 0, 0, 0.15)"
12615
+ },
12616
+ severity: {
12617
+ info: {
12618
+ backgroundColor: "#eff6ff",
12619
+ border: "1px solid #93c5fd",
12620
+ color: "#1e40af"
12621
+ },
12622
+ warning: {
12623
+ backgroundColor: "#fffbeb",
12624
+ border: "1px solid #fbbf24",
12625
+ color: "#92400e"
12626
+ },
12627
+ critical: {
12628
+ backgroundColor: "#fef2f2",
12629
+ border: "1px solid #fca5a5",
12630
+ color: "#991b1b"
12631
+ }
12632
+ },
12633
+ actions: {
12634
+ display: "flex",
12635
+ gap: "8px",
12636
+ alignItems: "center"
12637
+ },
12638
+ link: {
12639
+ fontWeight: 600,
12640
+ textDecoration: "underline",
12641
+ color: "inherit"
12642
+ },
12643
+ dismiss: {
12644
+ background: "none",
12645
+ border: "none",
12646
+ cursor: "pointer",
12647
+ color: "inherit",
12648
+ fontSize: "16px"
12649
+ }
12650
+ };
12651
+ /**
12652
+ * The bottom space the fixed banner takes: banner height (~36px) + bottom
12653
+ * offset (8px) + gap above the chat input (~8px). The chat input reads it
12654
+ * through `padding-bottom: var(--copilotkit-license-banner-offset)`.
12655
+ */
12656
+ const ɵLICENSE_BANNER_OFFSET = {
12657
+ cssVar: "--copilotkit-license-banner-offset",
12658
+ px: 52
12659
+ };
12660
+ /**
12661
+ * Publishes {@link ɵLICENSE_BANNER_OFFSET} on the root element while a
12662
+ * banner shows. Does nothing without a document (SSR).
12663
+ *
12664
+ * @returns A function that removes the offset again.
12665
+ */
12666
+ function ɵreserveLicenseBannerOffset() {
12667
+ if (typeof document === "undefined") return () => {};
12668
+ const root = document.documentElement;
12669
+ root.style.setProperty(ɵLICENSE_BANNER_OFFSET.cssVar, `${ɵLICENSE_BANNER_OFFSET.px}px`);
12670
+ return () => root.style.removeProperty(ɵLICENSE_BANNER_OFFSET.cssVar);
12671
+ }
12672
+ /**
12673
+ * What the inline warning shows when a chat component needs a license it
12674
+ * does not have: the `licenseFeatureUnlicensedText` label and a pricing
12675
+ * link. Render it with {@link ɵINLINE_FEATURE_WARNING_STYLE}.
12676
+ */
12677
+ function ɵgetInlineFeatureWarningSpec(featureName, labels) {
12678
+ return {
12679
+ message: ɵformatLabel(labels.licenseFeatureUnlicensedText, { feature: featureName }),
12680
+ actionLabel: "Get one at copilotkit.ai/pricing",
12681
+ actionUrl: PRICING_URL
12682
+ };
12683
+ }
12684
+ /** Inline styles of the inline feature warning, in camelCase. */
12685
+ const ɵINLINE_FEATURE_WARNING_STYLE = {
12686
+ container: {
12687
+ padding: "8px 12px",
12688
+ backgroundColor: "#fffbeb",
12689
+ border: "1px solid #fbbf24",
12690
+ borderRadius: "6px",
12691
+ fontSize: "13px",
12692
+ color: "#92400e",
12693
+ fontFamily: FONT_FAMILY
12694
+ },
12695
+ link: {
12696
+ color: "#b45309",
12697
+ textDecoration: "underline"
12698
+ }
12699
+ };
12700
+
12701
+ //#endregion
12702
+ //#region src/chat/icons.ts
12703
+ /*! @license
12704
+ * The icon data below is copied from Lucide v0.525.0 (https://lucide.dev).
12705
+ * The Lucide license follows. A copy is in LUCIDE-LICENSE.md next to this file.
12706
+ * This comment sits right above runtime code so the bundler keeps it in dist.
12707
+ *
12708
+ * ISC License
12709
+ *
12710
+ * 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.
12711
+ *
12712
+ * Permission to use, copy, modify, and/or distribute this software for any
12713
+ * purpose with or without fee is hereby granted, provided that the above
12714
+ * copyright notice and this permission notice appear in all copies.
12715
+ *
12716
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12717
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12718
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12719
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12720
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
12721
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
12722
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
12723
+ */
12724
+ function path(d) {
12725
+ return {
12726
+ tag: "path",
12727
+ attributes: { d }
12728
+ };
12729
+ }
12730
+ const icons = {
12731
+ ArrowUp: {
12732
+ name: "arrow-up",
12733
+ nodes: [path("m5 12 7-7 7 7"), path("M12 19V5")]
12734
+ },
12735
+ Check: {
12736
+ name: "check",
12737
+ nodes: [path("M20 6 9 17l-5-5")]
12738
+ },
12739
+ ChevronDown: {
12740
+ name: "chevron-down",
12741
+ nodes: [path("m6 9 6 6 6-6")]
12742
+ },
12743
+ ChevronLeft: {
12744
+ name: "chevron-left",
12745
+ nodes: [path("m15 18-6-6 6-6")]
12746
+ },
12747
+ ChevronRight: {
12748
+ name: "chevron-right",
12749
+ nodes: [path("m9 18 6-6-6-6")]
12750
+ },
12751
+ Circle: {
12752
+ name: "circle",
12753
+ nodes: [{
12754
+ tag: "circle",
12755
+ attributes: {
12756
+ cx: "12",
12757
+ cy: "12",
12758
+ r: "10"
12759
+ }
12760
+ }]
12761
+ },
12762
+ Copy: {
12763
+ name: "copy",
12764
+ nodes: [{
12765
+ tag: "rect",
12766
+ attributes: {
12767
+ width: "14",
12768
+ height: "14",
12769
+ x: "8",
12770
+ y: "8",
12771
+ rx: "2",
12772
+ ry: "2"
12773
+ }
12774
+ }, path("M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2")]
12775
+ },
12776
+ Edit: {
12777
+ name: "square-pen",
12778
+ 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")]
12779
+ },
12780
+ EyeOff: {
12781
+ name: "eye-off",
12782
+ nodes: [
12783
+ 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"),
12784
+ path("M14.084 14.158a3 3 0 0 1-4.242-4.242"),
12785
+ 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"),
12786
+ path("m2 2 20 20")
12787
+ ]
12788
+ },
12789
+ Loader2: {
12790
+ name: "loader-circle",
12791
+ nodes: [path("M21 12a9 9 0 1 1-6.219-8.56")]
12792
+ },
12793
+ MessageCircle: {
12794
+ name: "message-circle",
12795
+ nodes: [path("M7.9 20A9 9 0 1 0 4 16.1L2 22Z")]
12796
+ },
12797
+ Mic: {
12798
+ name: "mic",
12799
+ nodes: [
12800
+ path("M12 19v3"),
12801
+ path("M19 10v2a7 7 0 0 1-14 0v-2"),
12802
+ {
12803
+ tag: "rect",
12804
+ attributes: {
12805
+ x: "9",
12806
+ y: "2",
12807
+ width: "6",
12808
+ height: "13",
12809
+ rx: "3"
12810
+ }
12811
+ }
12812
+ ]
12813
+ },
12814
+ PanelLeftOpen: {
12815
+ name: "panel-left-open",
12816
+ nodes: [
12817
+ {
12818
+ tag: "rect",
12819
+ attributes: {
12820
+ width: "18",
12821
+ height: "18",
12822
+ x: "3",
12823
+ y: "3",
12824
+ rx: "2"
12825
+ }
12826
+ },
12827
+ path("M9 3v18"),
12828
+ path("m14 9 3 3-3 3")
12829
+ ]
12830
+ },
12831
+ Play: {
12832
+ name: "play",
12833
+ nodes: [{
12834
+ tag: "polygon",
12835
+ attributes: { points: "6 3 20 12 6 21 6 3" }
12836
+ }]
12837
+ },
12838
+ Plus: {
12839
+ name: "plus",
12840
+ nodes: [path("M5 12h14"), path("M12 5v14")]
12841
+ },
12842
+ RefreshCw: {
12843
+ name: "refresh-cw",
12844
+ nodes: [
12845
+ path("M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"),
12846
+ path("M21 3v5h-5"),
12847
+ path("M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"),
12848
+ path("M8 16H3v5")
12849
+ ]
12850
+ },
12851
+ Square: {
12852
+ name: "square",
12853
+ nodes: [{
12854
+ tag: "rect",
12855
+ attributes: {
12856
+ width: "18",
12857
+ height: "18",
12858
+ x: "3",
12859
+ y: "3",
12860
+ rx: "2"
12861
+ }
12862
+ }]
12863
+ },
12864
+ ThumbsDown: {
12865
+ name: "thumbs-down",
12866
+ 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")]
12867
+ },
12868
+ ThumbsUp: {
12869
+ name: "thumbs-up",
12870
+ 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")]
12871
+ },
12872
+ Upload: {
12873
+ name: "upload",
12874
+ nodes: [
12875
+ path("M12 3v12"),
12876
+ path("m17 8-5-5-5 5"),
12877
+ path("M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4")
12878
+ ]
12879
+ },
12880
+ Volume2: {
12881
+ name: "volume-2",
12882
+ nodes: [
12883
+ 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"),
12884
+ path("M16 9a5 5 0 0 1 0 6"),
12885
+ path("M19.364 18.364a9 9 0 0 0 0-12.728")
12886
+ ]
12887
+ },
12888
+ Wrench: {
12889
+ name: "wrench",
12890
+ 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")]
12891
+ },
12892
+ X: {
12893
+ name: "x",
12894
+ nodes: [path("M18 6 6 18"), path("m6 6 12 12")]
12895
+ }
12896
+ };
12897
+ /**
12898
+ * Internal. The SVG data for every icon the chat components draw.
12899
+ *
12900
+ * Each framework's `CopilotIcon` component reads an entry and draws it:
12901
+ *
12902
+ * ```ts
12903
+ * const { name, nodes } = ɵcopilotIcons.ArrowUp;
12904
+ * // <svg {...ɵcopilotIconSvgAttributes} class="lucide lucide-arrow-up">
12905
+ * // one child element per node: <{node.tag} {...node.attributes} />
12906
+ * // </svg>
12907
+ * ```
12908
+ */
12909
+ const ɵcopilotIcons = icons;
12910
+ /**
12911
+ * Internal. The attributes to put on the `<svg>` of every chat icon.
12912
+ *
12913
+ * These are Lucide's default attributes, so a drawn icon matches the Lucide
12914
+ * icon. Set `width` and `height` to change the size.
12915
+ */
12916
+ const ɵcopilotIconSvgAttributes = {
12917
+ xmlns: "http://www.w3.org/2000/svg",
12918
+ width: "24",
12919
+ height: "24",
12920
+ viewBox: "0 0 24 24",
12921
+ fill: "none",
12922
+ stroke: "currentColor",
12923
+ "stroke-width": "2",
12924
+ "stroke-linecap": "round",
12925
+ "stroke-linejoin": "round"
12926
+ };
12927
+
12928
+ //#endregion
12929
+ //#region src/chat/message-feedback.ts
12930
+ /** Trajectory event name for a rating of one assistant message. */
12931
+ const ɵMESSAGE_FEEDBACK_EVENT_NAME = "message.feedback";
12932
+ /** Longest comment kept, in characters; the rest is cut so the event stays small. */
12933
+ const ɵMESSAGE_FEEDBACK_MAX_COMMENT_LENGTH = 1e3;
12934
+ /** Longest excerpt of the rated response sent with the rating, in characters. */
12935
+ const RESPONSE_EXCERPT_LENGTH = 500;
12936
+ /**
12937
+ * How long the pointer may be away from the rating and its comment before the
12938
+ * comment closes: enough to cross the gap between them, short enough that
12939
+ * passing over a rating does not leave it open.
12940
+ */
12941
+ const ɵFEEDBACK_COMMENT_CLOSE_DELAY_MS = 150;
12942
+ const ratings = /* @__PURE__ */ new Map();
12943
+ const listeners = /* @__PURE__ */ new Map();
12944
+ const threadKey = (agentId, threadId) => JSON.stringify([agentId, threadId]);
12945
+ const messageKey = (agentId, threadId, messageId) => JSON.stringify([
12946
+ agentId,
12947
+ threadId,
12948
+ messageId
12949
+ ]);
12950
+ /** Cuts `text` to `max` characters without splitting a surrogate pair. */
12951
+ const clip = (text, max) => {
12952
+ const characters = Array.from(text);
12953
+ return characters.length > max ? characters.slice(0, max).join("") : text;
12954
+ };
12955
+ /** The comment as kept and sent: trimmed and capped, or none. */
12956
+ const normalizeComment = (comment) => {
12957
+ if (comment === void 0) return void 0;
12958
+ const text = clip(comment.trim(), ɵMESSAGE_FEEDBACK_MAX_COMMENT_LENGTH);
12959
+ return text === "" ? void 0 : text;
12960
+ };
12961
+ /** The rating this page gave one message, if any. */
12962
+ function ɵgetMessageFeedback(agentId, threadId, messageId) {
12963
+ return ratings.get(messageKey(agentId, threadId, messageId));
12964
+ }
12965
+ /** Calls `listener` whenever a rating in this Thread changes. */
12966
+ function ɵsubscribeToMessageFeedback(agentId, threadId, listener) {
12967
+ const key = threadKey(agentId, threadId);
12968
+ let set = listeners.get(key);
12969
+ if (set === void 0) {
12970
+ set = /* @__PURE__ */ new Set();
12971
+ listeners.set(key, set);
12972
+ }
12973
+ const subscribed = set;
12974
+ subscribed.add(listener);
12975
+ return () => {
12976
+ subscribed.delete(listener);
12977
+ if (subscribed.size === 0) listeners.delete(key);
12978
+ };
12979
+ }
12980
+ /**
12981
+ * Sets (or, with `null`, clears) this page's rating of one message and sends
12982
+ * it to the active Trajectory. Every change is a new event; the newest event
12983
+ * for a `feedbackId` is the current one. Like any Trajectory event, a change
12984
+ * made while no Trajectory captures, for example during a reconnect, is not
12985
+ * sent; the page still shows it.
12986
+ */
12987
+ function ɵsetMessageFeedback(params) {
12988
+ var _params$feedback, _listeners$get, _feedback$rating, _message$content;
12989
+ const { copilotkit, agentId, threadId, message } = params;
12990
+ const comment = normalizeComment((_params$feedback = params.feedback) === null || _params$feedback === void 0 ? void 0 : _params$feedback.comment);
12991
+ const feedback = params.feedback && {
12992
+ rating: params.feedback.rating,
12993
+ ...comment ? { comment } : {}
12994
+ };
12995
+ const key = messageKey(agentId, threadId, message.id);
12996
+ if (feedback) ratings.set(key, feedback);
12997
+ else ratings.delete(key);
12998
+ const threadListeners = (_listeners$get = listeners.get(threadKey(agentId, threadId))) !== null && _listeners$get !== void 0 ? _listeners$get : [];
12999
+ for (const listener of threadListeners) listener();
13000
+ const runId = copilotkit.getRunIdForMessage(agentId, threadId, message.id);
13001
+ copilotkit.emitTrajectoryEvent(ɵMESSAGE_FEEDBACK_EVENT_NAME, {
13002
+ feedbackId: `${threadId}:${message.id}`,
13003
+ threadId,
13004
+ messageId: message.id,
13005
+ agentId,
13006
+ ...runId ? { runId } : {},
13007
+ rating: (_feedback$rating = feedback === null || feedback === void 0 ? void 0 : feedback.rating) !== null && _feedback$rating !== void 0 ? _feedback$rating : null,
13008
+ ...(feedback === null || feedback === void 0 ? void 0 : feedback.comment) ? { comment: feedback.comment } : {},
13009
+ ...copilotkit.ɵlearningCapturesAgentText ? { response: clip((_message$content = message.content) !== null && _message$content !== void 0 ? _message$content : "", RESPONSE_EXCERPT_LENGTH) } : {}
13010
+ });
13011
+ }
13012
+ /** @internal Forgets every rating, so each test starts empty. */
13013
+ function ɵresetMessageFeedbackCache() {
13014
+ ratings.clear();
13015
+ }
13016
+ const capturedCores = /* @__PURE__ */ new WeakSet();
13017
+ const rememberCapture = (copilotkit) => {
13018
+ if (capturedCores.has(copilotkit)) return;
13019
+ capturedCores.add(copilotkit);
13020
+ const unsubscribe = copilotkit.ɵsubscribeToLearningConfigured(() => {
13021
+ if (copilotkit.ɵlearningConfigured) return;
13022
+ capturedCores.delete(copilotkit);
13023
+ unsubscribe();
13024
+ });
13025
+ };
13026
+ /**
13027
+ * Whether the thumbs record feedback for Learning. True once a Trajectory of
13028
+ * this Core has started and as long as Learning stays configured, also while
13029
+ * capture reconnects or is stopped, so the buttons do not flicker. Ratings
13030
+ * given meanwhile still show but, like any Trajectory event, are not sent. A
13031
+ * capture that never starts (for example without a license) leaves it false.
13032
+ *
13033
+ * Re-read it when {@link ɵsubscribeToLearningFeedbackEnabled} notifies.
13034
+ */
13035
+ function ɵisLearningFeedbackEnabled(copilotkit) {
13036
+ const capturing = copilotkit.trajectoryId !== null;
13037
+ if (capturing) rememberCapture(copilotkit);
13038
+ return copilotkit.ɵlearningConfigured && (capturing || capturedCores.has(copilotkit));
13039
+ }
13040
+ /**
13041
+ * Calls `listener` when {@link ɵisLearningFeedbackEnabled} may have changed:
13042
+ * when Learning is configured or removed, and when the Trajectory changes.
13043
+ * Returns the unsubscribe function.
13044
+ */
13045
+ function ɵsubscribeToLearningFeedbackEnabled(copilotkit, listener) {
13046
+ const unsubscribeConfigured = copilotkit.ɵsubscribeToLearningConfigured(listener);
13047
+ const subscription = copilotkit.subscribe({ onTrajectoryChanged: listener });
13048
+ return () => {
13049
+ unsubscribeConfigured();
13050
+ subscription.unsubscribe();
13051
+ };
13052
+ }
13053
+ /**
13054
+ * The feedback this page gave `message` in `scope`, and how to change it.
13055
+ * Read it again when {@link ɵsubscribeToMessageFeedback} notifies for the
13056
+ * scope's Thread.
13057
+ */
13058
+ function ɵgetMessageFeedbackControls(scope, message) {
13059
+ const feedback = ɵgetMessageFeedback(scope.agentId, scope.threadId, message.id);
13060
+ const save = (next) => ɵsetMessageFeedback({
13061
+ ...scope,
13062
+ message,
13063
+ feedback: next
13064
+ });
13065
+ return {
13066
+ feedback,
13067
+ rate: (rating) => {
13068
+ if ((feedback === null || feedback === void 0 ? void 0 : feedback.rating) !== rating) save({ rating });
13069
+ },
13070
+ clear: () => {
13071
+ if (feedback) save(null);
13072
+ },
13073
+ comment: (comment) => {
13074
+ if (feedback) save({
13075
+ rating: feedback.rating,
13076
+ comment
13077
+ });
13078
+ }
13079
+ };
13080
+ }
13081
+ var _getControls = /* @__PURE__ */ new WeakMap();
13082
+ var _closeDelayMs$1 = /* @__PURE__ */ new WeakMap();
13083
+ var _listeners$3 = /* @__PURE__ */ new WeakMap();
13084
+ var _state$2 = /* @__PURE__ */ new WeakMap();
13085
+ var _timer$3 = /* @__PURE__ */ new WeakMap();
13086
+ var _editing = /* @__PURE__ */ new WeakMap();
13087
+ var _focusWaiting = /* @__PURE__ */ new WeakMap();
13088
+ var _pointerOver = /* @__PURE__ */ new WeakMap();
13089
+ var _returning = /* @__PURE__ */ new WeakMap();
13090
+ var _ɵFeedbackCommentController_brand = /* @__PURE__ */ new WeakSet();
13091
+ /**
13092
+ * Drives the comment popover of a rated message.
13093
+ *
13094
+ * It opens when a rating is given and whenever the pointer or keyboard focus
13095
+ * reaches the chosen thumb, with the saved comment in the field. It closes by
13096
+ * itself shortly after the pointer leaves the thumb and the popover, unless
13097
+ * focus is in the field: then it stays until focus moves away, Enter, or
13098
+ * Escape. Closing saves a changed comment; Escape, a click on a thumb, and
13099
+ * removing the rating discard it.
13100
+ *
13101
+ * Frameworks render from `getSnapshot()` and re-render when `subscribe()`
13102
+ * notifies. Call `dispose()` on unmount: it keeps an unsaved edit, for a
13103
+ * message that scrolls out of a virtual list. The controller stays usable
13104
+ * after `dispose()`, so a remount (React Strict Mode) can keep it.
13105
+ *
13106
+ * @example
13107
+ * ```ts
13108
+ * const comment = new ɵFeedbackCommentController({ getControls: () => controls });
13109
+ * comment.subscribe(() => render(comment.getSnapshot()));
13110
+ * comment.show({ comment: "", focus: false });
13111
+ * // On unmount:
13112
+ * comment.dispose();
13113
+ * ```
13114
+ */
13115
+ var ɵFeedbackCommentController = class {
13116
+ constructor(options) {
13117
+ var _options$closeDelayMs;
13118
+ _classPrivateMethodInitSpec(this, _ɵFeedbackCommentController_brand);
13119
+ _classPrivateFieldInitSpec(this, _getControls, void 0);
13120
+ _classPrivateFieldInitSpec(this, _closeDelayMs$1, void 0);
13121
+ _classPrivateFieldInitSpec(this, _listeners$3, /* @__PURE__ */ new Set());
13122
+ _classPrivateFieldInitSpec(this, _state$2, {
13123
+ open: false,
13124
+ draft: "",
13125
+ focusRequest: 0
13126
+ });
13127
+ _classPrivateFieldInitSpec(this, _timer$3, void 0);
13128
+ _classPrivateFieldInitSpec(this, _editing, false);
13129
+ _classPrivateFieldInitSpec(this, _focusWaiting, false);
13130
+ _classPrivateFieldInitSpec(this, _pointerOver, false);
13131
+ _classPrivateFieldInitSpec(this, _returning, false);
13132
+ _defineProperty(
13133
+ this,
13134
+ /** The current state. The same object until something changes. */
13135
+ "getSnapshot",
13136
+ () => _classPrivateFieldGet2(_state$2, this)
13137
+ );
13138
+ _defineProperty(
13139
+ this,
13140
+ /** Calls `listener` when the state changes. Returns the unsubscribe function. */
13141
+ "subscribe",
13142
+ (listener) => {
13143
+ _classPrivateFieldGet2(_listeners$3, this).add(listener);
13144
+ return () => {
13145
+ _classPrivateFieldGet2(_listeners$3, this).delete(listener);
13146
+ };
13147
+ }
13148
+ );
13149
+ _defineProperty(
13150
+ this,
13151
+ /** Sets the comment being edited. */
13152
+ "setDraft",
13153
+ (draft) => {
13154
+ _assertClassBrand(_ɵFeedbackCommentController_brand, this, _update).call(this, { draft });
13155
+ }
13156
+ );
13157
+ _defineProperty(
13158
+ this,
13159
+ /** Whether a focus request waits; reading it answers the request. */
13160
+ "takeFocusRequest",
13161
+ () => {
13162
+ const waiting = _classPrivateFieldGet2(_focusWaiting, this);
13163
+ _classPrivateFieldSet2(_focusWaiting, this, false);
13164
+ return waiting;
13165
+ }
13166
+ );
13167
+ _defineProperty(
13168
+ this,
13169
+ /** Opens with `comment` in the field. */
13170
+ "show",
13171
+ ({ comment, focus }) => {
13172
+ _assertClassBrand(_ɵFeedbackCommentController_brand, this, _cancelClose).call(this);
13173
+ if (focus) _classPrivateFieldSet2(_focusWaiting, this, true);
13174
+ _assertClassBrand(_ɵFeedbackCommentController_brand, this, _update).call(this, {
13175
+ open: true,
13176
+ draft: comment,
13177
+ focusRequest: _classPrivateFieldGet2(_state$2, this).focusRequest + (focus ? 1 : 0)
13178
+ });
13179
+ }
13180
+ );
13181
+ _defineProperty(
13182
+ this,
13183
+ /** The pointer or focus reached the rating or the popover. */
13184
+ "enter",
13185
+ (via = "focus") => {
13186
+ var _classPrivateFieldGet2$2;
13187
+ _assertClassBrand(_ɵFeedbackCommentController_brand, this, _cancelClose).call(this);
13188
+ if (via === "pointer") _classPrivateFieldSet2(_pointerOver, this, true);
13189
+ if (_classPrivateFieldGet2(_returning, this)) return;
13190
+ if (!_classPrivateFieldGet2(_state$2, this).open && ((_classPrivateFieldGet2$2 = _classPrivateFieldGet2(_getControls, this).call(this)) === null || _classPrivateFieldGet2$2 === void 0 ? void 0 : _classPrivateFieldGet2$2.feedback)) this.show({
13191
+ comment: _assertClassBrand(_ɵFeedbackCommentController_brand, this, _savedComment).call(this),
13192
+ focus: false
13193
+ });
13194
+ }
13195
+ );
13196
+ _defineProperty(
13197
+ this,
13198
+ /**
13199
+ * It left them: close soon, unless the user is editing the comment or, when
13200
+ * focus left, the pointer is still on the rating or the popover.
13201
+ */
13202
+ "leave",
13203
+ (via = "focus") => {
13204
+ if (via === "pointer") _classPrivateFieldSet2(_pointerOver, this, false);
13205
+ else if (_classPrivateFieldGet2(_pointerOver, this)) return;
13206
+ _assertClassBrand(_ɵFeedbackCommentController_brand, this, _cancelClose).call(this);
13207
+ _classPrivateFieldSet2(_timer$3, this, setTimeout(() => {
13208
+ _classPrivateFieldSet2(_timer$3, this, void 0);
13209
+ if (!_classPrivateFieldGet2(_editing, this)) this.close();
13210
+ }, _classPrivateFieldGet2(_closeDelayMs$1, this)));
13211
+ }
13212
+ );
13213
+ _defineProperty(
13214
+ this,
13215
+ /** Tracks whether focus is in the comment form. */
13216
+ "setEditing",
13217
+ (editing) => {
13218
+ _classPrivateFieldSet2(_editing, this, editing);
13219
+ }
13220
+ );
13221
+ _defineProperty(
13222
+ this,
13223
+ /** Closes, saving a changed comment unless `save` is false. */
13224
+ "close",
13225
+ ({ save = true } = {}) => {
13226
+ _assertClassBrand(_ɵFeedbackCommentController_brand, this, _cancelClose).call(this);
13227
+ _classPrivateFieldSet2(_focusWaiting, this, false);
13228
+ _classPrivateFieldSet2(_pointerOver, this, false);
13229
+ if (!_classPrivateFieldGet2(_state$2, this).open) return;
13230
+ if (save) _assertClassBrand(_ɵFeedbackCommentController_brand, this, _saveDraft).call(this);
13231
+ _classPrivateFieldSet2(_editing, this, false);
13232
+ _assertClassBrand(_ɵFeedbackCommentController_brand, this, _update).call(this, { open: false });
13233
+ }
13234
+ );
13235
+ _defineProperty(
13236
+ this,
13237
+ /** Moves focus back to the thumb without opening the comment again. */
13238
+ "returnFocus",
13239
+ (target) => {
13240
+ _classPrivateFieldSet2(_returning, this, true);
13241
+ try {
13242
+ target === null || target === void 0 || target.focus();
13243
+ } finally {
13244
+ _classPrivateFieldSet2(_returning, this, false);
13245
+ }
13246
+ }
13247
+ );
13248
+ _defineProperty(
13249
+ this,
13250
+ /** Stops the close timer and saves a changed comment that is still open. */
13251
+ "dispose",
13252
+ () => {
13253
+ _assertClassBrand(_ɵFeedbackCommentController_brand, this, _cancelClose).call(this);
13254
+ if (_classPrivateFieldGet2(_state$2, this).open) _assertClassBrand(_ɵFeedbackCommentController_brand, this, _saveDraft).call(this);
13255
+ }
13256
+ );
13257
+ _classPrivateFieldSet2(_getControls, this, options.getControls);
13258
+ _classPrivateFieldSet2(_closeDelayMs$1, this, (_options$closeDelayMs = options.closeDelayMs) !== null && _options$closeDelayMs !== void 0 ? _options$closeDelayMs : ɵFEEDBACK_COMMENT_CLOSE_DELAY_MS);
13259
+ }
13260
+ };
13261
+ function _savedComment() {
13262
+ var _this$getControls$fee, _classPrivateFieldGet3;
13263
+ return (_this$getControls$fee = (_classPrivateFieldGet3 = _classPrivateFieldGet2(_getControls, this).call(this)) === null || _classPrivateFieldGet3 === void 0 || (_classPrivateFieldGet3 = _classPrivateFieldGet3.feedback) === null || _classPrivateFieldGet3 === void 0 ? void 0 : _classPrivateFieldGet3.comment) !== null && _this$getControls$fee !== void 0 ? _this$getControls$fee : "";
13264
+ }
13265
+ function _saveDraft() {
13266
+ const controls = _classPrivateFieldGet2(_getControls, this).call(this);
13267
+ const draft = _classPrivateFieldGet2(_state$2, this).draft;
13268
+ if ((controls === null || controls === void 0 ? void 0 : controls.feedback) && draft.trim() !== _assertClassBrand(_ɵFeedbackCommentController_brand, this, _savedComment).call(this)) controls.comment(draft);
13269
+ }
13270
+ function _cancelClose() {
13271
+ if (_classPrivateFieldGet2(_timer$3, this) === void 0) return;
13272
+ clearTimeout(_classPrivateFieldGet2(_timer$3, this));
13273
+ _classPrivateFieldSet2(_timer$3, this, void 0);
13274
+ }
13275
+ function _update(patch) {
13276
+ const next = {
13277
+ ..._classPrivateFieldGet2(_state$2, this),
13278
+ ...patch
13279
+ };
13280
+ if (next.open === _classPrivateFieldGet2(_state$2, this).open && next.draft === _classPrivateFieldGet2(_state$2, this).draft && next.focusRequest === _classPrivateFieldGet2(_state$2, this).focusRequest) return;
13281
+ _classPrivateFieldSet2(_state$2, this, next);
13282
+ for (const listener of _classPrivateFieldGet2(_listeners$3, this)) listener();
13283
+ }
13284
+
13285
+ //#endregion
13286
+ //#region src/chat/viewport.ts
13287
+ const AUTO_SCROLL_MODES = [
13288
+ "pin-to-bottom",
13289
+ "pin-to-send",
13290
+ "none"
13291
+ ];
13292
+ const isAutoScrollMode = (value) => AUTO_SCROLL_MODES.includes(value);
13293
+ /**
13294
+ * Turns the `autoScroll` prop into a mode. `true` and a missing value mean
13295
+ * `"pin-to-bottom"`, `false` means `"none"`, and an unknown string falls back
13296
+ * to `"pin-to-bottom"`.
13297
+ */
13298
+ function ɵnormalizeAutoScroll(value) {
13299
+ if (value === false) return "none";
13300
+ if (value === void 0 || value === true) return "pin-to-bottom";
13301
+ return isAutoScrollMode(value) ? value : "pin-to-bottom";
13302
+ }
13303
+ /**
13304
+ * Media query for the mobile range, where the threads drawer and the chat
13305
+ * modal are mutually exclusive.
13306
+ */
13307
+ const ɵMOBILE_MAX_WIDTH_QUERY = "(max-width: 767px)";
13308
+ /** `window.matchMedia` for the mobile query, or `null` without a DOM. */
13309
+ const mobileMediaQuery = () => {
13310
+ return typeof window !== "undefined" && typeof window.matchMedia === "function" ? window.matchMedia(ɵMOBILE_MAX_WIDTH_QUERY) : null;
13311
+ };
13312
+ /**
13313
+ * Whether the viewport is in the mobile range (`<768px`). `false` during SSR
13314
+ * and where `window.matchMedia` is missing (some test runners and webviews).
13315
+ */
13316
+ function ɵisMobileViewport() {
13317
+ var _mobileMediaQuery$mat, _mobileMediaQuery;
13318
+ return (_mobileMediaQuery$mat = (_mobileMediaQuery = mobileMediaQuery()) === null || _mobileMediaQuery === void 0 ? void 0 : _mobileMediaQuery.matches) !== null && _mobileMediaQuery$mat !== void 0 ? _mobileMediaQuery$mat : false;
13319
+ }
13320
+ /**
13321
+ * Calls `listener` with {@link ɵisMobileViewport} now and each time the
13322
+ * viewport enters or leaves the mobile range. Does nothing without
13323
+ * `window.matchMedia`. Returns the unsubscribe function.
13324
+ */
13325
+ function ɵwatchMobileViewport(listener) {
13326
+ const query = mobileMediaQuery();
13327
+ if (query === null) return () => {};
13328
+ const update = () => listener(query.matches);
13329
+ update();
13330
+ query.addEventListener("change", update);
13331
+ return () => query.removeEventListener("change", update);
13332
+ }
13333
+ /**
13334
+ * The on-screen keyboard is treated as open once it covers more than this
13335
+ * many pixels of the layout viewport.
13336
+ */
13337
+ const ɵKEYBOARD_OPEN_THRESHOLD_PX = 150;
13338
+ /**
13339
+ * Reads the keyboard state with the Visual Viewport API: the keyboard height
13340
+ * is `innerHeight - visualViewport.height`, clamped to 0. Without the API (or
13341
+ * during SSR) it reports a closed keyboard and the full window height.
13342
+ */
13343
+ function ɵreadKeyboardState() {
13344
+ if (typeof window === "undefined") return closedKeyboard(0);
13345
+ const visualViewport = window.visualViewport;
13346
+ if (!visualViewport) return closedKeyboard(window.innerHeight);
13347
+ const layoutHeight = window.innerHeight;
13348
+ const keyboardHeight = Math.max(0, layoutHeight - visualViewport.height);
13349
+ return {
13350
+ isKeyboardOpen: keyboardHeight > ɵKEYBOARD_OPEN_THRESHOLD_PX,
13351
+ keyboardHeight,
13352
+ availableHeight: visualViewport.height,
13353
+ viewportHeight: layoutHeight
13354
+ };
13355
+ }
13356
+ const closedKeyboard = (height) => ({
13357
+ isKeyboardOpen: false,
13358
+ keyboardHeight: 0,
13359
+ availableHeight: height,
13360
+ viewportHeight: height
13361
+ });
13362
+ /**
13363
+ * The state for the first render, before {@link ɵwatchKeyboardState} reads
13364
+ * the visual viewport: a closed keyboard over the full window height (0
13365
+ * during SSR).
13366
+ */
13367
+ function ɵinitialKeyboardState() {
13368
+ return closedKeyboard(typeof window === "undefined" ? 0 : window.innerHeight);
13369
+ }
13370
+ /**
13371
+ * Calls `listener` with {@link ɵreadKeyboardState} now and on each visual
13372
+ * viewport resize or scroll. Does nothing during SSR or without the Visual
13373
+ * Viewport API. Returns the unsubscribe function.
13374
+ */
13375
+ function ɵwatchKeyboardState(listener) {
13376
+ if (typeof window === "undefined") return () => {};
13377
+ const visualViewport = window.visualViewport;
13378
+ if (!visualViewport) return () => {};
13379
+ const update = () => listener(ɵreadKeyboardState());
13380
+ update();
13381
+ visualViewport.addEventListener("resize", update);
13382
+ visualViewport.addEventListener("scroll", update);
13383
+ return () => {
13384
+ visualViewport.removeEventListener("resize", update);
13385
+ visualViewport.removeEventListener("scroll", update);
13386
+ };
13387
+ }
13388
+ /** Escapes `id` for a CSS attribute selector, also without `CSS.escape`. */
13389
+ const escapeSelectorValue = (id) => typeof CSS !== "undefined" && typeof CSS.escape === "function" ? CSS.escape(id) : id.replace(/[!"#$%&'()*+,./:;<=>?@[\\\]^`{|}~]/g, "\\$&");
13390
+ /**
13391
+ * Offset of `el` from the top of `stopAt`'s content, including `stopAt`'s
13392
+ * scroll. Uses `getBoundingClientRect`, so it works for any CSS position.
13393
+ */
13394
+ const offsetTopWithin = (el, stopAt) => el.getBoundingClientRect().top - stopAt.getBoundingClientRect().top + stopAt.scrollTop;
13395
+ /**
13396
+ * Pins a sent message to the top of the chat: sizes the spacer so the
13397
+ * message bubble can scroll to `topOffset` from the viewport top, scrolls
13398
+ * there on the next frame, and then shrinks the spacer as the reply below
13399
+ * grows, so the bubble stays put.
13400
+ *
13401
+ * The message element's top padding is scrolled off-screen: the bubble, not
13402
+ * its padded box, is pinned. Does nothing when no element in `contentEl` has
13403
+ * `data-message-id` equal to `messageId`. Skips the scroll without
13404
+ * `requestAnimationFrame` and the spacer updates without `ResizeObserver`.
13405
+ *
13406
+ * @returns A function that cancels the scroll and stops the spacer updates.
13407
+ * It returns `false` when it cancelled a scroll that had not run yet, so the
13408
+ * caller can pin the same send again. React's StrictMode tears an effect
13409
+ * down before the next frame, so the first run never scrolls.
13410
+ *
13411
+ * @example
13412
+ * ```ts
13413
+ * const unpin = ɵpinMessageToTop({ scrollEl, contentEl, spacerEl, messageId });
13414
+ * // On the next send or on unmount:
13415
+ * unpin();
13416
+ * ```
13417
+ */
13418
+ function ɵpinMessageToTop({ scrollEl, contentEl, spacerEl, messageId, topOffset = 16 }) {
13419
+ const targetEl = contentEl.querySelector(`[data-message-id="${escapeSelectorValue(messageId)}"]`);
13420
+ if (!targetEl) return () => true;
13421
+ const viewportHeight = scrollEl.clientHeight;
13422
+ const userMessageHeight = targetEl.getBoundingClientRect().height;
13423
+ const paddingTop = parseFloat(getComputedStyle(targetEl).paddingTop) || 0;
13424
+ const bubbleHeight = Math.max(0, userMessageHeight - paddingTop);
13425
+ const spacerHeight = Math.max(0, viewportHeight - bubbleHeight - topOffset);
13426
+ spacerEl.style.height = `${spacerHeight}px`;
13427
+ let scrolled = false;
13428
+ const frame = typeof requestAnimationFrame === "function" ? requestAnimationFrame(() => {
13429
+ scrolled = true;
13430
+ const targetTop = offsetTopWithin(targetEl, scrollEl) + paddingTop - topOffset;
13431
+ scrollEl.scrollTo({
13432
+ top: Math.max(0, targetTop),
13433
+ behavior: "smooth"
13434
+ });
13435
+ }) : null;
13436
+ const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(() => {
13437
+ const consumedBelow = contentEl.getBoundingClientRect().height - offsetTopWithin(targetEl, contentEl) - userMessageHeight;
13438
+ const remaining = Math.max(0, spacerHeight - consumedBelow);
13439
+ spacerEl.style.height = `${remaining}px`;
13440
+ });
13441
+ observer === null || observer === void 0 || observer.observe(contentEl);
13442
+ return () => {
13443
+ if (frame !== null && typeof cancelAnimationFrame === "function") cancelAnimationFrame(frame);
13444
+ observer === null || observer === void 0 || observer.disconnect();
13445
+ return frame === null || scrolled;
13446
+ };
13447
+ }
13448
+
13449
+ //#endregion
13450
+ //#region src/chat/message-display.ts
13451
+ /**
13452
+ * How long the model reasoned, as label text: "a few seconds", "4 seconds",
13453
+ * "2 minutes", or "1m 5s".
13454
+ *
13455
+ * @param seconds - The elapsed time in seconds. It may have a fraction.
13456
+ * @param labels - The chat labels that hold the duration texts.
13457
+ */
13458
+ function ɵformatReasoningDurationLabel(seconds, labels) {
13459
+ const duration = formatReasoningDuration(seconds);
13460
+ switch (duration.unit) {
13461
+ case "fewSeconds": return labels.reasoningMessageDurationFewSeconds;
13462
+ case "seconds": return ɵformatLabel(labels.reasoningMessageDurationSeconds, { count: duration.seconds });
13463
+ case "minutes": return ɵformatCountLabel(duration.minutes, {
13464
+ one: labels.reasoningMessageDurationMinutesOne,
13465
+ other: labels.reasoningMessageDurationMinutesOther
13466
+ });
13467
+ case "minutesSeconds": return ɵformatLabel(labels.reasoningMessageDurationMinutesSeconds, {
13468
+ minutes: duration.minutes,
13469
+ seconds: duration.seconds
13470
+ });
13471
+ }
13472
+ }
13473
+ /**
13474
+ * The text of the work summary line at the top of a reply in the `"turn"`
13475
+ * tool-call display.
13476
+ *
13477
+ * - While working: `label` is "Working" and `detail` the live timer ("4s"),
13478
+ * or `null` when the elapsed time is not known.
13479
+ * - When done with a known time: `label` is "Worked for 9s" (at least 1s)
13480
+ * and `detail` the tool count ("7 tools").
13481
+ * - When done without a time: `label` is "Used 7 tools" and `detail` `null`.
13482
+ * - `failed` is "2 failed" when tool calls failed, otherwise `null`. It is
13483
+ * always `null` while working.
13484
+ */
13485
+ function ɵgetWorkSummaryText({ isWorking, calls, elapsedMs, workingSince, now, labels }) {
13486
+ if (isWorking) {
13487
+ const isTimed = elapsedMs !== void 0 && workingSince !== void 0;
13488
+ return {
13489
+ label: labels.workSummaryWorkingLabel,
13490
+ detail: isTimed ? formatWorkDuration(elapsedMs + Math.max(0, now - workingSince)) : null,
13491
+ failed: null
13492
+ };
13493
+ }
13494
+ const failedCount = countFailedToolCalls(calls);
13495
+ const failed = failedCount > 0 ? ɵformatLabel(labels.toolCallFailedCountLabel, { count: failedCount }) : null;
13496
+ if (elapsedMs === void 0) return {
13497
+ label: ɵformatCountLabel(calls.length, {
13498
+ one: labels.toolCallUsedToolsOne,
13499
+ other: labels.toolCallUsedToolsOther
13500
+ }),
13501
+ detail: null,
13502
+ failed
13503
+ };
13504
+ const duration = formatWorkDuration(Math.max(1e3, elapsedMs));
13505
+ return {
13506
+ label: ɵformatLabel(labels.workSummaryWorkedForLabel, { duration }),
13507
+ detail: ɵformatCountLabel(calls.length, {
13508
+ one: labels.toolCallToolCountOne,
13509
+ other: labels.toolCallToolCountOther
13510
+ }),
13511
+ failed
13512
+ };
13513
+ }
13514
+ /**
13515
+ * The text of a user message: the string content, or its text parts joined
13516
+ * by newlines. Parts that are not text, and malformed parts from untyped
13517
+ * data, add nothing.
13518
+ */
13519
+ function ɵflattenUserMessageContent(content) {
13520
+ if (!content) return "";
13521
+ if (typeof content === "string") return content;
13522
+ return content.map((part) => (part === null || part === void 0 ? void 0 : part.type) === "text" && typeof part.text === "string" ? part.text : "").filter((text) => text.length > 0).join("\n");
13523
+ }
13524
+ const isMediaPart = (part) => (part === null || part === void 0 ? void 0 : part.type) === "image" || (part === null || part === void 0 ? void 0 : part.type) === "audio" || (part === null || part === void 0 ? void 0 : part.type) === "video" || (part === null || part === void 0 ? void 0 : part.type) === "document";
13525
+ /** The image, audio, video, and document parts of a user message. */
13526
+ function ɵgetUserMessageMediaParts(content) {
13527
+ if (!content || typeof content === "string") return [];
13528
+ return content.filter(isMediaPart);
13529
+ }
13530
+ /** The file name stored in an attachment's `metadata.filename`, if any. */
13531
+ function ɵgetUserMessageMediaFilename(part) {
13532
+ const meta = part.metadata;
13533
+ return meta != null && typeof meta === "object" && "filename" in meta && typeof meta.filename === "string" ? meta.filename : void 0;
13534
+ }
13535
+ /**
13536
+ * Whether a user message shows its branch navigation and which arrows work.
13537
+ * It shows only with more than one branch and a switch handler: without the
13538
+ * handler the arrows would do nothing.
13539
+ */
13540
+ function ɵgetBranchNavState({ branchIndex, numberOfBranches, canSwitch }) {
13541
+ const show = canSwitch && numberOfBranches > 1;
13542
+ return {
13543
+ show,
13544
+ canGoPrev: show && branchIndex > 0,
13545
+ canGoNext: show && branchIndex < numberOfBranches - 1
13546
+ };
13547
+ }
13548
+ /** Whether an assistant message has text beyond whitespace. */
13549
+ function ɵhasAssistantMessageText(content) {
13550
+ return !!content && content.trim().length > 0;
13551
+ }
13552
+ /**
13553
+ * Whether an assistant message shows its toolbar: when toolbars are on, the
13554
+ * message has text or the Inspector shortcut shows, and the message is not
13555
+ * the one still streaming (the latest while the agent runs).
13556
+ */
13557
+ function ɵshouldShowAssistantToolbar({ toolbarVisible, hasContent, showInspectorShortcut, isRunning, isLatest }) {
13558
+ return toolbarVisible && (hasContent || showInspectorShortcut) && !(isRunning && isLatest);
13559
+ }
13560
+ /** How long a copy button shows its "copied" check mark, in ms. */
13561
+ const ɵCOPY_FEEDBACK_RESET_MS = 2e3;
13562
+ var _listeners$2 = /* @__PURE__ */ new WeakMap();
13563
+ var _resetMs = /* @__PURE__ */ new WeakMap();
13564
+ var _copied = /* @__PURE__ */ new WeakMap();
13565
+ var _timer$2 = /* @__PURE__ */ new WeakMap();
13566
+ var _ɵCopyFeedback_brand = /* @__PURE__ */ new WeakSet();
13567
+ /**
13568
+ * The "copied" state of a copy button. After a copy it is `true` for
13569
+ * {@link ɵCOPY_FEEDBACK_RESET_MS}; another copy in that time restarts the
13570
+ * wait, so rapid clicks do not flicker.
13571
+ *
13572
+ * Frameworks render from `getSnapshot()` and re-render when `subscribe()`
13573
+ * notifies. Call `dispose()` on unmount. The controller stays usable after
13574
+ * `dispose()`, so a remount (React Strict Mode) can keep it.
13575
+ *
13576
+ * @example
13577
+ * ```ts
13578
+ * const feedback = new ɵCopyFeedback();
13579
+ * feedback.subscribe(() => render(feedback.getSnapshot()));
13580
+ * await feedback.copy(text);
13581
+ * ```
13582
+ */
13583
+ var ɵCopyFeedback = class {
13584
+ constructor({ resetMs = ɵCOPY_FEEDBACK_RESET_MS } = {}) {
13585
+ _classPrivateMethodInitSpec(this, _ɵCopyFeedback_brand);
13586
+ _classPrivateFieldInitSpec(this, _listeners$2, /* @__PURE__ */ new Set());
13587
+ _classPrivateFieldInitSpec(this, _resetMs, void 0);
13588
+ _classPrivateFieldInitSpec(this, _copied, false);
13589
+ _classPrivateFieldInitSpec(this, _timer$2, void 0);
13590
+ _defineProperty(
13591
+ this,
13592
+ /** Whether the check mark shows. */
13593
+ "getSnapshot",
13594
+ () => _classPrivateFieldGet2(_copied, this)
13595
+ );
13596
+ _defineProperty(
13597
+ this,
13598
+ /** Calls `listener` when the state changes. Returns the unsubscribe function. */
13599
+ "subscribe",
13600
+ (listener) => {
13601
+ _classPrivateFieldGet2(_listeners$2, this).add(listener);
13602
+ return () => {
13603
+ _classPrivateFieldGet2(_listeners$2, this).delete(listener);
13604
+ };
13605
+ }
13606
+ );
13607
+ _defineProperty(
13608
+ this,
13609
+ /** Shows the check mark, or keeps it for the full time again. */
13610
+ "markCopied",
13611
+ () => {
13612
+ _assertClassBrand(_ɵCopyFeedback_brand, this, _clearTimer$1).call(this);
13613
+ _assertClassBrand(_ɵCopyFeedback_brand, this, _set).call(this, true);
13614
+ _classPrivateFieldSet2(_timer$2, this, setTimeout(() => {
13615
+ _classPrivateFieldSet2(_timer$2, this, void 0);
13616
+ _assertClassBrand(_ɵCopyFeedback_brand, this, _set).call(this, false);
13617
+ }, _classPrivateFieldGet2(_resetMs, this)));
13618
+ }
13619
+ );
13620
+ _defineProperty(
13621
+ this,
13622
+ /**
13623
+ * Copies `text` to the clipboard and shows the check mark on success.
13624
+ * Empty text copies nothing.
13625
+ *
13626
+ * @returns Whether the text was copied.
13627
+ */
13628
+ "copy",
13629
+ async (text) => {
13630
+ if (!text) return false;
13631
+ const copied = await (0, _copilotkit_shared.copyToClipboard)(text);
13632
+ if (copied) this.markCopied();
13633
+ return copied;
13634
+ }
13635
+ );
13636
+ _defineProperty(
13637
+ this,
13638
+ /** Stops the reset timer. */
13639
+ "dispose",
13640
+ () => {
13641
+ _assertClassBrand(_ɵCopyFeedback_brand, this, _clearTimer$1).call(this);
13642
+ }
13643
+ );
13644
+ _classPrivateFieldSet2(_resetMs, this, resetMs);
13645
+ }
13646
+ };
13647
+ function _clearTimer$1() {
13648
+ if (_classPrivateFieldGet2(_timer$2, this) === void 0) return;
13649
+ clearTimeout(_classPrivateFieldGet2(_timer$2, this));
13650
+ _classPrivateFieldSet2(_timer$2, this, void 0);
13651
+ }
13652
+ function _set(copied) {
13653
+ if (copied === _classPrivateFieldGet2(_copied, this)) return;
13654
+ _classPrivateFieldSet2(_copied, this, copied);
13655
+ for (const listener of _classPrivateFieldGet2(_listeners$2, this)) listener();
13656
+ }
13657
+
13658
+ //#endregion
13659
+ //#region src/chat/inspector-button.ts
13660
+ let shortcutsHidden = false;
13661
+ const shortcutListeners = /* @__PURE__ */ new Set();
13662
+ const notifyShortcutListeners = () => {
13663
+ for (const listener of shortcutListeners) listener();
13664
+ };
13665
+ /**
13666
+ * Whether the user hid the Inspector shortcuts in the message toolbars
13667
+ * ("Hide this icon"). It lasts until the page reloads and applies to every
13668
+ * chat on the page.
13669
+ *
13670
+ * @example
13671
+ * ```ts
13672
+ * ɵinspectorShortcuts.subscribe(() => render(ɵinspectorShortcuts.hidden));
13673
+ * ɵinspectorShortcuts.hide();
13674
+ * ```
13675
+ */
13676
+ const ɵinspectorShortcuts = {
13677
+ get hidden() {
13678
+ return shortcutsHidden;
13679
+ },
13680
+ hide() {
13681
+ if (shortcutsHidden) return;
13682
+ shortcutsHidden = true;
13683
+ notifyShortcutListeners();
13684
+ },
13685
+ subscribe(listener) {
13686
+ shortcutListeners.add(listener);
13687
+ return () => {
13688
+ shortcutListeners.delete(listener);
13689
+ };
13690
+ },
13691
+ reset() {
13692
+ if (!shortcutsHidden) return;
13693
+ shortcutsHidden = false;
13694
+ notifyShortcutListeners();
13695
+ }
13696
+ };
13697
+ const kiteStroke = (d, stroke, strokeWidth) => ({
13698
+ d,
13699
+ stroke,
13700
+ strokeWidth,
13701
+ strokeLinecap: "round"
13702
+ });
13703
+ /**
13704
+ * The Inspector kite artwork as data, as in
13705
+ * `web-inspector/src/assets/inspector-logo-kite.svg`. Render an `<svg>` with
13706
+ * `viewBox` and `fill="none"`, one `<path>` per entry of `paths`, and a
13707
+ * `<linearGradient gradientUnits="userSpaceOnUse">` per entry of `gradients`
13708
+ * in `<defs>`. Give each gradient the id `${prefix}-${gradient.id}` with a
13709
+ * prefix unique to the icon, and fill paths with
13710
+ * {@link ɵinspectorKiteFill}.
13711
+ */
13712
+ const ɵinspectorKiteIcon = {
13713
+ viewBox: "4.57 3.36 17.8 17.8",
13714
+ paths: [
13715
+ {
13716
+ d: "M6.36084 10.9855C8.34277 8.393 9.98843 5.82939 10.6204 3.75914C10.6382 3.70281 10.7043 3.67888 10.7534 3.7114C12.9536 5.16894 16.9635 6.12833 20.5086 6.15085C20.5703 6.15124 20.6124 6.2114 20.5895 6.26829C19.4109 9.25938 17.9705 14.6189 17.9148 20.7392C17.9148 20.8301 17.7873 20.8627 17.7419 20.7837C15.7236 17.2522 9.26021 12.2898 6.39414 11.1186C6.34112 11.0968 6.32556 11.0313 6.36084 10.9855Z",
13717
+ fillGradient: "paint0_linear"
13718
+ },
13719
+ {
13720
+ d: "M13.0475 9.39974C9.95016 10.3806 7.11935 10.9259 6.44331 11.0498C6.40027 11.0577 6.39115 11.1172 6.43152 11.134C9.3203 12.3347 15.7516 17.2826 17.7511 20.7998C17.7551 20.8075 17.7647 20.8103 17.7728 20.8068C17.7809 20.803 17.7853 20.793 17.7819 20.7844L13.0475 9.39974Z",
13721
+ fillGradient: "paint1_linear"
13722
+ },
13723
+ {
13724
+ d: "M10.762 3.705C13.4137 5.15161 16.4787 5.80132 20.545 6.14367C20.5703 6.14585 20.5787 6.18008 20.5557 6.19197C20.0359 6.45923 17.0574 7.97512 14.8455 8.78701C14.2524 9.00453 13.6564 9.20632 13.0692 9.39249C13.0562 9.39656 13.0419 9.39015 13.0369 9.37774L10.7005 3.75979C10.6849 3.72196 10.7257 3.68538 10.762 3.705Z",
13725
+ fillGradient: "paint2_linear"
13726
+ },
13727
+ kiteStroke("M10.7145 3.79041L17.8305 20.7659", "#513C9F", "0.17284"),
13728
+ kiteStroke("M6.44531 11.0476C6.44531 11.0476 10.375 10.3422 14.0686 9.06804C17.7623 7.7939 20.5122 6.23373 20.5122 6.23373", "#513C9F", "0.17284"),
13729
+ kiteStroke("M11.6914 5.93518L9.05534 14.7068M9.05534 14.7068H15.3203M9.05534 14.7068L0.15625 26.3646", "#ABABAB", "0.302474"),
13730
+ {
13731
+ d: "M6.02539 23.9646L4.85806 24.1287C5.46272 25.7287 6.70381 26.4276 8.18528 26.4276C11.8147 26.4276 10.707 22.3227 12.8103 22.3227C14.3358 22.3227 13.7155 25.6498 16.9992 25.6498C19.0029 25.6498 19.2028 23.631 18.8607 22.7625C18.8589 22.7572 18.8568 22.7524 18.8538 22.7476L18.3166 21.9253C18.2817 21.8706 18.1968 21.8912 18.1907 21.9562L18.0908 22.9529C18.0838 23.0222 18.0857 23.0913 18.0936 23.1605C18.1764 23.8491 18.2291 25.5202 16.9992 25.5202C15.7015 25.5202 15.3895 22.2362 12.8103 22.2362C9.78393 22.2362 10.1726 26.298 8.31487 26.298C7.08938 26.298 6.15447 24.9153 6.02539 23.9646Z",
13732
+ fillGradient: "paint3_linear"
13733
+ }
13734
+ ],
13735
+ gradients: [
13736
+ {
13737
+ id: "paint0_linear",
13738
+ x1: "15.5372",
13739
+ y1: "5.0278",
13740
+ x2: "12.0802",
13741
+ y2: "14.534",
13742
+ stops: [{ color: "#6430AB" }, {
13743
+ offset: "1",
13744
+ color: "#AA89D8"
13745
+ }]
13746
+ },
13747
+ {
13748
+ id: "paint1_linear",
13749
+ x1: "12.8583",
13750
+ y1: "10.3858",
13751
+ x2: "8.40764",
13752
+ y2: "18.9846",
13753
+ stops: [{ color: "#005DBB" }, {
13754
+ offset: "1",
13755
+ color: "#3D92E8"
13756
+ }]
13757
+ },
13758
+ {
13759
+ id: "paint2_linear",
13760
+ x1: "14.8452",
13761
+ y1: "5.02774",
13762
+ x2: "13.5047",
13763
+ y2: "9.21911",
13764
+ stops: [{ color: "#1B70C4" }, {
13765
+ offset: "1",
13766
+ color: "#54A4F2"
13767
+ }]
13768
+ },
13769
+ {
13770
+ id: "paint3_linear",
13771
+ x1: "4.85806",
13772
+ y1: "24.2455",
13773
+ x2: "18.9963",
13774
+ y2: "24.2455",
13775
+ stops: [
13776
+ { color: "#4497EA" },
13777
+ {
13778
+ offset: "0.254755",
13779
+ color: "#1463B2"
13780
+ },
13781
+ {
13782
+ offset: "0.498725",
13783
+ color: "#0A437D"
13784
+ },
13785
+ {
13786
+ offset: "0.666667",
13787
+ color: "#2476C8"
13788
+ },
13789
+ {
13790
+ offset: "0.972542",
13791
+ color: "#0C549A"
13792
+ }
13793
+ ]
13794
+ }
13795
+ ]
13796
+ };
13797
+ /**
13798
+ * The `fill` of a kite path: its gradient under the icon's id `prefix`, or
13799
+ * `undefined` for a stroke-only path.
13800
+ */
13801
+ function ɵinspectorKiteFill(prefix, path) {
13802
+ return path.fillGradient === void 0 ? void 0 : `url(#${prefix}-${path.fillGradient})`;
13803
+ }
13804
+ /** How long a hover-opened menu stays after the pointer leaves, in ms. */
13805
+ const ɵHOVER_MENU_CLOSE_DELAY_MS = 180;
13806
+ var _closeDelayMs = /* @__PURE__ */ new WeakMap();
13807
+ var _listeners$1 = /* @__PURE__ */ new WeakMap();
13808
+ var _state$1 = /* @__PURE__ */ new WeakMap();
13809
+ var _timer$1 = /* @__PURE__ */ new WeakMap();
13810
+ var _openedByHover = /* @__PURE__ */ new WeakMap();
13811
+ /**
13812
+ * The open state of a menu that opens when the pointer reaches its trigger,
13813
+ * like the Inspector shortcut's menu.
13814
+ *
13815
+ * - A mouse or pen over the trigger opens it; touch does not.
13816
+ * - Leaving the trigger or the menu closes it after `closeDelayMs`, unless
13817
+ * the pointer comes back first or the keyboard has used the menu since.
13818
+ * - Opening reads whether the trigger is inside a `.dark` element, so a menu
13819
+ * in a portal can match the theme.
13820
+ *
13821
+ * Frameworks render from `getSnapshot()` and re-render when `subscribe()`
13822
+ * notifies. Call `dispose()` on unmount; the controller stays usable.
13823
+ */
13824
+ var ɵHoverMenuController = class {
13825
+ constructor({ closeDelayMs = ɵHOVER_MENU_CLOSE_DELAY_MS } = {}) {
13826
+ _classPrivateFieldInitSpec(this, _closeDelayMs, void 0);
13827
+ _classPrivateFieldInitSpec(this, _listeners$1, /* @__PURE__ */ new Set());
13828
+ _classPrivateFieldInitSpec(this, _state$1, {
13829
+ open: false,
13830
+ dark: false
13831
+ });
13832
+ _classPrivateFieldInitSpec(this, _timer$1, void 0);
13833
+ _classPrivateFieldInitSpec(this, _openedByHover, false);
13834
+ _defineProperty(
13835
+ this,
13836
+ /** The current state. The same object until something changes. */
13837
+ "getSnapshot",
13838
+ () => _classPrivateFieldGet2(_state$1, this)
13839
+ );
13840
+ _defineProperty(
13841
+ this,
13842
+ /** Calls `listener` when the state changes. Returns the unsubscribe function. */
13843
+ "subscribe",
13844
+ (listener) => {
13845
+ _classPrivateFieldGet2(_listeners$1, this).add(listener);
13846
+ return () => {
13847
+ _classPrivateFieldGet2(_listeners$1, this).delete(listener);
13848
+ };
13849
+ }
13850
+ );
13851
+ _defineProperty(
13852
+ this,
13853
+ /**
13854
+ * Opens or closes the menu and stops a pending close. `trigger` is read on
13855
+ * open for the dark theme.
13856
+ */
13857
+ "setOpen",
13858
+ (open, trigger) => {
13859
+ this.cancelClose();
13860
+ const dark = open ? !!(trigger === null || trigger === void 0 ? void 0 : trigger.closest(".dark")) : _classPrivateFieldGet2(_state$1, this).dark;
13861
+ if (open === _classPrivateFieldGet2(_state$1, this).open && dark === _classPrivateFieldGet2(_state$1, this).dark) return;
13862
+ _classPrivateFieldSet2(_state$1, this, {
13863
+ open,
13864
+ dark
13865
+ });
13866
+ for (const listener of _classPrivateFieldGet2(_listeners$1, this)) listener();
13867
+ }
13868
+ );
13869
+ _defineProperty(
13870
+ this,
13871
+ /** The pointer reached the trigger: opens, except for touch or disabled. */
13872
+ "pointerEnter",
13873
+ ({ pointerType, disabled = false, trigger }) => {
13874
+ if (disabled || pointerType === "touch") return;
13875
+ _classPrivateFieldSet2(_openedByHover, this, true);
13876
+ this.setOpen(true, trigger);
13877
+ }
13878
+ );
13879
+ _defineProperty(
13880
+ this,
13881
+ /** The keyboard used the trigger or the menu: keep it open on leave. */
13882
+ "keyboardUsed",
13883
+ () => {
13884
+ _classPrivateFieldSet2(_openedByHover, this, false);
13885
+ }
13886
+ );
13887
+ _defineProperty(
13888
+ this,
13889
+ /** The pointer left the trigger or the menu: close soon if hover opened it. */
13890
+ "scheduleClose",
13891
+ () => {
13892
+ this.cancelClose();
13893
+ _classPrivateFieldSet2(_timer$1, this, setTimeout(() => {
13894
+ _classPrivateFieldSet2(_timer$1, this, void 0);
13895
+ if (_classPrivateFieldGet2(_openedByHover, this)) this.setOpen(false);
13896
+ }, _classPrivateFieldGet2(_closeDelayMs, this)));
13897
+ }
13898
+ );
13899
+ _defineProperty(
13900
+ this,
13901
+ /** The pointer came back: keep the menu open. */
13902
+ "cancelClose",
13903
+ () => {
13904
+ if (_classPrivateFieldGet2(_timer$1, this) === void 0) return;
13905
+ clearTimeout(_classPrivateFieldGet2(_timer$1, this));
13906
+ _classPrivateFieldSet2(_timer$1, this, void 0);
13907
+ }
13908
+ );
13909
+ _defineProperty(
13910
+ this,
13911
+ /** Stops a pending close. */
13912
+ "dispose",
13913
+ () => {
13914
+ this.cancelClose();
13915
+ }
13916
+ );
13917
+ _classPrivateFieldSet2(_closeDelayMs, this, closeDelayMs);
13918
+ }
13919
+ /** Whether the pointer opened the menu and the keyboard has not used it. */
13920
+ get openedByHover() {
13921
+ return _classPrivateFieldGet2(_openedByHover, this);
13922
+ }
13923
+ };
13924
+
13925
+ //#endregion
13926
+ //#region src/open-generative-ui/content.ts
13927
+ /**
13928
+ * Open Generative UI content: the activity the agent streams while it
13929
+ * generates a sandboxed UI, and the rules for when a new snapshot must reach
13930
+ * the sandbox at once.
13931
+ */
13932
+ /** The activity type of Open Generative UI messages. */
13933
+ const OPEN_GENERATIVE_UI_ACTIVITY_TYPE = "open-generative-ui";
13934
+ /** The name of the frontend tool the agent calls to generate a sandboxed UI. */
13935
+ const GENERATE_SANDBOXED_UI_TOOL_NAME = "generateSandboxedUi";
13936
+ /** The design guidance sent to the agent when no `designSkill` is set. */
13937
+ const DEFAULT_OPEN_GENERATIVE_UI_DESIGN_SKILL = `When generating UI with generateSandboxedUi, follow these design principles inspired by shadcn/ui:
13938
+
13939
+ - Use a minimal, flat aesthetic. Avoid drop shadows and gradients — rely on subtle borders (1px solid, light gray like #e5e7eb) to define surfaces.
13940
+ - Neutral base palette: white backgrounds, zinc/slate gray text (#09090b for headings, #71717a for secondary text). One accent color for interactive elements.
13941
+ - Use system font stacks (system-ui, -apple-system, sans-serif) at readable sizes (14px body, 600 weight for headings). Tight line-heights.
13942
+ - Small, consistent border-radius (6–8px). Cards and containers use border, not shadow, for separation.
13943
+ - Buttons: solid fill for primary (dark bg, white text), outline for secondary (border + transparent bg). Subtle hover state (slight opacity or background shift).
13944
+ - Use CSS Grid or Flexbox for layout. Ensure the UI looks good at any width.
13945
+ - Minimal transitions (150ms) for hover/focus states only. No decorative animations.
13946
+ - Keep the UI focused and dense — avoid excessive padding. Use compact spacing (8–12px gaps, 10–14px padding in controls).`;
13947
+ /** `true` when the content has HTML that a preview or final sandbox shows. */
13948
+ function hasRenderableContent(content) {
13949
+ var _content$html;
13950
+ if (!content) return false;
13951
+ const hasHtml = !!((_content$html = content.html) === null || _content$html === void 0 ? void 0 : _content$html.join("").trim());
13952
+ const hasFinalHtml = content.htmlComplete && hasHtml;
13953
+ const hasPreviewHtml = content.cssComplete && !content.htmlComplete && hasHtml;
13954
+ return !!hasFinalHtml || !!hasPreviewHtml;
13955
+ }
13956
+ /**
13957
+ * `true` when `next` must replace `previous` at once instead of waiting for
13958
+ * the throttle window: the UI restarts, a stage completes, or new JavaScript
13959
+ * arrives.
13960
+ */
13961
+ function shouldFlushImmediately(previous, next) {
13962
+ var _next$jsExpressions$l, _next$jsExpressions, _previous$jsExpressio, _previous$jsExpressio2, _next$html, _previous$html;
13963
+ if (hasRenderableContent(previous) && !hasRenderableContent(next)) return true;
13964
+ if (next.cssComplete && !(previous === null || previous === void 0 ? void 0 : previous.cssComplete)) return true;
13965
+ if (next.htmlComplete) return true;
13966
+ if (next.generating === false) return true;
13967
+ if (next.jsFunctions && !(previous === null || previous === void 0 ? void 0 : previous.jsFunctions)) return true;
13968
+ if (((_next$jsExpressions$l = (_next$jsExpressions = next.jsExpressions) === null || _next$jsExpressions === void 0 ? void 0 : _next$jsExpressions.length) !== null && _next$jsExpressions$l !== void 0 ? _next$jsExpressions$l : 0) > ((_previous$jsExpressio = previous === null || previous === void 0 || (_previous$jsExpressio2 = previous.jsExpressions) === null || _previous$jsExpressio2 === void 0 ? void 0 : _previous$jsExpressio2.length) !== null && _previous$jsExpressio !== void 0 ? _previous$jsExpressio : 0)) return true;
13969
+ if (((_next$html = next.html) === null || _next$html === void 0 ? void 0 : _next$html.length) && !(previous === null || previous === void 0 || (_previous$html = previous.html) === null || _previous$html === void 0 ? void 0 : _previous$html.length)) return true;
13970
+ return false;
13971
+ }
13972
+
13973
+ //#endregion
13974
+ //#region src/open-generative-ui/html.ts
13975
+ /**
13976
+ * Pure string helpers that turn streamed HTML into sandbox content.
13977
+ * No DOM access.
13978
+ */
13979
+ /**
13980
+ * Extracts all complete `<style>` blocks from the raw HTML.
13981
+ * Returns the concatenated style tags, suitable for injection into `<head>`.
13982
+ */
13983
+ function extractCompleteStyles(html) {
13984
+ const matches = html.match(/<style\b[^>]*>[\s\S]*?<\/style>/gi);
13985
+ return matches ? matches.join("") : "";
13986
+ }
13987
+ /**
13988
+ * Processes raw accumulated HTML for safe preview via innerHTML injection.
13989
+ *
13990
+ * Pipeline (order matters):
13991
+ * 1. Strip incomplete tag at end
13992
+ * 2. Strip complete <style>, <script>, and <head> blocks
13993
+ * 3. Strip incomplete <style>/<script>/<head> blocks
13994
+ * 4. Strip incomplete HTML entities
13995
+ * 5. Extract body content (or use full string if no <body>)
13996
+ */
13997
+ function processPartialHtml(html) {
13998
+ let result = html;
13999
+ result = result.replace(/<[^>]*$/, "");
14000
+ result = result.replace(/<(style|script|head)\b[^>]*>[\s\S]*?<\/\1>/gi, "");
14001
+ result = result.replace(/<(style|script|head)\b[^>]*>[\s\S]*$/gi, "");
14002
+ result = result.replace(/&[a-zA-Z0-9#]*$/, "");
14003
+ const bodyMatch = result.match(/<body[^>]*>([\s\S]*)/i);
14004
+ if (bodyMatch) {
14005
+ result = bodyMatch[1];
14006
+ result = result.replace(/<\/body>[\s\S]*/i, "");
14007
+ }
14008
+ return result;
14009
+ }
14010
+ /** Builds the final sandbox document: the HTML with the CSS in its `<head>`. */
14011
+ function buildFinalFrameContent(html, css) {
14012
+ const withCss = css ? injectCssIntoHtml(html, css) : html;
14013
+ return /<head[\s>]/i.test(withCss) ? withCss : `<head></head>${withCss}`;
14014
+ }
14015
+ function injectCssIntoHtml(html, css) {
14016
+ const headCloseIdx = html.indexOf("</head>");
14017
+ if (headCloseIdx !== -1) return html.slice(0, headCloseIdx) + `<style>${css}</style>` + html.slice(headCloseIdx);
14018
+ return `<head><style>${css}</style></head>${html}`;
14019
+ }
14020
+
14021
+ //#endregion
14022
+ //#region ../../node_modules/.pnpm/@jetbrains+websandbox@1.1.3/node_modules/@jetbrains/websandbox/dist/websandbox.js
14023
+ var require_websandbox = /* @__PURE__ */ __commonJSMin(((exports, module) => {
14024
+ (function webpackUniversalModuleDefinition(root, factory) {
14025
+ if (typeof exports === "object" && typeof module === "object") module.exports = factory();
14026
+ else if (typeof define === "function" && define.amd) define([], factory);
14027
+ else if (typeof exports === "object") exports["Websandbox"] = factory();
14028
+ else root["Websandbox"] = factory();
14029
+ })(self, () => {
14030
+ return (() => {
14031
+ var __webpack_modules__ = { 466: ((module$1) => {
14032
+ module$1.exports = "/******/ (() => { // webpackBootstrap\n/******/ \"use strict\";\n\n// UNUSED EXPORTS: default\n\n;// ./lib/object-path.ts\nconst PATH_REG = /([.[\\]:;'\"\\s])/;\nfunction escapePathPart(pathPart) {\n if (!PATH_REG.test(pathPart)) {\n return pathPart;\n }\n const escaped = pathPart.replace(new RegExp(PATH_REG.source, 'g'), '\\\\$1');\n return `[\"${escaped}\"]`;\n}\nfunction unescapePathPart(pathPart) {\n return pathPart.replace(/^\\[\"/, '').replace(/\"]$/, '').replace(/\\\\/, '');\n}\nfunction splitPath(path) {\n const result = [];\n let lastEnd = 0;\n for (let i = 0; i < path.length; i++) {\n const char = path[i];\n if (PATH_REG.test(char) && path[i - 1] !== '\\\\') {\n result.push(path.substring(lastEnd, i));\n lastEnd = i + 1;\n }\n }\n result.push(path.substring(lastEnd, path.length));\n return result.filter(pathPart => !!pathPart).map(pathPart => pathPart.replace(/\\\\/g, ''));\n}\n/**\n * Extracts object property value by given path. Supports nested and array values: 'foo[0].bar'\n * @param {Object} object source object\n * @param {string} path path to value\n * @return {any | null} value by given path\n * */\nfunction propertyByPath(object, path) {\n return splitPath(path).reduce((acc, pathPart) => {\n if (acc) {\n return acc[pathPart];\n }\n return null;\n }, object);\n}\n\n;// ./lib/connection.ts\n\nconst TYPE_MESSAGE = 'message';\nconst TYPE_RESPONSE = 'response';\nconst TYPE_SET_INTERFACE = 'set-interface';\nconst TYPE_SERVICE_MESSAGE = 'service-message';\n// @ts-expect-error this is IE11 obsolete check. It is not typed\nconst isIE11 = !!window.MSInputMethodContext && !!document.documentMode;\nconst defaultOptions = {\n //Will not affect IE11 because there sandboxed iframe has not 'null' origin\n //but base URL of iframe's src\n allowedSenderOrigin: undefined\n};\nclass Connection {\n constructor(postMessage, registerOnMessageListener, options = {}) {\n this.remote = {};\n this.serviceMethods = {};\n this.localApi = {};\n this.callbacks = {};\n this._resolveRemoteMethodsPromise = null;\n this.options = Object.assign(Object.assign({}, defaultOptions), options);\n //Random number between 0 and 100000\n this.incrementalID = Math.floor(Math.random() * 100000);\n this.postMessage = postMessage;\n this.remoteMethodsWaitPromise = new Promise(resolve => {\n this._resolveRemoteMethodsPromise = resolve;\n });\n registerOnMessageListener((e) => this.onMessageListener(e));\n }\n /**\n * Listens to remote messages. Calls local method if it is called outside or call stored callback if it is response.\n * @param e - onMessage event\n */\n onMessageListener(e) {\n const data = e.data;\n const { allowedSenderOrigin } = this.options;\n if (allowedSenderOrigin && e.origin !== allowedSenderOrigin && !isIE11) {\n return;\n }\n if (data.type === TYPE_RESPONSE) {\n this.popCallback(data.callId, data.success, data.result);\n }\n else if (data.type === TYPE_MESSAGE) {\n this\n .callLocalApi(data.methodName, data.arguments)\n .then(res => this.responseOtherSide(data.callId, res))\n .catch(err => this.responseOtherSide(data.callId, err, false));\n }\n else if (data.type === TYPE_SET_INTERFACE) {\n this.setInterface(data.apiMethods);\n this.responseOtherSide(data.callId);\n }\n else if (data.type === TYPE_SERVICE_MESSAGE) {\n this\n .callLocalServiceMethod(data.methodName, data.arguments)\n .then(res => this.responseOtherSide(data.callId, res))\n .catch(err => this.responseOtherSide(data.callId, err, false));\n }\n }\n postMessageToOtherSide(dataToPost) {\n this.postMessage(dataToPost, '*');\n }\n /**\n * Sets remote interface methods\n * @param remote - hash with keys of remote API methods. Values is ignored\n */\n setInterface(remoteMethods) {\n var _a;\n this.remote = {};\n remoteMethods.forEach((key) => {\n // If key is nested, we need to create nested structure\n const parts = splitPath(key);\n let current = this.remote;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n if (!current[part] || typeof current[part] !== 'object') {\n current[part] = {};\n }\n current = current[part];\n }\n current[parts[parts.length - 1]] = this.createMethodWrapper(key);\n });\n (_a = this._resolveRemoteMethodsPromise) === null || _a === void 0 ? void 0 : _a.call(this);\n }\n getMethodsFromInterface(api) {\n return Object.keys(api).reduce((acc, key) => {\n if (typeof api[key] === 'object') {\n acc.push(...this.getMethodsFromInterface(api[key]).map(subKey => `${key}.${subKey}`));\n }\n else {\n acc.push(key);\n }\n return acc;\n }, []);\n }\n setLocalApi(api) {\n return new Promise((resolve, reject) => {\n const id = this.registerCallback(resolve, reject);\n this.postMessageToOtherSide({\n callId: id,\n apiMethods: this.getMethodsFromInterface(api),\n type: TYPE_SET_INTERFACE\n });\n }).then(() => this.localApi = api);\n }\n setServiceMethods(api) {\n this.serviceMethods = api;\n }\n /**\n * Calls local method\n * @param methodName\n * @param args\n * @returns {Promise.<*>|string}\n */\n callLocalApi(methodName, args) {\n const method = propertyByPath(this.localApi, methodName);\n if (!method) {\n throw new Error(`Local method \"${methodName}\" is not registered`);\n }\n return Promise.resolve(method.call(this, ...args));\n }\n /**\n * Calls local method registered as \"service method\"\n * @param methodName\n * @param args\n * @returns {Promise.<*>}\n */\n callLocalServiceMethod(methodName, args) {\n const method = propertyByPath(this.serviceMethods, methodName);\n if (!method) {\n throw new Error(`Service method ${methodName} is not registered`);\n }\n return Promise.resolve(method.call(this, ...args));\n }\n /**\n * Wraps remote method with callback storing code\n * @param methodName - method to wrap\n * @returns {Function} - function to call as remote API interface\n */\n createMethodWrapper(methodName) {\n return (...args) => {\n return this.callRemoteMethod(methodName, ...args);\n };\n }\n /**\n * Calls other side with arguments provided\n * @param id\n * @param methodName\n * @param args\n */\n callRemoteMethod(methodName, ...args) {\n return new Promise((resolve, reject) => {\n const id = this.registerCallback(resolve, reject);\n this.postMessageToOtherSide({\n callId: id,\n methodName: methodName,\n type: TYPE_MESSAGE,\n arguments: args\n });\n });\n }\n /**\n * Calls remote service method\n * @param methodName\n * @param args\n * @returns {*}\n */\n callRemoteServiceMethod(methodName, ...args) {\n return new Promise((resolve, reject) => {\n const id = this.registerCallback(resolve, reject);\n this.postMessageToOtherSide({\n callId: id,\n methodName: methodName,\n type: TYPE_SERVICE_MESSAGE,\n arguments: args\n });\n });\n }\n /**\n * Respond to remote call\n * @param id - remote call ID\n * @param result - result to pass to calling function\n */\n responseOtherSide(id, result, success = true) {\n if (result instanceof Error) {\n // Error could be non-serializable, so we copy properties manually\n result = [...Object.keys(result), 'message'].reduce((acc, it) => {\n acc[it] = result[it];\n return acc;\n }, {});\n }\n const doPost = () => this.postMessage({\n callId: id,\n type: TYPE_RESPONSE,\n success,\n result\n }, '*');\n try {\n doPost();\n }\n catch (err) {\n console.error('Failed to post response, recovering...', err); // eslint-disable-line no-console\n if (err instanceof DOMException) {\n result = JSON.parse(JSON.stringify(result));\n doPost();\n }\n }\n }\n /*\n * Stores callbacks to call later when remote call will be answered\n */\n registerCallback(successCallback, failureCallback) {\n const id = (++this.incrementalID).toString();\n this.callbacks[id] = { successCallback, failureCallback };\n return id;\n }\n /**\n * Calls and delete stored callback\n * @param id - call id\n * @param success - was call successful\n * @param result - result of remote call\n */\n popCallback(id, success, result) {\n const callback = this.callbacks[id];\n if (!callback) {\n return;\n }\n if (success) {\n callback.successCallback(result);\n }\n else {\n callback.failureCallback(result);\n }\n delete this.callbacks[id];\n }\n}\n/* harmony default export */ const connection = (Connection);\n\n;// ./node_modules/ts-loader/index.js??ruleSet[1].rules[0]!./lib/frame.ts\n\nclass Frame {\n constructor() {\n this.connection = new connection(window.parent.postMessage.bind(window.parent), listener => {\n const sourceCheckListener = (event) => {\n if (event.source !== window.parent) {\n return;\n }\n return listener(event);\n };\n window.addEventListener('message', sourceCheckListener);\n });\n this.connection.setServiceMethods({\n runCode: (code) => this.runCode(code),\n importScript: (path) => this.importScript(path),\n injectStyle: (style) => this.injectStyle(style),\n importStyle: (path) => this.importStyle(path)\n });\n this.connection.callRemoteServiceMethod('iframeInitialized');\n }\n /**\n * Creates script tag with passed code and attaches it. Runs synchronous\n * @param code\n */\n runCode(code) {\n const scriptTag = document.createElement('script');\n scriptTag.innerHTML = code;\n document.getElementsByTagName('head')[0].appendChild(scriptTag);\n }\n importScript(scriptUrl) {\n const scriptTag = document.createElement('script');\n scriptTag.src = scriptUrl;\n document.getElementsByTagName('head')[0].appendChild(scriptTag);\n return new Promise(resolve => scriptTag.onload = () => resolve());\n }\n injectStyle(style) {\n const styleTag = document.createElement('style');\n styleTag.innerHTML = style;\n document.getElementsByTagName('head')[0].appendChild(styleTag);\n }\n importStyle(styleUrl) {\n const linkTag = document.createElement('link');\n linkTag.rel = 'stylesheet';\n linkTag.href = styleUrl;\n document.getElementsByTagName('head')[0].appendChild(linkTag);\n }\n}\n// @ts-expect-error we explicitly export library to global namespace because\nconst Websandbox = window.Websandbox || new Frame();\n// @ts-expect-error we explicitly export library to global namespace because\n// Webpack won't do it for us when this file is loaded via code-loader\nwindow.Websandbox = Websandbox;\n/* harmony default export */ const ts_loader_ruleSet_1_rules_0_lib_frame = ((/* unused pure expression or super */ null && (Websandbox)));\n\n/******/ })()\n;\n//# sourceMappingURL=compile-loader-file-name.js.map";
14033
+ }) };
14034
+ var __webpack_module_cache__ = {};
14035
+ function __webpack_require__(moduleId) {
14036
+ var cachedModule = __webpack_module_cache__[moduleId];
14037
+ if (cachedModule !== void 0) return cachedModule.exports;
14038
+ var module$2 = __webpack_module_cache__[moduleId] = { exports: {} };
14039
+ __webpack_modules__[moduleId](module$2, module$2.exports, __webpack_require__);
14040
+ return module$2.exports;
14041
+ }
14042
+ __webpack_require__.n = (module$3) => {
14043
+ var getter = module$3 && module$3.__esModule ? () => module$3["default"] : () => module$3;
14044
+ __webpack_require__.d(getter, { a: getter });
14045
+ return getter;
14046
+ };
14047
+ __webpack_require__.d = (exports$1, definition) => {
14048
+ for (var key in definition) if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports$1, key)) Object.defineProperty(exports$1, key, {
14049
+ enumerable: true,
14050
+ get: definition[key]
14051
+ });
14052
+ };
14053
+ __webpack_require__.o = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop);
14054
+ __webpack_require__.r = (exports$2) => {
14055
+ if (typeof Symbol !== "undefined" && Symbol.toStringTag) Object.defineProperty(exports$2, Symbol.toStringTag, { value: "Module" });
14056
+ Object.defineProperty(exports$2, "__esModule", { value: true });
14057
+ };
14058
+ var __webpack_exports__ = {};
14059
+ (() => {
14060
+ "use strict";
14061
+ __webpack_require__.r(__webpack_exports__);
14062
+ __webpack_require__.d(__webpack_exports__, {
14063
+ BaseOptions: () => BaseOptions,
14064
+ "default": () => websandbox
14065
+ });
14066
+ const PATH_REG = /([.[\]:;'"\s])/;
14067
+ function splitPath(path) {
14068
+ const result = [];
14069
+ let lastEnd = 0;
14070
+ for (let i = 0; i < path.length; i++) {
14071
+ const char = path[i];
14072
+ if (PATH_REG.test(char) && path[i - 1] !== "\\") {
14073
+ result.push(path.substring(lastEnd, i));
14074
+ lastEnd = i + 1;
14075
+ }
14076
+ }
14077
+ result.push(path.substring(lastEnd, path.length));
14078
+ return result.filter((pathPart) => !!pathPart).map((pathPart) => pathPart.replace(/\\/g, ""));
14079
+ }
14080
+ /**
14081
+ * Extracts object property value by given path. Supports nested and array values: 'foo[0].bar'
14082
+ * @param {Object} object source object
14083
+ * @param {string} path path to value
14084
+ * @return {any | null} value by given path
14085
+ * */
14086
+ function propertyByPath(object, path) {
14087
+ return splitPath(path).reduce((acc, pathPart) => {
14088
+ if (acc) return acc[pathPart];
14089
+ return null;
14090
+ }, object);
14091
+ }
14092
+ const TYPE_MESSAGE = "message";
14093
+ const TYPE_RESPONSE = "response";
14094
+ const TYPE_SET_INTERFACE = "set-interface";
14095
+ const TYPE_SERVICE_MESSAGE = "service-message";
14096
+ const isIE11 = !!window.MSInputMethodContext && !!document.documentMode;
14097
+ const defaultOptions = { allowedSenderOrigin: void 0 };
14098
+ class Connection {
14099
+ constructor(postMessage, registerOnMessageListener, options = {}) {
14100
+ this.remote = {};
14101
+ this.serviceMethods = {};
14102
+ this.localApi = {};
14103
+ this.callbacks = {};
14104
+ this._resolveRemoteMethodsPromise = null;
14105
+ this.options = Object.assign(Object.assign({}, defaultOptions), options);
14106
+ this.incrementalID = Math.floor(Math.random() * 1e5);
14107
+ this.postMessage = postMessage;
14108
+ this.remoteMethodsWaitPromise = new Promise((resolve) => {
14109
+ this._resolveRemoteMethodsPromise = resolve;
14110
+ });
14111
+ registerOnMessageListener((e) => this.onMessageListener(e));
14112
+ }
14113
+ /**
14114
+ * Listens to remote messages. Calls local method if it is called outside or call stored callback if it is response.
14115
+ * @param e - onMessage event
14116
+ */
14117
+ onMessageListener(e) {
14118
+ const data = e.data;
14119
+ const { allowedSenderOrigin } = this.options;
14120
+ if (allowedSenderOrigin && e.origin !== allowedSenderOrigin && !isIE11) return;
14121
+ if (data.type === TYPE_RESPONSE) this.popCallback(data.callId, data.success, data.result);
14122
+ else if (data.type === TYPE_MESSAGE) this.callLocalApi(data.methodName, data.arguments).then((res) => this.responseOtherSide(data.callId, res)).catch((err) => this.responseOtherSide(data.callId, err, false));
14123
+ else if (data.type === TYPE_SET_INTERFACE) {
14124
+ this.setInterface(data.apiMethods);
14125
+ this.responseOtherSide(data.callId);
14126
+ } else if (data.type === TYPE_SERVICE_MESSAGE) this.callLocalServiceMethod(data.methodName, data.arguments).then((res) => this.responseOtherSide(data.callId, res)).catch((err) => this.responseOtherSide(data.callId, err, false));
14127
+ }
14128
+ postMessageToOtherSide(dataToPost) {
14129
+ this.postMessage(dataToPost, "*");
14130
+ }
14131
+ /**
14132
+ * Sets remote interface methods
14133
+ * @param remote - hash with keys of remote API methods. Values is ignored
14134
+ */
14135
+ setInterface(remoteMethods) {
14136
+ var _a;
14137
+ this.remote = {};
14138
+ remoteMethods.forEach((key) => {
14139
+ const parts = splitPath(key);
14140
+ let current = this.remote;
14141
+ for (let i = 0; i < parts.length - 1; i++) {
14142
+ const part = parts[i];
14143
+ if (!current[part] || typeof current[part] !== "object") current[part] = {};
14144
+ current = current[part];
14145
+ }
14146
+ current[parts[parts.length - 1]] = this.createMethodWrapper(key);
14147
+ });
14148
+ (_a = this._resolveRemoteMethodsPromise) === null || _a === void 0 || _a.call(this);
14149
+ }
14150
+ getMethodsFromInterface(api) {
14151
+ return Object.keys(api).reduce((acc, key) => {
14152
+ if (typeof api[key] === "object") acc.push(...this.getMethodsFromInterface(api[key]).map((subKey) => `${key}.${subKey}`));
14153
+ else acc.push(key);
14154
+ return acc;
14155
+ }, []);
14156
+ }
14157
+ setLocalApi(api) {
14158
+ return new Promise((resolve, reject) => {
14159
+ const id = this.registerCallback(resolve, reject);
14160
+ this.postMessageToOtherSide({
14161
+ callId: id,
14162
+ apiMethods: this.getMethodsFromInterface(api),
14163
+ type: TYPE_SET_INTERFACE
14164
+ });
14165
+ }).then(() => this.localApi = api);
14166
+ }
14167
+ setServiceMethods(api) {
14168
+ this.serviceMethods = api;
14169
+ }
14170
+ /**
14171
+ * Calls local method
14172
+ * @param methodName
14173
+ * @param args
14174
+ * @returns {Promise.<*>|string}
14175
+ */
14176
+ callLocalApi(methodName, args) {
14177
+ const method = propertyByPath(this.localApi, methodName);
14178
+ if (!method) throw new Error(`Local method "${methodName}" is not registered`);
14179
+ return Promise.resolve(method.call(this, ...args));
14180
+ }
14181
+ /**
14182
+ * Calls local method registered as "service method"
14183
+ * @param methodName
14184
+ * @param args
14185
+ * @returns {Promise.<*>}
14186
+ */
14187
+ callLocalServiceMethod(methodName, args) {
14188
+ const method = propertyByPath(this.serviceMethods, methodName);
14189
+ if (!method) throw new Error(`Service method ${methodName} is not registered`);
14190
+ return Promise.resolve(method.call(this, ...args));
14191
+ }
14192
+ /**
14193
+ * Wraps remote method with callback storing code
14194
+ * @param methodName - method to wrap
14195
+ * @returns {Function} - function to call as remote API interface
14196
+ */
14197
+ createMethodWrapper(methodName) {
14198
+ return (...args) => {
14199
+ return this.callRemoteMethod(methodName, ...args);
14200
+ };
14201
+ }
14202
+ /**
14203
+ * Calls other side with arguments provided
14204
+ * @param id
14205
+ * @param methodName
14206
+ * @param args
14207
+ */
14208
+ callRemoteMethod(methodName, ...args) {
14209
+ return new Promise((resolve, reject) => {
14210
+ const id = this.registerCallback(resolve, reject);
14211
+ this.postMessageToOtherSide({
14212
+ callId: id,
14213
+ methodName,
14214
+ type: TYPE_MESSAGE,
14215
+ arguments: args
14216
+ });
14217
+ });
14218
+ }
14219
+ /**
14220
+ * Calls remote service method
14221
+ * @param methodName
14222
+ * @param args
14223
+ * @returns {*}
14224
+ */
14225
+ callRemoteServiceMethod(methodName, ...args) {
14226
+ return new Promise((resolve, reject) => {
14227
+ const id = this.registerCallback(resolve, reject);
14228
+ this.postMessageToOtherSide({
14229
+ callId: id,
14230
+ methodName,
14231
+ type: TYPE_SERVICE_MESSAGE,
14232
+ arguments: args
14233
+ });
14234
+ });
14235
+ }
14236
+ /**
14237
+ * Respond to remote call
14238
+ * @param id - remote call ID
14239
+ * @param result - result to pass to calling function
14240
+ */
14241
+ responseOtherSide(id, result, success = true) {
14242
+ if (result instanceof Error) result = [...Object.keys(result), "message"].reduce((acc, it) => {
14243
+ acc[it] = result[it];
14244
+ return acc;
14245
+ }, {});
14246
+ const doPost = () => this.postMessage({
14247
+ callId: id,
14248
+ type: TYPE_RESPONSE,
14249
+ success,
14250
+ result
14251
+ }, "*");
14252
+ try {
14253
+ doPost();
14254
+ } catch (err) {
14255
+ console.error("Failed to post response, recovering...", err);
14256
+ if (err instanceof DOMException) {
14257
+ result = JSON.parse(JSON.stringify(result));
14258
+ doPost();
14259
+ }
14260
+ }
14261
+ }
14262
+ registerCallback(successCallback, failureCallback) {
14263
+ const id = (++this.incrementalID).toString();
14264
+ this.callbacks[id] = {
14265
+ successCallback,
14266
+ failureCallback
14267
+ };
14268
+ return id;
14269
+ }
14270
+ /**
14271
+ * Calls and delete stored callback
14272
+ * @param id - call id
14273
+ * @param success - was call successful
14274
+ * @param result - result of remote call
14275
+ */
14276
+ popCallback(id, success, result) {
14277
+ const callback = this.callbacks[id];
14278
+ if (!callback) return;
14279
+ if (success) callback.successCallback(result);
14280
+ else callback.failureCallback(result);
14281
+ delete this.callbacks[id];
14282
+ }
14283
+ }
14284
+ const connection = Connection;
14285
+ var index_js_lib_frame = __webpack_require__(466);
14286
+ var frame_default = /* @__PURE__ */ __webpack_require__.n(index_js_lib_frame);
14287
+ const BaseOptions = {
14288
+ frameContainer: "body",
14289
+ frameClassName: "websandbox__frame",
14290
+ frameSrc: null,
14291
+ frameContent: `
14292
+ <!DOCTYPE html>
14293
+ <html>
14294
+ <head><meta charset="UTF-8"></head>
14295
+ <body></body>
14296
+ </html>
14297
+ `,
14298
+ codeToRunBeforeInit: null,
14299
+ initialStyles: null,
14300
+ baseUrl: null,
14301
+ allowPointerLock: false,
14302
+ allowFullScreen: false,
14303
+ sandboxAdditionalAttributes: ""
14304
+ };
14305
+ class Websandbox {
14306
+ /**
14307
+ * Creates sandbox instancea
14308
+ * @param localApi Api of this side. Will be available for sandboxed code as remoteApi
14309
+ * @param options Options of created sandbox
14310
+ */
14311
+ static create(localApi, options = {}) {
14312
+ return new Websandbox(localApi, options);
14313
+ }
14314
+ /**
14315
+ * {Constructor}
14316
+ * @param localApi
14317
+ * @param options
14318
+ */
14319
+ constructor(localApi, options) {
14320
+ this.connection = null;
14321
+ this.removeMessageListener = () => {};
14322
+ this.validateOptions(options);
14323
+ this.options = Object.assign(Object.assign({}, BaseOptions), options);
14324
+ this.iframe = this.createIframe();
14325
+ this.promise = new Promise((resolve) => {
14326
+ this.connection = new connection(this.iframe.contentWindow.postMessage.bind(this.iframe.contentWindow), (listener) => {
14327
+ const sourceCheckListener = (event) => {
14328
+ if (event.source !== this.iframe.contentWindow) return;
14329
+ return listener(event);
14330
+ };
14331
+ window.addEventListener("message", sourceCheckListener);
14332
+ this.removeMessageListener = () => window.removeEventListener("message", sourceCheckListener);
14333
+ }, { allowedSenderOrigin: "null" });
14334
+ this.connection.setServiceMethods({ iframeInitialized: () => {
14335
+ return this.connection.setLocalApi(localApi).then(() => resolve(this));
14336
+ } });
14337
+ });
14338
+ }
14339
+ validateOptions(options) {
14340
+ var _a;
14341
+ if (options.frameSrc && (options.frameContent || options.initialStyles || options.baseUrl || options.codeToRunBeforeInit)) throw new Error("You can not set both \"frameSrc\" and any of frameContent,initialStyles,baseUrl,codeToRunBeforeInit options");
14342
+ if ("frameContent" in options && !((_a = options.frameContent) === null || _a === void 0 ? void 0 : _a.includes("<head>"))) throw new Error("Websandbox: iFrame content must have \"<head>\" tag.");
14343
+ }
14344
+ _prepareFrameContent(options) {
14345
+ var _a, _b, _c;
14346
+ let frameContent = (_a = options.frameContent) !== null && _a !== void 0 ? _a : "";
14347
+ if (options.codeToRunBeforeInit) frameContent = (_b = frameContent.replace("<head>", `<head>\n<script>${options.codeToRunBeforeInit}<\/script>`)) !== null && _b !== void 0 ? _b : "";
14348
+ frameContent = (_c = frameContent.replace("<head>", `<head>\n<script>${frame_default()}<\/script>`)) !== null && _c !== void 0 ? _c : "";
14349
+ if (options.initialStyles) frameContent = frameContent.replace("</head>", `<style>${options.initialStyles}</style>\n</head>`);
14350
+ if (options.baseUrl) frameContent = frameContent.replace("<head>", `<head>\n<base target="_parent" href="${options.baseUrl}"/>`);
14351
+ return frameContent;
14352
+ }
14353
+ createIframe() {
14354
+ var _a;
14355
+ const containerSelector = this.options.frameContainer;
14356
+ const container = typeof containerSelector === "string" ? document.querySelector(containerSelector) : containerSelector;
14357
+ if (!container) throw new Error("Websandbox: Cannot find container for sandbox " + container);
14358
+ const frame = document.createElement("iframe");
14359
+ frame.sandbox = `allow-scripts ${this.options.sandboxAdditionalAttributes}`;
14360
+ frame.allow = `${this.options.allowAdditionalAttributes}`;
14361
+ frame.className = (_a = this.options.frameClassName) !== null && _a !== void 0 ? _a : "";
14362
+ if (this.options.allowFullScreen) frame.allowFullscreen = true;
14363
+ if (this.options.frameSrc) {
14364
+ frame.src = this.options.frameSrc;
14365
+ container.appendChild(frame);
14366
+ return frame;
14367
+ }
14368
+ frame.setAttribute("srcdoc", this._prepareFrameContent(this.options));
14369
+ container.appendChild(frame);
14370
+ return frame;
14371
+ }
14372
+ destroy() {
14373
+ this.iframe.remove();
14374
+ this.removeMessageListener();
14375
+ }
14376
+ _runCode(code) {
14377
+ return this.connection.callRemoteServiceMethod("runCode", code);
14378
+ }
14379
+ _runFunction(fn) {
14380
+ return this._runCode(`(${fn.toString()})()`);
14381
+ }
14382
+ run(codeOrFunction) {
14383
+ if (codeOrFunction.name) return this._runFunction(codeOrFunction);
14384
+ return this._runCode(codeOrFunction);
14385
+ }
14386
+ importScript(path) {
14387
+ return this.connection.callRemoteServiceMethod("importScript", path);
14388
+ }
14389
+ injectStyle(style) {
14390
+ return this.connection.callRemoteServiceMethod("injectStyle", style);
14391
+ }
14392
+ }
14393
+ const websandbox = Websandbox;
14394
+ })();
14395
+ return __webpack_exports__;
14396
+ })();
14397
+ });
14398
+ }));
14399
+
14400
+ //#endregion
14401
+ //#region src/open-generative-ui/websandbox.ts
14402
+ /**
14403
+ * Imports `@jetbrains/websandbox` on demand. The import is dynamic because
14404
+ * the package touches `self` when it loads, which breaks server rendering.
14405
+ */
14406
+ const loadWebsandbox = async () => {
14407
+ const defaultExport = (await Promise.resolve().then(() => /* @__PURE__ */ __toESM(require_websandbox(), 1))).default;
14408
+ return "default" in defaultExport ? defaultExport.default : defaultExport;
14409
+ };
14410
+
14411
+ //#endregion
14412
+ //#region src/open-generative-ui/controller.ts
14413
+ /** Non-immediate content updates reach the sandbox at most this often. */
14414
+ const OPEN_GENERATIVE_UI_THROTTLE_MS = 1e3;
14415
+ const DEFAULT_HEIGHT = 200;
14416
+ const HIDE_SCROLLBARS = `
14417
+ var s = document.createElement('style');
14418
+ s.textContent = 'html, body { overflow: hidden !important; }';
14419
+ document.head.appendChild(s);
14420
+ `;
14421
+ const HIDE_SCROLLBARS_STYLE = "<style>html, body { overflow: hidden !important; }</style>";
14422
+ const MEASURE_HEIGHT = `
14423
+ (function() {
14424
+ var s = document.createElement('style');
14425
+ s.textContent = 'body { height: auto !important; min-height: 0 !important; }';
14426
+ document.head.appendChild(s);
14427
+ var h = document.body.scrollHeight;
14428
+ var cs = getComputedStyle(document.body);
14429
+ h += parseFloat(cs.marginTop) || 0;
14430
+ h += parseFloat(cs.marginBottom) || 0;
14431
+ s.remove();
14432
+ parent.postMessage({ type: "__ck_resize", height: Math.ceil(h) }, "*");
14433
+ })();
14434
+ `;
14435
+ function deriveContent(content) {
14436
+ var _content$html;
14437
+ const html = ((_content$html = content.html) === null || _content$html === void 0 ? void 0 : _content$html.join("")) || void 0;
14438
+ const css = content.cssComplete ? content.css : void 0;
14439
+ if (content.htmlComplete) return {
14440
+ fullHtml: html,
14441
+ css,
14442
+ previewStyles: ""
14443
+ };
14444
+ const previewBody = html && content.cssComplete ? processPartialHtml(html) : void 0;
14445
+ return {
14446
+ css,
14447
+ previewBody: (previewBody === null || previewBody === void 0 ? void 0 : previewBody.trim()) ? previewBody : void 0,
14448
+ previewStyles: html ? extractCompleteStyles(html) : ""
14449
+ };
14450
+ }
14451
+ function prepareIframe(iframe, testId) {
14452
+ iframe.setAttribute("data-testid", testId);
14453
+ iframe.style.width = "100%";
14454
+ iframe.style.height = "100%";
14455
+ iframe.style.border = "none";
14456
+ iframe.style.backgroundColor = "transparent";
14457
+ }
14458
+ function logLoadError(error) {
14459
+ console.error("[OpenGenerativeUI] Failed to load sandbox module:", error);
14460
+ }
14461
+ function sameFunctions(a, b) {
14462
+ return a.length === b.length && a.every((fn, i) => fn.name === b[i].name && fn.handler === b[i].handler);
14463
+ }
14464
+ var _load = /* @__PURE__ */ new WeakMap();
14465
+ var _listeners = /* @__PURE__ */ new WeakMap();
14466
+ var _content = /* @__PURE__ */ new WeakMap();
14467
+ var _latest = /* @__PURE__ */ new WeakMap();
14468
+ var _derived = /* @__PURE__ */ new WeakMap();
14469
+ var _timer = /* @__PURE__ */ new WeakMap();
14470
+ var _host = /* @__PURE__ */ new WeakMap();
14471
+ var _functions = /* @__PURE__ */ new WeakMap();
14472
+ var _localApi = /* @__PURE__ */ new WeakMap();
14473
+ var _preview = /* @__PURE__ */ new WeakMap();
14474
+ var _final = /* @__PURE__ */ new WeakMap();
14475
+ var _measuredHeight = /* @__PURE__ */ new WeakMap();
14476
+ var _state = /* @__PURE__ */ new WeakMap();
14477
+ var _OpenGenerativeUIController_brand = /* @__PURE__ */ new WeakSet();
14478
+ /**
14479
+ * Runs Open Generative UI content in websandbox iframes inside a host element.
14480
+ *
14481
+ * Give it content snapshots with `setContent()` and a host element with
14482
+ * `setHost()`. It throttles the snapshots, streams a preview while HTML
14483
+ * arrives, swaps in the final sandbox once HTML is complete, runs
14484
+ * `jsFunctions` and `jsExpressions` in it once each, and measures the final
14485
+ * height. Frameworks render the container from `getState()` and re-render
14486
+ * when `subscribe()` notifies.
14487
+ *
14488
+ * @example
14489
+ * ```ts
14490
+ * const controller = new ɵOpenGenerativeUIController();
14491
+ * controller.subscribe(() => render(controller.getState()));
14492
+ * controller.setContent(content);
14493
+ * controller.setHost(containerElement);
14494
+ * // On unmount:
14495
+ * controller.destroy();
14496
+ * ```
14497
+ */
14498
+ var OpenGenerativeUIController = class {
14499
+ constructor(options = {}) {
14500
+ var _options$loadWebsandb;
14501
+ _classPrivateMethodInitSpec(this, _OpenGenerativeUIController_brand);
14502
+ _classPrivateFieldInitSpec(this, _load, void 0);
14503
+ _classPrivateFieldInitSpec(this, _listeners, /* @__PURE__ */ new Set());
14504
+ _classPrivateFieldInitSpec(this, _content, void 0);
14505
+ _classPrivateFieldInitSpec(this, _latest, void 0);
14506
+ _classPrivateFieldInitSpec(this, _derived, { previewStyles: "" });
14507
+ _classPrivateFieldInitSpec(this, _timer, void 0);
14508
+ _classPrivateFieldInitSpec(this, _host, null);
14509
+ _classPrivateFieldInitSpec(this, _functions, []);
14510
+ _classPrivateFieldInitSpec(this, _localApi, {});
14511
+ _classPrivateFieldInitSpec(this, _preview, void 0);
14512
+ _classPrivateFieldInitSpec(this, _final, void 0);
14513
+ _classPrivateFieldInitSpec(this, _measuredHeight, void 0);
14514
+ _classPrivateFieldInitSpec(this, _state, {
14515
+ phase: "placeholder",
14516
+ generating: true,
14517
+ height: DEFAULT_HEIGHT
14518
+ });
14519
+ _defineProperty(
14520
+ this,
14521
+ /** The current state. The same object until something changes. */
14522
+ "getState",
14523
+ () => _classPrivateFieldGet2(_state, this)
14524
+ );
14525
+ _defineProperty(
14526
+ this,
14527
+ /** Calls `listener` when the state changes. Returns the unsubscribe function. */
14528
+ "subscribe",
14529
+ (listener) => {
14530
+ _classPrivateFieldGet2(_listeners, this).add(listener);
14531
+ return () => {
14532
+ _classPrivateFieldGet2(_listeners, this).delete(listener);
14533
+ };
14534
+ }
14535
+ );
14536
+ _classPrivateFieldSet2(_load, this, (_options$loadWebsandb = options.loadWebsandbox) !== null && _options$loadWebsandb !== void 0 ? _options$loadWebsandb : loadWebsandbox);
14537
+ }
14538
+ /**
14539
+ * Sets the latest content snapshot. The first snapshot and snapshots that
14540
+ * finish a stage apply at once; others apply at most once per second.
14541
+ */
14542
+ setContent(content) {
14543
+ _classPrivateFieldSet2(_latest, this, content);
14544
+ if (_classPrivateFieldGet2(_content, this) === void 0 || shouldFlushImmediately(_classPrivateFieldGet2(_content, this), content)) {
14545
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _clearTimer).call(this);
14546
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _commit).call(this, content);
14547
+ return;
14548
+ }
14549
+ if (content === _classPrivateFieldGet2(_content, this) || _classPrivateFieldGet2(_timer, this) !== void 0) return;
14550
+ _classPrivateFieldSet2(_timer, this, setTimeout(() => {
14551
+ _classPrivateFieldSet2(_timer, this, void 0);
14552
+ if (_classPrivateFieldGet2(_latest, this)) _assertClassBrand(_OpenGenerativeUIController_brand, this, _commit).call(this, _classPrivateFieldGet2(_latest, this));
14553
+ }, OPEN_GENERATIVE_UI_THROTTLE_MS));
14554
+ }
14555
+ /** Sets the element the sandbox iframes go into. `null` removes them. */
14556
+ setHost(host) {
14557
+ if (host === _classPrivateFieldGet2(_host, this)) return;
14558
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _destroyPreview).call(this);
14559
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _destroyFinal).call(this);
14560
+ _classPrivateFieldSet2(_host, this, host);
14561
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _reconcile).call(this);
14562
+ }
14563
+ /**
14564
+ * Sets the host functions sandboxed code can call. A change recreates the
14565
+ * final sandbox.
14566
+ */
14567
+ setSandboxFunctions(functions) {
14568
+ if (sameFunctions(functions, _classPrivateFieldGet2(_functions, this))) return;
14569
+ _classPrivateFieldSet2(_functions, this, functions);
14570
+ const localApi = {};
14571
+ for (const fn of functions) localApi[fn.name] = fn.handler;
14572
+ _classPrivateFieldSet2(_localApi, this, localApi);
14573
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _reconcile).call(this);
14574
+ }
14575
+ /**
14576
+ * Removes the sandboxes and stops pending work. A later `setHost()`
14577
+ * starts again from the current content.
14578
+ */
14579
+ destroy() {
14580
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _clearTimer).call(this);
14581
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _destroyPreview).call(this);
14582
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _destroyFinal).call(this);
14583
+ _classPrivateFieldSet2(_host, this, null);
14584
+ }
14585
+ };
14586
+ function _commit(content) {
14587
+ if (content === _classPrivateFieldGet2(_content, this)) return;
14588
+ _classPrivateFieldSet2(_content, this, content);
14589
+ _classPrivateFieldSet2(_derived, this, deriveContent(content));
14590
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _reconcile).call(this);
14591
+ }
14592
+ function _reconcile() {
14593
+ const host = _classPrivateFieldGet2(_host, this);
14594
+ const content = _classPrivateFieldGet2(_content, this);
14595
+ const derived = _classPrivateFieldGet2(_derived, this);
14596
+ if (host && content) if (derived.fullHtml) {
14597
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _destroyPreview).call(this);
14598
+ const frameContent = buildFinalFrameContent(derived.fullHtml, derived.css);
14599
+ let final = _classPrivateFieldGet2(_final, this);
14600
+ if ((final === null || final === void 0 ? void 0 : final.frameContent) !== frameContent || final.localApi !== _classPrivateFieldGet2(_localApi, this)) {
14601
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _destroyFinal).call(this);
14602
+ final = _classPrivateFieldSet2(_final, this, _assertClassBrand(_OpenGenerativeUIController_brand, this, _createFinal).call(this, host, frameContent));
14603
+ }
14604
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _runScripts).call(this, final, content);
14605
+ } else {
14606
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _destroyFinal).call(this);
14607
+ if (derived.previewBody) {
14608
+ var _classPrivateFieldGet2$1;
14609
+ (_classPrivateFieldGet2$1 = _classPrivateFieldGet2(_preview, this)) !== null && _classPrivateFieldGet2$1 !== void 0 || _classPrivateFieldSet2(_preview, this, _assertClassBrand(_OpenGenerativeUIController_brand, this, _createPreview).call(this, host));
14610
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _writePreview).call(this);
14611
+ } else _assertClassBrand(_OpenGenerativeUIController_brand, this, _destroyPreview).call(this);
14612
+ }
14613
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _updateState).call(this);
14614
+ }
14615
+ function _createPreview(host) {
14616
+ const slot = {
14617
+ ready: false,
14618
+ cancelled: false
14619
+ };
14620
+ _classPrivateFieldGet2(_load, this).call(this).then((Websandbox) => {
14621
+ if (slot.cancelled) return;
14622
+ const sandbox = Websandbox.create({}, {
14623
+ frameContainer: host,
14624
+ frameContent: "<head></head><body></body>",
14625
+ allowAdditionalAttributes: ""
14626
+ });
14627
+ slot.sandbox = sandbox;
14628
+ prepareIframe(sandbox.iframe, "open-generative-ui-preview-sandbox");
14629
+ sandbox.promise.then(() => {
14630
+ if (slot.cancelled) return;
14631
+ slot.ready = true;
14632
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _writePreview).call(this);
14633
+ });
14634
+ }).catch(logLoadError);
14635
+ return slot;
14636
+ }
14637
+ function _writePreview() {
14638
+ const slot = _classPrivateFieldGet2(_preview, this);
14639
+ if (!(slot === null || slot === void 0 ? void 0 : slot.sandbox) || !slot.ready) return;
14640
+ const { css, previewStyles, previewBody } = _classPrivateFieldGet2(_derived, this);
14641
+ const head = HIDE_SCROLLBARS_STYLE + (css ? `<style>${css}</style>` : "") + previewStyles;
14642
+ if (head !== slot.head) {
14643
+ slot.head = head;
14644
+ slot.sandbox.run(`document.head.innerHTML = ${JSON.stringify(head)}`);
14645
+ }
14646
+ if (previewBody && previewBody !== slot.body) {
14647
+ slot.body = previewBody;
14648
+ slot.sandbox.run(`document.body.innerHTML = ${JSON.stringify(previewBody)}`);
14649
+ }
14650
+ }
14651
+ function _createFinal(host, frameContent) {
14652
+ const slot = {
14653
+ frameContent,
14654
+ localApi: _classPrivateFieldGet2(_localApi, this),
14655
+ ready: false,
14656
+ cancelled: false,
14657
+ queue: [],
14658
+ jsFunctionsInjected: false,
14659
+ executedExpressions: 0,
14660
+ heightRequested: false
14661
+ };
14662
+ _classPrivateFieldGet2(_load, this).call(this).then((Websandbox) => {
14663
+ if (slot.cancelled) return;
14664
+ const sandbox = Websandbox.create(slot.localApi, {
14665
+ frameContainer: host,
14666
+ frameContent,
14667
+ allowAdditionalAttributes: ""
14668
+ });
14669
+ slot.sandbox = sandbox;
14670
+ prepareIframe(sandbox.iframe, "open-generative-ui-final-sandbox");
14671
+ sandbox.promise.then(() => {
14672
+ if (slot.cancelled) return;
14673
+ slot.ready = true;
14674
+ sandbox.run(HIDE_SCROLLBARS);
14675
+ const queue = slot.queue;
14676
+ slot.queue = [];
14677
+ for (const code of queue) sandbox.run(code);
14678
+ });
14679
+ }).catch(logLoadError);
14680
+ return slot;
14681
+ }
14682
+ /** Runs new `jsFunctions`, new `jsExpressions`, and the height measurement. */
14683
+ function _runScripts(slot, content) {
14684
+ var _content$jsExpression;
14685
+ if (content.jsFunctions && !slot.jsFunctionsInjected) {
14686
+ slot.jsFunctionsInjected = true;
14687
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _runOrQueue).call(this, slot, content.jsFunctions);
14688
+ }
14689
+ const expressions = (_content$jsExpression = content.jsExpressions) !== null && _content$jsExpression !== void 0 ? _content$jsExpression : [];
14690
+ if (expressions.length > slot.executedExpressions) {
14691
+ const newExpressions = expressions.slice(slot.executedExpressions);
14692
+ slot.executedExpressions = expressions.length;
14693
+ const sandbox = slot.sandbox;
14694
+ if (slot.ready && sandbox) (async () => {
14695
+ for (const expression of newExpressions) await sandbox.run(expression);
14696
+ })();
14697
+ else slot.queue.push(...newExpressions);
14698
+ }
14699
+ if (content.generating === false && !slot.heightRequested) {
14700
+ slot.heightRequested = true;
14701
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _listenForHeight).call(this, slot);
14702
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _runOrQueue).call(this, slot, MEASURE_HEIGHT);
14703
+ }
14704
+ }
14705
+ function _runOrQueue(slot, code) {
14706
+ if (slot.ready && slot.sandbox) slot.sandbox.run(code);
14707
+ else slot.queue.push(code);
14708
+ }
14709
+ function _listenForHeight(slot) {
14710
+ if (typeof window === "undefined") return;
14711
+ const onMessage = (event) => {
14712
+ var _slot$stopHeightListe;
14713
+ const data = event.data;
14714
+ if (!slot.sandbox || event.source !== slot.sandbox.iframe.contentWindow || (data === null || data === void 0 ? void 0 : data.type) !== "__ck_resize" || typeof data.height !== "number") return;
14715
+ (_slot$stopHeightListe = slot.stopHeightListener) === null || _slot$stopHeightListe === void 0 || _slot$stopHeightListe.call(slot);
14716
+ _classPrivateFieldSet2(_measuredHeight, this, data.height);
14717
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _updateState).call(this);
14718
+ };
14719
+ window.addEventListener("message", onMessage);
14720
+ slot.stopHeightListener = () => {
14721
+ window.removeEventListener("message", onMessage);
14722
+ slot.stopHeightListener = void 0;
14723
+ };
14724
+ }
14725
+ function _destroyPreview() {
14726
+ var _slot$sandbox;
14727
+ const slot = _classPrivateFieldGet2(_preview, this);
14728
+ if (!slot) return;
14729
+ slot.cancelled = true;
14730
+ (_slot$sandbox = slot.sandbox) === null || _slot$sandbox === void 0 || _slot$sandbox.destroy();
14731
+ _classPrivateFieldSet2(_preview, this, void 0);
14732
+ }
14733
+ function _destroyFinal() {
14734
+ var _slot$stopHeightListe2, _slot$sandbox2;
14735
+ const slot = _classPrivateFieldGet2(_final, this);
14736
+ if (!slot) return;
14737
+ slot.cancelled = true;
14738
+ (_slot$stopHeightListe2 = slot.stopHeightListener) === null || _slot$stopHeightListe2 === void 0 || _slot$stopHeightListe2.call(slot);
14739
+ (_slot$sandbox2 = slot.sandbox) === null || _slot$sandbox2 === void 0 || _slot$sandbox2.destroy();
14740
+ _classPrivateFieldSet2(_final, this, void 0);
14741
+ _classPrivateFieldSet2(_measuredHeight, this, void 0);
14742
+ }
14743
+ function _clearTimer() {
14744
+ if (_classPrivateFieldGet2(_timer, this) === void 0) return;
14745
+ clearTimeout(_classPrivateFieldGet2(_timer, this));
14746
+ _classPrivateFieldSet2(_timer, this, void 0);
14747
+ }
14748
+ function _updateState() {
14749
+ var _this$content, _ref, _this$measuredHeight;
14750
+ const content = (_this$content = _classPrivateFieldGet2(_content, this)) !== null && _this$content !== void 0 ? _this$content : {};
14751
+ const derived = _classPrivateFieldGet2(_derived, this);
14752
+ const next = {
14753
+ phase: derived.fullHtml ? "final" : derived.previewBody ? "preview" : "placeholder",
14754
+ generating: content.generating !== false,
14755
+ height: (_ref = (_this$measuredHeight = _classPrivateFieldGet2(_measuredHeight, this)) !== null && _this$measuredHeight !== void 0 ? _this$measuredHeight : content.initialHeight) !== null && _ref !== void 0 ? _ref : DEFAULT_HEIGHT
14756
+ };
14757
+ const current = _classPrivateFieldGet2(_state, this);
14758
+ if (next.phase === current.phase && next.generating === current.generating && next.height === current.height) return;
14759
+ _classPrivateFieldSet2(_state, this, next);
14760
+ for (const listener of _classPrivateFieldGet2(_listeners, this)) listener();
14761
+ }
14762
+
14763
+ //#endregion
14764
+ //#region src/utils/class-names.ts
14765
+ /**
14766
+ * Joins class names, skipping falsy values. Takes the same inputs as `clsx`.
14767
+ * Classes are not merged: every rule CopilotKit ships sits in `:where()`, so a
14768
+ * class the app adds wins without removing ours.
14769
+ */
14770
+ function cn(...inputs) {
14771
+ const out = [];
14772
+ for (const input of inputs) {
14773
+ if (!input) continue;
14774
+ if (typeof input === "string" || typeof input === "number" || typeof input === "bigint") out.push(String(input));
14775
+ else if (Array.isArray(input)) {
14776
+ const nested = cn(...input);
14777
+ if (nested) out.push(nested);
14778
+ } else if (typeof input === "object") {
14779
+ for (const key in input) if (input[key]) out.push(key);
14780
+ }
14781
+ }
14782
+ return out.join(" ");
14783
+ }
14784
+
11033
14785
  //#endregion
11034
14786
  exports.A2UI_FENCE_LANGUAGE = A2UI_FENCE_LANGUAGE;
11035
14787
  exports.AgentRegistry = AgentRegistry;
11036
14788
  exports.AgentThreadLockedError = AgentThreadLockedError;
11037
14789
  exports.ContextStore = ContextStore;
14790
+ exports.CopilotChatDefaultLabels = CopilotChatDefaultLabels;
11038
14791
  exports.CopilotKitCore = CopilotKitCore;
11039
14792
  exports.CopilotKitCoreErrorCode = CopilotKitCoreErrorCode;
11040
14793
  exports.CopilotKitCoreRuntimeConnectionStatus = CopilotKitCoreRuntimeConnectionStatus;
11041
14794
  exports.CopilotKitHeaderResolutionError = CopilotKitHeaderResolutionError;
14795
+ exports.DEFAULT_OPEN_GENERATIVE_UI_DESIGN_SKILL = DEFAULT_OPEN_GENERATIVE_UI_DESIGN_SKILL;
14796
+ exports.GENERATE_SANDBOXED_UI_TOOL_NAME = GENERATE_SANDBOXED_UI_TOOL_NAME;
11042
14797
  exports.INSPECTOR_THREAD_BRIDGE_PLUGIN_ID = INSPECTOR_THREAD_BRIDGE_PLUGIN_ID;
14798
+ exports.INTERRUPT_EVENT_NAME = INTERRUPT_EVENT_NAME;
11043
14799
  exports.IntelligenceAgent = IntelligenceAgent;
11044
14800
  exports.MEMORY_ERROR_REGISTRY = MEMORY_ERROR_REGISTRY;
11045
14801
  exports.MemoryError = MemoryError;
14802
+ exports.OPEN_GENERATIVE_UI_ACTIVITY_TYPE = OPEN_GENERATIVE_UI_ACTIVITY_TYPE;
11046
14803
  exports.ProxiedCopilotRuntimeAgent = ProxiedCopilotRuntimeAgent;
11047
14804
  exports.RunHandler = RunHandler;
11048
14805
  exports.StateManager = StateManager;
11049
14806
  exports.SuggestionEngine = SuggestionEngine;
11050
14807
  exports.ToolCallStatus = ToolCallStatus;
14808
+ exports.TranscriptionError = TranscriptionError;
14809
+ exports.TranscriptionErrorCode = _copilotkit_shared.TranscriptionErrorCode;
11051
14810
  exports.WebMCPRegistry = WebMCPRegistry;
11052
14811
  exports.classifySurfaceCards = classifySurfaceCards;
11053
14812
  exports.completePartialMarkdown = completePartialMarkdown;
@@ -11078,7 +14837,6 @@ exports.onInspectorActiveThread = onInspectorActiveThread;
11078
14837
  exports.onInspectorStopViewing = onInspectorStopViewing;
11079
14838
  exports.onInspectorViewThread = onInspectorViewThread;
11080
14839
  exports.onInspectorViewThreadResult = onInspectorViewThreadResult;
11081
- exports.parseMarkdown = parseMarkdown;
11082
14840
  exports.parseToolArguments = parseToolArguments;
11083
14841
  exports.prepareSurfaceOperations = prepareSurfaceOperations;
11084
14842
  exports.props = props;
@@ -11086,30 +14844,100 @@ exports.segmentSurfaceProse = segmentSurfaceProse;
11086
14844
  exports.select = select;
11087
14845
  exports.splitA2UIMarkdown = splitA2UIMarkdown;
11088
14846
  exports.ɵCOPILOTKIT_FEATURES = ɵCOPILOTKIT_FEATURES;
14847
+ exports.ɵCOPY_FEEDBACK_RESET_MS = ɵCOPY_FEEDBACK_RESET_MS;
14848
+ exports.ɵCopyFeedback = ɵCopyFeedback;
14849
+ exports.ɵFEEDBACK_COMMENT_CLOSE_DELAY_MS = ɵFEEDBACK_COMMENT_CLOSE_DELAY_MS;
14850
+ exports.ɵFeedbackCommentController = ɵFeedbackCommentController;
14851
+ exports.ɵHOVER_MENU_CLOSE_DELAY_MS = ɵHOVER_MENU_CLOSE_DELAY_MS;
14852
+ exports.ɵHoverMenuController = ɵHoverMenuController;
14853
+ exports.ɵINLINE_FEATURE_WARNING_STYLE = ɵINLINE_FEATURE_WARNING_STYLE;
11089
14854
  exports.ɵInterruptState = ɵInterruptState;
14855
+ exports.ɵKEYBOARD_OPEN_THRESHOLD_PX = ɵKEYBOARD_OPEN_THRESHOLD_PX;
14856
+ exports.ɵLICENSE_BANNER_OFFSET = ɵLICENSE_BANNER_OFFSET;
14857
+ exports.ɵLICENSE_BANNER_STYLE = ɵLICENSE_BANNER_STYLE;
11090
14858
  exports.ɵMAX_SOCKET_RETRIES = ɵMAX_SOCKET_RETRIES;
14859
+ exports.ɵMESSAGE_FEEDBACK_EVENT_NAME = ɵMESSAGE_FEEDBACK_EVENT_NAME;
14860
+ exports.ɵMESSAGE_FEEDBACK_MAX_COMMENT_LENGTH = ɵMESSAGE_FEEDBACK_MAX_COMMENT_LENGTH;
14861
+ exports.ɵMOBILE_MAX_WIDTH_QUERY = ɵMOBILE_MAX_WIDTH_QUERY;
14862
+ exports.ɵOpenGenerativeUIController = OpenGenerativeUIController;
11091
14863
  exports.ɵRUNTIME_PROBE_TIMEOUT_MS = ɵRUNTIME_PROBE_TIMEOUT_MS;
11092
14864
  exports.ɵTHREAD_REQUEST_TIMEOUT_MS = ɵTHREAD_REQUEST_TIMEOUT_MS;
11093
14865
  exports.ɵclearAgentInterruptState = ɵclearAgentInterruptState;
14866
+ exports.ɵcn = cn;
14867
+ exports.ɵcomposerButtonState = ɵcomposerButtonState;
14868
+ exports.ɵcopilotIconSvgAttributes = ɵcopilotIconSvgAttributes;
14869
+ exports.ɵcopilotIcons = ɵcopilotIcons;
14870
+ exports.ɵcountFailedToolCalls = countFailedToolCalls;
11094
14871
  exports.ɵcreateMemoryStore = createMemoryStore;
11095
14872
  exports.ɵcreateThreadSelectors = ɵcreateThreadSelectors;
11096
14873
  exports.ɵcreateThreadStore = createThreadStore;
14874
+ exports.ɵdeduplicateMessages = ɵdeduplicateMessages;
14875
+ exports.ɵextractCompleteStyles = extractCompleteStyles;
14876
+ exports.ɵflattenUserMessageContent = ɵflattenUserMessageContent;
14877
+ exports.ɵformatCountLabel = ɵformatCountLabel;
14878
+ exports.ɵformatLabel = ɵformatLabel;
14879
+ exports.ɵformatReasoningDuration = formatReasoningDuration;
14880
+ exports.ɵformatReasoningDurationLabel = ɵformatReasoningDurationLabel;
14881
+ exports.ɵformatToolNames = formatToolNames;
14882
+ exports.ɵformatWorkDuration = formatWorkDuration;
11097
14883
  exports.ɵgetAgentInterruptState = ɵgetAgentInterruptState;
14884
+ exports.ɵgetArgumentPreview = getArgumentPreview;
14885
+ exports.ɵgetBranchNavState = ɵgetBranchNavState;
14886
+ exports.ɵgetInlineFeatureWarningSpec = ɵgetInlineFeatureWarningSpec;
14887
+ exports.ɵgetLatestTurnKey = getLatestTurnKey;
14888
+ exports.ɵgetLicenseBannerSpec = ɵgetLicenseBannerSpec;
14889
+ exports.ɵgetMessageFeedback = ɵgetMessageFeedback;
14890
+ exports.ɵgetMessageFeedbackControls = ɵgetMessageFeedbackControls;
14891
+ exports.ɵgetToolCallLayouts = getToolCallLayouts;
14892
+ exports.ɵgetToolCallPreview = getToolCallPreview;
14893
+ exports.ɵgetToolCallRendererNames = getToolCallRendererNames;
14894
+ exports.ɵgetToolCallRowStatus = getToolCallRowStatus;
14895
+ exports.ɵgetToolResults = getToolResults;
14896
+ exports.ɵgetTurnWork = getTurnWork;
14897
+ exports.ɵgetUserMessageMediaFilename = ɵgetUserMessageMediaFilename;
14898
+ exports.ɵgetUserMessageMediaParts = ɵgetUserMessageMediaParts;
14899
+ exports.ɵgetWorkOpenState = getWorkOpenState;
14900
+ exports.ɵgetWorkSummaryText = ɵgetWorkSummaryText;
14901
+ exports.ɵhasAssistantMessageText = ɵhasAssistantMessageText;
14902
+ exports.ɵinitialKeyboardState = ɵinitialKeyboardState;
14903
+ exports.ɵinspectorKiteFill = ɵinspectorKiteFill;
14904
+ exports.ɵinspectorKiteIcon = ɵinspectorKiteIcon;
14905
+ exports.ɵinspectorShortcuts = ɵinspectorShortcuts;
11098
14906
  exports.ɵisCopilotKitFeature = ɵisCopilotKitFeature;
11099
14907
  exports.ɵisHttpAgent = ɵisHttpAgent;
14908
+ exports.ɵisLearningFeedbackEnabled = ɵisLearningFeedbackEnabled;
14909
+ exports.ɵisMobileViewport = ɵisMobileViewport;
11100
14910
  exports.ɵisRetryableMemoryStatus = isRetryableStatus;
14911
+ exports.ɵisTurnWorkOpen = isTurnWorkOpen;
14912
+ exports.ɵisTurnWorking = isTurnWorking;
11101
14913
  exports.ɵjoinPhoenixChannel$ = ɵjoinPhoenixChannel$;
14914
+ exports.ɵloadWebsandbox = loadWebsandbox;
11102
14915
  exports.ɵmapMemoryMetadataEvent = ɵmapMemoryMetadataEvent;
11103
14916
  exports.ɵmemoryAdapterEvents = ɵmemoryAdapterEvents;
11104
14917
  exports.ɵmemoryDomainEvents = ɵmemoryDomainEvents;
11105
14918
  exports.ɵmemoryReducer = ɵmemoryReducer;
11106
14919
  exports.ɵmemoryRestEvents = ɵmemoryRestEvents;
14920
+ exports.ɵmessagesFingerprint = ɵmessagesFingerprint;
14921
+ exports.ɵnormalizeAutoScroll = ɵnormalizeAutoScroll;
11107
14922
  exports.ɵobservePhoenixEvent$ = ɵobservePhoenixEvent$;
11108
14923
  exports.ɵobservePhoenixJoinOutcome$ = ɵobservePhoenixJoinOutcome$;
11109
14924
  exports.ɵobservePhoenixSocketHealth$ = ɵobservePhoenixSocketHealth$;
11110
14925
  exports.ɵobservePhoenixSocketSignals$ = ɵobservePhoenixSocketSignals$;
11111
14926
  exports.ɵphoenixChannel$ = ɵphoenixChannel$;
11112
14927
  exports.ɵphoenixSocket$ = ɵphoenixSocket$;
14928
+ exports.ɵpinMessageToTop = ɵpinMessageToTop;
14929
+ exports.ɵpluralize = pluralize;
14930
+ exports.ɵprocessPartialHtml = processPartialHtml;
14931
+ exports.ɵreadKeyboardState = ɵreadKeyboardState;
14932
+ exports.ɵrecordWorkTime = recordWorkTime;
14933
+ exports.ɵreserveLicenseBannerOffset = ɵreserveLicenseBannerOffset;
14934
+ exports.ɵresetMessageFeedbackCache = ɵresetMessageFeedbackCache;
14935
+ exports.ɵresolveActivityRenderer = ɵresolveActivityRenderer;
14936
+ exports.ɵresolveComposerKey = ɵresolveComposerKey;
14937
+ exports.ɵresolveCustomMessageRenderers = ɵresolveCustomMessageRenderers;
14938
+ exports.ɵresolveLicenseState = ɵresolveLicenseState;
14939
+ exports.ɵresolveThreadsLicense = ɵresolveThreadsLicense;
14940
+ exports.ɵresolveToolCallRenderer = ɵresolveToolCallRenderer;
11113
14941
  exports.ɵselectFetchMoreError = ɵselectFetchMoreError;
11114
14942
  exports.ɵselectHasNextPage = ɵselectHasNextPage;
11115
14943
  exports.ɵselectIsFetchingNextPage = ɵselectIsFetchingNextPage;
@@ -11123,7 +14951,17 @@ exports.ɵselectMemoriesRealtimeStatus = ɵselectMemoriesRealtimeStatus;
11123
14951
  exports.ɵselectThreads = ɵselectThreads;
11124
14952
  exports.ɵselectThreadsError = ɵselectThreadsError;
11125
14953
  exports.ɵselectThreadsIsLoading = ɵselectThreadsIsLoading;
14954
+ exports.ɵsetMessageFeedback = ɵsetMessageFeedback;
14955
+ exports.ɵshallowEqualRecord = shallowEqualRecord;
14956
+ exports.ɵshouldShowAssistantToolbar = ɵshouldShowAssistantToolbar;
14957
+ exports.ɵstringifyToolCallPayload = stringifyToolCallPayload;
14958
+ exports.ɵsubscribeToLearningFeedbackEnabled = ɵsubscribeToLearningFeedbackEnabled;
14959
+ exports.ɵsubscribeToMessageFeedback = ɵsubscribeToMessageFeedback;
11126
14960
  exports.ɵthreadAdapterEvents = ɵthreadAdapterEvents;
14961
+ exports.ɵtranscribeAudio = ɵtranscribeAudio;
14962
+ exports.ɵtranscriptionErrorMessageKey = ɵtranscriptionErrorMessageKey;
14963
+ exports.ɵwatchKeyboardState = ɵwatchKeyboardState;
14964
+ exports.ɵwatchMobileViewport = ɵwatchMobileViewport;
11127
14965
  exports.ɵwithHeaderDefaults = ɵwithHeaderDefaults;
11128
14966
  });
11129
14967
  //# sourceMappingURL=index.umd.js.map