@copilotkit/core 2.0.0-rc.1 → 2.0.0-rc.11

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$2;
4022
+ if (((_classPrivateFieldGet2$2 = _classPrivateFieldGet2(_pending, this)) === null || _classPrivateFieldGet2$2 === void 0 ? void 0 : _classPrivateFieldGet2$2.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";
@@ -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 !== "v1.0") 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,2297 @@ 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
+ modalHeaderTitle: "CopilotKit Chat",
11404
+ welcomeMessageText: "How can I help you today?",
11405
+ reasoningMessageThinkingLabel: "Thinking…",
11406
+ chatInputSlashMenuLabel: "Slash commands",
11407
+ chatInputSlashMenuEmptyText: "No commands found",
11408
+ attachmentRemoveButtonLabel: "Remove attachment",
11409
+ attachmentPlayVideoButtonLabel: "Play video",
11410
+ attachmentPreviewCloseButtonLabel: "Close preview",
11411
+ modalHeaderCloseButtonLabel: "Close",
11412
+ modalHeaderThreadsButtonLabel: "Open threads",
11413
+ sidebarLabel: "Copilot chat sidebar",
11414
+ chatDropFilesLabel: "Drop files here",
11415
+ threadLoadErrorText: "Could not load saved conversation. Reopen the thread and try again.",
11416
+ reasoningMessageThoughtForLabel: "Thought for {duration}",
11417
+ reasoningMessageDurationFewSeconds: "a few seconds",
11418
+ reasoningMessageDurationSeconds: "{count} seconds",
11419
+ reasoningMessageDurationMinutesOne: "{count} minute",
11420
+ reasoningMessageDurationMinutesOther: "{count} minutes",
11421
+ reasoningMessageDurationMinutesSeconds: "{minutes}m {seconds}s",
11422
+ toolCallStatusRunningLabel: "Running",
11423
+ toolCallStatusDoneLabel: "Done",
11424
+ toolCallStatusFailedLabel: "Failed",
11425
+ toolCallStatusStoppedLabel: "Stopped",
11426
+ toolCallRunningLabel: "Running {name}",
11427
+ toolCallFailedCountLabel: "{count} failed",
11428
+ toolCallDoneCountLabel: "{count} done",
11429
+ toolCallArgumentsLabel: "Arguments",
11430
+ toolCallResultLabel: "Result",
11431
+ toolCallCollapseLabel: "Collapse",
11432
+ toolCallUsedToolsOne: "Used {count} tool",
11433
+ toolCallUsedToolsOther: "Used {count} tools",
11434
+ toolCallToolCountOne: "{count} tool",
11435
+ toolCallToolCountOther: "{count} tools",
11436
+ toolCallToolCallCountOne: "{count} tool call",
11437
+ toolCallToolCallCountOther: "{count} tool calls",
11438
+ toolCallCallCountOne: "{count} call",
11439
+ toolCallCallCountOther: "{count} calls",
11440
+ workSummaryWorkingLabel: "Working",
11441
+ workSummaryWorkedForLabel: "Worked for {duration}",
11442
+ attachmentImageLoadErrorText: "Failed to load image",
11443
+ attachmentImageAltText: "Image attachment",
11444
+ attachmentUnknownTypeText: "Unknown type",
11445
+ attachmentDocumentLabel: "Document",
11446
+ attachmentDocumentAltText: "Document attachment",
11447
+ attachmentNoPreviewText: "No preview available for this file type",
11448
+ chatAttachmentsUploadingText: "Cannot send while attachments are uploading.",
11449
+ transcriptionErrorRateLimitedText: "Too many requests. Please wait a moment.",
11450
+ transcriptionErrorAuthFailedText: "Authentication error. Please check your configuration.",
11451
+ transcriptionErrorAudioTooLongText: "Recording is too long. Please try a shorter recording.",
11452
+ transcriptionErrorAudioTooShortText: "Recording is too short. Please try again.",
11453
+ transcriptionErrorInvalidAudioFormatText: "Audio format not supported.",
11454
+ transcriptionErrorServiceNotConfiguredText: "Transcription service is not available.",
11455
+ transcriptionErrorNetworkText: "Network error. Please check your connection.",
11456
+ transcriptionErrorGenericText: "Transcription failed. Please try again.",
11457
+ licensePoweredByText: "Powered by CopilotKit",
11458
+ licenseGetLicenseLabel: "Get a license",
11459
+ licenseFeatureUnlicensedText: "⚠ The \"{feature}\" feature requires a CopilotKit license.",
11460
+ licenseExpiringText: "Your CopilotKit license expires soon. Please renew.",
11461
+ licenseExpiringInDaysOne: "Your CopilotKit license expires in {days} day. Please renew.",
11462
+ licenseExpiringInDaysOther: "Your CopilotKit license expires in {days} days. Please renew.",
11463
+ licenseExpiredText: "Your CopilotKit license expired. Please renew at copilotkit.ai/pricing",
11464
+ licenseExpiredOnDateText: "Your CopilotKit license expired on {date}. Please renew at copilotkit.ai/pricing",
11465
+ licenseInvalidText: "Invalid CopilotKit license token. Please check your configuration.",
11466
+ licenseRenewLabel: "Renew",
11467
+ licenseRenewNowLabel: "Renew now"
11468
+ });
11469
+ /**
11470
+ * Puts values into a label template. Each `{name}` in the template is replaced
11471
+ * by `values[name]`. A placeholder with no value stays in the text as is.
11472
+ *
11473
+ * @param template - A label value, such as `"Running {name}"`.
11474
+ * @param values - The value for each placeholder.
11475
+ *
11476
+ * ```ts
11477
+ * ɵformatLabel(labels.toolCallRunningLabel, { name: "read_file" });
11478
+ * // "Running read_file"
11479
+ * ```
11480
+ */
11481
+ function ɵformatLabel(template, values) {
11482
+ return template.replace(/\{(\w+)\}/g, (placeholder, name) => Object.hasOwn(values, name) ? String(values[name]) : placeholder);
11483
+ }
11484
+ /**
11485
+ * Fills a counted label pair: the `one` template for a count of 1, the
11486
+ * `other` template for any other count. Both templates take `{count}`.
11487
+ *
11488
+ * @param count - The number to show.
11489
+ * @param templates - The `...One` and `...Other` label templates.
11490
+ *
11491
+ * ```ts
11492
+ * ɵformatCountLabel(3, {
11493
+ * one: labels.toolCallToolCountOne,
11494
+ * other: labels.toolCallToolCountOther,
11495
+ * }); // "3 tools"
11496
+ * ```
11497
+ */
11498
+ function ɵformatCountLabel(count, templates) {
11499
+ return ɵformatLabel(count === 1 ? templates.one : templates.other, { count });
11500
+ }
11501
+
11502
+ //#endregion
11503
+ //#region src/chat/renderers.ts
11504
+ /** Name or activity type that matches anything. */
11505
+ const WILDCARD = "*";
11506
+ /**
11507
+ * Find the renderer that draws a tool call.
11508
+ *
11509
+ * The first rule that matches wins:
11510
+ *
11511
+ * 1. A renderer for `toolName` with `agentId` equal to the current agent.
11512
+ * 2. A renderer for `toolName` with no `agentId`.
11513
+ * 3. The first renderer for `toolName` from any other agent.
11514
+ * 4. The first `"*"` renderer, from any agent.
11515
+ *
11516
+ * Inside each rule, the earlier renderer in the list wins.
11517
+ *
11518
+ * @param renderers - Registered renderers in registration order. If you
11519
+ * build tiers (for example app renderers before built-in ones), flatten
11520
+ * them into one ordered list first.
11521
+ * @param toolName - Name of the tool the agent called.
11522
+ * @param agentId - The agent that owns the chat. The caller picks the
11523
+ * default: React and Vue pass `DEFAULT_AGENT_ID` when the chat has no
11524
+ * agent. With `undefined`, rule 1 matches the same renderers as rule 2.
11525
+ * @returns The renderer, or `null` when no renderer matches. Draw nothing
11526
+ * for `null`.
11527
+ *
11528
+ * @example
11529
+ * ```ts
11530
+ * const renderer = ɵresolveToolCallRenderer(
11531
+ * core.renderToolCalls,
11532
+ * toolCall.function.name,
11533
+ * chatAgentId ?? DEFAULT_AGENT_ID,
11534
+ * );
11535
+ * ```
11536
+ */
11537
+ function ɵresolveToolCallRenderer(renderers, toolName, agentId) {
11538
+ var _ref, _ref2, _ref3, _named$find;
11539
+ const named = renderers.filter((renderer) => renderer.name === toolName);
11540
+ 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;
11541
+ }
11542
+ /**
11543
+ * Find the renderer that draws an activity message, and validate the
11544
+ * message content with that renderer's `content` schema.
11545
+ *
11546
+ * The first rule that matches picks the renderer:
11547
+ *
11548
+ * 1. A renderer for `activityType` with `agentId` equal to the current agent.
11549
+ * 2. A renderer for `activityType` with no `agentId`.
11550
+ * 3. The first `"*"` renderer, from any agent.
11551
+ *
11552
+ * A renderer for `activityType` that belongs to a different agent never
11553
+ * matches. Inside each rule, the earlier renderer in the list wins.
11554
+ *
11555
+ * Only the picked renderer validates the content. When validation fails, or
11556
+ * the schema validates asynchronously, the result is `null`. The function
11557
+ * does not try the next renderer.
11558
+ *
11559
+ * @param renderers - Registered renderers in registration order.
11560
+ * @param query - The activity type, the current agent, and the raw content.
11561
+ * @returns `{ renderer, content }`, where `content` is the value the schema
11562
+ * returned. Pass that value to `render`, not the raw content. Returns
11563
+ * `null` when no renderer matches or validation does not pass.
11564
+ *
11565
+ * @example
11566
+ * ```ts
11567
+ * const match = ɵresolveActivityRenderer(core.renderActivityMessages, {
11568
+ * activityType: message.activityType,
11569
+ * agentId,
11570
+ * content: message.content,
11571
+ * });
11572
+ * if (match) draw(match.renderer.render, match.content);
11573
+ * ```
11574
+ */
11575
+ function ɵresolveActivityRenderer(renderers, query) {
11576
+ var _ref4, _sameType$find;
11577
+ const { activityType, agentId, content } = query;
11578
+ const sameType = renderers.filter((renderer) => renderer.activityType === activityType);
11579
+ 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);
11580
+ if (renderer === void 0) return null;
11581
+ const result = renderer.content["~standard"].validate(content);
11582
+ if (result instanceof Promise) return null;
11583
+ if (result.issues) return null;
11584
+ return {
11585
+ renderer,
11586
+ content: result.value
11587
+ };
11588
+ }
11589
+ /**
11590
+ * List the custom message renderers that apply to an agent, in the order to
11591
+ * try them.
11592
+ *
11593
+ * The list keeps renderers with no `agentId` and renderers for `agentId`.
11594
+ * Renderers for `agentId` come first. Inside each group, registration order
11595
+ * stays the same.
11596
+ *
11597
+ * The framework tries each renderer in this order and shows the first one
11598
+ * that draws something (a non-null result).
11599
+ *
11600
+ * @param renderers - Registered renderers in registration order.
11601
+ * @param agentId - The agent that owns the chat.
11602
+ * @returns A new array. Empty when no renderer applies.
11603
+ *
11604
+ * @example
11605
+ * ```ts
11606
+ * const candidates = ɵresolveCustomMessageRenderers(
11607
+ * core.renderCustomMessages,
11608
+ * agentId,
11609
+ * );
11610
+ * ```
11611
+ */
11612
+ function ɵresolveCustomMessageRenderers(renderers, agentId) {
11613
+ const scoped = renderers.filter((renderer) => renderer.agentId === agentId);
11614
+ const unscoped = renderers.filter((renderer) => renderer.agentId === void 0);
11615
+ return [...scoped, ...unscoped];
11616
+ }
11617
+
11618
+ //#endregion
11619
+ //#region src/chat/interrupt-types.ts
11620
+ /** Name of the legacy custom event agents emit to signal an interrupt. */
11621
+ const INTERRUPT_EVENT_NAME = "on_interrupt";
11622
+
11623
+ //#endregion
11624
+ //#region src/chat/tool-call-layout.ts
11625
+ function contentLength(content) {
11626
+ return typeof content === "string" ? content.length : JSON.stringify(content !== null && content !== void 0 ? content : "").length;
11627
+ }
11628
+ const entrySignature = ({ toolCall, toolMessage }) => [
11629
+ toolCall.id,
11630
+ toolCall.function.name,
11631
+ toolCall.function.arguments.length,
11632
+ toolMessage ? `${contentLength(toolMessage.content)}${toolMessage.error ? "!" : ""}` : "-"
11633
+ ].join(":");
11634
+ function signatureOf(segments) {
11635
+ return segments.map((segment) => segment.kind === "call" ? `c(${entrySignature(segment.call)})` : `g${segment.trailing ? "*" : ""}(${segment.calls.map(entrySignature).join(",")})`).join("|");
11636
+ }
11637
+ /**
11638
+ * Indexes tool results by the id of the call they answer.
11639
+ *
11640
+ * @param messages - The messages to search. Only `role: "tool"` messages count.
11641
+ */
11642
+ function getToolResults(messages) {
11643
+ const results = /* @__PURE__ */ new Map();
11644
+ for (const message of messages) if (message.role === "tool") results.set(message.toolCallId, message);
11645
+ return results;
11646
+ }
11647
+ /**
11648
+ * Lays out the tool calls of every assistant message in `rendered`.
11649
+ *
11650
+ * Calls drawn by a renderer that opted into grouping join the group that is
11651
+ * open. Anything else that shows between them closes it: assistant text, a
11652
+ * user, reasoning or activity message, or a call drawn by any other renderer.
11653
+ * A group belongs to the message where it starts, so later messages whose
11654
+ * calls joined it render no tool calls themselves.
11655
+ *
11656
+ * @param rendered - The messages as the chat renders them, in order.
11657
+ * @param all - Every message, for finding tool results (a transform may hide them).
11658
+ * @param renderers - The registered renderers, from `getToolCallRendererNames`.
11659
+ * @returns A map from assistant message id to its layout.
11660
+ *
11661
+ * @example
11662
+ * ```ts
11663
+ * const names = getToolCallRendererNames(core.renderToolCalls);
11664
+ * const layouts = getToolCallLayouts(renderedMessages, messages, names);
11665
+ * layouts.get(message.id)?.segments;
11666
+ * ```
11667
+ */
11668
+ function getToolCallLayouts(rendered, all, renderers) {
11669
+ const results = getToolResults(all);
11670
+ const layouts = /* @__PURE__ */ new Map();
11671
+ let open;
11672
+ for (const message of rendered) {
11673
+ var _message$toolCalls;
11674
+ if (message.role === "tool") continue;
11675
+ if (message.role !== "assistant") {
11676
+ open = void 0;
11677
+ continue;
11678
+ }
11679
+ if (typeof message.content === "string" && message.content.trim() !== "") open = void 0;
11680
+ const segments = [];
11681
+ layouts.set(message.id, segments);
11682
+ const toolCalls = /* @__PURE__ */ new Map();
11683
+ const messageToolCalls = (_message$toolCalls = message.toolCalls) !== null && _message$toolCalls !== void 0 ? _message$toolCalls : [];
11684
+ for (const toolCall of messageToolCalls) toolCalls.set(toolCall.id, toolCall);
11685
+ const uniqueToolCalls = toolCalls.values();
11686
+ for (const toolCall of uniqueToolCalls) {
11687
+ const entry = {
11688
+ toolCall,
11689
+ toolMessage: results.get(toolCall.id)
11690
+ };
11691
+ const name = toolCall.function.name;
11692
+ const named = renderers.named.has(name);
11693
+ const isRendered = named || renderers.wildcard;
11694
+ const groups = named ? renderers.groupedNames.has(name) : renderers.wildcardGroups;
11695
+ if (!isRendered || !groups) {
11696
+ if (isRendered) open = void 0;
11697
+ segments.push({
11698
+ kind: "call",
11699
+ id: toolCall.id,
11700
+ call: entry,
11701
+ rendered: isRendered
11702
+ });
11703
+ } else if (open) open.calls.push(entry);
11704
+ else {
11705
+ open = {
11706
+ kind: "group",
11707
+ id: toolCall.id,
11708
+ calls: [entry],
11709
+ trailing: false
11710
+ };
11711
+ segments.push(open);
11712
+ }
11713
+ }
11714
+ }
11715
+ if (open) open.trailing = true;
11716
+ const layout = /* @__PURE__ */ new Map();
11717
+ for (const [id, segments] of layouts) layout.set(id, {
11718
+ segments,
11719
+ signature: signatureOf(segments)
11720
+ });
11721
+ return layout;
11722
+ }
11723
+ const TOOL_CALL_SLOT_PREFIX = "tool-call-";
11724
+ const WILDCARD_TOOL_CALL_SLOT = "tool-call";
11725
+ /**
11726
+ * Works out which tool calls have a renderer and which of those group, for
11727
+ * `getToolCallLayouts`.
11728
+ *
11729
+ * @param renderers - The registered renderers. A renderer named `"*"` is the
11730
+ * wildcard. `group: true` opts the renderer into grouping.
11731
+ * @param options - Slots, extra named tools, and a built-in wildcard card.
11732
+ * See `ToolCallRendererNamesOptions`.
11733
+ *
11734
+ * @example
11735
+ * ```ts
11736
+ * // React: only registered renderers.
11737
+ * getToolCallRendererNames(core.renderToolCalls);
11738
+ * // Vue: the view's slots count too.
11739
+ * getToolCallRendererNames(core.renderToolCalls, { slotNames: Object.keys(slots) });
11740
+ * // Angular: client and human-in-the-loop renderers, and the built-in card.
11741
+ * getToolCallRendererNames(appRenderers, {
11742
+ * extraNamed: [...clientNames, ...hitlNames],
11743
+ * builtInWildcard: { enabled: defaultToolRenderingEnabled, groups: true },
11744
+ * });
11745
+ * ```
11746
+ */
11747
+ function getToolCallRendererNames(renderers, options = {}) {
11748
+ var _builtInWildcard$enab, _builtInWildcard$grou;
11749
+ const { slotNames = [], extraNamed = [], builtInWildcard } = options;
11750
+ const hasWildcardSlot = slotNames.includes(WILDCARD_TOOL_CALL_SLOT);
11751
+ const slotTools = slotNames.filter((name) => name.startsWith(TOOL_CALL_SLOT_PREFIX)).map((name) => name.slice(10));
11752
+ const named = renderers.filter((renderer) => renderer.name !== "*");
11753
+ const wildcards = renderers.filter((renderer) => renderer.name === "*");
11754
+ const hasAppWildcard = wildcards.length > 0;
11755
+ const isBuiltInEnabled = (_builtInWildcard$enab = builtInWildcard === null || builtInWildcard === void 0 ? void 0 : builtInWildcard.enabled) !== null && _builtInWildcard$enab !== void 0 ? _builtInWildcard$enab : false;
11756
+ const builtInGroups = isBuiltInEnabled && ((_builtInWildcard$grou = builtInWildcard === null || builtInWildcard === void 0 ? void 0 : builtInWildcard.groups) !== null && _builtInWildcard$grou !== void 0 ? _builtInWildcard$grou : false);
11757
+ const groupedNames = hasWildcardSlot ? [] : named.filter((renderer) => renderer.group && !slotTools.includes(renderer.name)).map((renderer) => renderer.name);
11758
+ const appWildcardGroups = wildcards.some((renderer) => renderer.group);
11759
+ return {
11760
+ named: new Set([
11761
+ ...named.map((renderer) => renderer.name),
11762
+ ...slotTools,
11763
+ ...extraNamed
11764
+ ]),
11765
+ groupedNames: new Set(groupedNames),
11766
+ wildcard: hasAppWildcard || hasWildcardSlot || isBuiltInEnabled,
11767
+ wildcardGroups: !hasWildcardSlot && (hasAppWildcard ? appWildcardGroups : builtInGroups)
11768
+ };
11769
+ }
11770
+ /** The turn key of a reply that no user message starts. */
11771
+ const FIRST_TURN_KEY = "start";
11772
+ /**
11773
+ * Finds the working phase of every reply in `rendered`: its messages up to the
11774
+ * last one that calls a tool. Text in there was narration. What follows is the
11775
+ * reply itself. Replies that called no tools are left out, except the latest,
11776
+ * which may be about to.
11777
+ *
11778
+ * @param rendered - The messages as the chat renders them, in order.
11779
+ * @param layouts - The layouts from `getToolCallLayouts` for the same messages.
11780
+ * @returns A map from turn key (see `TurnWork.key`) to the turn's work.
11781
+ */
11782
+ function getTurnWork(rendered, layouts) {
11783
+ const turns = /* @__PURE__ */ new Map();
11784
+ let start = 0;
11785
+ while (start < rendered.length) {
11786
+ let end = start;
11787
+ while (end < rendered.length && rendered[end].role !== "user") end++;
11788
+ const key = start > 0 ? rendered[start - 1].id : FIRST_TURN_KEY;
11789
+ const visible = rendered.slice(start, end).filter((message) => message.role !== "tool");
11790
+ const isLatest = end === rendered.length;
11791
+ const calls = [];
11792
+ for (const message of visible) {
11793
+ var _layouts$get$segments, _layouts$get;
11794
+ 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 : [];
11795
+ for (const segment of segments) if (segment.kind === "group") calls.push(...segment.calls);
11796
+ else if (segment.rendered) calls.push(segment.call);
11797
+ }
11798
+ const shown = new Set(calls.map((entry) => entry.toolCall.id));
11799
+ let lastWork = -1;
11800
+ visible.forEach((message, index) => {
11801
+ var _message$toolCalls2;
11802
+ 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;
11803
+ });
11804
+ const first = visible[0];
11805
+ if (first && (calls.length > 0 || isLatest)) {
11806
+ var _visible$lastAssistan;
11807
+ let lastAssistant = -1;
11808
+ visible.forEach((message, index) => {
11809
+ if (message.role === "assistant") lastAssistant = index;
11810
+ });
11811
+ const replyText = (_visible$lastAssistan = visible[lastAssistant]) === null || _visible$lastAssistan === void 0 ? void 0 : _visible$lastAssistan.content;
11812
+ const endsWithWork = lastAssistant >= 0 && lastAssistant <= lastWork && typeof replyText === "string" && replyText.trim().length > 0;
11813
+ turns.set(key, {
11814
+ key,
11815
+ firstMessageId: first.id,
11816
+ workMessageIds: new Set(visible.slice(0, lastWork + 1).map((message) => message.id)),
11817
+ replyTextMessageId: endsWithWork ? visible[lastAssistant].id : void 0,
11818
+ calls,
11819
+ isLatest
11820
+ });
11821
+ }
11822
+ start = end + 1;
11823
+ }
11824
+ return turns;
11825
+ }
11826
+ /**
11827
+ * The key of the latest reply (see `TurnWork.key`): the id of the last user
11828
+ * message, or `"start"` when there is none.
11829
+ *
11830
+ * @param rendered - The messages as the chat renders them, in order.
11831
+ */
11832
+ function getLatestTurnKey(rendered) {
11833
+ for (let i = rendered.length - 1; i >= 0; i--) {
11834
+ const message = rendered[i];
11835
+ if (message.role === "user") return message.id;
11836
+ }
11837
+ return FIRST_TURN_KEY;
11838
+ }
11839
+ /**
11840
+ * Whether the agent is working on this reply now: it is the latest one and a
11841
+ * run is going.
11842
+ *
11843
+ * @param turnKey - The reply's `TurnWork.key`.
11844
+ * @param state - The run state and the latest turn key.
11845
+ */
11846
+ function isTurnWorking(turnKey, state) {
11847
+ return state.isRunning && turnKey === state.latestTurnKey;
11848
+ }
11849
+ /**
11850
+ * Whether a reply's work shows. It shows while the agent works on the reply
11851
+ * and folds once the reply is done, unless the user opened or closed it.
11852
+ *
11853
+ * @param turnKey - The reply's `TurnWork.key`.
11854
+ * @param state - The user's toggles, the run state, and the latest turn key.
11855
+ */
11856
+ function isTurnWorkOpen(turnKey, state) {
11857
+ var _state$toggledTurns$g;
11858
+ return (_state$toggledTurns$g = state.toggledTurns.get(turnKey)) !== null && _state$toggledTurns$g !== void 0 ? _state$toggledTurns$g : isTurnWorking(turnKey, state);
11859
+ }
11860
+ /**
11861
+ * For each message in a reply's working phase, whether its work and its text
11862
+ * show. Text that ends the reply stays out of `workTextOpen` even when its
11863
+ * message also calls a tool, because it is the answer.
11864
+ *
11865
+ * @param turns - The turns from `getTurnWork`.
11866
+ * @param state - The user's toggles, the run state, and the latest turn key.
11867
+ * @returns The `workOpen` and `workTextOpen` maps of `ToolCallDisplayContextValue`.
11868
+ */
11869
+ function getWorkOpenState(turns, state) {
11870
+ const workOpen = /* @__PURE__ */ new Map();
11871
+ const workTextOpen = /* @__PURE__ */ new Map();
11872
+ for (const turn of turns) {
11873
+ const turnOpen = isTurnWorkOpen(turn.key, state);
11874
+ for (const id of turn.workMessageIds) {
11875
+ workOpen.set(id, turnOpen);
11876
+ if (id !== turn.replyTextMessageId) workTextOpen.set(id, turnOpen);
11877
+ }
11878
+ }
11879
+ return {
11880
+ workOpen,
11881
+ workTextOpen
11882
+ };
11883
+ }
11884
+ /**
11885
+ * Records run starts and ends in `workTimes`, for "Worked for 9s". Time spent
11886
+ * between runs (say, waiting for an approval) does not count. A reply is only
11887
+ * timed when this client saw it start from the user's message, so a restored
11888
+ * thread gets no entry. Calling it again with the same state changes nothing.
11889
+ *
11890
+ * @param workTimes - The times by turn key. This function updates it in place.
11891
+ * @param state - The run state now.
11892
+ * @param state.lastMessageRole - The role of the last rendered message.
11893
+ * @param state.now - The current time, in epoch ms.
11894
+ */
11895
+ function recordWorkTime(workTimes, state) {
11896
+ const { isRunning, latestTurnKey, lastMessageRole, now } = state;
11897
+ if (isRunning) {
11898
+ var _times$workingSince;
11899
+ const times = workTimes.get(latestTurnKey);
11900
+ if (times) (_times$workingSince = times.workingSince) !== null && _times$workingSince !== void 0 || (times.workingSince = now);
11901
+ else if (lastMessageRole === "user") workTimes.set(latestTurnKey, {
11902
+ elapsedMs: 0,
11903
+ workingSince: now
11904
+ });
11905
+ return;
11906
+ }
11907
+ const allTimes = workTimes.values();
11908
+ for (const times of allTimes) {
11909
+ if (times.workingSince === void 0) continue;
11910
+ times.elapsedMs += now - times.workingSince;
11911
+ times.workingSince = void 0;
11912
+ }
11913
+ }
11914
+ /**
11915
+ * The status of one call in a group. A call without a result is running only
11916
+ * while the group is active: once the run has moved on or ended, its result
11917
+ * is never coming.
11918
+ *
11919
+ * @param entry - The call and its result, if any.
11920
+ * @param active - The agent may still finish the group's calls.
11921
+ */
11922
+ function getToolCallRowStatus(entry, active) {
11923
+ const { toolMessage } = entry;
11924
+ let status;
11925
+ if (toolMessage) status = toolMessage.error ? "failed" : "done";
11926
+ else status = active ? "running" : "stopped";
11927
+ return status;
11928
+ }
11929
+ /**
11930
+ * The first non-empty string argument, with runs of whitespace collapsed to
11931
+ * one space. This is usually a command, path or query.
11932
+ *
11933
+ * @param parameters - The call's parsed arguments.
11934
+ * @returns The preview, or `undefined` when no argument is a non-empty string.
11935
+ */
11936
+ function getArgumentPreview(parameters) {
11937
+ if (!parameters || typeof parameters !== "object") return void 0;
11938
+ const value = Object.values(parameters).find((v) => typeof v === "string" && v.trim().length > 0);
11939
+ return value === null || value === void 0 ? void 0 : value.replace(/\s+/g, " ");
11940
+ }
11941
+ /**
11942
+ * `getArgumentPreview` for a call whose arguments may still be streaming in
11943
+ * as partial JSON.
11944
+ *
11945
+ * @param entry - The call.
11946
+ */
11947
+ function getToolCallPreview(entry) {
11948
+ return getArgumentPreview((0, _copilotkit_shared.partialJSONParse)(entry.toolCall.function.arguments));
11949
+ }
11950
+ /**
11951
+ * The names of the tools the calls used, in first-use order, with a count
11952
+ * for repeats: `"run_command ×2, read_file"`.
11953
+ *
11954
+ * @param calls - The calls to name.
11955
+ */
11956
+ function formatToolNames(calls) {
11957
+ const counts = /* @__PURE__ */ new Map();
11958
+ for (const { toolCall } of calls) {
11959
+ var _counts$get;
11960
+ const name = toolCall.function.name;
11961
+ counts.set(name, ((_counts$get = counts.get(name)) !== null && _counts$get !== void 0 ? _counts$get : 0) + 1);
11962
+ }
11963
+ return [...counts].map(([name, count]) => count > 1 ? `${name} ×${count}` : name).join(", ");
11964
+ }
11965
+ /**
11966
+ * How many of the calls finished with an error.
11967
+ *
11968
+ * @param calls - The calls to count.
11969
+ */
11970
+ function countFailedToolCalls(calls) {
11971
+ return calls.filter((call) => {
11972
+ var _call$toolMessage;
11973
+ return (_call$toolMessage = call.toolMessage) === null || _call$toolMessage === void 0 ? void 0 : _call$toolMessage.error;
11974
+ }).length;
11975
+ }
11976
+ /**
11977
+ * A count followed by the word that fits it: `"1 tool"`, `"3 tools"`.
11978
+ *
11979
+ * @param count - The number to show.
11980
+ * @param words - The word for exactly one (`one`) and for any other count (`other`).
11981
+ *
11982
+ * @example
11983
+ * ```ts
11984
+ * pluralize(3, { one: "tool", other: "tools" }); // "3 tools"
11985
+ * ```
11986
+ */
11987
+ function pluralize(count, words) {
11988
+ return `${count} ${count === 1 ? words.one : words.other}`;
11989
+ }
11990
+ /**
11991
+ * A tool call's arguments or result as display text. Strings pass through.
11992
+ * Other values are pretty-printed JSON. A value JSON cannot encode (say, a
11993
+ * circular reference) falls back to `String(value)`, then to
11994
+ * `"[unserializable]"`, so it never throws during a render.
11995
+ *
11996
+ * @param value - The arguments or the result.
11997
+ */
11998
+ function stringifyToolCallPayload(value) {
11999
+ if (typeof value === "string") return value;
12000
+ try {
12001
+ return JSON.stringify(value, null, 2);
12002
+ } catch (err) {
12003
+ console.warn("[CopilotKit] Failed to JSON.stringify tool-call payload; falling back to String():", err);
12004
+ try {
12005
+ return String(value);
12006
+ } catch (_unused) {
12007
+ return "[unserializable]";
12008
+ }
12009
+ }
12010
+ }
12011
+ /**
12012
+ * How long a `"turn"` reply worked, as short text: `"45s"`, `"1m 5s"`, `"2m"`.
12013
+ * Used for the live timer and the final duration. Partial seconds round down,
12014
+ * and a negative time reads `"0s"`.
12015
+ *
12016
+ * @param ms - The time in milliseconds.
12017
+ */
12018
+ function formatWorkDuration(ms) {
12019
+ const seconds = Math.max(0, Math.floor(ms / 1e3));
12020
+ if (seconds < 60) return `${seconds}s`;
12021
+ const minutes = Math.floor(seconds / 60);
12022
+ const rest = seconds % 60;
12023
+ return rest ? `${minutes}m ${rest}s` : `${minutes}m`;
12024
+ }
12025
+ /**
12026
+ * Splits a reasoning time into the unit and counts the "Thought for ..."
12027
+ * header shows. See `ReasoningDuration` for the text each unit maps to.
12028
+ *
12029
+ * - Under 1 second: `fewSeconds`.
12030
+ * - Under 60 seconds: `seconds`, rounded to the nearest second.
12031
+ * - Whole minutes after rounding the seconds: `minutes`.
12032
+ * - Otherwise: `minutesSeconds`.
12033
+ *
12034
+ * @param seconds - The elapsed time in seconds. It may have a fraction.
12035
+ */
12036
+ function formatReasoningDuration(seconds) {
12037
+ if (seconds < 1) return { unit: "fewSeconds" };
12038
+ if (seconds < 60) return {
12039
+ unit: "seconds",
12040
+ seconds: Math.round(seconds)
12041
+ };
12042
+ const minutes = Math.floor(seconds / 60);
12043
+ const rest = Math.round(seconds % 60);
12044
+ if (rest === 0) return {
12045
+ unit: "minutes",
12046
+ minutes
12047
+ };
12048
+ return {
12049
+ unit: "minutesSeconds",
12050
+ minutes,
12051
+ seconds: rest
12052
+ };
12053
+ }
12054
+
12055
+ //#endregion
12056
+ //#region src/chat/messages.ts
12057
+ /**
12058
+ * Collapses tool calls that share an id, keeping first-seen order.
12059
+ *
12060
+ * AG-UI's TOOL_CALL_START handler appends to the parent message's `toolCalls`
12061
+ * without checking whether that id is already present. When a start event is
12062
+ * applied twice (the human-in-the-loop flow does this when the run syncs after
12063
+ * `respond()`), the message carries the same call twice. The second copy has
12064
+ * empty `arguments`, because a start event carries none. The args arrive later
12065
+ * as TOOL_CALL_ARGS deltas addressed to the first copy.
12066
+ *
12067
+ * Left alone, the same tool call renders twice: once populated and once blank.
12068
+ * The blank copy is the redundant one, so the copy that carries arguments wins,
12069
+ * whatever order the two arrive in.
12070
+ *
12071
+ * @param toolCalls - The tool calls of one assistant message.
12072
+ * @returns The same array when no id repeats, so memoized consumers keep a
12073
+ * stable reference. Otherwise a new array with one entry per id.
12074
+ */
12075
+ function dedupeToolCalls(toolCalls) {
12076
+ const byId = /* @__PURE__ */ new Map();
12077
+ for (const toolCall of toolCalls) {
12078
+ var _existing$function, _toolCall$function;
12079
+ const existing = byId.get(toolCall.id);
12080
+ if (!existing) {
12081
+ byId.set(toolCall.id, toolCall);
12082
+ continue;
12083
+ }
12084
+ 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);
12085
+ }
12086
+ return byId.size === toolCalls.length ? toolCalls : [...byId.values()];
12087
+ }
12088
+ /**
12089
+ * Merges two snapshots of the same assistant message.
12090
+ *
12091
+ * - Empty `content` means a streaming update cleared the field, so the earlier
12092
+ * non-empty content is kept.
12093
+ * - `toolCalls: undefined` means the later chunk had no tool-call activity, so
12094
+ * the earlier tool calls are kept. An explicit `[]` is kept as-is.
12095
+ * - Fields that only the earlier snapshot has are kept.
12096
+ */
12097
+ function mergeAssistantMessages(existing, message) {
12098
+ var _message$toolCalls;
12099
+ const content = message.content || existing.content;
12100
+ const toolCalls = (_message$toolCalls = message.toolCalls) !== null && _message$toolCalls !== void 0 ? _message$toolCalls : existing.toolCalls;
12101
+ return {
12102
+ ...existing,
12103
+ ...message,
12104
+ content,
12105
+ toolCalls: toolCalls ? dedupeToolCalls(toolCalls) : toolCalls
12106
+ };
12107
+ }
12108
+ /**
12109
+ * Returns the assistant message with repeated tool-call ids collapsed. Returns
12110
+ * the same object when nothing collapsed.
12111
+ */
12112
+ function withDedupedToolCalls(message) {
12113
+ if (!message.toolCalls) return message;
12114
+ const toolCalls = dedupeToolCalls(message.toolCalls);
12115
+ return toolCalls === message.toolCalls ? message : {
12116
+ ...message,
12117
+ toolCalls
12118
+ };
12119
+ }
12120
+ /**
12121
+ * De-duplicates chat messages by id, for rendering.
12122
+ *
12123
+ * A message list from an agent can hold the same message id more than once
12124
+ * while it streams. This keeps one entry per id, at the position the id first
12125
+ * appears:
12126
+ *
12127
+ * - **Assistant messages** are merged. Later fields win, but empty `content`
12128
+ * falls back to earlier non-empty content, and `toolCalls: undefined` falls
12129
+ * back to earlier tool calls (an explicit `[]` is kept).
12130
+ * - **Tool calls** on an assistant message are de-duplicated by id, also
12131
+ * when the message itself is not repeated. The copy that has arguments
12132
+ * wins, and the first-seen order is kept.
12133
+ * - **Other roles** keep the last copy.
12134
+ *
12135
+ * @param messages - The agent's messages, in order.
12136
+ * @returns A new array. A message that needed no change is returned as the
12137
+ * same object.
12138
+ *
12139
+ * @example
12140
+ * ```ts
12141
+ * const visible = ɵdeduplicateMessages(agent.messages);
12142
+ * ```
12143
+ */
12144
+ function ɵdeduplicateMessages(messages) {
12145
+ const byId = /* @__PURE__ */ new Map();
12146
+ for (const message of messages) {
12147
+ if (message.role !== "assistant") {
12148
+ byId.set(message.id, message);
12149
+ continue;
12150
+ }
12151
+ const existing = byId.get(message.id);
12152
+ const merged = (existing === null || existing === void 0 ? void 0 : existing.role) === "assistant" ? mergeAssistantMessages(existing, message) : withDedupedToolCalls(message);
12153
+ byId.set(message.id, merged);
12154
+ }
12155
+ return [...byId.values()];
12156
+ }
12157
+ /**
12158
+ * Serializes object content for {@link ɵmessagesFingerprint}.
12159
+ *
12160
+ * `JSON.stringify` throws on a circular structure (and on a `BigInt`). The
12161
+ * fingerprint runs on every render, so a throw would take the chat down. A
12162
+ * value that cannot be serialized gets a constant key instead: it does not
12163
+ * trigger a change on its own, but every other part of the fingerprint still
12164
+ * does.
12165
+ */
12166
+ function objectContentKey(content) {
12167
+ try {
12168
+ var _JSON$stringify;
12169
+ return (_JSON$stringify = JSON.stringify(content)) !== null && _JSON$stringify !== void 0 ? _JSON$stringify : "";
12170
+ } catch (_unused) {
12171
+ return "[unserializable]";
12172
+ }
12173
+ }
12174
+ /**
12175
+ * Gives the part of the fingerprint that tracks a message's content:
12176
+ * - string content: its length, so streamed text changes it.
12177
+ * - array content: the part count, so an added attachment changes it. The
12178
+ * parts are not serialized, which keeps base64 uploads out of the key.
12179
+ * - object content (activity messages): its JSON, so a snapshot that replaces
12180
+ * the content under the same message id changes it.
12181
+ */
12182
+ function contentKey(content) {
12183
+ if (typeof content === "string" || Array.isArray(content)) return String(content.length);
12184
+ if (content !== null && typeof content === "object") return objectContentKey(content);
12185
+ return "0";
12186
+ }
12187
+ /**
12188
+ * Builds a string that changes whenever a render of the message list could
12189
+ * change. Use it as a cheap memo key in place of a deep comparison.
12190
+ *
12191
+ * The key covers, per message:
12192
+ * - the id and the role.
12193
+ * - the content: text length, part count, or the JSON of object content.
12194
+ * - the `toolCallId` of a tool message.
12195
+ * - each tool call's id and the length of its arguments, so streamed
12196
+ * arguments change the key.
12197
+ *
12198
+ * It never throws. Object content that cannot be serialized (for example a
12199
+ * circular tool result) gets a constant key.
12200
+ *
12201
+ * @param messages - The agent's messages, in order.
12202
+ * @returns The fingerprint string.
12203
+ *
12204
+ * @example
12205
+ * ```ts
12206
+ * const key = ɵmessagesFingerprint(agent.messages);
12207
+ * if (key !== previousKey) rerender();
12208
+ * ```
12209
+ */
12210
+ function ɵmessagesFingerprint(messages) {
12211
+ return messages.map((message) => {
12212
+ const toolCallId = "toolCallId" in message ? message.toolCallId : "";
12213
+ const toolCallsKey = ("toolCalls" in message && Array.isArray(message.toolCalls) ? message.toolCalls : []).map((tc) => {
12214
+ var _tc$function$argument, _tc$function;
12215
+ 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}`;
12216
+ }).join(";");
12217
+ return `${message.id}:${message.role}:${contentKey(message.content)}:${toolCallId}:${toolCallsKey}`;
12218
+ }).join(",");
12219
+ }
12220
+
12221
+ //#endregion
12222
+ //#region src/chat/composer.ts
12223
+ /**
12224
+ * Get the state of the send/stop button in the chat input.
12225
+ *
12226
+ * @param input - The current state of the chat input.
12227
+ * @returns
12228
+ * - `isProcessing`: the agent runs and the input does not record audio.
12229
+ * - `canSend`: the text is not empty and nothing blocks a send.
12230
+ * - `action`: `"stop"` when the button stops the run, else `"send"`.
12231
+ * Use it for the icon, the label, and the click.
12232
+ * - `disabled`: `true` when a click does nothing.
12233
+ *
12234
+ * @example
12235
+ * ```ts
12236
+ * const button = ɵcomposerButtonState({
12237
+ * mode: "input",
12238
+ * isRunning: agent.isRunning,
12239
+ * value: text,
12240
+ * canSubmit: true,
12241
+ * canStop: true,
12242
+ * });
12243
+ * // On click:
12244
+ * if (button.action === "stop") stopRun();
12245
+ * else if (button.canSend) sendMessage(text.trim());
12246
+ * ```
12247
+ */
12248
+ function ɵcomposerButtonState(input) {
12249
+ const isProcessing = input.mode !== "transcribe" && input.isRunning;
12250
+ const isSendBlocked = input.disabled === true || input.attachmentsUploading === true;
12251
+ const canSend = input.canSubmit && !isSendBlocked && input.value.trim().length > 0;
12252
+ return {
12253
+ isProcessing,
12254
+ canSend,
12255
+ action: isProcessing && input.canStop ? "stop" : "send",
12256
+ disabled: isProcessing ? !input.canStop : !canSend
12257
+ };
12258
+ }
12259
+ /**
12260
+ * Decide what a key press in the chat input does.
12261
+ *
12262
+ * This handles Enter only. Keys for the slash-command menu stay in each
12263
+ * framework, and the framework handles them before it calls this function.
12264
+ *
12265
+ * Results:
12266
+ * - `"send"`: send the trimmed text.
12267
+ * - `"stop"`: stop the run. This happens for Enter in an empty input while
12268
+ * the agent runs. Text in the input always means send, not stop.
12269
+ * - `"newline"`: Shift+Enter. Let the browser add the line break.
12270
+ * - `"none"`: do nothing. Returned during IME composition, while the input
12271
+ * is disabled, for keys other than Enter, and for an Enter that has
12272
+ * nothing to send or stop.
12273
+ *
12274
+ * Call `preventDefault()` for every Enter without Shift that is not part of
12275
+ * IME composition, including when the result is `"none"`. This stops Enter
12276
+ * from adding a line break that the user cannot send.
12277
+ *
12278
+ * @param event - The keyboard event, or an object with the same fields.
12279
+ * @param input - The current state of the chat input.
12280
+ *
12281
+ * @example
12282
+ * ```ts
12283
+ * function onKeyDown(event: KeyboardEvent) {
12284
+ * if (event.isComposing || event.keyCode === 229) return;
12285
+ * // ...slash-command menu keys...
12286
+ * const result = ɵresolveComposerKey(event, composerInput);
12287
+ * if (event.key === "Enter" && !event.shiftKey) event.preventDefault();
12288
+ * if (result === "send") sendMessage(composerInput.value.trim());
12289
+ * if (result === "stop") stopRun();
12290
+ * }
12291
+ * ```
12292
+ */
12293
+ function ɵresolveComposerKey(event, input) {
12294
+ if (event.isComposing || event.keyCode === 229 || input.disabled === true || event.key !== "Enter") return "none";
12295
+ if (event.shiftKey) return "newline";
12296
+ const button = ɵcomposerButtonState(input);
12297
+ const isEmpty = input.value.trim().length === 0;
12298
+ if (button.isProcessing && isEmpty) return input.canStop ? "stop" : "none";
12299
+ return button.canSend ? "send" : "none";
12300
+ }
12301
+
12302
+ //#endregion
12303
+ //#region src/chat/transcription.ts
12304
+ /**
12305
+ * The error `ɵtranscribeAudio` throws. Read `error.info.code` to pick a
12306
+ * message for the user, or pass `error.info` to
12307
+ * `ɵtranscriptionErrorMessageKey`.
12308
+ */
12309
+ var TranscriptionError = class extends Error {
12310
+ constructor(info) {
12311
+ super(info.message);
12312
+ _defineProperty(this, "info", void 0);
12313
+ this.name = "TranscriptionError";
12314
+ this.info = info;
12315
+ }
12316
+ };
12317
+ /**
12318
+ * Send a recording to the CopilotKit runtime and get its text back.
12319
+ *
12320
+ * The request follows the transport set on the core:
12321
+ * - `"single"`: one JSON POST to `runtimeUrl`, with the audio as base64.
12322
+ * - any other transport: a multipart POST to `${runtimeUrl}/transcribe`.
12323
+ *
12324
+ * Headers are resolved on each call. The core's `credentials` are sent when
12325
+ * they are set, the same as for agent requests.
12326
+ *
12327
+ * @param core - The `CopilotKitCore` (or a framework subclass) to send through.
12328
+ * @param audioBlob - The recorded audio.
12329
+ * @param filename - The file name the runtime sees. Defaults to `"recording.webm"`.
12330
+ * @returns The transcription result, with the text in `result.text`.
12331
+ * @throws {TranscriptionError} When the runtime URL is not set, the request
12332
+ * fails, or the runtime returns an error. `error.info` has the code.
12333
+ *
12334
+ * @example
12335
+ * ```ts
12336
+ * try {
12337
+ * const { text } = await ɵtranscribeAudio(core, blob);
12338
+ * } catch (error) {
12339
+ * if (error instanceof TranscriptionError) {
12340
+ * const key = ɵtranscriptionErrorMessageKey(error.info);
12341
+ * showError(key ? labels[key] : error.info.message);
12342
+ * }
12343
+ * }
12344
+ * ```
12345
+ */
12346
+ async function ɵtranscribeAudio(core, audioBlob, filename = "recording.webm") {
12347
+ const { runtimeUrl, credentials } = core;
12348
+ if (!runtimeUrl) throw new TranscriptionError({
12349
+ code: _copilotkit_shared.TranscriptionErrorCode.INVALID_REQUEST,
12350
+ message: "Runtime URL is not configured",
12351
+ retryable: false
12352
+ });
12353
+ const resolvedHeaders = await core.resolveHeaders();
12354
+ const credentialsInit = credentials ? { credentials } : {};
12355
+ let response;
12356
+ try {
12357
+ response = core.runtimeTransport === "single" ? await fetch(runtimeUrl, {
12358
+ method: "POST",
12359
+ headers: {
12360
+ ...omitContentType(resolvedHeaders),
12361
+ "Content-Type": "application/json"
12362
+ },
12363
+ body: JSON.stringify({
12364
+ method: "transcribe",
12365
+ body: {
12366
+ audio: await blobToBase64(audioBlob),
12367
+ mimeType: audioBlob.type || "audio/webm",
12368
+ filename
12369
+ }
12370
+ }),
12371
+ ...credentialsInit
12372
+ }) : await fetch(`${runtimeUrl}/transcribe`, {
12373
+ method: "POST",
12374
+ headers: omitContentType(resolvedHeaders),
12375
+ body: toFormData(audioBlob, filename),
12376
+ ...credentialsInit
12377
+ });
12378
+ } catch (error) {
12379
+ throw new TranscriptionError({
12380
+ code: _copilotkit_shared.TranscriptionErrorCode.NETWORK_ERROR,
12381
+ message: error instanceof Error ? error.message : "Network request failed",
12382
+ retryable: true
12383
+ });
12384
+ }
12385
+ if (!response.ok) throw await toTranscriptionError(response);
12386
+ return await response.json();
12387
+ }
12388
+ /**
12389
+ * Pick the chat label to show the user for a transcription error.
12390
+ *
12391
+ * @param error - The `info` of a `TranscriptionError`.
12392
+ * @returns A key of the chat labels, or `null`. `null` means no label fits:
12393
+ * show `error.message` instead.
12394
+ *
12395
+ * @example
12396
+ * ```ts
12397
+ * const key = ɵtranscriptionErrorMessageKey(error.info);
12398
+ * const text = key ? labels[key] : error.info.message;
12399
+ * ```
12400
+ */
12401
+ function ɵtranscriptionErrorMessageKey(error) {
12402
+ switch (error.code) {
12403
+ case _copilotkit_shared.TranscriptionErrorCode.RATE_LIMITED: return "transcriptionErrorRateLimitedText";
12404
+ case _copilotkit_shared.TranscriptionErrorCode.AUTH_FAILED: return "transcriptionErrorAuthFailedText";
12405
+ case _copilotkit_shared.TranscriptionErrorCode.AUDIO_TOO_LONG: return "transcriptionErrorAudioTooLongText";
12406
+ case _copilotkit_shared.TranscriptionErrorCode.AUDIO_TOO_SHORT: return "transcriptionErrorAudioTooShortText";
12407
+ case _copilotkit_shared.TranscriptionErrorCode.INVALID_AUDIO_FORMAT: return "transcriptionErrorInvalidAudioFormatText";
12408
+ case _copilotkit_shared.TranscriptionErrorCode.SERVICE_NOT_CONFIGURED: return "transcriptionErrorServiceNotConfiguredText";
12409
+ case _copilotkit_shared.TranscriptionErrorCode.NETWORK_ERROR: return "transcriptionErrorNetworkText";
12410
+ default: return error.retryable ? "transcriptionErrorGenericText" : null;
12411
+ }
12412
+ }
12413
+ function toFormData(audioBlob, filename) {
12414
+ const formData = new FormData();
12415
+ formData.append("audio", audioBlob, filename);
12416
+ return formData;
12417
+ }
12418
+ function omitContentType(headers) {
12419
+ const entries = Object.entries(headers);
12420
+ return Object.fromEntries(entries.filter(([name]) => name.toLowerCase() !== "content-type"));
12421
+ }
12422
+ async function blobToBase64(blob) {
12423
+ const bytes = new Uint8Array(await blob.arrayBuffer());
12424
+ const chunkSize = 32768;
12425
+ let binary = "";
12426
+ for (let offset = 0; offset < bytes.length; offset += chunkSize) binary += String.fromCharCode(...bytes.subarray(offset, offset + chunkSize));
12427
+ return btoa(binary);
12428
+ }
12429
+ /** Build a typed error from a non-OK transcription response. */
12430
+ async function toTranscriptionError(response) {
12431
+ const retryable = response.status >= 500;
12432
+ let data;
12433
+ try {
12434
+ data = await response.json();
12435
+ } catch (_unused) {
12436
+ return new TranscriptionError({
12437
+ code: _copilotkit_shared.TranscriptionErrorCode.PROVIDER_ERROR,
12438
+ message: `HTTP ${response.status}: ${response.statusText}`,
12439
+ retryable
12440
+ });
12441
+ }
12442
+ if (isTranscriptionErrorResponse(data)) {
12443
+ var _data$retryable;
12444
+ return new TranscriptionError({
12445
+ code: data.error,
12446
+ message: data.message,
12447
+ retryable: (_data$retryable = data.retryable) !== null && _data$retryable !== void 0 ? _data$retryable : false
12448
+ });
12449
+ }
12450
+ const message = typeof data === "object" && data !== null && "message" in data ? String(data.message) : "Transcription failed";
12451
+ return new TranscriptionError({
12452
+ code: _copilotkit_shared.TranscriptionErrorCode.PROVIDER_ERROR,
12453
+ message,
12454
+ retryable
12455
+ });
12456
+ }
12457
+ function isTranscriptionErrorResponse(data) {
12458
+ return typeof data === "object" && data !== null && "error" in data && "message" in data && typeof data.error === "string" && typeof data.message === "string";
12459
+ }
12460
+
12461
+ //#endregion
12462
+ //#region src/chat/license.ts
12463
+ /**
12464
+ * Resolves the license context and the license banner from the runtime
12465
+ * license authority. React, Vue, and Angular call it with the values core
12466
+ * reports, then show the banner and provide the context.
12467
+ *
12468
+ * Rules:
12469
+ *
12470
+ * - A retryable entitlement failure that core is still retrying hides the
12471
+ * status, so no banner shows until the retry ends. A `valid` or `expiring`
12472
+ * legacy status stays in use during the retry.
12473
+ * - A terminal entitlement failure (not retryable, no `valid` or `expiring`
12474
+ * legacy status) keeps the reported status, but `checkFeature` returns
12475
+ * `false` and `getLimit` returns `null` for every feature.
12476
+ * - The `no_license` banner shows only when the status is `none` and no
12477
+ * public key is set.
12478
+ *
12479
+ * The banner text has no day count. No data source gives the days left.
12480
+ *
12481
+ * @param input - The runtime license values and the public key. See
12482
+ * {@link LicenseStateInput}.
12483
+ * @returns `context` for the license context, `warningStatus` (the status the
12484
+ * banner is based on, `undefined` while a retry runs), and `bannerType`
12485
+ * (`null` when no banner shows).
12486
+ *
12487
+ * @example
12488
+ * ```ts
12489
+ * const { context, bannerType } = ɵresolveLicenseState({
12490
+ * status: core.licenseStatus,
12491
+ * entitlements: core.runtimeEntitlements,
12492
+ * retryPending: core.runtimeEntitlementRetryPending,
12493
+ * publicKey,
12494
+ * });
12495
+ * ```
12496
+ */
12497
+ function ɵresolveLicenseState({ status, entitlements, retryPending, publicKey }) {
12498
+ var _context$status;
12499
+ const isRetryableFailure = (entitlements === null || entitlements === void 0 ? void 0 : entitlements.status) !== "ready" && (entitlements === null || entitlements === void 0 ? void 0 : entitlements.error.retryable) === true;
12500
+ const isNonReady = entitlements !== void 0 && entitlements.status !== "ready";
12501
+ const hasLegacyFallback = status === "valid" || status === "expiring";
12502
+ const isRetrying = isRetryableFailure && retryPending && !hasLegacyFallback;
12503
+ const isTerminalFailure = isNonReady && !isRetryableFailure && !hasLegacyFallback;
12504
+ const runtimeContext = (0, _copilotkit_shared.createLicenseContextValue)(isRetrying ? void 0 : status, entitlements);
12505
+ const context = isTerminalFailure ? {
12506
+ ...runtimeContext,
12507
+ checkFeature: () => false,
12508
+ getLimit: () => null
12509
+ } : runtimeContext;
12510
+ const warningStatus = isRetrying ? void 0 : (_context$status = context.status) !== null && _context$status !== void 0 ? _context$status : void 0;
12511
+ return {
12512
+ context,
12513
+ warningStatus,
12514
+ bannerType: resolveLicenseBannerType(warningStatus, publicKey)
12515
+ };
12516
+ }
12517
+ function resolveLicenseBannerType(warningStatus, publicKey) {
12518
+ switch (warningStatus) {
12519
+ case "none": return publicKey ? null : "no_license";
12520
+ case "expired":
12521
+ case "invalid":
12522
+ case "expiring": return warningStatus;
12523
+ case "valid":
12524
+ case "unknown":
12525
+ case void 0: return null;
12526
+ }
12527
+ }
12528
+ /**
12529
+ * Resolves whether the threads drawer can load its thread list.
12530
+ *
12531
+ * - `licensed` is `true` when the status is `unknown` (an entitlement lookup
12532
+ * that did not recover, so the threads endpoint decides), or when the
12533
+ * status is `valid` or `expiring` and `checkFeature("threads")` is `true`.
12534
+ * - `licensePending` is `true` while the status is `null` (the runtime has
12535
+ * not reported yet). Show the loading state then, not the locked view.
12536
+ *
12537
+ * @param context - The license context from {@link ɵresolveLicenseState}.
12538
+ *
12539
+ * @example
12540
+ * ```ts
12541
+ * const { licensed, licensePending } = ɵresolveThreadsLicense(context);
12542
+ * ```
12543
+ */
12544
+ function ɵresolveThreadsLicense(context) {
12545
+ const { status } = context;
12546
+ return {
12547
+ licensed: status === "unknown" || (status === "valid" || status === "expiring") && context.checkFeature("threads"),
12548
+ licensePending: status === null
12549
+ };
12550
+ }
12551
+
12552
+ //#endregion
12553
+ //#region src/chat/icons.ts
12554
+ /*! @license
12555
+ * The icon data below is copied from Lucide v0.525.0 (https://lucide.dev).
12556
+ * The Lucide license follows. A copy is in LUCIDE-LICENSE.md next to this file.
12557
+ * This comment sits right above runtime code so the bundler keeps it in dist.
12558
+ *
12559
+ * ISC License
12560
+ *
12561
+ * 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.
12562
+ *
12563
+ * Permission to use, copy, modify, and/or distribute this software for any
12564
+ * purpose with or without fee is hereby granted, provided that the above
12565
+ * copyright notice and this permission notice appear in all copies.
12566
+ *
12567
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12568
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12569
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12570
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12571
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
12572
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
12573
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
12574
+ */
12575
+ function path(d) {
12576
+ return {
12577
+ tag: "path",
12578
+ attributes: { d }
12579
+ };
12580
+ }
12581
+ const icons = {
12582
+ ArrowUp: {
12583
+ name: "arrow-up",
12584
+ nodes: [path("m5 12 7-7 7 7"), path("M12 19V5")]
12585
+ },
12586
+ Check: {
12587
+ name: "check",
12588
+ nodes: [path("M20 6 9 17l-5-5")]
12589
+ },
12590
+ ChevronDown: {
12591
+ name: "chevron-down",
12592
+ nodes: [path("m6 9 6 6 6-6")]
12593
+ },
12594
+ ChevronLeft: {
12595
+ name: "chevron-left",
12596
+ nodes: [path("m15 18-6-6 6-6")]
12597
+ },
12598
+ ChevronRight: {
12599
+ name: "chevron-right",
12600
+ nodes: [path("m9 18 6-6-6-6")]
12601
+ },
12602
+ Circle: {
12603
+ name: "circle",
12604
+ nodes: [{
12605
+ tag: "circle",
12606
+ attributes: {
12607
+ cx: "12",
12608
+ cy: "12",
12609
+ r: "10"
12610
+ }
12611
+ }]
12612
+ },
12613
+ Copy: {
12614
+ name: "copy",
12615
+ nodes: [{
12616
+ tag: "rect",
12617
+ attributes: {
12618
+ width: "14",
12619
+ height: "14",
12620
+ x: "8",
12621
+ y: "8",
12622
+ rx: "2",
12623
+ ry: "2"
12624
+ }
12625
+ }, path("M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2")]
12626
+ },
12627
+ Edit: {
12628
+ name: "square-pen",
12629
+ 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")]
12630
+ },
12631
+ EyeOff: {
12632
+ name: "eye-off",
12633
+ nodes: [
12634
+ 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"),
12635
+ path("M14.084 14.158a3 3 0 0 1-4.242-4.242"),
12636
+ 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"),
12637
+ path("m2 2 20 20")
12638
+ ]
12639
+ },
12640
+ Loader2: {
12641
+ name: "loader-circle",
12642
+ nodes: [path("M21 12a9 9 0 1 1-6.219-8.56")]
12643
+ },
12644
+ MessageCircle: {
12645
+ name: "message-circle",
12646
+ nodes: [path("M7.9 20A9 9 0 1 0 4 16.1L2 22Z")]
12647
+ },
12648
+ Mic: {
12649
+ name: "mic",
12650
+ nodes: [
12651
+ path("M12 19v3"),
12652
+ path("M19 10v2a7 7 0 0 1-14 0v-2"),
12653
+ {
12654
+ tag: "rect",
12655
+ attributes: {
12656
+ x: "9",
12657
+ y: "2",
12658
+ width: "6",
12659
+ height: "13",
12660
+ rx: "3"
12661
+ }
12662
+ }
12663
+ ]
12664
+ },
12665
+ PanelLeftOpen: {
12666
+ name: "panel-left-open",
12667
+ nodes: [
12668
+ {
12669
+ tag: "rect",
12670
+ attributes: {
12671
+ width: "18",
12672
+ height: "18",
12673
+ x: "3",
12674
+ y: "3",
12675
+ rx: "2"
12676
+ }
12677
+ },
12678
+ path("M9 3v18"),
12679
+ path("m14 9 3 3-3 3")
12680
+ ]
12681
+ },
12682
+ Play: {
12683
+ name: "play",
12684
+ nodes: [{
12685
+ tag: "polygon",
12686
+ attributes: { points: "6 3 20 12 6 21 6 3" }
12687
+ }]
12688
+ },
12689
+ Plus: {
12690
+ name: "plus",
12691
+ nodes: [path("M5 12h14"), path("M12 5v14")]
12692
+ },
12693
+ RefreshCw: {
12694
+ name: "refresh-cw",
12695
+ nodes: [
12696
+ path("M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"),
12697
+ path("M21 3v5h-5"),
12698
+ path("M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"),
12699
+ path("M8 16H3v5")
12700
+ ]
12701
+ },
12702
+ Square: {
12703
+ name: "square",
12704
+ nodes: [{
12705
+ tag: "rect",
12706
+ attributes: {
12707
+ width: "18",
12708
+ height: "18",
12709
+ x: "3",
12710
+ y: "3",
12711
+ rx: "2"
12712
+ }
12713
+ }]
12714
+ },
12715
+ ThumbsDown: {
12716
+ name: "thumbs-down",
12717
+ 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")]
12718
+ },
12719
+ ThumbsUp: {
12720
+ name: "thumbs-up",
12721
+ 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")]
12722
+ },
12723
+ Upload: {
12724
+ name: "upload",
12725
+ nodes: [
12726
+ path("M12 3v12"),
12727
+ path("m17 8-5-5-5 5"),
12728
+ path("M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4")
12729
+ ]
12730
+ },
12731
+ Volume2: {
12732
+ name: "volume-2",
12733
+ nodes: [
12734
+ 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"),
12735
+ path("M16 9a5 5 0 0 1 0 6"),
12736
+ path("M19.364 18.364a9 9 0 0 0 0-12.728")
12737
+ ]
12738
+ },
12739
+ Wrench: {
12740
+ name: "wrench",
12741
+ 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")]
12742
+ },
12743
+ X: {
12744
+ name: "x",
12745
+ nodes: [path("M18 6 6 18"), path("m6 6 12 12")]
12746
+ }
12747
+ };
12748
+ /**
12749
+ * Internal. The SVG data for every icon the chat components draw.
12750
+ *
12751
+ * Each framework's `CopilotIcon` component reads an entry and draws it:
12752
+ *
12753
+ * ```ts
12754
+ * const { name, nodes } = ɵcopilotIcons.ArrowUp;
12755
+ * // <svg {...ɵcopilotIconSvgAttributes} class="lucide lucide-arrow-up">
12756
+ * // one child element per node: <{node.tag} {...node.attributes} />
12757
+ * // </svg>
12758
+ * ```
12759
+ */
12760
+ const ɵcopilotIcons = icons;
12761
+ /**
12762
+ * Internal. The attributes to put on the `<svg>` of every chat icon.
12763
+ *
12764
+ * These are Lucide's default attributes, so a drawn icon matches the Lucide
12765
+ * icon. Set `width` and `height` to change the size.
12766
+ */
12767
+ const ɵcopilotIconSvgAttributes = {
12768
+ xmlns: "http://www.w3.org/2000/svg",
12769
+ width: "24",
12770
+ height: "24",
12771
+ viewBox: "0 0 24 24",
12772
+ fill: "none",
12773
+ stroke: "currentColor",
12774
+ "stroke-width": "2",
12775
+ "stroke-linecap": "round",
12776
+ "stroke-linejoin": "round"
12777
+ };
12778
+
12779
+ //#endregion
12780
+ //#region src/open-generative-ui/content.ts
12781
+ /**
12782
+ * Open Generative UI content: the activity the agent streams while it
12783
+ * generates a sandboxed UI, and the rules for when a new snapshot must reach
12784
+ * the sandbox at once.
12785
+ */
12786
+ /** The activity type of Open Generative UI messages. */
12787
+ const OPEN_GENERATIVE_UI_ACTIVITY_TYPE = "open-generative-ui";
12788
+ /** The name of the frontend tool the agent calls to generate a sandboxed UI. */
12789
+ const GENERATE_SANDBOXED_UI_TOOL_NAME = "generateSandboxedUi";
12790
+ /** The design guidance sent to the agent when no `designSkill` is set. */
12791
+ const DEFAULT_OPEN_GENERATIVE_UI_DESIGN_SKILL = `When generating UI with generateSandboxedUi, follow these design principles inspired by shadcn/ui:
12792
+
12793
+ - Use a minimal, flat aesthetic. Avoid drop shadows and gradients — rely on subtle borders (1px solid, light gray like #e5e7eb) to define surfaces.
12794
+ - Neutral base palette: white backgrounds, zinc/slate gray text (#09090b for headings, #71717a for secondary text). One accent color for interactive elements.
12795
+ - Use system font stacks (system-ui, -apple-system, sans-serif) at readable sizes (14px body, 600 weight for headings). Tight line-heights.
12796
+ - Small, consistent border-radius (6–8px). Cards and containers use border, not shadow, for separation.
12797
+ - Buttons: solid fill for primary (dark bg, white text), outline for secondary (border + transparent bg). Subtle hover state (slight opacity or background shift).
12798
+ - Use CSS Grid or Flexbox for layout. Ensure the UI looks good at any width.
12799
+ - Minimal transitions (150ms) for hover/focus states only. No decorative animations.
12800
+ - Keep the UI focused and dense — avoid excessive padding. Use compact spacing (8–12px gaps, 10–14px padding in controls).`;
12801
+ /** `true` when the content has HTML that a preview or final sandbox shows. */
12802
+ function hasRenderableContent(content) {
12803
+ var _content$html;
12804
+ if (!content) return false;
12805
+ const hasHtml = !!((_content$html = content.html) === null || _content$html === void 0 ? void 0 : _content$html.join("").trim());
12806
+ const hasFinalHtml = content.htmlComplete && hasHtml;
12807
+ const hasPreviewHtml = content.cssComplete && !content.htmlComplete && hasHtml;
12808
+ return !!hasFinalHtml || !!hasPreviewHtml;
12809
+ }
12810
+ /**
12811
+ * `true` when `next` must replace `previous` at once instead of waiting for
12812
+ * the throttle window: the UI restarts, a stage completes, or new JavaScript
12813
+ * arrives.
12814
+ */
12815
+ function shouldFlushImmediately(previous, next) {
12816
+ var _next$jsExpressions$l, _next$jsExpressions, _previous$jsExpressio, _previous$jsExpressio2, _next$html, _previous$html;
12817
+ if (hasRenderableContent(previous) && !hasRenderableContent(next)) return true;
12818
+ if (next.cssComplete && !(previous === null || previous === void 0 ? void 0 : previous.cssComplete)) return true;
12819
+ if (next.htmlComplete) return true;
12820
+ if (next.generating === false) return true;
12821
+ if (next.jsFunctions && !(previous === null || previous === void 0 ? void 0 : previous.jsFunctions)) return true;
12822
+ 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;
12823
+ 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;
12824
+ return false;
12825
+ }
12826
+
12827
+ //#endregion
12828
+ //#region src/open-generative-ui/html.ts
12829
+ /**
12830
+ * Pure string helpers that turn streamed HTML into sandbox content.
12831
+ * No DOM access.
12832
+ */
12833
+ /**
12834
+ * Extracts all complete `<style>` blocks from the raw HTML.
12835
+ * Returns the concatenated style tags, suitable for injection into `<head>`.
12836
+ */
12837
+ function extractCompleteStyles(html) {
12838
+ const matches = html.match(/<style\b[^>]*>[\s\S]*?<\/style>/gi);
12839
+ return matches ? matches.join("") : "";
12840
+ }
12841
+ /**
12842
+ * Processes raw accumulated HTML for safe preview via innerHTML injection.
12843
+ *
12844
+ * Pipeline (order matters):
12845
+ * 1. Strip incomplete tag at end
12846
+ * 2. Strip complete <style>, <script>, and <head> blocks
12847
+ * 3. Strip incomplete <style>/<script>/<head> blocks
12848
+ * 4. Strip incomplete HTML entities
12849
+ * 5. Extract body content (or use full string if no <body>)
12850
+ */
12851
+ function processPartialHtml(html) {
12852
+ let result = html;
12853
+ result = result.replace(/<[^>]*$/, "");
12854
+ result = result.replace(/<(style|script|head)\b[^>]*>[\s\S]*?<\/\1>/gi, "");
12855
+ result = result.replace(/<(style|script|head)\b[^>]*>[\s\S]*$/gi, "");
12856
+ result = result.replace(/&[a-zA-Z0-9#]*$/, "");
12857
+ const bodyMatch = result.match(/<body[^>]*>([\s\S]*)/i);
12858
+ if (bodyMatch) {
12859
+ result = bodyMatch[1];
12860
+ result = result.replace(/<\/body>[\s\S]*/i, "");
12861
+ }
12862
+ return result;
12863
+ }
12864
+ /** Builds the final sandbox document: the HTML with the CSS in its `<head>`. */
12865
+ function buildFinalFrameContent(html, css) {
12866
+ const withCss = css ? injectCssIntoHtml(html, css) : html;
12867
+ return /<head[\s>]/i.test(withCss) ? withCss : `<head></head>${withCss}`;
12868
+ }
12869
+ function injectCssIntoHtml(html, css) {
12870
+ const headCloseIdx = html.indexOf("</head>");
12871
+ if (headCloseIdx !== -1) return html.slice(0, headCloseIdx) + `<style>${css}</style>` + html.slice(headCloseIdx);
12872
+ return `<head><style>${css}</style></head>${html}`;
12873
+ }
12874
+
12875
+ //#endregion
12876
+ //#region ../../node_modules/.pnpm/@jetbrains+websandbox@1.1.3/node_modules/@jetbrains/websandbox/dist/websandbox.js
12877
+ var require_websandbox = /* @__PURE__ */ __commonJSMin(((exports, module) => {
12878
+ (function webpackUniversalModuleDefinition(root, factory) {
12879
+ if (typeof exports === "object" && typeof module === "object") module.exports = factory();
12880
+ else if (typeof define === "function" && define.amd) define([], factory);
12881
+ else if (typeof exports === "object") exports["Websandbox"] = factory();
12882
+ else root["Websandbox"] = factory();
12883
+ })(self, () => {
12884
+ return (() => {
12885
+ var __webpack_modules__ = { 466: ((module$1) => {
12886
+ 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";
12887
+ }) };
12888
+ var __webpack_module_cache__ = {};
12889
+ function __webpack_require__(moduleId) {
12890
+ var cachedModule = __webpack_module_cache__[moduleId];
12891
+ if (cachedModule !== void 0) return cachedModule.exports;
12892
+ var module$2 = __webpack_module_cache__[moduleId] = { exports: {} };
12893
+ __webpack_modules__[moduleId](module$2, module$2.exports, __webpack_require__);
12894
+ return module$2.exports;
12895
+ }
12896
+ __webpack_require__.n = (module$3) => {
12897
+ var getter = module$3 && module$3.__esModule ? () => module$3["default"] : () => module$3;
12898
+ __webpack_require__.d(getter, { a: getter });
12899
+ return getter;
12900
+ };
12901
+ __webpack_require__.d = (exports$1, definition) => {
12902
+ for (var key in definition) if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports$1, key)) Object.defineProperty(exports$1, key, {
12903
+ enumerable: true,
12904
+ get: definition[key]
12905
+ });
12906
+ };
12907
+ __webpack_require__.o = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop);
12908
+ __webpack_require__.r = (exports$2) => {
12909
+ if (typeof Symbol !== "undefined" && Symbol.toStringTag) Object.defineProperty(exports$2, Symbol.toStringTag, { value: "Module" });
12910
+ Object.defineProperty(exports$2, "__esModule", { value: true });
12911
+ };
12912
+ var __webpack_exports__ = {};
12913
+ (() => {
12914
+ "use strict";
12915
+ __webpack_require__.r(__webpack_exports__);
12916
+ __webpack_require__.d(__webpack_exports__, {
12917
+ BaseOptions: () => BaseOptions,
12918
+ "default": () => websandbox
12919
+ });
12920
+ const PATH_REG = /([.[\]:;'"\s])/;
12921
+ function splitPath(path) {
12922
+ const result = [];
12923
+ let lastEnd = 0;
12924
+ for (let i = 0; i < path.length; i++) {
12925
+ const char = path[i];
12926
+ if (PATH_REG.test(char) && path[i - 1] !== "\\") {
12927
+ result.push(path.substring(lastEnd, i));
12928
+ lastEnd = i + 1;
12929
+ }
12930
+ }
12931
+ result.push(path.substring(lastEnd, path.length));
12932
+ return result.filter((pathPart) => !!pathPart).map((pathPart) => pathPart.replace(/\\/g, ""));
12933
+ }
12934
+ /**
12935
+ * Extracts object property value by given path. Supports nested and array values: 'foo[0].bar'
12936
+ * @param {Object} object source object
12937
+ * @param {string} path path to value
12938
+ * @return {any | null} value by given path
12939
+ * */
12940
+ function propertyByPath(object, path) {
12941
+ return splitPath(path).reduce((acc, pathPart) => {
12942
+ if (acc) return acc[pathPart];
12943
+ return null;
12944
+ }, object);
12945
+ }
12946
+ const TYPE_MESSAGE = "message";
12947
+ const TYPE_RESPONSE = "response";
12948
+ const TYPE_SET_INTERFACE = "set-interface";
12949
+ const TYPE_SERVICE_MESSAGE = "service-message";
12950
+ const isIE11 = !!window.MSInputMethodContext && !!document.documentMode;
12951
+ const defaultOptions = { allowedSenderOrigin: void 0 };
12952
+ class Connection {
12953
+ constructor(postMessage, registerOnMessageListener, options = {}) {
12954
+ this.remote = {};
12955
+ this.serviceMethods = {};
12956
+ this.localApi = {};
12957
+ this.callbacks = {};
12958
+ this._resolveRemoteMethodsPromise = null;
12959
+ this.options = Object.assign(Object.assign({}, defaultOptions), options);
12960
+ this.incrementalID = Math.floor(Math.random() * 1e5);
12961
+ this.postMessage = postMessage;
12962
+ this.remoteMethodsWaitPromise = new Promise((resolve) => {
12963
+ this._resolveRemoteMethodsPromise = resolve;
12964
+ });
12965
+ registerOnMessageListener((e) => this.onMessageListener(e));
12966
+ }
12967
+ /**
12968
+ * Listens to remote messages. Calls local method if it is called outside or call stored callback if it is response.
12969
+ * @param e - onMessage event
12970
+ */
12971
+ onMessageListener(e) {
12972
+ const data = e.data;
12973
+ const { allowedSenderOrigin } = this.options;
12974
+ if (allowedSenderOrigin && e.origin !== allowedSenderOrigin && !isIE11) return;
12975
+ if (data.type === TYPE_RESPONSE) this.popCallback(data.callId, data.success, data.result);
12976
+ 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));
12977
+ else if (data.type === TYPE_SET_INTERFACE) {
12978
+ this.setInterface(data.apiMethods);
12979
+ this.responseOtherSide(data.callId);
12980
+ } 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));
12981
+ }
12982
+ postMessageToOtherSide(dataToPost) {
12983
+ this.postMessage(dataToPost, "*");
12984
+ }
12985
+ /**
12986
+ * Sets remote interface methods
12987
+ * @param remote - hash with keys of remote API methods. Values is ignored
12988
+ */
12989
+ setInterface(remoteMethods) {
12990
+ var _a;
12991
+ this.remote = {};
12992
+ remoteMethods.forEach((key) => {
12993
+ const parts = splitPath(key);
12994
+ let current = this.remote;
12995
+ for (let i = 0; i < parts.length - 1; i++) {
12996
+ const part = parts[i];
12997
+ if (!current[part] || typeof current[part] !== "object") current[part] = {};
12998
+ current = current[part];
12999
+ }
13000
+ current[parts[parts.length - 1]] = this.createMethodWrapper(key);
13001
+ });
13002
+ (_a = this._resolveRemoteMethodsPromise) === null || _a === void 0 || _a.call(this);
13003
+ }
13004
+ getMethodsFromInterface(api) {
13005
+ return Object.keys(api).reduce((acc, key) => {
13006
+ if (typeof api[key] === "object") acc.push(...this.getMethodsFromInterface(api[key]).map((subKey) => `${key}.${subKey}`));
13007
+ else acc.push(key);
13008
+ return acc;
13009
+ }, []);
13010
+ }
13011
+ setLocalApi(api) {
13012
+ return new Promise((resolve, reject) => {
13013
+ const id = this.registerCallback(resolve, reject);
13014
+ this.postMessageToOtherSide({
13015
+ callId: id,
13016
+ apiMethods: this.getMethodsFromInterface(api),
13017
+ type: TYPE_SET_INTERFACE
13018
+ });
13019
+ }).then(() => this.localApi = api);
13020
+ }
13021
+ setServiceMethods(api) {
13022
+ this.serviceMethods = api;
13023
+ }
13024
+ /**
13025
+ * Calls local method
13026
+ * @param methodName
13027
+ * @param args
13028
+ * @returns {Promise.<*>|string}
13029
+ */
13030
+ callLocalApi(methodName, args) {
13031
+ const method = propertyByPath(this.localApi, methodName);
13032
+ if (!method) throw new Error(`Local method "${methodName}" is not registered`);
13033
+ return Promise.resolve(method.call(this, ...args));
13034
+ }
13035
+ /**
13036
+ * Calls local method registered as "service method"
13037
+ * @param methodName
13038
+ * @param args
13039
+ * @returns {Promise.<*>}
13040
+ */
13041
+ callLocalServiceMethod(methodName, args) {
13042
+ const method = propertyByPath(this.serviceMethods, methodName);
13043
+ if (!method) throw new Error(`Service method ${methodName} is not registered`);
13044
+ return Promise.resolve(method.call(this, ...args));
13045
+ }
13046
+ /**
13047
+ * Wraps remote method with callback storing code
13048
+ * @param methodName - method to wrap
13049
+ * @returns {Function} - function to call as remote API interface
13050
+ */
13051
+ createMethodWrapper(methodName) {
13052
+ return (...args) => {
13053
+ return this.callRemoteMethod(methodName, ...args);
13054
+ };
13055
+ }
13056
+ /**
13057
+ * Calls other side with arguments provided
13058
+ * @param id
13059
+ * @param methodName
13060
+ * @param args
13061
+ */
13062
+ callRemoteMethod(methodName, ...args) {
13063
+ return new Promise((resolve, reject) => {
13064
+ const id = this.registerCallback(resolve, reject);
13065
+ this.postMessageToOtherSide({
13066
+ callId: id,
13067
+ methodName,
13068
+ type: TYPE_MESSAGE,
13069
+ arguments: args
13070
+ });
13071
+ });
13072
+ }
13073
+ /**
13074
+ * Calls remote service method
13075
+ * @param methodName
13076
+ * @param args
13077
+ * @returns {*}
13078
+ */
13079
+ callRemoteServiceMethod(methodName, ...args) {
13080
+ return new Promise((resolve, reject) => {
13081
+ const id = this.registerCallback(resolve, reject);
13082
+ this.postMessageToOtherSide({
13083
+ callId: id,
13084
+ methodName,
13085
+ type: TYPE_SERVICE_MESSAGE,
13086
+ arguments: args
13087
+ });
13088
+ });
13089
+ }
13090
+ /**
13091
+ * Respond to remote call
13092
+ * @param id - remote call ID
13093
+ * @param result - result to pass to calling function
13094
+ */
13095
+ responseOtherSide(id, result, success = true) {
13096
+ if (result instanceof Error) result = [...Object.keys(result), "message"].reduce((acc, it) => {
13097
+ acc[it] = result[it];
13098
+ return acc;
13099
+ }, {});
13100
+ const doPost = () => this.postMessage({
13101
+ callId: id,
13102
+ type: TYPE_RESPONSE,
13103
+ success,
13104
+ result
13105
+ }, "*");
13106
+ try {
13107
+ doPost();
13108
+ } catch (err) {
13109
+ console.error("Failed to post response, recovering...", err);
13110
+ if (err instanceof DOMException) {
13111
+ result = JSON.parse(JSON.stringify(result));
13112
+ doPost();
13113
+ }
13114
+ }
13115
+ }
13116
+ registerCallback(successCallback, failureCallback) {
13117
+ const id = (++this.incrementalID).toString();
13118
+ this.callbacks[id] = {
13119
+ successCallback,
13120
+ failureCallback
13121
+ };
13122
+ return id;
13123
+ }
13124
+ /**
13125
+ * Calls and delete stored callback
13126
+ * @param id - call id
13127
+ * @param success - was call successful
13128
+ * @param result - result of remote call
13129
+ */
13130
+ popCallback(id, success, result) {
13131
+ const callback = this.callbacks[id];
13132
+ if (!callback) return;
13133
+ if (success) callback.successCallback(result);
13134
+ else callback.failureCallback(result);
13135
+ delete this.callbacks[id];
13136
+ }
13137
+ }
13138
+ const connection = Connection;
13139
+ var index_js_lib_frame = __webpack_require__(466);
13140
+ var frame_default = /* @__PURE__ */ __webpack_require__.n(index_js_lib_frame);
13141
+ const BaseOptions = {
13142
+ frameContainer: "body",
13143
+ frameClassName: "websandbox__frame",
13144
+ frameSrc: null,
13145
+ frameContent: `
13146
+ <!DOCTYPE html>
13147
+ <html>
13148
+ <head><meta charset="UTF-8"></head>
13149
+ <body></body>
13150
+ </html>
13151
+ `,
13152
+ codeToRunBeforeInit: null,
13153
+ initialStyles: null,
13154
+ baseUrl: null,
13155
+ allowPointerLock: false,
13156
+ allowFullScreen: false,
13157
+ sandboxAdditionalAttributes: ""
13158
+ };
13159
+ class Websandbox {
13160
+ /**
13161
+ * Creates sandbox instancea
13162
+ * @param localApi Api of this side. Will be available for sandboxed code as remoteApi
13163
+ * @param options Options of created sandbox
13164
+ */
13165
+ static create(localApi, options = {}) {
13166
+ return new Websandbox(localApi, options);
13167
+ }
13168
+ /**
13169
+ * {Constructor}
13170
+ * @param localApi
13171
+ * @param options
13172
+ */
13173
+ constructor(localApi, options) {
13174
+ this.connection = null;
13175
+ this.removeMessageListener = () => {};
13176
+ this.validateOptions(options);
13177
+ this.options = Object.assign(Object.assign({}, BaseOptions), options);
13178
+ this.iframe = this.createIframe();
13179
+ this.promise = new Promise((resolve) => {
13180
+ this.connection = new connection(this.iframe.contentWindow.postMessage.bind(this.iframe.contentWindow), (listener) => {
13181
+ const sourceCheckListener = (event) => {
13182
+ if (event.source !== this.iframe.contentWindow) return;
13183
+ return listener(event);
13184
+ };
13185
+ window.addEventListener("message", sourceCheckListener);
13186
+ this.removeMessageListener = () => window.removeEventListener("message", sourceCheckListener);
13187
+ }, { allowedSenderOrigin: "null" });
13188
+ this.connection.setServiceMethods({ iframeInitialized: () => {
13189
+ return this.connection.setLocalApi(localApi).then(() => resolve(this));
13190
+ } });
13191
+ });
13192
+ }
13193
+ validateOptions(options) {
13194
+ var _a;
13195
+ 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");
13196
+ 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.");
13197
+ }
13198
+ _prepareFrameContent(options) {
13199
+ var _a, _b, _c;
13200
+ let frameContent = (_a = options.frameContent) !== null && _a !== void 0 ? _a : "";
13201
+ if (options.codeToRunBeforeInit) frameContent = (_b = frameContent.replace("<head>", `<head>\n<script>${options.codeToRunBeforeInit}<\/script>`)) !== null && _b !== void 0 ? _b : "";
13202
+ frameContent = (_c = frameContent.replace("<head>", `<head>\n<script>${frame_default()}<\/script>`)) !== null && _c !== void 0 ? _c : "";
13203
+ if (options.initialStyles) frameContent = frameContent.replace("</head>", `<style>${options.initialStyles}</style>\n</head>`);
13204
+ if (options.baseUrl) frameContent = frameContent.replace("<head>", `<head>\n<base target="_parent" href="${options.baseUrl}"/>`);
13205
+ return frameContent;
13206
+ }
13207
+ createIframe() {
13208
+ var _a;
13209
+ const containerSelector = this.options.frameContainer;
13210
+ const container = typeof containerSelector === "string" ? document.querySelector(containerSelector) : containerSelector;
13211
+ if (!container) throw new Error("Websandbox: Cannot find container for sandbox " + container);
13212
+ const frame = document.createElement("iframe");
13213
+ frame.sandbox = `allow-scripts ${this.options.sandboxAdditionalAttributes}`;
13214
+ frame.allow = `${this.options.allowAdditionalAttributes}`;
13215
+ frame.className = (_a = this.options.frameClassName) !== null && _a !== void 0 ? _a : "";
13216
+ if (this.options.allowFullScreen) frame.allowFullscreen = true;
13217
+ if (this.options.frameSrc) {
13218
+ frame.src = this.options.frameSrc;
13219
+ container.appendChild(frame);
13220
+ return frame;
13221
+ }
13222
+ frame.setAttribute("srcdoc", this._prepareFrameContent(this.options));
13223
+ container.appendChild(frame);
13224
+ return frame;
13225
+ }
13226
+ destroy() {
13227
+ this.iframe.remove();
13228
+ this.removeMessageListener();
13229
+ }
13230
+ _runCode(code) {
13231
+ return this.connection.callRemoteServiceMethod("runCode", code);
13232
+ }
13233
+ _runFunction(fn) {
13234
+ return this._runCode(`(${fn.toString()})()`);
13235
+ }
13236
+ run(codeOrFunction) {
13237
+ if (codeOrFunction.name) return this._runFunction(codeOrFunction);
13238
+ return this._runCode(codeOrFunction);
13239
+ }
13240
+ importScript(path) {
13241
+ return this.connection.callRemoteServiceMethod("importScript", path);
13242
+ }
13243
+ injectStyle(style) {
13244
+ return this.connection.callRemoteServiceMethod("injectStyle", style);
13245
+ }
13246
+ }
13247
+ const websandbox = Websandbox;
13248
+ })();
13249
+ return __webpack_exports__;
13250
+ })();
13251
+ });
13252
+ }));
13253
+
13254
+ //#endregion
13255
+ //#region src/open-generative-ui/websandbox.ts
13256
+ /**
13257
+ * Imports `@jetbrains/websandbox` on demand. The import is dynamic because
13258
+ * the package touches `self` when it loads, which breaks server rendering.
13259
+ */
13260
+ const loadWebsandbox = async () => {
13261
+ const defaultExport = (await Promise.resolve().then(() => /* @__PURE__ */ __toESM(require_websandbox(), 1))).default;
13262
+ return "default" in defaultExport ? defaultExport.default : defaultExport;
13263
+ };
13264
+
13265
+ //#endregion
13266
+ //#region src/open-generative-ui/controller.ts
13267
+ /** Non-immediate content updates reach the sandbox at most this often. */
13268
+ const OPEN_GENERATIVE_UI_THROTTLE_MS = 1e3;
13269
+ const DEFAULT_HEIGHT = 200;
13270
+ const HIDE_SCROLLBARS = `
13271
+ var s = document.createElement('style');
13272
+ s.textContent = 'html, body { overflow: hidden !important; }';
13273
+ document.head.appendChild(s);
13274
+ `;
13275
+ const HIDE_SCROLLBARS_STYLE = "<style>html, body { overflow: hidden !important; }</style>";
13276
+ const MEASURE_HEIGHT = `
13277
+ (function() {
13278
+ var s = document.createElement('style');
13279
+ s.textContent = 'body { height: auto !important; min-height: 0 !important; }';
13280
+ document.head.appendChild(s);
13281
+ var h = document.body.scrollHeight;
13282
+ var cs = getComputedStyle(document.body);
13283
+ h += parseFloat(cs.marginTop) || 0;
13284
+ h += parseFloat(cs.marginBottom) || 0;
13285
+ s.remove();
13286
+ parent.postMessage({ type: "__ck_resize", height: Math.ceil(h) }, "*");
13287
+ })();
13288
+ `;
13289
+ function deriveContent(content) {
13290
+ var _content$html;
13291
+ const html = ((_content$html = content.html) === null || _content$html === void 0 ? void 0 : _content$html.join("")) || void 0;
13292
+ const css = content.cssComplete ? content.css : void 0;
13293
+ if (content.htmlComplete) return {
13294
+ fullHtml: html,
13295
+ css,
13296
+ previewStyles: ""
13297
+ };
13298
+ const previewBody = html && content.cssComplete ? processPartialHtml(html) : void 0;
13299
+ return {
13300
+ css,
13301
+ previewBody: (previewBody === null || previewBody === void 0 ? void 0 : previewBody.trim()) ? previewBody : void 0,
13302
+ previewStyles: html ? extractCompleteStyles(html) : ""
13303
+ };
13304
+ }
13305
+ function prepareIframe(iframe, testId) {
13306
+ iframe.setAttribute("data-testid", testId);
13307
+ iframe.style.width = "100%";
13308
+ iframe.style.height = "100%";
13309
+ iframe.style.border = "none";
13310
+ iframe.style.backgroundColor = "transparent";
13311
+ }
13312
+ function logLoadError(error) {
13313
+ console.error("[OpenGenerativeUI] Failed to load sandbox module:", error);
13314
+ }
13315
+ function sameFunctions(a, b) {
13316
+ return a.length === b.length && a.every((fn, i) => fn.name === b[i].name && fn.handler === b[i].handler);
13317
+ }
13318
+ var _load = /* @__PURE__ */ new WeakMap();
13319
+ var _listeners = /* @__PURE__ */ new WeakMap();
13320
+ var _content = /* @__PURE__ */ new WeakMap();
13321
+ var _latest = /* @__PURE__ */ new WeakMap();
13322
+ var _derived = /* @__PURE__ */ new WeakMap();
13323
+ var _timer = /* @__PURE__ */ new WeakMap();
13324
+ var _host = /* @__PURE__ */ new WeakMap();
13325
+ var _functions = /* @__PURE__ */ new WeakMap();
13326
+ var _localApi = /* @__PURE__ */ new WeakMap();
13327
+ var _preview = /* @__PURE__ */ new WeakMap();
13328
+ var _final = /* @__PURE__ */ new WeakMap();
13329
+ var _measuredHeight = /* @__PURE__ */ new WeakMap();
13330
+ var _state = /* @__PURE__ */ new WeakMap();
13331
+ var _OpenGenerativeUIController_brand = /* @__PURE__ */ new WeakSet();
13332
+ /**
13333
+ * Runs Open Generative UI content in websandbox iframes inside a host element.
13334
+ *
13335
+ * Give it content snapshots with `setContent()` and a host element with
13336
+ * `setHost()`. It throttles the snapshots, streams a preview while HTML
13337
+ * arrives, swaps in the final sandbox once HTML is complete, runs
13338
+ * `jsFunctions` and `jsExpressions` in it once each, and measures the final
13339
+ * height. Frameworks render the container from `getState()` and re-render
13340
+ * when `subscribe()` notifies.
13341
+ *
13342
+ * @example
13343
+ * ```ts
13344
+ * const controller = new ɵOpenGenerativeUIController();
13345
+ * controller.subscribe(() => render(controller.getState()));
13346
+ * controller.setContent(content);
13347
+ * controller.setHost(containerElement);
13348
+ * // On unmount:
13349
+ * controller.destroy();
13350
+ * ```
13351
+ */
13352
+ var OpenGenerativeUIController = class {
13353
+ constructor(options = {}) {
13354
+ var _options$loadWebsandb;
13355
+ _classPrivateMethodInitSpec(this, _OpenGenerativeUIController_brand);
13356
+ _classPrivateFieldInitSpec(this, _load, void 0);
13357
+ _classPrivateFieldInitSpec(this, _listeners, /* @__PURE__ */ new Set());
13358
+ _classPrivateFieldInitSpec(this, _content, void 0);
13359
+ _classPrivateFieldInitSpec(this, _latest, void 0);
13360
+ _classPrivateFieldInitSpec(this, _derived, { previewStyles: "" });
13361
+ _classPrivateFieldInitSpec(this, _timer, void 0);
13362
+ _classPrivateFieldInitSpec(this, _host, null);
13363
+ _classPrivateFieldInitSpec(this, _functions, []);
13364
+ _classPrivateFieldInitSpec(this, _localApi, {});
13365
+ _classPrivateFieldInitSpec(this, _preview, void 0);
13366
+ _classPrivateFieldInitSpec(this, _final, void 0);
13367
+ _classPrivateFieldInitSpec(this, _measuredHeight, void 0);
13368
+ _classPrivateFieldInitSpec(this, _state, {
13369
+ phase: "placeholder",
13370
+ generating: true,
13371
+ height: DEFAULT_HEIGHT
13372
+ });
13373
+ _defineProperty(
13374
+ this,
13375
+ /** The current state. The same object until something changes. */
13376
+ "getState",
13377
+ () => _classPrivateFieldGet2(_state, this)
13378
+ );
13379
+ _defineProperty(
13380
+ this,
13381
+ /** Calls `listener` when the state changes. Returns the unsubscribe function. */
13382
+ "subscribe",
13383
+ (listener) => {
13384
+ _classPrivateFieldGet2(_listeners, this).add(listener);
13385
+ return () => {
13386
+ _classPrivateFieldGet2(_listeners, this).delete(listener);
13387
+ };
13388
+ }
13389
+ );
13390
+ _classPrivateFieldSet2(_load, this, (_options$loadWebsandb = options.loadWebsandbox) !== null && _options$loadWebsandb !== void 0 ? _options$loadWebsandb : loadWebsandbox);
13391
+ }
13392
+ /**
13393
+ * Sets the latest content snapshot. The first snapshot and snapshots that
13394
+ * finish a stage apply at once; others apply at most once per second.
13395
+ */
13396
+ setContent(content) {
13397
+ _classPrivateFieldSet2(_latest, this, content);
13398
+ if (_classPrivateFieldGet2(_content, this) === void 0 || shouldFlushImmediately(_classPrivateFieldGet2(_content, this), content)) {
13399
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _clearTimer).call(this);
13400
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _commit).call(this, content);
13401
+ return;
13402
+ }
13403
+ if (content === _classPrivateFieldGet2(_content, this) || _classPrivateFieldGet2(_timer, this) !== void 0) return;
13404
+ _classPrivateFieldSet2(_timer, this, setTimeout(() => {
13405
+ _classPrivateFieldSet2(_timer, this, void 0);
13406
+ if (_classPrivateFieldGet2(_latest, this)) _assertClassBrand(_OpenGenerativeUIController_brand, this, _commit).call(this, _classPrivateFieldGet2(_latest, this));
13407
+ }, OPEN_GENERATIVE_UI_THROTTLE_MS));
13408
+ }
13409
+ /** Sets the element the sandbox iframes go into. `null` removes them. */
13410
+ setHost(host) {
13411
+ if (host === _classPrivateFieldGet2(_host, this)) return;
13412
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _destroyPreview).call(this);
13413
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _destroyFinal).call(this);
13414
+ _classPrivateFieldSet2(_host, this, host);
13415
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _reconcile).call(this);
13416
+ }
13417
+ /**
13418
+ * Sets the host functions sandboxed code can call. A change recreates the
13419
+ * final sandbox.
13420
+ */
13421
+ setSandboxFunctions(functions) {
13422
+ if (sameFunctions(functions, _classPrivateFieldGet2(_functions, this))) return;
13423
+ _classPrivateFieldSet2(_functions, this, functions);
13424
+ const localApi = {};
13425
+ for (const fn of functions) localApi[fn.name] = fn.handler;
13426
+ _classPrivateFieldSet2(_localApi, this, localApi);
13427
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _reconcile).call(this);
13428
+ }
13429
+ /**
13430
+ * Removes the sandboxes and stops pending work. A later `setHost()`
13431
+ * starts again from the current content.
13432
+ */
13433
+ destroy() {
13434
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _clearTimer).call(this);
13435
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _destroyPreview).call(this);
13436
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _destroyFinal).call(this);
13437
+ _classPrivateFieldSet2(_host, this, null);
13438
+ }
13439
+ };
13440
+ function _commit(content) {
13441
+ if (content === _classPrivateFieldGet2(_content, this)) return;
13442
+ _classPrivateFieldSet2(_content, this, content);
13443
+ _classPrivateFieldSet2(_derived, this, deriveContent(content));
13444
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _reconcile).call(this);
13445
+ }
13446
+ function _reconcile() {
13447
+ const host = _classPrivateFieldGet2(_host, this);
13448
+ const content = _classPrivateFieldGet2(_content, this);
13449
+ const derived = _classPrivateFieldGet2(_derived, this);
13450
+ if (host && content) if (derived.fullHtml) {
13451
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _destroyPreview).call(this);
13452
+ const frameContent = buildFinalFrameContent(derived.fullHtml, derived.css);
13453
+ let final = _classPrivateFieldGet2(_final, this);
13454
+ if ((final === null || final === void 0 ? void 0 : final.frameContent) !== frameContent || final.localApi !== _classPrivateFieldGet2(_localApi, this)) {
13455
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _destroyFinal).call(this);
13456
+ final = _classPrivateFieldSet2(_final, this, _assertClassBrand(_OpenGenerativeUIController_brand, this, _createFinal).call(this, host, frameContent));
13457
+ }
13458
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _runScripts).call(this, final, content);
13459
+ } else {
13460
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _destroyFinal).call(this);
13461
+ if (derived.previewBody) {
13462
+ var _classPrivateFieldGet2$1;
13463
+ (_classPrivateFieldGet2$1 = _classPrivateFieldGet2(_preview, this)) !== null && _classPrivateFieldGet2$1 !== void 0 || _classPrivateFieldSet2(_preview, this, _assertClassBrand(_OpenGenerativeUIController_brand, this, _createPreview).call(this, host));
13464
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _writePreview).call(this);
13465
+ } else _assertClassBrand(_OpenGenerativeUIController_brand, this, _destroyPreview).call(this);
13466
+ }
13467
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _updateState).call(this);
13468
+ }
13469
+ function _createPreview(host) {
13470
+ const slot = {
13471
+ ready: false,
13472
+ cancelled: false
13473
+ };
13474
+ _classPrivateFieldGet2(_load, this).call(this).then((Websandbox) => {
13475
+ if (slot.cancelled) return;
13476
+ const sandbox = Websandbox.create({}, {
13477
+ frameContainer: host,
13478
+ frameContent: "<head></head><body></body>",
13479
+ allowAdditionalAttributes: ""
13480
+ });
13481
+ slot.sandbox = sandbox;
13482
+ prepareIframe(sandbox.iframe, "open-generative-ui-preview-sandbox");
13483
+ sandbox.promise.then(() => {
13484
+ if (slot.cancelled) return;
13485
+ slot.ready = true;
13486
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _writePreview).call(this);
13487
+ });
13488
+ }).catch(logLoadError);
13489
+ return slot;
13490
+ }
13491
+ function _writePreview() {
13492
+ const slot = _classPrivateFieldGet2(_preview, this);
13493
+ if (!(slot === null || slot === void 0 ? void 0 : slot.sandbox) || !slot.ready) return;
13494
+ const { css, previewStyles, previewBody } = _classPrivateFieldGet2(_derived, this);
13495
+ const head = HIDE_SCROLLBARS_STYLE + (css ? `<style>${css}</style>` : "") + previewStyles;
13496
+ if (head !== slot.head) {
13497
+ slot.head = head;
13498
+ slot.sandbox.run(`document.head.innerHTML = ${JSON.stringify(head)}`);
13499
+ }
13500
+ if (previewBody && previewBody !== slot.body) {
13501
+ slot.body = previewBody;
13502
+ slot.sandbox.run(`document.body.innerHTML = ${JSON.stringify(previewBody)}`);
13503
+ }
13504
+ }
13505
+ function _createFinal(host, frameContent) {
13506
+ const slot = {
13507
+ frameContent,
13508
+ localApi: _classPrivateFieldGet2(_localApi, this),
13509
+ ready: false,
13510
+ cancelled: false,
13511
+ queue: [],
13512
+ jsFunctionsInjected: false,
13513
+ executedExpressions: 0,
13514
+ heightRequested: false
13515
+ };
13516
+ _classPrivateFieldGet2(_load, this).call(this).then((Websandbox) => {
13517
+ if (slot.cancelled) return;
13518
+ const sandbox = Websandbox.create(slot.localApi, {
13519
+ frameContainer: host,
13520
+ frameContent,
13521
+ allowAdditionalAttributes: ""
13522
+ });
13523
+ slot.sandbox = sandbox;
13524
+ prepareIframe(sandbox.iframe, "open-generative-ui-final-sandbox");
13525
+ sandbox.promise.then(() => {
13526
+ if (slot.cancelled) return;
13527
+ slot.ready = true;
13528
+ sandbox.run(HIDE_SCROLLBARS);
13529
+ const queue = slot.queue;
13530
+ slot.queue = [];
13531
+ for (const code of queue) sandbox.run(code);
13532
+ });
13533
+ }).catch(logLoadError);
13534
+ return slot;
13535
+ }
13536
+ /** Runs new `jsFunctions`, new `jsExpressions`, and the height measurement. */
13537
+ function _runScripts(slot, content) {
13538
+ var _content$jsExpression;
13539
+ if (content.jsFunctions && !slot.jsFunctionsInjected) {
13540
+ slot.jsFunctionsInjected = true;
13541
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _runOrQueue).call(this, slot, content.jsFunctions);
13542
+ }
13543
+ const expressions = (_content$jsExpression = content.jsExpressions) !== null && _content$jsExpression !== void 0 ? _content$jsExpression : [];
13544
+ if (expressions.length > slot.executedExpressions) {
13545
+ const newExpressions = expressions.slice(slot.executedExpressions);
13546
+ slot.executedExpressions = expressions.length;
13547
+ const sandbox = slot.sandbox;
13548
+ if (slot.ready && sandbox) (async () => {
13549
+ for (const expression of newExpressions) await sandbox.run(expression);
13550
+ })();
13551
+ else slot.queue.push(...newExpressions);
13552
+ }
13553
+ if (content.generating === false && !slot.heightRequested) {
13554
+ slot.heightRequested = true;
13555
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _listenForHeight).call(this, slot);
13556
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _runOrQueue).call(this, slot, MEASURE_HEIGHT);
13557
+ }
13558
+ }
13559
+ function _runOrQueue(slot, code) {
13560
+ if (slot.ready && slot.sandbox) slot.sandbox.run(code);
13561
+ else slot.queue.push(code);
13562
+ }
13563
+ function _listenForHeight(slot) {
13564
+ if (typeof window === "undefined") return;
13565
+ const onMessage = (event) => {
13566
+ var _slot$stopHeightListe;
13567
+ const data = event.data;
13568
+ 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;
13569
+ (_slot$stopHeightListe = slot.stopHeightListener) === null || _slot$stopHeightListe === void 0 || _slot$stopHeightListe.call(slot);
13570
+ _classPrivateFieldSet2(_measuredHeight, this, data.height);
13571
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _updateState).call(this);
13572
+ };
13573
+ window.addEventListener("message", onMessage);
13574
+ slot.stopHeightListener = () => {
13575
+ window.removeEventListener("message", onMessage);
13576
+ slot.stopHeightListener = void 0;
13577
+ };
13578
+ }
13579
+ function _destroyPreview() {
13580
+ var _slot$sandbox;
13581
+ const slot = _classPrivateFieldGet2(_preview, this);
13582
+ if (!slot) return;
13583
+ slot.cancelled = true;
13584
+ (_slot$sandbox = slot.sandbox) === null || _slot$sandbox === void 0 || _slot$sandbox.destroy();
13585
+ _classPrivateFieldSet2(_preview, this, void 0);
13586
+ }
13587
+ function _destroyFinal() {
13588
+ var _slot$stopHeightListe2, _slot$sandbox2;
13589
+ const slot = _classPrivateFieldGet2(_final, this);
13590
+ if (!slot) return;
13591
+ slot.cancelled = true;
13592
+ (_slot$stopHeightListe2 = slot.stopHeightListener) === null || _slot$stopHeightListe2 === void 0 || _slot$stopHeightListe2.call(slot);
13593
+ (_slot$sandbox2 = slot.sandbox) === null || _slot$sandbox2 === void 0 || _slot$sandbox2.destroy();
13594
+ _classPrivateFieldSet2(_final, this, void 0);
13595
+ _classPrivateFieldSet2(_measuredHeight, this, void 0);
13596
+ }
13597
+ function _clearTimer() {
13598
+ if (_classPrivateFieldGet2(_timer, this) === void 0) return;
13599
+ clearTimeout(_classPrivateFieldGet2(_timer, this));
13600
+ _classPrivateFieldSet2(_timer, this, void 0);
13601
+ }
13602
+ function _updateState() {
13603
+ var _this$content, _ref, _this$measuredHeight;
13604
+ const content = (_this$content = _classPrivateFieldGet2(_content, this)) !== null && _this$content !== void 0 ? _this$content : {};
13605
+ const derived = _classPrivateFieldGet2(_derived, this);
13606
+ const next = {
13607
+ phase: derived.fullHtml ? "final" : derived.previewBody ? "preview" : "placeholder",
13608
+ generating: content.generating !== false,
13609
+ height: (_ref = (_this$measuredHeight = _classPrivateFieldGet2(_measuredHeight, this)) !== null && _this$measuredHeight !== void 0 ? _this$measuredHeight : content.initialHeight) !== null && _ref !== void 0 ? _ref : DEFAULT_HEIGHT
13610
+ };
13611
+ const current = _classPrivateFieldGet2(_state, this);
13612
+ if (next.phase === current.phase && next.generating === current.generating && next.height === current.height) return;
13613
+ _classPrivateFieldSet2(_state, this, next);
13614
+ for (const listener of _classPrivateFieldGet2(_listeners, this)) listener();
13615
+ }
13616
+
11033
13617
  //#endregion
11034
13618
  exports.A2UI_FENCE_LANGUAGE = A2UI_FENCE_LANGUAGE;
11035
13619
  exports.AgentRegistry = AgentRegistry;
11036
13620
  exports.AgentThreadLockedError = AgentThreadLockedError;
11037
13621
  exports.ContextStore = ContextStore;
13622
+ exports.CopilotChatDefaultLabels = CopilotChatDefaultLabels;
11038
13623
  exports.CopilotKitCore = CopilotKitCore;
11039
13624
  exports.CopilotKitCoreErrorCode = CopilotKitCoreErrorCode;
11040
13625
  exports.CopilotKitCoreRuntimeConnectionStatus = CopilotKitCoreRuntimeConnectionStatus;
11041
13626
  exports.CopilotKitHeaderResolutionError = CopilotKitHeaderResolutionError;
13627
+ exports.DEFAULT_OPEN_GENERATIVE_UI_DESIGN_SKILL = DEFAULT_OPEN_GENERATIVE_UI_DESIGN_SKILL;
13628
+ exports.GENERATE_SANDBOXED_UI_TOOL_NAME = GENERATE_SANDBOXED_UI_TOOL_NAME;
11042
13629
  exports.INSPECTOR_THREAD_BRIDGE_PLUGIN_ID = INSPECTOR_THREAD_BRIDGE_PLUGIN_ID;
13630
+ exports.INTERRUPT_EVENT_NAME = INTERRUPT_EVENT_NAME;
11043
13631
  exports.IntelligenceAgent = IntelligenceAgent;
11044
13632
  exports.MEMORY_ERROR_REGISTRY = MEMORY_ERROR_REGISTRY;
11045
13633
  exports.MemoryError = MemoryError;
13634
+ exports.OPEN_GENERATIVE_UI_ACTIVITY_TYPE = OPEN_GENERATIVE_UI_ACTIVITY_TYPE;
11046
13635
  exports.ProxiedCopilotRuntimeAgent = ProxiedCopilotRuntimeAgent;
11047
13636
  exports.RunHandler = RunHandler;
11048
13637
  exports.StateManager = StateManager;
11049
13638
  exports.SuggestionEngine = SuggestionEngine;
11050
13639
  exports.ToolCallStatus = ToolCallStatus;
13640
+ exports.TranscriptionError = TranscriptionError;
13641
+ exports.TranscriptionErrorCode = _copilotkit_shared.TranscriptionErrorCode;
11051
13642
  exports.WebMCPRegistry = WebMCPRegistry;
11052
13643
  exports.classifySurfaceCards = classifySurfaceCards;
11053
13644
  exports.completePartialMarkdown = completePartialMarkdown;
@@ -11078,7 +13669,6 @@ exports.onInspectorActiveThread = onInspectorActiveThread;
11078
13669
  exports.onInspectorStopViewing = onInspectorStopViewing;
11079
13670
  exports.onInspectorViewThread = onInspectorViewThread;
11080
13671
  exports.onInspectorViewThreadResult = onInspectorViewThreadResult;
11081
- exports.parseMarkdown = parseMarkdown;
11082
13672
  exports.parseToolArguments = parseToolArguments;
11083
13673
  exports.prepareSurfaceOperations = prepareSurfaceOperations;
11084
13674
  exports.props = props;
@@ -11088,28 +13678,62 @@ exports.splitA2UIMarkdown = splitA2UIMarkdown;
11088
13678
  exports.ɵCOPILOTKIT_FEATURES = ɵCOPILOTKIT_FEATURES;
11089
13679
  exports.ɵInterruptState = ɵInterruptState;
11090
13680
  exports.ɵMAX_SOCKET_RETRIES = ɵMAX_SOCKET_RETRIES;
13681
+ exports.ɵOpenGenerativeUIController = OpenGenerativeUIController;
11091
13682
  exports.ɵRUNTIME_PROBE_TIMEOUT_MS = ɵRUNTIME_PROBE_TIMEOUT_MS;
11092
13683
  exports.ɵTHREAD_REQUEST_TIMEOUT_MS = ɵTHREAD_REQUEST_TIMEOUT_MS;
11093
13684
  exports.ɵclearAgentInterruptState = ɵclearAgentInterruptState;
13685
+ exports.ɵcomposerButtonState = ɵcomposerButtonState;
13686
+ exports.ɵcopilotIconSvgAttributes = ɵcopilotIconSvgAttributes;
13687
+ exports.ɵcopilotIcons = ɵcopilotIcons;
13688
+ exports.ɵcountFailedToolCalls = countFailedToolCalls;
11094
13689
  exports.ɵcreateMemoryStore = createMemoryStore;
11095
13690
  exports.ɵcreateThreadSelectors = ɵcreateThreadSelectors;
11096
13691
  exports.ɵcreateThreadStore = createThreadStore;
13692
+ exports.ɵdeduplicateMessages = ɵdeduplicateMessages;
13693
+ exports.ɵextractCompleteStyles = extractCompleteStyles;
13694
+ exports.ɵformatCountLabel = ɵformatCountLabel;
13695
+ exports.ɵformatLabel = ɵformatLabel;
13696
+ exports.ɵformatReasoningDuration = formatReasoningDuration;
13697
+ exports.ɵformatToolNames = formatToolNames;
13698
+ exports.ɵformatWorkDuration = formatWorkDuration;
11097
13699
  exports.ɵgetAgentInterruptState = ɵgetAgentInterruptState;
13700
+ exports.ɵgetArgumentPreview = getArgumentPreview;
13701
+ exports.ɵgetLatestTurnKey = getLatestTurnKey;
13702
+ exports.ɵgetToolCallLayouts = getToolCallLayouts;
13703
+ exports.ɵgetToolCallPreview = getToolCallPreview;
13704
+ exports.ɵgetToolCallRendererNames = getToolCallRendererNames;
13705
+ exports.ɵgetToolCallRowStatus = getToolCallRowStatus;
13706
+ exports.ɵgetToolResults = getToolResults;
13707
+ exports.ɵgetTurnWork = getTurnWork;
13708
+ exports.ɵgetWorkOpenState = getWorkOpenState;
11098
13709
  exports.ɵisCopilotKitFeature = ɵisCopilotKitFeature;
11099
13710
  exports.ɵisHttpAgent = ɵisHttpAgent;
11100
13711
  exports.ɵisRetryableMemoryStatus = isRetryableStatus;
13712
+ exports.ɵisTurnWorkOpen = isTurnWorkOpen;
13713
+ exports.ɵisTurnWorking = isTurnWorking;
11101
13714
  exports.ɵjoinPhoenixChannel$ = ɵjoinPhoenixChannel$;
13715
+ exports.ɵloadWebsandbox = loadWebsandbox;
11102
13716
  exports.ɵmapMemoryMetadataEvent = ɵmapMemoryMetadataEvent;
11103
13717
  exports.ɵmemoryAdapterEvents = ɵmemoryAdapterEvents;
11104
13718
  exports.ɵmemoryDomainEvents = ɵmemoryDomainEvents;
11105
13719
  exports.ɵmemoryReducer = ɵmemoryReducer;
11106
13720
  exports.ɵmemoryRestEvents = ɵmemoryRestEvents;
13721
+ exports.ɵmessagesFingerprint = ɵmessagesFingerprint;
11107
13722
  exports.ɵobservePhoenixEvent$ = ɵobservePhoenixEvent$;
11108
13723
  exports.ɵobservePhoenixJoinOutcome$ = ɵobservePhoenixJoinOutcome$;
11109
13724
  exports.ɵobservePhoenixSocketHealth$ = ɵobservePhoenixSocketHealth$;
11110
13725
  exports.ɵobservePhoenixSocketSignals$ = ɵobservePhoenixSocketSignals$;
11111
13726
  exports.ɵphoenixChannel$ = ɵphoenixChannel$;
11112
13727
  exports.ɵphoenixSocket$ = ɵphoenixSocket$;
13728
+ exports.ɵpluralize = pluralize;
13729
+ exports.ɵprocessPartialHtml = processPartialHtml;
13730
+ exports.ɵrecordWorkTime = recordWorkTime;
13731
+ exports.ɵresolveActivityRenderer = ɵresolveActivityRenderer;
13732
+ exports.ɵresolveComposerKey = ɵresolveComposerKey;
13733
+ exports.ɵresolveCustomMessageRenderers = ɵresolveCustomMessageRenderers;
13734
+ exports.ɵresolveLicenseState = ɵresolveLicenseState;
13735
+ exports.ɵresolveThreadsLicense = ɵresolveThreadsLicense;
13736
+ exports.ɵresolveToolCallRenderer = ɵresolveToolCallRenderer;
11113
13737
  exports.ɵselectFetchMoreError = ɵselectFetchMoreError;
11114
13738
  exports.ɵselectHasNextPage = ɵselectHasNextPage;
11115
13739
  exports.ɵselectIsFetchingNextPage = ɵselectIsFetchingNextPage;
@@ -11123,7 +13747,10 @@ exports.ɵselectMemoriesRealtimeStatus = ɵselectMemoriesRealtimeStatus;
11123
13747
  exports.ɵselectThreads = ɵselectThreads;
11124
13748
  exports.ɵselectThreadsError = ɵselectThreadsError;
11125
13749
  exports.ɵselectThreadsIsLoading = ɵselectThreadsIsLoading;
13750
+ exports.ɵstringifyToolCallPayload = stringifyToolCallPayload;
11126
13751
  exports.ɵthreadAdapterEvents = ɵthreadAdapterEvents;
13752
+ exports.ɵtranscribeAudio = ɵtranscribeAudio;
13753
+ exports.ɵtranscriptionErrorMessageKey = ɵtranscriptionErrorMessageKey;
11127
13754
  exports.ɵwithHeaderDefaults = ɵwithHeaderDefaults;
11128
13755
  });
11129
13756
  //# sourceMappingURL=index.umd.js.map