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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -5,9 +5,8 @@ let _copilotkit_shared = require("@copilotkit/shared");
5
5
  let rxjs = require("rxjs");
6
6
  let rxjs_operators = require("rxjs/operators");
7
7
  let phoenix = require("phoenix");
8
- let zod_to_json_schema = require("zod-to-json-schema");
9
8
  let _copilotkit_learning = require("@copilotkit/learning");
10
- let marked = require("marked");
9
+ let jsonrepair = require("jsonrepair");
11
10
 
12
11
  //#region src/utils/http-agent.ts
13
12
  /**
@@ -1765,6 +1764,20 @@ function isAbortError$1(error) {
1765
1764
  return typeof message === "string" && ABORT_MESSAGES.has(message);
1766
1765
  }
1767
1766
 
1767
+ //#endregion
1768
+ //#region src/utils/shallow-equal.ts
1769
+ /**
1770
+ * True when both records have the same own keys and each key holds the same
1771
+ * value (compared with `Object.is`). Key order does not matter. Nested
1772
+ * objects are compared by reference, not by content.
1773
+ */
1774
+ function shallowEqualRecord(a, b) {
1775
+ if (a === b) return true;
1776
+ const aKeys = Object.keys(a);
1777
+ if (aKeys.length !== Object.keys(b).length) return false;
1778
+ return aKeys.every((key) => Object.prototype.hasOwnProperty.call(b, key) && Object.is(a[key], b[key]));
1779
+ }
1780
+
1768
1781
  //#endregion
1769
1782
  //#region src/utils/runtime-request.ts
1770
1783
  const RUNTIME_REQUEST_WATCHDOG_MS = 1e4;
@@ -1867,13 +1880,6 @@ function isPromiseLike(value) {
1867
1880
  function normalizeHeaders(headers) {
1868
1881
  return Object.fromEntries(Object.entries(headers).filter((entry) => entry[1] != null));
1869
1882
  }
1870
- /** Same keys, same values (order-independent). */
1871
- function shallowEqualRecord(a, b) {
1872
- const aKeys = Object.keys(a);
1873
- const bKeys = Object.keys(b);
1874
- if (aKeys.length !== bKeys.length) return false;
1875
- return aKeys.every((key) => a[key] === b[key]);
1876
- }
1877
1883
  function isHeaderRecordInput(value) {
1878
1884
  return typeof value === "object" && value !== null && !Array.isArray(value);
1879
1885
  }
@@ -2042,6 +2048,13 @@ const RUNTIME_ENTITLEMENT_RETRY_DELAY_MS = 5e3;
2042
2048
  var AgentRegistry = class {
2043
2049
  _agents = {};
2044
2050
  localAgents = {};
2051
+ /**
2052
+ * Whether `onAgentsChanged` has run since {@link initialize}. Constructor
2053
+ * agents are not announced, so the first `setAgents__unsafe_dev_only` with
2054
+ * the same agents must still announce them (core subscribes to agents on
2055
+ * that notification).
2056
+ */
2057
+ agentsPublished = false;
2045
2058
  remoteAgents = {};
2046
2059
  mintedThreadIds = /* @__PURE__ */ new WeakMap();
2047
2060
  _runtimeUrl;
@@ -2088,6 +2101,12 @@ var AgentRegistry = class {
2088
2101
  runtimeRecoveryPending = false;
2089
2102
  runtimeHealthGeneration = 0;
2090
2103
  /**
2104
+ * Aborted by {@link dispose}. Runtime probes, recovery fetches and request
2105
+ * watchdogs listen to it so a disposed core leaves no timer or request
2106
+ * behind.
2107
+ */
2108
+ disposeController = new AbortController();
2109
+ /**
2091
2110
  * The headers each HttpAgent was constructed with, captured on the first
2092
2111
  * `applyHeadersToAgent` call for that agent (which, for agents the registry
2093
2112
  * owns, happens at registration before any core headers are applied). Core
@@ -2167,6 +2186,27 @@ var AgentRegistry = class {
2167
2186
  return this._telemetryDisabled;
2168
2187
  }
2169
2188
  /**
2189
+ * Stop runtime work this registry owns: the entitlement retry timer, the
2190
+ * inspector metadata request, runtime probes and recovery fetches with
2191
+ * their timeouts, and request watchdogs. In-flight `/info` connections are
2192
+ * detached so their late results change nothing. Called by
2193
+ * `CopilotKitCore.dispose`.
2194
+ */
2195
+ dispose() {
2196
+ if (this.disposeController.signal.aborted) return;
2197
+ this.disposeController.abort();
2198
+ this._activeRuntimeConnectionAttempt = void 0;
2199
+ this._connectionInFlight = void 0;
2200
+ this.resetRuntimeEntitlementRetry();
2201
+ this.inspectorMetadataGeneration += 1;
2202
+ this.inspectorMetadataAbortController?.abort();
2203
+ this.inspectorMetadataAbortController = void 0;
2204
+ this.abandonRuntimeHealthProbe();
2205
+ }
2206
+ get isDisposed() {
2207
+ return this.disposeController.signal.aborted;
2208
+ }
2209
+ /**
2170
2210
  * Initialize agents from configuration
2171
2211
  */
2172
2212
  initialize(agents) {
@@ -2252,9 +2292,12 @@ var AgentRegistry = class {
2252
2292
  this.runtimeProbeAbortController = void 0;
2253
2293
  }
2254
2294
  /**
2255
- * Set all agents at once (for development use)
2295
+ * Set all agents at once (for development use). Same ids mapped to the
2296
+ * same instances as the current local agents is a no-op once the agents
2297
+ * have been announced.
2256
2298
  */
2257
2299
  setAgents__unsafe_dev_only(agents) {
2300
+ if (this.agentsPublished && shallowEqualRecord(agents, this.localAgents)) return;
2258
2301
  Object.entries(agents).forEach(([id, agent]) => {
2259
2302
  if (agent) this.validateAndAssignAgentId(id, agent);
2260
2303
  });
@@ -2518,11 +2561,17 @@ var AgentRegistry = class {
2518
2561
  checked: () => false
2519
2562
  };
2520
2563
  let checked = false;
2564
+ const disposeSignal = this.disposeController.signal;
2521
2565
  const timeoutId = setTimeout(() => {
2522
2566
  checked = this.handleRuntimeRequestOutcome("failed");
2523
2567
  }, RUNTIME_REQUEST_WATCHDOG_MS);
2568
+ const clear = () => {
2569
+ clearTimeout(timeoutId);
2570
+ disposeSignal.removeEventListener("abort", clear);
2571
+ };
2572
+ disposeSignal.addEventListener("abort", clear, { once: true });
2524
2573
  return {
2525
- clear: () => clearTimeout(timeoutId),
2574
+ clear,
2526
2575
  checked: () => checked
2527
2576
  };
2528
2577
  }
@@ -2683,7 +2732,7 @@ var AgentRegistry = class {
2683
2732
  this.runtimeHealthGeneration += 1;
2684
2733
  }
2685
2734
  handleRuntimeRequestOutcome(outcome, alreadyChecked = () => false) {
2686
- if (outcome === "aborted" || outcome === "ignored") return false;
2735
+ if (outcome === "aborted" || outcome === "ignored" || this.isDisposed) return false;
2687
2736
  if (outcome === "failed" && alreadyChecked()) return false;
2688
2737
  if (typeof window === "undefined") return false;
2689
2738
  if (!this._runtimeUrl) return false;
@@ -2703,16 +2752,32 @@ var AgentRegistry = class {
2703
2752
  let timeoutId;
2704
2753
  const request = this.fetchRuntimeInfo(runtimeUrl, runtimeTransport, abortController.signal);
2705
2754
  request.catch(() => {});
2755
+ const disposeSignal = this.disposeController.signal;
2756
+ let rejectOnAbort;
2757
+ const abortOnDispose = () => abortController.abort();
2706
2758
  try {
2707
2759
  const timedOut = new Promise((_resolve, reject) => {
2708
2760
  timeoutId = setTimeout(() => {
2709
- abortController.abort();
2710
2761
  reject(/* @__PURE__ */ new Error(`Runtime did not answer within ${ɵRUNTIME_PROBE_TIMEOUT_MS}ms`));
2762
+ abortController.abort();
2711
2763
  }, ɵRUNTIME_PROBE_TIMEOUT_MS);
2712
2764
  });
2713
- return await Promise.race([request, timedOut]);
2765
+ const aborted = new Promise((_resolve, reject) => {
2766
+ rejectOnAbort = () => reject(/* @__PURE__ */ new Error("Runtime request aborted"));
2767
+ abortController.signal.addEventListener("abort", rejectOnAbort, { once: true });
2768
+ });
2769
+ aborted.catch(() => {});
2770
+ disposeSignal.addEventListener("abort", abortOnDispose, { once: true });
2771
+ if (disposeSignal.aborted) abortController.abort();
2772
+ return await Promise.race([
2773
+ request,
2774
+ timedOut,
2775
+ aborted
2776
+ ]);
2714
2777
  } finally {
2715
2778
  if (timeoutId !== void 0) clearTimeout(timeoutId);
2779
+ if (rejectOnAbort) abortController.signal.removeEventListener("abort", rejectOnAbort);
2780
+ disposeSignal.removeEventListener("abort", abortOnDispose);
2716
2781
  }
2717
2782
  }
2718
2783
  async probeRuntimeReachability() {
@@ -2773,7 +2838,7 @@ var AgentRegistry = class {
2773
2838
  * Update runtime connection and fetch remote agents
2774
2839
  */
2775
2840
  async updateRuntimeConnection(options) {
2776
- if (typeof window === "undefined") return;
2841
+ if (typeof window === "undefined" || this.isDisposed) return;
2777
2842
  const key = this.runtimeConnectionKey();
2778
2843
  const inFlight = this._connectionInFlight;
2779
2844
  if (inFlight && inFlight.attempt.key === key && this.isCurrentRuntimeConnection(inFlight.attempt)) return inFlight.promise;
@@ -2835,6 +2900,7 @@ var AgentRegistry = class {
2835
2900
  }
2836
2901
  this._runtimeEntitlementRetryAttemptedKey = key;
2837
2902
  this._runtimeEntitlementRetryPendingKey = key;
2903
+ if (this.isDisposed) return;
2838
2904
  this._runtimeEntitlementRetryTimer = setTimeout(() => {
2839
2905
  this._runtimeEntitlementRetryTimer = void 0;
2840
2906
  this.executeRuntimeEntitlementRetry(attempt).catch((error) => {
@@ -3089,6 +3155,7 @@ var AgentRegistry = class {
3089
3155
  * Notify subscribers of agent changes
3090
3156
  */
3091
3157
  async notifyAgentsChanged() {
3158
+ this.agentsPublished = true;
3092
3159
  await this.core.notifySubscribers((subscriber) => subscriber.onAgentsChanged?.({
3093
3160
  copilotkit: this.core,
3094
3161
  agents: this._agents
@@ -3184,6 +3251,13 @@ var SuggestionEngine = class {
3184
3251
  _suggestionsConfig = {};
3185
3252
  _suggestions = {};
3186
3253
  _runningSuggestions = {};
3254
+ /**
3255
+ * The last `getSuggestions` result per agent, with the per-generation
3256
+ * arrays it was built from. Each generation's array is replaced (never
3257
+ * mutated) on change, so comparing those references tells whether the
3258
+ * cached result is still current.
3259
+ */
3260
+ _snapshots = /* @__PURE__ */ new Map();
3187
3261
  constructor(core) {
3188
3262
  this.core = core;
3189
3263
  }
@@ -3246,13 +3320,29 @@ var SuggestionEngine = class {
3246
3320
  this.notifySuggestionsChanged(agentId, []);
3247
3321
  }
3248
3322
  /**
3249
- * Get current suggestions for an agent
3323
+ * Get current suggestions for an agent. Returns the same object until the
3324
+ * agent's suggestions or loading state change.
3250
3325
  */
3251
3326
  getSuggestions(agentId) {
3252
- return {
3253
- suggestions: Object.values(this._suggestions[agentId] ?? {}).flat(),
3254
- isLoading: (this._runningSuggestions[agentId]?.length ?? 0) > 0
3327
+ const parts = Object.values(this._suggestions[agentId] ?? {});
3328
+ const isLoading = (this._runningSuggestions[agentId]?.length ?? 0) > 0;
3329
+ const cached = this._snapshots.get(agentId);
3330
+ if (cached !== void 0 && cached.result.isLoading === isLoading && cached.parts.length === parts.length && parts.every((part, index) => part === cached.parts[index])) return cached.result;
3331
+ const result = {
3332
+ suggestions: parts.flat(),
3333
+ isLoading
3255
3334
  };
3335
+ this._snapshots.set(agentId, {
3336
+ parts,
3337
+ result
3338
+ });
3339
+ return result;
3340
+ }
3341
+ /** Abort every running suggestion generation. Called by `CopilotKitCore.dispose`. */
3342
+ dispose() {
3343
+ const runs = Object.values(this._runningSuggestions).flat();
3344
+ this._runningSuggestions = {};
3345
+ for (const run of runs) run.abortRun();
3256
3346
  }
3257
3347
  /**
3258
3348
  * Generate suggestions by running a provider agent and extracting the
@@ -3623,7 +3713,7 @@ const EMPTY_TOOL_SCHEMA = {
3623
3713
  */
3624
3714
  function createToolSchema(tool) {
3625
3715
  if (!tool.parameters) return { ...EMPTY_TOOL_SCHEMA };
3626
- const rawSchema = (0, _copilotkit_shared.schemaToJsonSchema)(tool.parameters, { zodToJsonSchema: (schema, options) => (0, zod_to_json_schema.zodToJsonSchema)(schema, options) });
3716
+ const rawSchema = (0, _copilotkit_shared.schemaToJsonSchema)(tool.parameters);
3627
3717
  if (!rawSchema || typeof rawSchema !== "object") return { ...EMPTY_TOOL_SCHEMA };
3628
3718
  const { $schema: _$schema, ...schema } = rawSchema;
3629
3719
  if (typeof schema.type !== "string") schema.type = "object";
@@ -3662,14 +3752,14 @@ var ɵInterruptState = class {
3662
3752
  #adoptedContent = /* @__PURE__ */ new Map();
3663
3753
  #pending = null;
3664
3754
  #sealed = false;
3665
- /** Return the active normalized interrupt without exposing mutable state. */
3755
+ /**
3756
+ * Return the active normalized interrupt. A standard interrupt set is a
3757
+ * frozen snapshot, and every read returns the same object until the
3758
+ * interrupt is replaced or cleared, so a framework can compare it by
3759
+ * reference.
3760
+ */
3666
3761
  get pending() {
3667
- const pending = this.#pending;
3668
- if (pending?.kind === "standard") return {
3669
- kind: "standard",
3670
- interrupts: [...pending.interrupts]
3671
- };
3672
- return pending;
3762
+ return this.#pending;
3673
3763
  }
3674
3764
  /** Replace the current interrupt with a legacy custom-event interrupt. */
3675
3765
  setLegacy(event) {
@@ -3690,10 +3780,10 @@ var ɵInterruptState = class {
3690
3780
  callIds.add(interrupt.toolCallId);
3691
3781
  }
3692
3782
  }
3693
- this.#replace({
3783
+ this.#replace(Object.freeze({
3694
3784
  kind: "standard",
3695
- interrupts: [...interrupts]
3696
- });
3785
+ interrupts: Object.freeze([...interrupts])
3786
+ }));
3697
3787
  }
3698
3788
  /** Clear all pending interrupt data and accumulated responses. */
3699
3789
  clear() {
@@ -4012,6 +4102,12 @@ var RunHandler = class {
4012
4102
  * one array before, so the `/info` response flipping `openGenerativeUI` (or
4013
4103
  * any other provider-prop change) silently dropped every hook-registered
4014
4104
  * tool (#4952). Key = `capabilityKey(name, agentId)`.
4105
+ *
4106
+ * Each key holds a stack of registrations. The last one is the active tool;
4107
+ * removing it (via the function `addTool` returns) brings back the one
4108
+ * below, and an empty stack lets the provider tool of that key show again.
4109
+ * A registration is its own object, so removing one never removes another
4110
+ * registration of the same tool object.
4015
4111
  */
4016
4112
  _hookTools = /* @__PURE__ */ new Map();
4017
4113
  /**
@@ -4068,6 +4164,13 @@ var RunHandler = class {
4068
4164
  */
4069
4165
  _runDepths = /* @__PURE__ */ new WeakMap();
4070
4166
  /**
4167
+ * Agents with at least one run in flight (depth above 0), so
4168
+ * {@link dispose} can stop them. Removed when the last run ends.
4169
+ */
4170
+ _runningAgents = /* @__PURE__ */ new Set();
4171
+ /** Set by {@link dispose}. Stops WebMCP from registering tools again. */
4172
+ _disposed = false;
4173
+ /**
4071
4174
  * Each agent's own `abortRun`, saved while RunHandler's intercept is
4072
4175
  * installed. Restored only once none of the agent's runs is in flight, so an
4073
4176
  * overlapping run keeps the intercept after an earlier run finishes.
@@ -4113,7 +4216,7 @@ var RunHandler = class {
4113
4216
  _executingToolCalls = /* @__PURE__ */ new WeakMap();
4114
4217
  _connectionGenerations = /* @__PURE__ */ new WeakMap();
4115
4218
  _runGenerations = /* @__PURE__ */ new WeakMap();
4116
- _interactionAbortControllers = /* @__PURE__ */ new WeakMap();
4219
+ _interactionAbortControllers = /* @__PURE__ */ new Map();
4117
4220
  constructor(core) {
4118
4221
  this.core = core;
4119
4222
  }
@@ -4131,6 +4234,29 @@ var RunHandler = class {
4131
4234
  this._executingToolCalls.delete(agent);
4132
4235
  }
4133
4236
  }
4237
+ /**
4238
+ * Stop every run chain and tool interaction this handler tracks, and every
4239
+ * agent in `agents` that reports a run in flight, the same way `stopAgent`
4240
+ * does. Then unregister all WebMCP tools. Called by `CopilotKitCore.dispose`.
4241
+ */
4242
+ dispose(agents) {
4243
+ this._disposed = true;
4244
+ const candidates = new Set([
4245
+ ...agents,
4246
+ ...this._runningAgents,
4247
+ ...this._interactionAbortControllers.keys()
4248
+ ]);
4249
+ for (const agent of candidates) {
4250
+ const hasActiveRun = agent.isRunning || this._runningAgents.has(agent);
4251
+ try {
4252
+ this.abortCurrentRun(agent);
4253
+ if (hasActiveRun) agent.abortRun();
4254
+ } catch (error) {
4255
+ _copilotkit_shared.logger.error(`Failed to stop agent '${agent.agentId ?? "(unknown agent)"}' on dispose:`, error);
4256
+ }
4257
+ }
4258
+ this._webmcpRegistry.sync(/* @__PURE__ */ new Map());
4259
+ }
4134
4260
  abortAgentRuns(agent) {
4135
4261
  for (const controller of this._runAbortControllers.get(agent) ?? []) controller.abort();
4136
4262
  }
@@ -4171,7 +4297,10 @@ var RunHandler = class {
4171
4297
  if (this._cachedMergedTools) return this._cachedMergedTools;
4172
4298
  const merged = /* @__PURE__ */ new Map();
4173
4299
  for (const tool of this._propTools) merged.set(this.capabilityKey(tool.name, tool.agentId), tool);
4174
- for (const [key, tool] of this._hookTools) merged.set(key, tool);
4300
+ for (const [key, stack] of this._hookTools) {
4301
+ const active = stack[stack.length - 1];
4302
+ if (active) merged.set(key, active.tool);
4303
+ }
4175
4304
  this._cachedMergedTools = Array.from(merged.values());
4176
4305
  return this._cachedMergedTools;
4177
4306
  }
@@ -4187,17 +4316,34 @@ var RunHandler = class {
4187
4316
  /**
4188
4317
  * Add a tool to the registry. Survives provider re-syncs ({@link setTools}),
4189
4318
  * and shadows a provider tool of the same name + agentId.
4319
+ *
4320
+ * Registrations of the same name + agentId stack: the most recent one is
4321
+ * active. Call the returned function to remove exactly this registration;
4322
+ * the previous registration (or the provider tool) becomes active again.
4323
+ * Calling it more than once does nothing.
4190
4324
  */
4191
4325
  addTool(tool) {
4192
4326
  const key = this.capabilityKey(tool.name, tool.agentId);
4193
- if (this._hookTools.has(key)) {
4194
- _copilotkit_shared.logger.warn(`Tool already exists: '${tool.name}' for agent '${tool.agentId || "global"}', skipping.`);
4195
- return;
4196
- }
4197
- this._hookTools.set(key, tool);
4327
+ const registration = { tool };
4328
+ const stack = this._hookTools.get(key);
4329
+ if (stack) {
4330
+ if (process.env.NODE_ENV !== "production") _copilotkit_shared.logger.warn(`Tool already exists: '${tool.name}' for agent '${tool.agentId || "global"}'. The new registration shadows it until the new one is removed.`);
4331
+ stack.push(registration);
4332
+ } else this._hookTools.set(key, [registration]);
4198
4333
  this._cachedMergedTools = null;
4199
4334
  this.warnOnMissingToolParameters([tool]);
4200
4335
  this.syncWebMCP();
4336
+ return () => this.unregisterHookTool(key, registration);
4337
+ }
4338
+ /** Remove one `addTool` registration. Unknown registrations are ignored. */
4339
+ unregisterHookTool(key, registration) {
4340
+ const stack = this._hookTools.get(key);
4341
+ const index = stack?.indexOf(registration) ?? -1;
4342
+ if (!stack || index === -1) return;
4343
+ stack.splice(index, 1);
4344
+ if (stack.length === 0) this._hookTools.delete(key);
4345
+ this._cachedMergedTools = null;
4346
+ this.syncWebMCP();
4201
4347
  }
4202
4348
  /**
4203
4349
  * Report, once per tool and at development time only, a tool registered with
@@ -4229,7 +4375,10 @@ var RunHandler = class {
4229
4375
  }
4230
4376
  }
4231
4377
  /**
4232
- * Remove a tool by name and optionally by agentId
4378
+ * Remove a tool by name and optionally by agentId: every `addTool`
4379
+ * registration of that key and the provider tool of that key. Without an
4380
+ * agentId only global tools are removed. To remove one `addTool`
4381
+ * registration and keep the others, call the function `addTool` returned.
4233
4382
  */
4234
4383
  removeTool(id, agentId) {
4235
4384
  this._hookTools.delete(this.capabilityKey(id, agentId));
@@ -4427,6 +4576,7 @@ var RunHandler = class {
4427
4576
  this._runAbortControllers.set(agent, controllers);
4428
4577
  }
4429
4578
  if (depth === 0) {
4579
+ this._runningAgents.add(agent);
4430
4580
  const originalAbortRun = agent.abortRun;
4431
4581
  this._originalAbortRuns.set(agent, originalAbortRun);
4432
4582
  agent.abortRun = () => {
@@ -4500,6 +4650,7 @@ var RunHandler = class {
4500
4650
  if (controllers?.size === 0) this._runAbortControllers.delete(agent);
4501
4651
  }
4502
4652
  if (remainingDepth === 0) {
4653
+ this._runningAgents.delete(agent);
4503
4654
  const originalAbortRun = this._originalAbortRuns.get(agent);
4504
4655
  if (originalAbortRun) {
4505
4656
  agent.abortRun = originalAbortRun;
@@ -5004,6 +5155,7 @@ var RunHandler = class {
5004
5155
  * agentId — a name collision across agentIds keeps the first registration.
5005
5156
  */
5006
5157
  syncWebMCP() {
5158
+ if (this._disposed) return;
5007
5159
  const desired = /* @__PURE__ */ new Map();
5008
5160
  const warnedCollisions = /* @__PURE__ */ new Set();
5009
5161
  for (const tool of this.tools) {
@@ -5333,6 +5485,11 @@ var StateManager = class {
5333
5485
  }
5334
5486
  this.rawEventByMessage.delete(agentId);
5335
5487
  }
5488
+ /** Unsubscribe from every agent. Called by `CopilotKitCore.dispose`. */
5489
+ dispose() {
5490
+ const agentIds = [...this.agentSubscriptions.keys()];
5491
+ for (const agentId of agentIds) this.unsubscribeFromAgent(agentId);
5492
+ }
5336
5493
  /**
5337
5494
  * Get state for a specific run
5338
5495
  * Returns a deep copy to prevent external mutations
@@ -7505,6 +7662,8 @@ var CopilotKitCore = class {
7505
7662
  _defaultThrottleMs;
7506
7663
  _debug;
7507
7664
  subscribers = /* @__PURE__ */ new Set();
7665
+ _disposed = false;
7666
+ waitForFrameworkUpdates;
7508
7667
  agentRegistry;
7509
7668
  contextStore;
7510
7669
  suggestionEngine;
@@ -7530,7 +7689,8 @@ var CopilotKitCore = class {
7530
7689
  * store that was registered prior to that initial notification.
7531
7690
  */
7532
7691
  previousAgentIds = /* @__PURE__ */ new Set();
7533
- constructor({ runtimeUrl, runtimeTransport = "auto", deferInitialConnection = false, headers = {}, credentials, messageFilter, properties = {}, agents__unsafe_dev_only = {}, tools = [], suggestionsConfig = [], debug, learning }) {
7692
+ constructor({ runtimeUrl, runtimeTransport = "auto", deferInitialConnection = false, headers = {}, credentials, messageFilter, properties = {}, agents__unsafe_dev_only = {}, tools = [], suggestionsConfig = [], debug, learning, ɵwaitForFrameworkUpdates }) {
7693
+ this.waitForFrameworkUpdates = ɵwaitForFrameworkUpdates;
7534
7694
  this.headerSource = new HeaderSourceResolver((error) => {
7535
7695
  this.emitError({
7536
7696
  error,
@@ -7584,6 +7744,7 @@ var CopilotKitCore = class {
7584
7744
  * Internal method used by delegate classes and subclasses to notify subscribers
7585
7745
  */
7586
7746
  async notifySubscribers(handler, errorMessage) {
7747
+ if (this._disposed) return;
7587
7748
  await Promise.all(Array.from(this.subscribers).map(async (subscriber) => {
7588
7749
  try {
7589
7750
  await handler(subscriber);
@@ -7833,7 +7994,12 @@ var CopilotKitCore = class {
7833
7994
  headers: this.headers
7834
7995
  }), "Subscriber onHeadersChanged error:");
7835
7996
  }
7997
+ /**
7998
+ * Set the credentials mode for runtime requests (for example `"include"`
7999
+ * to send HTTP-only cookies). Passing the current value does nothing.
8000
+ */
7836
8001
  setCredentials(credentials) {
8002
+ if (credentials === this._credentials) return;
7837
8003
  this._credentials = credentials;
7838
8004
  this.agentRegistry.applyCredentialsToAgents(this.agentRegistry.agents);
7839
8005
  this.agentRegistry.handleCredentialsChanged();
@@ -7843,9 +8009,11 @@ var CopilotKitCore = class {
7843
8009
  *
7844
8010
  * Applies to agents already discovered as well as ones discovered later, so
7845
8011
  * a filter set before `/info` lands is not lost. Pass `undefined` to go back
7846
- * to sending the full thread.
8012
+ * to sending the full thread. Passing the current filter function again
8013
+ * does nothing.
7847
8014
  */
7848
8015
  setMessageFilter(messageFilter) {
8016
+ if (messageFilter === this._messageFilter) return;
7849
8017
  this._messageFilter = messageFilter;
7850
8018
  this.agentRegistry.applyMessageFilterToAgents(this.agentRegistry.agents);
7851
8019
  }
@@ -7902,7 +8070,14 @@ var CopilotKitCore = class {
7902
8070
  }
7903
8071
  return merged;
7904
8072
  }
8073
+ /**
8074
+ * Replace the properties sent as `forwardedProps` with every run, and
8075
+ * notify `onPropertiesChanged`. Passing an object with the same keys and
8076
+ * values as the current one does nothing, so a fresh object literal on
8077
+ * every render is safe.
8078
+ */
7905
8079
  setProperties(properties) {
8080
+ if (shallowEqualRecord(properties, this._properties)) return;
7906
8081
  this._properties = properties;
7907
8082
  this.notifySubscribers((subscriber) => subscriber.onPropertiesChanged?.({
7908
8083
  copilotkit: this,
@@ -7910,7 +8085,10 @@ var CopilotKitCore = class {
7910
8085
  }), "Subscriber onPropertiesChanged error:");
7911
8086
  }
7912
8087
  /**
7913
- * Agent management (delegated to AgentRegistry)
8088
+ * Agent management (delegated to AgentRegistry).
8089
+ *
8090
+ * Replace the local (development) agents. Passing the same ids mapped to
8091
+ * the same agent instances does nothing.
7914
8092
  */
7915
8093
  setAgents__unsafe_dev_only(agents) {
7916
8094
  this.agentRegistry.setAgents__unsafe_dev_only(agents);
@@ -8189,11 +8367,34 @@ var CopilotKitCore = class {
8189
8367
  return this.suggestionEngine.getSuggestions(agentId);
8190
8368
  }
8191
8369
  /**
8192
- * Tool management (delegated to RunHandler)
8370
+ * Register a frontend tool. It shadows a provider tool (from the `tools`
8371
+ * config or `setTools`) with the same name and agentId.
8372
+ *
8373
+ * A second registration with the same name and agentId shadows the first.
8374
+ * Call the returned function to remove only this registration: the tool it
8375
+ * shadowed becomes active again. Calling it more than once does nothing.
8376
+ *
8377
+ * @param tool - The tool to register.
8378
+ * @returns A function that removes this registration.
8379
+ *
8380
+ * @example
8381
+ * const unregister = copilotkit.addTool({
8382
+ * name: "showWeather",
8383
+ * handler: async ({ city }) => `Sunny in ${city}`,
8384
+ * });
8385
+ * // later
8386
+ * unregister();
8193
8387
  */
8194
8388
  addTool(tool) {
8195
- this.runHandler.addTool(tool);
8389
+ return this.runHandler.addTool(tool);
8196
8390
  }
8391
+ /**
8392
+ * Remove a tool by name, and by agentId when given. This removes every
8393
+ * `addTool` registration with that name and agentId, and the provider tool
8394
+ * with that name and agentId. Without an agentId, only global tools are
8395
+ * removed. To remove one registration, call the function `addTool`
8396
+ * returned.
8397
+ */
8197
8398
  removeTool(id, agentId) {
8198
8399
  this.runHandler.removeTool(id, agentId);
8199
8400
  }
@@ -8437,11 +8638,52 @@ var CopilotKitCore = class {
8437
8638
  * synchronously while the deferred updates are still pending, producing stale
8438
8639
  * context for the next agent turn.
8439
8640
  *
8440
- * Override in framework-specific subclasses to yield to the framework
8441
- * scheduler before the follow-up run. The base implementation is a no-op
8442
- * because non-React environments have no deferred state to flush.
8641
+ * Awaits the `ɵwaitForFrameworkUpdates` config option when one is given.
8642
+ * Without it there is nothing to wait for, because a plain JavaScript
8643
+ * environment has no deferred state to flush. Framework subclasses that
8644
+ * still override this method keep working.
8443
8645
  */
8444
- async waitForPendingFrameworkUpdates() {}
8646
+ async waitForPendingFrameworkUpdates() {
8647
+ await this.waitForFrameworkUpdates?.();
8648
+ }
8649
+ /**
8650
+ * Stop everything this core started, so it can be dropped without leaks.
8651
+ *
8652
+ * Call it when you created a `CopilotKitCore` yourself and are done with it
8653
+ * (for example when a page or test tears down). Framework providers call it
8654
+ * for you.
8655
+ *
8656
+ * It does this, in order:
8657
+ *
8658
+ * - removes every subscriber, so no callback runs after this call;
8659
+ * - stops agent runs in flight and aborts running frontend tools;
8660
+ * - aborts suggestion generation;
8661
+ * - clears runtime timers and aborts runtime requests it can cancel;
8662
+ * - removes agent subscriptions, WebMCP tools, and the learning capture;
8663
+ * - stops the memory store and every registered thread store.
8664
+ *
8665
+ * Calling it again does nothing. Do not use the core after this call.
8666
+ *
8667
+ * @example
8668
+ * const copilotkit = new CopilotKitCore({ runtimeUrl: "/api/copilotkit" });
8669
+ * // ... use it ...
8670
+ * copilotkit.dispose();
8671
+ */
8672
+ dispose() {
8673
+ if (this._disposed) return;
8674
+ this._disposed = true;
8675
+ this.subscribers.clear();
8676
+ this.learningConfiguredListeners.clear();
8677
+ this.generativeUIDebugListeners.clear();
8678
+ this.runHandler.dispose(Object.values(this.agentRegistry.agents));
8679
+ this.suggestionEngine.dispose();
8680
+ this.agentRegistry.dispose();
8681
+ this.stateManager.dispose();
8682
+ this.stopTrajectory();
8683
+ this._memoryStore?.stop();
8684
+ const threadStores = Object.values(this.threadStoreRegistry.getAll());
8685
+ for (const store of threadStores) store.stop();
8686
+ }
8445
8687
  };
8446
8688
 
8447
8689
  //#endregion
@@ -8624,23 +8866,6 @@ function completePartialMarkdown(input) {
8624
8866
  return result;
8625
8867
  }
8626
8868
 
8627
- //#endregion
8628
- //#region src/utils/markdown/parse.ts
8629
- /**
8630
- * Parse a markdown string into a framework-agnostic token tree.
8631
- *
8632
- * Uses `marked`'s lexer (GFM enabled) so the result is DOM-free and can be
8633
- * walked into React, Vue, or React Native elements by each framework's
8634
- * built-in renderer.
8635
- */
8636
- function parseMarkdown(content, options = {}) {
8637
- const src = !content ? "" : options.complete === false ? content : completePartialMarkdown(content);
8638
- return marked.marked.lexer(src, {
8639
- gfm: true,
8640
- breaks: true
8641
- });
8642
- }
8643
-
8644
8869
  //#endregion
8645
8870
  //#region src/threads.ts
8646
8871
  const THREADS_CHANNEL_EVENT = "thread_metadata";
@@ -10135,11 +10360,11 @@ function partialOperation(line) {
10135
10360
  return null;
10136
10361
  }
10137
10362
  /**
10138
- * A line that opens a new top-level operation: `{"version":"v…` or
10363
+ * A line that opens a new top-level operation: `{"version":"1…` or
10139
10364
  * `{"<operation>":{`. Seen at the start of a line while an earlier object is
10140
10365
  * still unbalanced, it means that object is malformed and has ended.
10141
10366
  */
10142
- const OPERATION_START = new RegExp(`^\\{\\s*"(?:version"\\s*:\\s*"v\\d|(?:${OP_KEYS.join("|")})"\\s*:\\s*\\{)`);
10367
+ const OPERATION_START = new RegExp(`^\\{\\s*"(?:version"\\s*:\\s*"\\d|(?:${OP_KEYS.join("|")})"\\s*:\\s*\\{)`);
10143
10368
  /**
10144
10369
  * Scan the top-level object whose "{" is at `start`. Returns the index just
10145
10370
  * past it and whether it balanced. An unbalanced object ends early (at the
@@ -10181,6 +10406,91 @@ function scanTopLevelObject(s, start) {
10181
10406
  balanced: false
10182
10407
  };
10183
10408
  }
10409
+ const OPERATION_NAMES = [
10410
+ "createSurface",
10411
+ "updateComponents",
10412
+ "updateDataModel",
10413
+ "deleteSurface",
10414
+ "callRendererFunction"
10415
+ ];
10416
+ /** Whether a value is shaped like one A2UI operation, with named components. */
10417
+ function isOperationShape(value) {
10418
+ if (!isRecord(value) || value.version !== _copilotkit_shared.A2UI_VERSION) return false;
10419
+ const names = OPERATION_NAMES.filter((name) => name in value);
10420
+ if (names.length !== 1 || Object.keys(value).length !== 2) return false;
10421
+ const body = value[names[0]];
10422
+ if (!isRecord(body)) return false;
10423
+ if (names[0] === "callRendererFunction") return true;
10424
+ if (typeof body.surfaceId !== "string") return false;
10425
+ const components = body.components;
10426
+ return components === void 0 || Array.isArray(components) && components.every((c) => isRecord(c) && typeof c.id === "string" && typeof c.component === "string");
10427
+ }
10428
+ /** Openers minus closers ({ and [ against } and ]) outside strings. */
10429
+ function closerImbalance(line) {
10430
+ let depth = 0;
10431
+ let inString = false;
10432
+ for (let i = 0; i < line.length; i++) {
10433
+ const c = line[i];
10434
+ if (inString) {
10435
+ if (c === "\\") i++;
10436
+ else if (c === "\"") inString = false;
10437
+ } else if (c === "\"") inString = true;
10438
+ else if (c === "{" || c === "[") depth++;
10439
+ else if (c === "}" || c === "]") depth--;
10440
+ }
10441
+ return depth;
10442
+ }
10443
+ /** The text with closers and whitespace removed, to compare a repair. */
10444
+ function withoutClosers(text) {
10445
+ return text.replace(/[\]}\s]/g, "");
10446
+ }
10447
+ /**
10448
+ * Whether a component of the operation holds a structural key (`id`,
10449
+ * `component`, `child`, `children`) in a nested object: a closer added at
10450
+ * the end instead of where it was dropped. The scan below repairs those.
10451
+ */
10452
+ function nestsStructuralKey(value) {
10453
+ const nests = (v) => isRecord(v) && Object.entries(v).some(([k, x]) => STRUCTURAL_KEYS.has(k) || nests(x));
10454
+ const components = (isRecord(value) ? Object.values(value).find(isRecord) : void 0)?.components;
10455
+ return Array.isArray(components) && components.some((c) => isRecord(c) && Object.values(c).some((prop) => nests(prop)));
10456
+ }
10457
+ /**
10458
+ * Repairs the complete lines of a fence that are not valid JSON (a missing
10459
+ * or extra brace) with jsonrepair, when the repair only adds or removes
10460
+ * closers and the result is shaped like an operation. A line still streaming in (no newline yet) is left alone.
10461
+ */
10462
+ function repairFenceLines(fenceText) {
10463
+ const repaired = [];
10464
+ const lines = fenceText.split("\n");
10465
+ if (fenceText.trimStart().startsWith("[")) return {
10466
+ text: fenceText,
10467
+ repaired
10468
+ };
10469
+ for (let n = 0; n < lines.length - 1; n++) {
10470
+ const line = lines[n];
10471
+ if (!line.trim().startsWith("{")) continue;
10472
+ try {
10473
+ JSON.parse(line);
10474
+ continue;
10475
+ } catch {}
10476
+ const imbalance = closerImbalance(line);
10477
+ if (Math.abs(imbalance) !== 1) continue;
10478
+ const next = lines.slice(n + 1).find((l) => l.trim() !== "");
10479
+ if (imbalance > 0 && next !== void 0 && !next.trim().startsWith("{")) continue;
10480
+ try {
10481
+ const fixed = (0, jsonrepair.jsonrepair)(line);
10482
+ const value = JSON.parse(fixed);
10483
+ if (withoutClosers(fixed) === withoutClosers(line) && isOperationShape(value) && !nestsStructuralKey(value) && !(isRecord(value) && "callRendererFunction" in value)) {
10484
+ repaired.push(line.trim());
10485
+ lines[n] = JSON.stringify(value);
10486
+ }
10487
+ } catch {}
10488
+ }
10489
+ return {
10490
+ text: lines.join("\n"),
10491
+ repaired
10492
+ };
10493
+ }
10184
10494
  /**
10185
10495
  * Parse the body of an a2ui fence as a stream of top-level JSON values, so
10186
10496
  * operations may be one per line (the documented format), several per line,
@@ -10210,7 +10520,7 @@ function scanTopLevelObject(s, start) {
10210
10520
  * ```
10211
10521
  */
10212
10522
  function extractFenceOperations(fenceText) {
10213
- const s = fenceText;
10523
+ const { text: s, repaired: repairedLines } = repairFenceLines(fenceText);
10214
10524
  const operations = [];
10215
10525
  const invalidLines = [];
10216
10526
  const recovered = [];
@@ -10264,7 +10574,8 @@ function extractFenceOperations(fenceText) {
10264
10574
  partialObject,
10265
10575
  partialLine: partialObject,
10266
10576
  invalidLines,
10267
- recovered
10577
+ recovered,
10578
+ repairedLines
10268
10579
  };
10269
10580
  }
10270
10581
  /**
@@ -10771,24 +11082,2906 @@ function segmentSurfaceProse(components, options = {}) {
10771
11082
  });
10772
11083
  }
10773
11084
 
11085
+ //#endregion
11086
+ //#region src/chat/labels.ts
11087
+ /**
11088
+ * The default English text for every word the chat UI shows. React, Vue and
11089
+ * Angular all read their chat text from this one set.
11090
+ *
11091
+ * To change or translate the text, pass a partial set to your framework's chat
11092
+ * configuration. Keys you leave out keep their default:
11093
+ *
11094
+ * ```ts
11095
+ * const labels = { ...CopilotChatDefaultLabels, chatInputPlaceholder: "Ask me" };
11096
+ * ```
11097
+ *
11098
+ * Some values are templates with `{name}` placeholders, such as
11099
+ * `"Thought for {duration}"`. Keep the placeholders when you translate them.
11100
+ *
11101
+ * Counts use two keys: `...One` for a count of 1, and `...Other` for any other
11102
+ * count.
11103
+ */
11104
+ const CopilotChatDefaultLabels = Object.freeze({
11105
+ chatInputPlaceholder: "Type a message...",
11106
+ chatInputToolbarStartTranscribeButtonLabel: "Transcribe",
11107
+ chatInputToolbarCancelTranscribeButtonLabel: "Cancel",
11108
+ chatInputToolbarFinishTranscribeButtonLabel: "Finish",
11109
+ chatInputToolbarAddButtonLabel: "Add attachments",
11110
+ chatInputToolbarToolsButtonLabel: "Tools",
11111
+ chatInputToolbarSendButtonLabel: "Send message",
11112
+ chatInputToolbarStopButtonLabel: "Stop",
11113
+ assistantMessageToolbarCopyCodeLabel: "Copy",
11114
+ assistantMessageToolbarCopyCodeCopiedLabel: "Copied",
11115
+ assistantMessageToolbarCopyMessageLabel: "Copy",
11116
+ assistantMessageToolbarInspectorLabel: "View in Inspector",
11117
+ assistantMessageToolbarInspectorDescription: "Open this message in the Inspector",
11118
+ assistantMessageToolbarInspectorLocalOnlyLabel: "Local only",
11119
+ assistantMessageToolbarInspectorLocalOnlyDescription: "Only visible on localhost or loopback hosts in development. Never shown in production.",
11120
+ assistantMessageToolbarInspectorTitle: "CopilotKit Inspector",
11121
+ assistantMessageToolbarInspectorHideLabel: "Hide this icon",
11122
+ assistantMessageToolbarInspectorHideDescription: "Until you reload this page",
11123
+ assistantMessageToolbarThumbsUpLabel: "Good response",
11124
+ assistantMessageToolbarThumbsDownLabel: "Bad response",
11125
+ assistantMessageFeedbackCommentPlaceholder: "Add a comment (optional)",
11126
+ assistantMessageFeedbackCommentSubmitLabel: "Send comment",
11127
+ assistantMessageToolbarReadAloudLabel: "Read aloud",
11128
+ assistantMessageToolbarRegenerateLabel: "Regenerate",
11129
+ userMessageToolbarCopyMessageLabel: "Copy",
11130
+ userMessageToolbarEditMessageLabel: "Edit",
11131
+ userMessageToolbarPreviousBranchLabel: "Previous branch",
11132
+ userMessageToolbarNextBranchLabel: "Next branch",
11133
+ chatDisclaimerText: "AI can make mistakes. Please verify important information.",
11134
+ chatToggleOpenLabel: "Open chat",
11135
+ chatToggleCloseLabel: "Close chat",
11136
+ chatScrollToBottomLabel: "Scroll to bottom",
11137
+ chatConnectingLabel: "Loading conversation",
11138
+ modalHeaderTitle: "CopilotKit Chat",
11139
+ welcomeMessageText: "How can I help you today?",
11140
+ reasoningMessageThinkingLabel: "Thinking…",
11141
+ chatInputSlashMenuLabel: "Slash commands",
11142
+ chatInputSlashMenuEmptyText: "No commands found",
11143
+ attachmentRemoveButtonLabel: "Remove attachment",
11144
+ attachmentPlayVideoButtonLabel: "Play video",
11145
+ attachmentPreviewCloseButtonLabel: "Close preview",
11146
+ modalHeaderCloseButtonLabel: "Close",
11147
+ modalHeaderThreadsButtonLabel: "Open threads",
11148
+ sidebarLabel: "Copilot chat sidebar",
11149
+ chatDropFilesLabel: "Drop files here",
11150
+ threadLoadErrorText: "Could not load saved conversation. Reopen the thread and try again.",
11151
+ reasoningMessageThoughtForLabel: "Thought for {duration}",
11152
+ reasoningMessageDurationFewSeconds: "a few seconds",
11153
+ reasoningMessageDurationSeconds: "{count} seconds",
11154
+ reasoningMessageDurationMinutesOne: "{count} minute",
11155
+ reasoningMessageDurationMinutesOther: "{count} minutes",
11156
+ reasoningMessageDurationMinutesSeconds: "{minutes}m {seconds}s",
11157
+ toolCallStatusRunningLabel: "Running",
11158
+ toolCallStatusDoneLabel: "Done",
11159
+ toolCallStatusFailedLabel: "Failed",
11160
+ toolCallStatusStoppedLabel: "Stopped",
11161
+ toolCallRunningLabel: "Running {name}",
11162
+ toolCallFailedCountLabel: "{count} failed",
11163
+ toolCallDoneCountLabel: "{count} done",
11164
+ toolCallArgumentsLabel: "Arguments",
11165
+ toolCallResultLabel: "Result",
11166
+ toolCallCollapseLabel: "Collapse",
11167
+ toolCallUsedToolsOne: "Used {count} tool",
11168
+ toolCallUsedToolsOther: "Used {count} tools",
11169
+ toolCallToolCountOne: "{count} tool",
11170
+ toolCallToolCountOther: "{count} tools",
11171
+ toolCallToolCallCountOne: "{count} tool call",
11172
+ toolCallToolCallCountOther: "{count} tool calls",
11173
+ toolCallCallCountOne: "{count} call",
11174
+ toolCallCallCountOther: "{count} calls",
11175
+ workSummaryWorkingLabel: "Working",
11176
+ workSummaryWorkedForLabel: "Worked for {duration}",
11177
+ attachmentImageLoadErrorText: "Failed to load image",
11178
+ attachmentImageAltText: "Image attachment",
11179
+ attachmentUnknownTypeText: "Unknown type",
11180
+ attachmentDocumentLabel: "Document",
11181
+ attachmentDocumentAltText: "Document attachment",
11182
+ attachmentNoPreviewText: "No preview available for this file type",
11183
+ chatAttachmentsUploadingText: "Cannot send while attachments are uploading.",
11184
+ transcriptionErrorRateLimitedText: "Too many requests. Please wait a moment.",
11185
+ transcriptionErrorAuthFailedText: "Authentication error. Please check your configuration.",
11186
+ transcriptionErrorAudioTooLongText: "Recording is too long. Please try a shorter recording.",
11187
+ transcriptionErrorAudioTooShortText: "Recording is too short. Please try again.",
11188
+ transcriptionErrorInvalidAudioFormatText: "Audio format not supported.",
11189
+ transcriptionErrorServiceNotConfiguredText: "Transcription service is not available.",
11190
+ transcriptionErrorNetworkText: "Network error. Please check your connection.",
11191
+ transcriptionErrorGenericText: "Transcription failed. Please try again.",
11192
+ licensePoweredByText: "Powered by CopilotKit",
11193
+ licenseGetLicenseLabel: "Get a license",
11194
+ licenseFeatureUnlicensedText: "⚠ The \"{feature}\" feature requires a CopilotKit license.",
11195
+ licenseExpiringText: "Your CopilotKit license expires soon. Please renew.",
11196
+ licenseExpiringInDaysOne: "Your CopilotKit license expires in {days} day. Please renew.",
11197
+ licenseExpiringInDaysOther: "Your CopilotKit license expires in {days} days. Please renew.",
11198
+ licenseExpiredText: "Your CopilotKit license expired. Please renew at copilotkit.ai/pricing",
11199
+ licenseExpiredOnDateText: "Your CopilotKit license expired on {date}. Please renew at copilotkit.ai/pricing",
11200
+ licenseInvalidText: "Invalid CopilotKit license token. Please check your configuration.",
11201
+ licenseRenewLabel: "Renew",
11202
+ licenseRenewNowLabel: "Renew now"
11203
+ });
11204
+ /**
11205
+ * Puts values into a label template. Each `{name}` in the template is replaced
11206
+ * by `values[name]`. A placeholder with no value stays in the text as is.
11207
+ *
11208
+ * @param template - A label value, such as `"Running {name}"`.
11209
+ * @param values - The value for each placeholder.
11210
+ *
11211
+ * ```ts
11212
+ * ɵformatLabel(labels.toolCallRunningLabel, { name: "read_file" });
11213
+ * // "Running read_file"
11214
+ * ```
11215
+ */
11216
+ function ɵformatLabel(template, values) {
11217
+ return template.replace(/\{(\w+)\}/g, (placeholder, name) => Object.hasOwn(values, name) ? String(values[name]) : placeholder);
11218
+ }
11219
+ /**
11220
+ * Fills a counted label pair: the `one` template for a count of 1, the
11221
+ * `other` template for any other count. Both templates take `{count}`.
11222
+ *
11223
+ * @param count - The number to show.
11224
+ * @param templates - The `...One` and `...Other` label templates.
11225
+ *
11226
+ * ```ts
11227
+ * ɵformatCountLabel(3, {
11228
+ * one: labels.toolCallToolCountOne,
11229
+ * other: labels.toolCallToolCountOther,
11230
+ * }); // "3 tools"
11231
+ * ```
11232
+ */
11233
+ function ɵformatCountLabel(count, templates) {
11234
+ return ɵformatLabel(count === 1 ? templates.one : templates.other, { count });
11235
+ }
11236
+
11237
+ //#endregion
11238
+ //#region src/chat/renderers.ts
11239
+ /** Name or activity type that matches anything. */
11240
+ const WILDCARD = "*";
11241
+ /**
11242
+ * Find the renderer that draws a tool call.
11243
+ *
11244
+ * The first rule that matches wins:
11245
+ *
11246
+ * 1. A renderer for `toolName` with `agentId` equal to the current agent.
11247
+ * 2. A renderer for `toolName` with no `agentId`.
11248
+ * 3. The first renderer for `toolName` from any other agent.
11249
+ * 4. The first `"*"` renderer, from any agent.
11250
+ *
11251
+ * Inside each rule, the earlier renderer in the list wins.
11252
+ *
11253
+ * @param renderers - Registered renderers in registration order. If you
11254
+ * build tiers (for example app renderers before built-in ones), flatten
11255
+ * them into one ordered list first.
11256
+ * @param toolName - Name of the tool the agent called.
11257
+ * @param agentId - The agent that owns the chat. The caller picks the
11258
+ * default: React and Vue pass `DEFAULT_AGENT_ID` when the chat has no
11259
+ * agent. With `undefined`, rule 1 matches the same renderers as rule 2.
11260
+ * @returns The renderer, or `null` when no renderer matches. Draw nothing
11261
+ * for `null`.
11262
+ *
11263
+ * @example
11264
+ * ```ts
11265
+ * const renderer = ɵresolveToolCallRenderer(
11266
+ * core.renderToolCalls,
11267
+ * toolCall.function.name,
11268
+ * chatAgentId ?? DEFAULT_AGENT_ID,
11269
+ * );
11270
+ * ```
11271
+ */
11272
+ function ɵresolveToolCallRenderer(renderers, toolName, agentId) {
11273
+ const named = renderers.filter((renderer) => renderer.name === toolName);
11274
+ return named.find((renderer) => renderer.agentId === agentId) ?? named.find((renderer) => !renderer.agentId) ?? named[0] ?? renderers.find((renderer) => renderer.name === WILDCARD) ?? null;
11275
+ }
11276
+ /**
11277
+ * Find the renderer that draws an activity message, and validate the
11278
+ * message content with that renderer's `content` schema.
11279
+ *
11280
+ * The first rule that matches picks the renderer:
11281
+ *
11282
+ * 1. A renderer for `activityType` with `agentId` equal to the current agent.
11283
+ * 2. A renderer for `activityType` with no `agentId`.
11284
+ * 3. The first `"*"` renderer, from any agent.
11285
+ *
11286
+ * A renderer for `activityType` that belongs to a different agent never
11287
+ * matches. Inside each rule, the earlier renderer in the list wins.
11288
+ *
11289
+ * Only the picked renderer validates the content. When validation fails, or
11290
+ * the schema validates asynchronously, the result is `null`. The function
11291
+ * does not try the next renderer.
11292
+ *
11293
+ * @param renderers - Registered renderers in registration order.
11294
+ * @param query - The activity type, the current agent, and the raw content.
11295
+ * @returns `{ renderer, content }`, where `content` is the value the schema
11296
+ * returned. Pass that value to `render`, not the raw content. Returns
11297
+ * `null` when no renderer matches or validation does not pass.
11298
+ *
11299
+ * @example
11300
+ * ```ts
11301
+ * const match = ɵresolveActivityRenderer(core.renderActivityMessages, {
11302
+ * activityType: message.activityType,
11303
+ * agentId,
11304
+ * content: message.content,
11305
+ * });
11306
+ * if (match) draw(match.renderer.render, match.content);
11307
+ * ```
11308
+ */
11309
+ function ɵresolveActivityRenderer(renderers, query) {
11310
+ const { activityType, agentId, content } = query;
11311
+ const sameType = renderers.filter((renderer) => renderer.activityType === activityType);
11312
+ const renderer = sameType.find((candidate) => candidate.agentId === agentId) ?? sameType.find((candidate) => candidate.agentId === void 0) ?? renderers.find((candidate) => candidate.activityType === WILDCARD);
11313
+ if (renderer === void 0) return null;
11314
+ const result = renderer.content["~standard"].validate(content);
11315
+ if (result instanceof Promise) return null;
11316
+ if (result.issues) return null;
11317
+ return {
11318
+ renderer,
11319
+ content: result.value
11320
+ };
11321
+ }
11322
+ /**
11323
+ * List the custom message renderers that apply to an agent, in the order to
11324
+ * try them.
11325
+ *
11326
+ * The list keeps renderers with no `agentId` and renderers for `agentId`.
11327
+ * Renderers for `agentId` come first. Inside each group, registration order
11328
+ * stays the same.
11329
+ *
11330
+ * The framework tries each renderer in this order and shows the first one
11331
+ * that draws something (a non-null result).
11332
+ *
11333
+ * @param renderers - Registered renderers in registration order.
11334
+ * @param agentId - The agent that owns the chat.
11335
+ * @returns A new array. Empty when no renderer applies.
11336
+ *
11337
+ * @example
11338
+ * ```ts
11339
+ * const candidates = ɵresolveCustomMessageRenderers(
11340
+ * core.renderCustomMessages,
11341
+ * agentId,
11342
+ * );
11343
+ * ```
11344
+ */
11345
+ function ɵresolveCustomMessageRenderers(renderers, agentId) {
11346
+ const scoped = renderers.filter((renderer) => renderer.agentId === agentId);
11347
+ const unscoped = renderers.filter((renderer) => renderer.agentId === void 0);
11348
+ return [...scoped, ...unscoped];
11349
+ }
11350
+
11351
+ //#endregion
11352
+ //#region src/chat/interrupt-types.ts
11353
+ /** Name of the legacy custom event agents emit to signal an interrupt. */
11354
+ const INTERRUPT_EVENT_NAME = "on_interrupt";
11355
+
11356
+ //#endregion
11357
+ //#region src/chat/tool-call-layout.ts
11358
+ function contentLength(content) {
11359
+ return typeof content === "string" ? content.length : JSON.stringify(content ?? "").length;
11360
+ }
11361
+ const entrySignature = ({ toolCall, toolMessage }) => [
11362
+ toolCall.id,
11363
+ toolCall.function.name,
11364
+ toolCall.function.arguments.length,
11365
+ toolMessage ? `${contentLength(toolMessage.content)}${toolMessage.error ? "!" : ""}` : "-"
11366
+ ].join(":");
11367
+ function signatureOf(segments) {
11368
+ return segments.map((segment) => segment.kind === "call" ? `c(${entrySignature(segment.call)})` : `g${segment.trailing ? "*" : ""}(${segment.calls.map(entrySignature).join(",")})`).join("|");
11369
+ }
11370
+ /**
11371
+ * Indexes tool results by the id of the call they answer.
11372
+ *
11373
+ * @param messages - The messages to search. Only `role: "tool"` messages count.
11374
+ */
11375
+ function getToolResults(messages) {
11376
+ const results = /* @__PURE__ */ new Map();
11377
+ for (const message of messages) if (message.role === "tool") results.set(message.toolCallId, message);
11378
+ return results;
11379
+ }
11380
+ /**
11381
+ * Lays out the tool calls of every assistant message in `rendered`.
11382
+ *
11383
+ * Calls drawn by a renderer that opted into grouping join the group that is
11384
+ * open. Anything else that shows between them closes it: assistant text, a
11385
+ * user, reasoning or activity message, or a call drawn by any other renderer.
11386
+ * A group belongs to the message where it starts, so later messages whose
11387
+ * calls joined it render no tool calls themselves.
11388
+ *
11389
+ * @param rendered - The messages as the chat renders them, in order.
11390
+ * @param all - Every message, for finding tool results (a transform may hide them).
11391
+ * @param renderers - The registered renderers, from `getToolCallRendererNames`.
11392
+ * @returns A map from assistant message id to its layout.
11393
+ *
11394
+ * @example
11395
+ * ```ts
11396
+ * const names = getToolCallRendererNames(core.renderToolCalls);
11397
+ * const layouts = getToolCallLayouts(renderedMessages, messages, names);
11398
+ * layouts.get(message.id)?.segments;
11399
+ * ```
11400
+ */
11401
+ function getToolCallLayouts(rendered, all, renderers) {
11402
+ const results = getToolResults(all);
11403
+ const layouts = /* @__PURE__ */ new Map();
11404
+ let open;
11405
+ for (const message of rendered) {
11406
+ if (message.role === "tool") continue;
11407
+ if (message.role !== "assistant") {
11408
+ open = void 0;
11409
+ continue;
11410
+ }
11411
+ if (typeof message.content === "string" && message.content.trim() !== "") open = void 0;
11412
+ const segments = [];
11413
+ layouts.set(message.id, segments);
11414
+ const toolCalls = /* @__PURE__ */ new Map();
11415
+ const messageToolCalls = message.toolCalls ?? [];
11416
+ for (const toolCall of messageToolCalls) toolCalls.set(toolCall.id, toolCall);
11417
+ const uniqueToolCalls = toolCalls.values();
11418
+ for (const toolCall of uniqueToolCalls) {
11419
+ const entry = {
11420
+ toolCall,
11421
+ toolMessage: results.get(toolCall.id)
11422
+ };
11423
+ const name = toolCall.function.name;
11424
+ const named = renderers.named.has(name);
11425
+ const isRendered = named || renderers.wildcard;
11426
+ const groups = named ? renderers.groupedNames.has(name) : renderers.wildcardGroups;
11427
+ if (!isRendered || !groups) {
11428
+ if (isRendered) open = void 0;
11429
+ segments.push({
11430
+ kind: "call",
11431
+ id: toolCall.id,
11432
+ call: entry,
11433
+ rendered: isRendered
11434
+ });
11435
+ } else if (open) open.calls.push(entry);
11436
+ else {
11437
+ open = {
11438
+ kind: "group",
11439
+ id: toolCall.id,
11440
+ calls: [entry],
11441
+ trailing: false
11442
+ };
11443
+ segments.push(open);
11444
+ }
11445
+ }
11446
+ }
11447
+ if (open) open.trailing = true;
11448
+ const layout = /* @__PURE__ */ new Map();
11449
+ for (const [id, segments] of layouts) layout.set(id, {
11450
+ segments,
11451
+ signature: signatureOf(segments)
11452
+ });
11453
+ return layout;
11454
+ }
11455
+ const TOOL_CALL_SLOT_PREFIX = "tool-call-";
11456
+ const WILDCARD_TOOL_CALL_SLOT = "tool-call";
11457
+ /**
11458
+ * Works out which tool calls have a renderer and which of those group, for
11459
+ * `getToolCallLayouts`.
11460
+ *
11461
+ * @param renderers - The registered renderers. A renderer named `"*"` is the
11462
+ * wildcard. `group: true` opts the renderer into grouping.
11463
+ * @param options - Slots, extra named tools, and a built-in wildcard card.
11464
+ * See `ToolCallRendererNamesOptions`.
11465
+ *
11466
+ * @example
11467
+ * ```ts
11468
+ * // React: only registered renderers.
11469
+ * getToolCallRendererNames(core.renderToolCalls);
11470
+ * // Vue: the view's slots count too.
11471
+ * getToolCallRendererNames(core.renderToolCalls, { slotNames: Object.keys(slots) });
11472
+ * // Angular: client and human-in-the-loop renderers, and the built-in card.
11473
+ * getToolCallRendererNames(appRenderers, {
11474
+ * extraNamed: [...clientNames, ...hitlNames],
11475
+ * builtInWildcard: { enabled: defaultToolRenderingEnabled, groups: true },
11476
+ * });
11477
+ * ```
11478
+ */
11479
+ function getToolCallRendererNames(renderers, options = {}) {
11480
+ const { slotNames = [], extraNamed = [], builtInWildcard } = options;
11481
+ const hasWildcardSlot = slotNames.includes(WILDCARD_TOOL_CALL_SLOT);
11482
+ const slotTools = slotNames.filter((name) => name.startsWith(TOOL_CALL_SLOT_PREFIX)).map((name) => name.slice(10));
11483
+ const named = renderers.filter((renderer) => renderer.name !== "*");
11484
+ const wildcards = renderers.filter((renderer) => renderer.name === "*");
11485
+ const hasAppWildcard = wildcards.length > 0;
11486
+ const isBuiltInEnabled = builtInWildcard?.enabled ?? false;
11487
+ const builtInGroups = isBuiltInEnabled && (builtInWildcard?.groups ?? false);
11488
+ const groupedNames = hasWildcardSlot ? [] : named.filter((renderer) => renderer.group && !slotTools.includes(renderer.name)).map((renderer) => renderer.name);
11489
+ const appWildcardGroups = wildcards.some((renderer) => renderer.group);
11490
+ return {
11491
+ named: new Set([
11492
+ ...named.map((renderer) => renderer.name),
11493
+ ...slotTools,
11494
+ ...extraNamed
11495
+ ]),
11496
+ groupedNames: new Set(groupedNames),
11497
+ wildcard: hasAppWildcard || hasWildcardSlot || isBuiltInEnabled,
11498
+ wildcardGroups: !hasWildcardSlot && (hasAppWildcard ? appWildcardGroups : builtInGroups)
11499
+ };
11500
+ }
11501
+ /** The turn key of a reply that no user message starts. */
11502
+ const FIRST_TURN_KEY = "start";
11503
+ /**
11504
+ * Finds the working phase of every reply in `rendered`: its messages up to the
11505
+ * last one that calls a tool. Text in there was narration. What follows is the
11506
+ * reply itself. Replies that called no tools are left out, except the latest,
11507
+ * which may be about to.
11508
+ *
11509
+ * @param rendered - The messages as the chat renders them, in order.
11510
+ * @param layouts - The layouts from `getToolCallLayouts` for the same messages.
11511
+ * @returns A map from turn key (see `TurnWork.key`) to the turn's work.
11512
+ */
11513
+ function getTurnWork(rendered, layouts) {
11514
+ const turns = /* @__PURE__ */ new Map();
11515
+ let start = 0;
11516
+ while (start < rendered.length) {
11517
+ let end = start;
11518
+ while (end < rendered.length && rendered[end].role !== "user") end++;
11519
+ const key = start > 0 ? rendered[start - 1].id : FIRST_TURN_KEY;
11520
+ const visible = rendered.slice(start, end).filter((message) => message.role !== "tool");
11521
+ const isLatest = end === rendered.length;
11522
+ const calls = [];
11523
+ for (const message of visible) {
11524
+ const segments = layouts.get(message.id)?.segments ?? [];
11525
+ for (const segment of segments) if (segment.kind === "group") calls.push(...segment.calls);
11526
+ else if (segment.rendered) calls.push(segment.call);
11527
+ }
11528
+ const shown = new Set(calls.map((entry) => entry.toolCall.id));
11529
+ let lastWork = -1;
11530
+ visible.forEach((message, index) => {
11531
+ if (message.role === "assistant" && message.toolCalls?.some((call) => shown.has(call.id))) lastWork = index;
11532
+ });
11533
+ const first = visible[0];
11534
+ if (first && (calls.length > 0 || isLatest)) {
11535
+ let lastAssistant = -1;
11536
+ visible.forEach((message, index) => {
11537
+ if (message.role === "assistant") lastAssistant = index;
11538
+ });
11539
+ const replyText = visible[lastAssistant]?.content;
11540
+ const endsWithWork = lastAssistant >= 0 && lastAssistant <= lastWork && typeof replyText === "string" && replyText.trim().length > 0;
11541
+ turns.set(key, {
11542
+ key,
11543
+ firstMessageId: first.id,
11544
+ workMessageIds: new Set(visible.slice(0, lastWork + 1).map((message) => message.id)),
11545
+ replyTextMessageId: endsWithWork ? visible[lastAssistant].id : void 0,
11546
+ calls,
11547
+ isLatest
11548
+ });
11549
+ }
11550
+ start = end + 1;
11551
+ }
11552
+ return turns;
11553
+ }
11554
+ /**
11555
+ * The key of the latest reply (see `TurnWork.key`): the id of the last user
11556
+ * message, or `"start"` when there is none.
11557
+ *
11558
+ * @param rendered - The messages as the chat renders them, in order.
11559
+ */
11560
+ function getLatestTurnKey(rendered) {
11561
+ for (let i = rendered.length - 1; i >= 0; i--) {
11562
+ const message = rendered[i];
11563
+ if (message.role === "user") return message.id;
11564
+ }
11565
+ return FIRST_TURN_KEY;
11566
+ }
11567
+ /**
11568
+ * Whether the agent is working on this reply now: it is the latest one and a
11569
+ * run is going.
11570
+ *
11571
+ * @param turnKey - The reply's `TurnWork.key`.
11572
+ * @param state - The run state and the latest turn key.
11573
+ */
11574
+ function isTurnWorking(turnKey, state) {
11575
+ return state.isRunning && turnKey === state.latestTurnKey;
11576
+ }
11577
+ /**
11578
+ * Whether a reply's work shows. It shows while the agent works on the reply
11579
+ * and folds once the reply is done, unless the user opened or closed it.
11580
+ *
11581
+ * @param turnKey - The reply's `TurnWork.key`.
11582
+ * @param state - The user's toggles, the run state, and the latest turn key.
11583
+ */
11584
+ function isTurnWorkOpen(turnKey, state) {
11585
+ return state.toggledTurns.get(turnKey) ?? isTurnWorking(turnKey, state);
11586
+ }
11587
+ /**
11588
+ * For each message in a reply's working phase, whether its work and its text
11589
+ * show. Text that ends the reply stays out of `workTextOpen` even when its
11590
+ * message also calls a tool, because it is the answer.
11591
+ *
11592
+ * @param turns - The turns from `getTurnWork`.
11593
+ * @param state - The user's toggles, the run state, and the latest turn key.
11594
+ * @returns The `workOpen` and `workTextOpen` maps of `ToolCallDisplayContextValue`.
11595
+ */
11596
+ function getWorkOpenState(turns, state) {
11597
+ const workOpen = /* @__PURE__ */ new Map();
11598
+ const workTextOpen = /* @__PURE__ */ new Map();
11599
+ for (const turn of turns) {
11600
+ const turnOpen = isTurnWorkOpen(turn.key, state);
11601
+ for (const id of turn.workMessageIds) {
11602
+ workOpen.set(id, turnOpen);
11603
+ if (id !== turn.replyTextMessageId) workTextOpen.set(id, turnOpen);
11604
+ }
11605
+ }
11606
+ return {
11607
+ workOpen,
11608
+ workTextOpen
11609
+ };
11610
+ }
11611
+ /**
11612
+ * Records run starts and ends in `workTimes`, for "Worked for 9s". Time spent
11613
+ * between runs (say, waiting for an approval) does not count. A reply is only
11614
+ * timed when this client saw it start from the user's message, so a restored
11615
+ * thread gets no entry. Calling it again with the same state changes nothing.
11616
+ *
11617
+ * @param workTimes - The times by turn key. This function updates it in place.
11618
+ * @param state - The run state now.
11619
+ * @param state.lastMessageRole - The role of the last rendered message.
11620
+ * @param state.now - The current time, in epoch ms.
11621
+ */
11622
+ function recordWorkTime(workTimes, state) {
11623
+ const { isRunning, latestTurnKey, lastMessageRole, now } = state;
11624
+ if (isRunning) {
11625
+ const times = workTimes.get(latestTurnKey);
11626
+ if (times) times.workingSince ??= now;
11627
+ else if (lastMessageRole === "user") workTimes.set(latestTurnKey, {
11628
+ elapsedMs: 0,
11629
+ workingSince: now
11630
+ });
11631
+ return;
11632
+ }
11633
+ const allTimes = workTimes.values();
11634
+ for (const times of allTimes) {
11635
+ if (times.workingSince === void 0) continue;
11636
+ times.elapsedMs += now - times.workingSince;
11637
+ times.workingSince = void 0;
11638
+ }
11639
+ }
11640
+ /**
11641
+ * The status of one call in a group. A call without a result is running only
11642
+ * while the group is active: once the run has moved on or ended, its result
11643
+ * is never coming.
11644
+ *
11645
+ * @param entry - The call and its result, if any.
11646
+ * @param active - The agent may still finish the group's calls.
11647
+ */
11648
+ function getToolCallRowStatus(entry, active) {
11649
+ const { toolMessage } = entry;
11650
+ let status;
11651
+ if (toolMessage) status = toolMessage.error ? "failed" : "done";
11652
+ else status = active ? "running" : "stopped";
11653
+ return status;
11654
+ }
11655
+ /**
11656
+ * The first non-empty string argument, with runs of whitespace collapsed to
11657
+ * one space. This is usually a command, path or query.
11658
+ *
11659
+ * @param parameters - The call's parsed arguments.
11660
+ * @returns The preview, or `undefined` when no argument is a non-empty string.
11661
+ */
11662
+ function getArgumentPreview(parameters) {
11663
+ if (!parameters || typeof parameters !== "object") return void 0;
11664
+ return Object.values(parameters).find((v) => typeof v === "string" && v.trim().length > 0)?.replace(/\s+/g, " ");
11665
+ }
11666
+ /**
11667
+ * `getArgumentPreview` for a call whose arguments may still be streaming in
11668
+ * as partial JSON.
11669
+ *
11670
+ * @param entry - The call.
11671
+ */
11672
+ function getToolCallPreview(entry) {
11673
+ return getArgumentPreview((0, _copilotkit_shared.partialJSONParse)(entry.toolCall.function.arguments));
11674
+ }
11675
+ /**
11676
+ * The names of the tools the calls used, in first-use order, with a count
11677
+ * for repeats: `"run_command ×2, read_file"`.
11678
+ *
11679
+ * @param calls - The calls to name.
11680
+ */
11681
+ function formatToolNames(calls) {
11682
+ const counts = /* @__PURE__ */ new Map();
11683
+ for (const { toolCall } of calls) {
11684
+ const name = toolCall.function.name;
11685
+ counts.set(name, (counts.get(name) ?? 0) + 1);
11686
+ }
11687
+ return [...counts].map(([name, count]) => count > 1 ? `${name} ×${count}` : name).join(", ");
11688
+ }
11689
+ /**
11690
+ * How many of the calls finished with an error.
11691
+ *
11692
+ * @param calls - The calls to count.
11693
+ */
11694
+ function countFailedToolCalls(calls) {
11695
+ return calls.filter((call) => call.toolMessage?.error).length;
11696
+ }
11697
+ /**
11698
+ * A count followed by the word that fits it: `"1 tool"`, `"3 tools"`.
11699
+ *
11700
+ * @param count - The number to show.
11701
+ * @param words - The word for exactly one (`one`) and for any other count (`other`).
11702
+ *
11703
+ * @example
11704
+ * ```ts
11705
+ * pluralize(3, { one: "tool", other: "tools" }); // "3 tools"
11706
+ * ```
11707
+ */
11708
+ function pluralize(count, words) {
11709
+ return `${count} ${count === 1 ? words.one : words.other}`;
11710
+ }
11711
+ /**
11712
+ * A tool call's arguments or result as display text. Strings pass through.
11713
+ * Other values are pretty-printed JSON. A value JSON cannot encode (say, a
11714
+ * circular reference) falls back to `String(value)`, then to
11715
+ * `"[unserializable]"`, so it never throws during a render.
11716
+ *
11717
+ * @param value - The arguments or the result.
11718
+ */
11719
+ function stringifyToolCallPayload(value) {
11720
+ if (typeof value === "string") return value;
11721
+ try {
11722
+ return JSON.stringify(value, null, 2);
11723
+ } catch (err) {
11724
+ console.warn("[CopilotKit] Failed to JSON.stringify tool-call payload; falling back to String():", err);
11725
+ try {
11726
+ return String(value);
11727
+ } catch {
11728
+ return "[unserializable]";
11729
+ }
11730
+ }
11731
+ }
11732
+ /**
11733
+ * How long a `"turn"` reply worked, as short text: `"45s"`, `"1m 5s"`, `"2m"`.
11734
+ * Used for the live timer and the final duration. Partial seconds round down,
11735
+ * and a negative time reads `"0s"`.
11736
+ *
11737
+ * @param ms - The time in milliseconds.
11738
+ */
11739
+ function formatWorkDuration(ms) {
11740
+ const seconds = Math.max(0, Math.floor(ms / 1e3));
11741
+ if (seconds < 60) return `${seconds}s`;
11742
+ const minutes = Math.floor(seconds / 60);
11743
+ const rest = seconds % 60;
11744
+ return rest ? `${minutes}m ${rest}s` : `${minutes}m`;
11745
+ }
11746
+ /**
11747
+ * Splits a reasoning time into the unit and counts the "Thought for ..."
11748
+ * header shows. See `ReasoningDuration` for the text each unit maps to.
11749
+ *
11750
+ * - Under 1 second: `fewSeconds`.
11751
+ * - Under 60 seconds: `seconds`, rounded to the nearest second.
11752
+ * - Whole minutes after rounding the seconds: `minutes`.
11753
+ * - Otherwise: `minutesSeconds`.
11754
+ *
11755
+ * @param seconds - The elapsed time in seconds. It may have a fraction.
11756
+ */
11757
+ function formatReasoningDuration(seconds) {
11758
+ if (seconds < 1) return { unit: "fewSeconds" };
11759
+ if (seconds < 60) return {
11760
+ unit: "seconds",
11761
+ seconds: Math.round(seconds)
11762
+ };
11763
+ const minutes = Math.floor(seconds / 60);
11764
+ const rest = Math.round(seconds % 60);
11765
+ if (rest === 0) return {
11766
+ unit: "minutes",
11767
+ minutes
11768
+ };
11769
+ return {
11770
+ unit: "minutesSeconds",
11771
+ minutes,
11772
+ seconds: rest
11773
+ };
11774
+ }
11775
+
11776
+ //#endregion
11777
+ //#region src/chat/messages.ts
11778
+ /**
11779
+ * Collapses tool calls that share an id, keeping first-seen order.
11780
+ *
11781
+ * AG-UI's TOOL_CALL_START handler appends to the parent message's `toolCalls`
11782
+ * without checking whether that id is already present. When a start event is
11783
+ * applied twice (the human-in-the-loop flow does this when the run syncs after
11784
+ * `respond()`), the message carries the same call twice. The second copy has
11785
+ * empty `arguments`, because a start event carries none. The args arrive later
11786
+ * as TOOL_CALL_ARGS deltas addressed to the first copy.
11787
+ *
11788
+ * Left alone, the same tool call renders twice: once populated and once blank.
11789
+ * The blank copy is the redundant one, so the copy that carries arguments wins,
11790
+ * whatever order the two arrive in.
11791
+ *
11792
+ * @param toolCalls - The tool calls of one assistant message.
11793
+ * @returns The same array when no id repeats, so memoized consumers keep a
11794
+ * stable reference. Otherwise a new array with one entry per id.
11795
+ */
11796
+ function dedupeToolCalls(toolCalls) {
11797
+ const byId = /* @__PURE__ */ new Map();
11798
+ for (const toolCall of toolCalls) {
11799
+ const existing = byId.get(toolCall.id);
11800
+ if (!existing) {
11801
+ byId.set(toolCall.id, toolCall);
11802
+ continue;
11803
+ }
11804
+ if (!existing.function?.arguments && Boolean(toolCall.function?.arguments)) byId.set(toolCall.id, toolCall);
11805
+ }
11806
+ return byId.size === toolCalls.length ? toolCalls : [...byId.values()];
11807
+ }
11808
+ /**
11809
+ * Merges two snapshots of the same assistant message.
11810
+ *
11811
+ * - Empty `content` means a streaming update cleared the field, so the earlier
11812
+ * non-empty content is kept.
11813
+ * - `toolCalls: undefined` means the later chunk had no tool-call activity, so
11814
+ * the earlier tool calls are kept. An explicit `[]` is kept as-is.
11815
+ * - Fields that only the earlier snapshot has are kept.
11816
+ */
11817
+ function mergeAssistantMessages(existing, message) {
11818
+ const content = message.content || existing.content;
11819
+ const toolCalls = message.toolCalls ?? existing.toolCalls;
11820
+ return {
11821
+ ...existing,
11822
+ ...message,
11823
+ content,
11824
+ toolCalls: toolCalls ? dedupeToolCalls(toolCalls) : toolCalls
11825
+ };
11826
+ }
11827
+ /**
11828
+ * Returns the assistant message with repeated tool-call ids collapsed. Returns
11829
+ * the same object when nothing collapsed.
11830
+ */
11831
+ function withDedupedToolCalls(message) {
11832
+ if (!message.toolCalls) return message;
11833
+ const toolCalls = dedupeToolCalls(message.toolCalls);
11834
+ return toolCalls === message.toolCalls ? message : {
11835
+ ...message,
11836
+ toolCalls
11837
+ };
11838
+ }
11839
+ /**
11840
+ * De-duplicates chat messages by id, for rendering.
11841
+ *
11842
+ * A message list from an agent can hold the same message id more than once
11843
+ * while it streams. This keeps one entry per id, at the position the id first
11844
+ * appears:
11845
+ *
11846
+ * - **Assistant messages** are merged. Later fields win, but empty `content`
11847
+ * falls back to earlier non-empty content, and `toolCalls: undefined` falls
11848
+ * back to earlier tool calls (an explicit `[]` is kept).
11849
+ * - **Tool calls** on an assistant message are de-duplicated by id, also
11850
+ * when the message itself is not repeated. The copy that has arguments
11851
+ * wins, and the first-seen order is kept.
11852
+ * - **Other roles** keep the last copy.
11853
+ *
11854
+ * @param messages - The agent's messages, in order.
11855
+ * @returns A new array. A message that needed no change is returned as the
11856
+ * same object.
11857
+ *
11858
+ * @example
11859
+ * ```ts
11860
+ * const visible = ɵdeduplicateMessages(agent.messages);
11861
+ * ```
11862
+ */
11863
+ function ɵdeduplicateMessages(messages) {
11864
+ const byId = /* @__PURE__ */ new Map();
11865
+ for (const message of messages) {
11866
+ if (message.role !== "assistant") {
11867
+ byId.set(message.id, message);
11868
+ continue;
11869
+ }
11870
+ const existing = byId.get(message.id);
11871
+ const merged = existing?.role === "assistant" ? mergeAssistantMessages(existing, message) : withDedupedToolCalls(message);
11872
+ byId.set(message.id, merged);
11873
+ }
11874
+ return [...byId.values()];
11875
+ }
11876
+ /**
11877
+ * Serializes object content for {@link ɵmessagesFingerprint}.
11878
+ *
11879
+ * `JSON.stringify` throws on a circular structure (and on a `BigInt`). The
11880
+ * fingerprint runs on every render, so a throw would take the chat down. A
11881
+ * value that cannot be serialized gets a constant key instead: it does not
11882
+ * trigger a change on its own, but every other part of the fingerprint still
11883
+ * does.
11884
+ */
11885
+ function objectContentKey(content) {
11886
+ try {
11887
+ return JSON.stringify(content) ?? "";
11888
+ } catch {
11889
+ return "[unserializable]";
11890
+ }
11891
+ }
11892
+ /**
11893
+ * Gives the part of the fingerprint that tracks a message's content:
11894
+ * - string content: its length, so streamed text changes it.
11895
+ * - array content: the part count, so an added attachment changes it. The
11896
+ * parts are not serialized, which keeps base64 uploads out of the key.
11897
+ * - object content (activity messages): its JSON, so a snapshot that replaces
11898
+ * the content under the same message id changes it.
11899
+ */
11900
+ function contentKey(content) {
11901
+ if (typeof content === "string" || Array.isArray(content)) return String(content.length);
11902
+ if (content !== null && typeof content === "object") return objectContentKey(content);
11903
+ return "0";
11904
+ }
11905
+ /**
11906
+ * Builds a string that changes whenever a render of the message list could
11907
+ * change. Use it as a cheap memo key in place of a deep comparison.
11908
+ *
11909
+ * The key covers, per message:
11910
+ * - the id and the role.
11911
+ * - the content: text length, part count, or the JSON of object content.
11912
+ * - the `toolCallId` of a tool message.
11913
+ * - each tool call's id and the length of its arguments, so streamed
11914
+ * arguments change the key.
11915
+ *
11916
+ * It never throws. Object content that cannot be serialized (for example a
11917
+ * circular tool result) gets a constant key.
11918
+ *
11919
+ * @param messages - The agent's messages, in order.
11920
+ * @returns The fingerprint string.
11921
+ *
11922
+ * @example
11923
+ * ```ts
11924
+ * const key = ɵmessagesFingerprint(agent.messages);
11925
+ * if (key !== previousKey) rerender();
11926
+ * ```
11927
+ */
11928
+ function ɵmessagesFingerprint(messages) {
11929
+ return messages.map((message) => {
11930
+ const toolCallId = "toolCallId" in message ? message.toolCallId : "";
11931
+ const toolCallsKey = ("toolCalls" in message && Array.isArray(message.toolCalls) ? message.toolCalls : []).map((tc) => `${tc.id}:${tc.function?.arguments?.length ?? 0}`).join(";");
11932
+ return `${message.id}:${message.role}:${contentKey(message.content)}:${toolCallId}:${toolCallsKey}`;
11933
+ }).join(",");
11934
+ }
11935
+
11936
+ //#endregion
11937
+ //#region src/chat/composer.ts
11938
+ /**
11939
+ * Get the state of the send/stop button in the chat input.
11940
+ *
11941
+ * @param input - The current state of the chat input.
11942
+ * @returns
11943
+ * - `isProcessing`: the agent runs and the input does not record audio.
11944
+ * - `canSend`: the text is not empty and nothing blocks a send.
11945
+ * - `action`: `"stop"` when the button stops the run, else `"send"`.
11946
+ * Use it for the icon, the label, and the click.
11947
+ * - `disabled`: `true` when a click does nothing.
11948
+ *
11949
+ * @example
11950
+ * ```ts
11951
+ * const button = ɵcomposerButtonState({
11952
+ * mode: "input",
11953
+ * isRunning: agent.isRunning,
11954
+ * value: text,
11955
+ * canSubmit: true,
11956
+ * canStop: true,
11957
+ * });
11958
+ * // On click:
11959
+ * if (button.action === "stop") stopRun();
11960
+ * else if (button.canSend) sendMessage(text.trim());
11961
+ * ```
11962
+ */
11963
+ function ɵcomposerButtonState(input) {
11964
+ const isProcessing = input.mode !== "transcribe" && input.isRunning;
11965
+ const isSendBlocked = input.disabled === true || input.attachmentsUploading === true;
11966
+ const canSend = input.canSubmit && !isSendBlocked && input.value.trim().length > 0;
11967
+ return {
11968
+ isProcessing,
11969
+ canSend,
11970
+ action: isProcessing && input.canStop ? "stop" : "send",
11971
+ disabled: isProcessing ? !input.canStop : !canSend
11972
+ };
11973
+ }
11974
+ /**
11975
+ * Decide what a key press in the chat input does.
11976
+ *
11977
+ * This handles Enter only. Keys for the slash-command menu stay in each
11978
+ * framework, and the framework handles them before it calls this function.
11979
+ *
11980
+ * Results:
11981
+ * - `"send"`: send the trimmed text.
11982
+ * - `"stop"`: stop the run. This happens for Enter in an empty input while
11983
+ * the agent runs. Text in the input always means send, not stop.
11984
+ * - `"newline"`: Shift+Enter. Let the browser add the line break.
11985
+ * - `"none"`: do nothing. Returned during IME composition, while the input
11986
+ * is disabled, for keys other than Enter, and for an Enter that has
11987
+ * nothing to send or stop.
11988
+ *
11989
+ * Call `preventDefault()` for every Enter without Shift that is not part of
11990
+ * IME composition, including when the result is `"none"`. This stops Enter
11991
+ * from adding a line break that the user cannot send.
11992
+ *
11993
+ * @param event - The keyboard event, or an object with the same fields.
11994
+ * @param input - The current state of the chat input.
11995
+ *
11996
+ * @example
11997
+ * ```ts
11998
+ * function onKeyDown(event: KeyboardEvent) {
11999
+ * if (event.isComposing || event.keyCode === 229) return;
12000
+ * // ...slash-command menu keys...
12001
+ * const result = ɵresolveComposerKey(event, composerInput);
12002
+ * if (event.key === "Enter" && !event.shiftKey) event.preventDefault();
12003
+ * if (result === "send") sendMessage(composerInput.value.trim());
12004
+ * if (result === "stop") stopRun();
12005
+ * }
12006
+ * ```
12007
+ */
12008
+ function ɵresolveComposerKey(event, input) {
12009
+ if (event.isComposing || event.keyCode === 229 || input.disabled === true || event.key !== "Enter") return "none";
12010
+ if (event.shiftKey) return "newline";
12011
+ const button = ɵcomposerButtonState(input);
12012
+ const isEmpty = input.value.trim().length === 0;
12013
+ if (button.isProcessing && isEmpty) return input.canStop ? "stop" : "none";
12014
+ return button.canSend ? "send" : "none";
12015
+ }
12016
+
12017
+ //#endregion
12018
+ //#region src/chat/transcription.ts
12019
+ /**
12020
+ * The error `ɵtranscribeAudio` throws. Read `error.info.code` to pick a
12021
+ * message for the user, or pass `error.info` to
12022
+ * `ɵtranscriptionErrorMessageKey`.
12023
+ */
12024
+ var TranscriptionError = class extends Error {
12025
+ info;
12026
+ constructor(info) {
12027
+ super(info.message);
12028
+ this.name = "TranscriptionError";
12029
+ this.info = info;
12030
+ }
12031
+ };
12032
+ /**
12033
+ * Send a recording to the CopilotKit runtime and get its text back.
12034
+ *
12035
+ * The request follows the transport set on the core:
12036
+ * - `"single"`: one JSON POST to `runtimeUrl`, with the audio as base64.
12037
+ * - any other transport: a multipart POST to `${runtimeUrl}/transcribe`.
12038
+ *
12039
+ * Headers are resolved on each call. The core's `credentials` are sent when
12040
+ * they are set, the same as for agent requests.
12041
+ *
12042
+ * @param core - The `CopilotKitCore` (or a framework subclass) to send through.
12043
+ * @param audioBlob - The recorded audio.
12044
+ * @param filename - The file name the runtime sees. Defaults to `"recording.webm"`.
12045
+ * @returns The transcription result, with the text in `result.text`.
12046
+ * @throws {TranscriptionError} When the runtime URL is not set, the request
12047
+ * fails, or the runtime returns an error. `error.info` has the code.
12048
+ *
12049
+ * @example
12050
+ * ```ts
12051
+ * try {
12052
+ * const { text } = await ɵtranscribeAudio(core, blob);
12053
+ * } catch (error) {
12054
+ * if (error instanceof TranscriptionError) {
12055
+ * const key = ɵtranscriptionErrorMessageKey(error.info);
12056
+ * showError(key ? labels[key] : error.info.message);
12057
+ * }
12058
+ * }
12059
+ * ```
12060
+ */
12061
+ async function ɵtranscribeAudio(core, audioBlob, filename = "recording.webm") {
12062
+ const { runtimeUrl, credentials } = core;
12063
+ if (!runtimeUrl) throw new TranscriptionError({
12064
+ code: _copilotkit_shared.TranscriptionErrorCode.INVALID_REQUEST,
12065
+ message: "Runtime URL is not configured",
12066
+ retryable: false
12067
+ });
12068
+ const resolvedHeaders = await core.resolveHeaders();
12069
+ const credentialsInit = credentials ? { credentials } : {};
12070
+ let response;
12071
+ try {
12072
+ response = core.runtimeTransport === "single" ? await fetch(runtimeUrl, {
12073
+ method: "POST",
12074
+ headers: {
12075
+ ...omitContentType(resolvedHeaders),
12076
+ "Content-Type": "application/json"
12077
+ },
12078
+ body: JSON.stringify({
12079
+ method: "transcribe",
12080
+ body: {
12081
+ audio: await blobToBase64(audioBlob),
12082
+ mimeType: audioBlob.type || "audio/webm",
12083
+ filename
12084
+ }
12085
+ }),
12086
+ ...credentialsInit
12087
+ }) : await fetch(`${runtimeUrl}/transcribe`, {
12088
+ method: "POST",
12089
+ headers: omitContentType(resolvedHeaders),
12090
+ body: toFormData(audioBlob, filename),
12091
+ ...credentialsInit
12092
+ });
12093
+ } catch (error) {
12094
+ throw new TranscriptionError({
12095
+ code: _copilotkit_shared.TranscriptionErrorCode.NETWORK_ERROR,
12096
+ message: error instanceof Error ? error.message : "Network request failed",
12097
+ retryable: true
12098
+ });
12099
+ }
12100
+ if (!response.ok) throw await toTranscriptionError(response);
12101
+ return await response.json();
12102
+ }
12103
+ /**
12104
+ * Pick the chat label to show the user for a transcription error.
12105
+ *
12106
+ * @param error - The `info` of a `TranscriptionError`.
12107
+ * @returns A key of the chat labels, or `null`. `null` means no label fits:
12108
+ * show `error.message` instead.
12109
+ *
12110
+ * @example
12111
+ * ```ts
12112
+ * const key = ɵtranscriptionErrorMessageKey(error.info);
12113
+ * const text = key ? labels[key] : error.info.message;
12114
+ * ```
12115
+ */
12116
+ function ɵtranscriptionErrorMessageKey(error) {
12117
+ switch (error.code) {
12118
+ case _copilotkit_shared.TranscriptionErrorCode.RATE_LIMITED: return "transcriptionErrorRateLimitedText";
12119
+ case _copilotkit_shared.TranscriptionErrorCode.AUTH_FAILED: return "transcriptionErrorAuthFailedText";
12120
+ case _copilotkit_shared.TranscriptionErrorCode.AUDIO_TOO_LONG: return "transcriptionErrorAudioTooLongText";
12121
+ case _copilotkit_shared.TranscriptionErrorCode.AUDIO_TOO_SHORT: return "transcriptionErrorAudioTooShortText";
12122
+ case _copilotkit_shared.TranscriptionErrorCode.INVALID_AUDIO_FORMAT: return "transcriptionErrorInvalidAudioFormatText";
12123
+ case _copilotkit_shared.TranscriptionErrorCode.SERVICE_NOT_CONFIGURED: return "transcriptionErrorServiceNotConfiguredText";
12124
+ case _copilotkit_shared.TranscriptionErrorCode.NETWORK_ERROR: return "transcriptionErrorNetworkText";
12125
+ case _copilotkit_shared.TranscriptionErrorCode.PROVIDER_ERROR:
12126
+ case _copilotkit_shared.TranscriptionErrorCode.INVALID_REQUEST:
12127
+ default: return error.retryable ? "transcriptionErrorGenericText" : null;
12128
+ }
12129
+ }
12130
+ function toFormData(audioBlob, filename) {
12131
+ const formData = new FormData();
12132
+ formData.append("audio", audioBlob, filename);
12133
+ return formData;
12134
+ }
12135
+ function omitContentType(headers) {
12136
+ const entries = Object.entries(headers);
12137
+ return Object.fromEntries(entries.filter(([name]) => name.toLowerCase() !== "content-type"));
12138
+ }
12139
+ async function blobToBase64(blob) {
12140
+ const bytes = new Uint8Array(await blob.arrayBuffer());
12141
+ const chunkSize = 32768;
12142
+ let binary = "";
12143
+ for (let offset = 0; offset < bytes.length; offset += chunkSize) binary += String.fromCharCode(...bytes.subarray(offset, offset + chunkSize));
12144
+ return btoa(binary);
12145
+ }
12146
+ /** Build a typed error from a non-OK transcription response. */
12147
+ async function toTranscriptionError(response) {
12148
+ const retryable = response.status >= 500;
12149
+ let data;
12150
+ try {
12151
+ data = await response.json();
12152
+ } catch {
12153
+ return new TranscriptionError({
12154
+ code: _copilotkit_shared.TranscriptionErrorCode.PROVIDER_ERROR,
12155
+ message: `HTTP ${response.status}: ${response.statusText}`,
12156
+ retryable
12157
+ });
12158
+ }
12159
+ if (isTranscriptionErrorResponse(data)) return new TranscriptionError({
12160
+ code: data.error,
12161
+ message: data.message,
12162
+ retryable: data.retryable ?? false
12163
+ });
12164
+ const message = typeof data === "object" && data !== null && "message" in data ? String(data.message) : "Transcription failed";
12165
+ return new TranscriptionError({
12166
+ code: _copilotkit_shared.TranscriptionErrorCode.PROVIDER_ERROR,
12167
+ message,
12168
+ retryable
12169
+ });
12170
+ }
12171
+ function isTranscriptionErrorResponse(data) {
12172
+ return typeof data === "object" && data !== null && "error" in data && "message" in data && typeof data.error === "string" && typeof data.message === "string";
12173
+ }
12174
+
12175
+ //#endregion
12176
+ //#region src/chat/license.ts
12177
+ /**
12178
+ * Resolves the license context and the license banner from the runtime
12179
+ * license authority. React, Vue, and Angular call it with the values core
12180
+ * reports, then show the banner and provide the context.
12181
+ *
12182
+ * Rules:
12183
+ *
12184
+ * - A retryable entitlement failure that core is still retrying hides the
12185
+ * status, so no banner shows until the retry ends. A `valid` or `expiring`
12186
+ * legacy status stays in use during the retry.
12187
+ * - A terminal entitlement failure (not retryable, no `valid` or `expiring`
12188
+ * legacy status) keeps the reported status, but `checkFeature` returns
12189
+ * `false` and `getLimit` returns `null` for every feature.
12190
+ * - The `no_license` banner shows only when the status is `none` and no
12191
+ * public key is set.
12192
+ *
12193
+ * The banner text has no day count. No data source gives the days left.
12194
+ *
12195
+ * @param input - The runtime license values and the public key. See
12196
+ * {@link LicenseStateInput}.
12197
+ * @returns `context` for the license context, `warningStatus` (the status the
12198
+ * banner is based on, `undefined` while a retry runs), and `bannerType`
12199
+ * (`null` when no banner shows).
12200
+ *
12201
+ * @example
12202
+ * ```ts
12203
+ * const { context, bannerType } = ɵresolveLicenseState({
12204
+ * status: core.licenseStatus,
12205
+ * entitlements: core.runtimeEntitlements,
12206
+ * retryPending: core.runtimeEntitlementRetryPending,
12207
+ * publicKey,
12208
+ * });
12209
+ * ```
12210
+ */
12211
+ function ɵresolveLicenseState({ status, entitlements, retryPending, publicKey }) {
12212
+ const isRetryableFailure = entitlements?.status !== "ready" && entitlements?.error.retryable === true;
12213
+ const isNonReady = entitlements !== void 0 && entitlements.status !== "ready";
12214
+ const hasLegacyFallback = status === "valid" || status === "expiring";
12215
+ const isRetrying = isRetryableFailure && retryPending && !hasLegacyFallback;
12216
+ const isTerminalFailure = isNonReady && !isRetryableFailure && !hasLegacyFallback;
12217
+ const runtimeContext = (0, _copilotkit_shared.createLicenseContextValue)(isRetrying ? void 0 : status, entitlements);
12218
+ const context = isTerminalFailure ? {
12219
+ ...runtimeContext,
12220
+ checkFeature: () => false,
12221
+ getLimit: () => null
12222
+ } : runtimeContext;
12223
+ const warningStatus = isRetrying ? void 0 : context.status ?? void 0;
12224
+ return {
12225
+ context,
12226
+ warningStatus,
12227
+ bannerType: resolveLicenseBannerType(warningStatus, publicKey)
12228
+ };
12229
+ }
12230
+ function resolveLicenseBannerType(warningStatus, publicKey) {
12231
+ switch (warningStatus) {
12232
+ case "none": return publicKey ? null : "no_license";
12233
+ case "expired":
12234
+ case "invalid":
12235
+ case "expiring": return warningStatus;
12236
+ case "valid":
12237
+ case "unknown":
12238
+ case void 0: return null;
12239
+ }
12240
+ }
12241
+ /**
12242
+ * Resolves whether the threads drawer can load its thread list.
12243
+ *
12244
+ * - `licensed` is `true` when the status is `unknown` (an entitlement lookup
12245
+ * that did not recover, so the threads endpoint decides), or when the
12246
+ * status is `valid` or `expiring` and `checkFeature("threads")` is `true`.
12247
+ * - `licensePending` is `true` while the status is `null` (the runtime has
12248
+ * not reported yet). Show the loading state then, not the locked view.
12249
+ *
12250
+ * @param context - The license context from {@link ɵresolveLicenseState}.
12251
+ *
12252
+ * @example
12253
+ * ```ts
12254
+ * const { licensed, licensePending } = ɵresolveThreadsLicense(context);
12255
+ * ```
12256
+ */
12257
+ function ɵresolveThreadsLicense(context) {
12258
+ const { status } = context;
12259
+ return {
12260
+ licensed: status === "unknown" || (status === "valid" || status === "expiring") && context.checkFeature("threads"),
12261
+ licensePending: status === null
12262
+ };
12263
+ }
12264
+ const PRICING_URL = "https://copilotkit.ai/pricing";
12265
+ const DASHBOARD_URL = "https://dashboard.operations.copilotkit.ai";
12266
+ /**
12267
+ * What one license banner shows: its severity, text, and link. React, Vue,
12268
+ * and Angular render it with {@link ɵLICENSE_BANNER_STYLE}.
12269
+ *
12270
+ * @param type - The banner type, for example from
12271
+ * {@link ɵresolveLicenseState}'s `bannerType`.
12272
+ * @param labels - The chat labels in effect, so apps can translate the text.
12273
+ * @param details - The feature name, expiry date, or days left.
12274
+ *
12275
+ * @example
12276
+ * ```ts
12277
+ * const spec = ɵgetLicenseBannerSpec("expiring", labels, { graceRemaining: 3 });
12278
+ * // { severity: "warning", message: "… expires in 3 days …", actionLabel: "Renew", … }
12279
+ * ```
12280
+ */
12281
+ function ɵgetLicenseBannerSpec(type, labels, { featureName, expiryDate, graceRemaining } = {}) {
12282
+ switch (type) {
12283
+ case "no_license": return bannerSpec("info", labels.licensePoweredByText, labels.licenseGetLicenseLabel, PRICING_URL);
12284
+ case "feature_unlicensed": return bannerSpec("warning", ɵformatLabel(labels.licenseFeatureUnlicensedText, { feature: featureName ?? "" }), labels.licenseGetLicenseLabel, PRICING_URL);
12285
+ case "expiring": return bannerSpec("warning", expiringMessage(labels, graceRemaining), labels.licenseRenewLabel, DASHBOARD_URL);
12286
+ case "expired": return bannerSpec("critical", expiryDate ? ɵformatLabel(labels.licenseExpiredOnDateText, { date: expiryDate }) : labels.licenseExpiredText, labels.licenseRenewNowLabel, PRICING_URL);
12287
+ case "invalid": return bannerSpec("critical", labels.licenseInvalidText, labels.licenseGetLicenseLabel, PRICING_URL);
12288
+ }
12289
+ }
12290
+ const bannerSpec = (severity, message, actionLabel, actionUrl) => ({
12291
+ severity,
12292
+ message,
12293
+ actionLabel,
12294
+ actionUrl
12295
+ });
12296
+ /**
12297
+ * The "expires soon" text. Without a day count it says "soon", never "in
12298
+ * undefined days".
12299
+ */
12300
+ function expiringMessage(labels, graceRemaining) {
12301
+ if (graceRemaining === void 0) return labels.licenseExpiringText;
12302
+ return ɵformatLabel(graceRemaining === 1 ? labels.licenseExpiringInDaysOne : labels.licenseExpiringInDaysOther, { days: graceRemaining });
12303
+ }
12304
+ const FONT_FAMILY = "-apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif";
12305
+ /**
12306
+ * Inline styles of the fixed license banner, in camelCase, for React `style`
12307
+ * and Vue `:style`. `base` is the layout; `severity` holds the colours.
12308
+ */
12309
+ const ɵLICENSE_BANNER_STYLE = {
12310
+ base: {
12311
+ position: "fixed",
12312
+ bottom: "8px",
12313
+ left: "50%",
12314
+ transform: "translateX(-50%)",
12315
+ zIndex: 99999,
12316
+ display: "inline-flex",
12317
+ alignItems: "center",
12318
+ gap: "12px",
12319
+ whiteSpace: "nowrap",
12320
+ padding: "8px 16px",
12321
+ fontSize: "13px",
12322
+ fontFamily: FONT_FAMILY,
12323
+ borderRadius: "6px",
12324
+ boxShadow: "0 2px 8px rgba(0, 0, 0, 0.15)"
12325
+ },
12326
+ severity: {
12327
+ info: {
12328
+ backgroundColor: "#eff6ff",
12329
+ border: "1px solid #93c5fd",
12330
+ color: "#1e40af"
12331
+ },
12332
+ warning: {
12333
+ backgroundColor: "#fffbeb",
12334
+ border: "1px solid #fbbf24",
12335
+ color: "#92400e"
12336
+ },
12337
+ critical: {
12338
+ backgroundColor: "#fef2f2",
12339
+ border: "1px solid #fca5a5",
12340
+ color: "#991b1b"
12341
+ }
12342
+ },
12343
+ actions: {
12344
+ display: "flex",
12345
+ gap: "8px",
12346
+ alignItems: "center"
12347
+ },
12348
+ link: {
12349
+ fontWeight: 600,
12350
+ textDecoration: "underline",
12351
+ color: "inherit"
12352
+ },
12353
+ dismiss: {
12354
+ background: "none",
12355
+ border: "none",
12356
+ cursor: "pointer",
12357
+ color: "inherit",
12358
+ fontSize: "16px"
12359
+ }
12360
+ };
12361
+ /**
12362
+ * The bottom space the fixed banner takes: banner height (~36px) + bottom
12363
+ * offset (8px) + gap above the chat input (~8px). The chat input reads it
12364
+ * through `padding-bottom: var(--copilotkit-license-banner-offset)`.
12365
+ */
12366
+ const ɵLICENSE_BANNER_OFFSET = {
12367
+ cssVar: "--copilotkit-license-banner-offset",
12368
+ px: 52
12369
+ };
12370
+ /**
12371
+ * Publishes {@link ɵLICENSE_BANNER_OFFSET} on the root element while a
12372
+ * banner shows. Does nothing without a document (SSR).
12373
+ *
12374
+ * @returns A function that removes the offset again.
12375
+ */
12376
+ function ɵreserveLicenseBannerOffset() {
12377
+ if (typeof document === "undefined") return () => {};
12378
+ const root = document.documentElement;
12379
+ root.style.setProperty(ɵLICENSE_BANNER_OFFSET.cssVar, `${ɵLICENSE_BANNER_OFFSET.px}px`);
12380
+ return () => root.style.removeProperty(ɵLICENSE_BANNER_OFFSET.cssVar);
12381
+ }
12382
+ /**
12383
+ * What the inline warning shows when a chat component needs a license it
12384
+ * does not have: the `licenseFeatureUnlicensedText` label and a pricing
12385
+ * link. Render it with {@link ɵINLINE_FEATURE_WARNING_STYLE}.
12386
+ */
12387
+ function ɵgetInlineFeatureWarningSpec(featureName, labels) {
12388
+ return {
12389
+ message: ɵformatLabel(labels.licenseFeatureUnlicensedText, { feature: featureName }),
12390
+ actionLabel: "Get one at copilotkit.ai/pricing",
12391
+ actionUrl: PRICING_URL
12392
+ };
12393
+ }
12394
+ /** Inline styles of the inline feature warning, in camelCase. */
12395
+ const ɵINLINE_FEATURE_WARNING_STYLE = {
12396
+ container: {
12397
+ padding: "8px 12px",
12398
+ backgroundColor: "#fffbeb",
12399
+ border: "1px solid #fbbf24",
12400
+ borderRadius: "6px",
12401
+ fontSize: "13px",
12402
+ color: "#92400e",
12403
+ fontFamily: FONT_FAMILY
12404
+ },
12405
+ link: {
12406
+ color: "#b45309",
12407
+ textDecoration: "underline"
12408
+ }
12409
+ };
12410
+
12411
+ //#endregion
12412
+ //#region src/chat/icons.ts
12413
+ /*! @license
12414
+ * The icon data below is copied from Lucide v0.525.0 (https://lucide.dev).
12415
+ * The Lucide license follows. A copy is in LUCIDE-LICENSE.md next to this file.
12416
+ * This comment sits right above runtime code so the bundler keeps it in dist.
12417
+ *
12418
+ * ISC License
12419
+ *
12420
+ * 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.
12421
+ *
12422
+ * Permission to use, copy, modify, and/or distribute this software for any
12423
+ * purpose with or without fee is hereby granted, provided that the above
12424
+ * copyright notice and this permission notice appear in all copies.
12425
+ *
12426
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12427
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12428
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12429
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12430
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
12431
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
12432
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
12433
+ */
12434
+ function path(d) {
12435
+ return {
12436
+ tag: "path",
12437
+ attributes: { d }
12438
+ };
12439
+ }
12440
+ const icons = {
12441
+ ArrowUp: {
12442
+ name: "arrow-up",
12443
+ nodes: [path("m5 12 7-7 7 7"), path("M12 19V5")]
12444
+ },
12445
+ Check: {
12446
+ name: "check",
12447
+ nodes: [path("M20 6 9 17l-5-5")]
12448
+ },
12449
+ ChevronDown: {
12450
+ name: "chevron-down",
12451
+ nodes: [path("m6 9 6 6 6-6")]
12452
+ },
12453
+ ChevronLeft: {
12454
+ name: "chevron-left",
12455
+ nodes: [path("m15 18-6-6 6-6")]
12456
+ },
12457
+ ChevronRight: {
12458
+ name: "chevron-right",
12459
+ nodes: [path("m9 18 6-6-6-6")]
12460
+ },
12461
+ Circle: {
12462
+ name: "circle",
12463
+ nodes: [{
12464
+ tag: "circle",
12465
+ attributes: {
12466
+ cx: "12",
12467
+ cy: "12",
12468
+ r: "10"
12469
+ }
12470
+ }]
12471
+ },
12472
+ Copy: {
12473
+ name: "copy",
12474
+ nodes: [{
12475
+ tag: "rect",
12476
+ attributes: {
12477
+ width: "14",
12478
+ height: "14",
12479
+ x: "8",
12480
+ y: "8",
12481
+ rx: "2",
12482
+ ry: "2"
12483
+ }
12484
+ }, path("M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2")]
12485
+ },
12486
+ Edit: {
12487
+ name: "square-pen",
12488
+ 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")]
12489
+ },
12490
+ EyeOff: {
12491
+ name: "eye-off",
12492
+ nodes: [
12493
+ 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"),
12494
+ path("M14.084 14.158a3 3 0 0 1-4.242-4.242"),
12495
+ 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"),
12496
+ path("m2 2 20 20")
12497
+ ]
12498
+ },
12499
+ Loader2: {
12500
+ name: "loader-circle",
12501
+ nodes: [path("M21 12a9 9 0 1 1-6.219-8.56")]
12502
+ },
12503
+ MessageCircle: {
12504
+ name: "message-circle",
12505
+ nodes: [path("M7.9 20A9 9 0 1 0 4 16.1L2 22Z")]
12506
+ },
12507
+ Mic: {
12508
+ name: "mic",
12509
+ nodes: [
12510
+ path("M12 19v3"),
12511
+ path("M19 10v2a7 7 0 0 1-14 0v-2"),
12512
+ {
12513
+ tag: "rect",
12514
+ attributes: {
12515
+ x: "9",
12516
+ y: "2",
12517
+ width: "6",
12518
+ height: "13",
12519
+ rx: "3"
12520
+ }
12521
+ }
12522
+ ]
12523
+ },
12524
+ PanelLeftOpen: {
12525
+ name: "panel-left-open",
12526
+ nodes: [
12527
+ {
12528
+ tag: "rect",
12529
+ attributes: {
12530
+ width: "18",
12531
+ height: "18",
12532
+ x: "3",
12533
+ y: "3",
12534
+ rx: "2"
12535
+ }
12536
+ },
12537
+ path("M9 3v18"),
12538
+ path("m14 9 3 3-3 3")
12539
+ ]
12540
+ },
12541
+ Play: {
12542
+ name: "play",
12543
+ nodes: [{
12544
+ tag: "polygon",
12545
+ attributes: { points: "6 3 20 12 6 21 6 3" }
12546
+ }]
12547
+ },
12548
+ Plus: {
12549
+ name: "plus",
12550
+ nodes: [path("M5 12h14"), path("M12 5v14")]
12551
+ },
12552
+ RefreshCw: {
12553
+ name: "refresh-cw",
12554
+ nodes: [
12555
+ path("M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"),
12556
+ path("M21 3v5h-5"),
12557
+ path("M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"),
12558
+ path("M8 16H3v5")
12559
+ ]
12560
+ },
12561
+ Square: {
12562
+ name: "square",
12563
+ nodes: [{
12564
+ tag: "rect",
12565
+ attributes: {
12566
+ width: "18",
12567
+ height: "18",
12568
+ x: "3",
12569
+ y: "3",
12570
+ rx: "2"
12571
+ }
12572
+ }]
12573
+ },
12574
+ ThumbsDown: {
12575
+ name: "thumbs-down",
12576
+ 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")]
12577
+ },
12578
+ ThumbsUp: {
12579
+ name: "thumbs-up",
12580
+ 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")]
12581
+ },
12582
+ Upload: {
12583
+ name: "upload",
12584
+ nodes: [
12585
+ path("M12 3v12"),
12586
+ path("m17 8-5-5-5 5"),
12587
+ path("M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4")
12588
+ ]
12589
+ },
12590
+ Volume2: {
12591
+ name: "volume-2",
12592
+ nodes: [
12593
+ 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"),
12594
+ path("M16 9a5 5 0 0 1 0 6"),
12595
+ path("M19.364 18.364a9 9 0 0 0 0-12.728")
12596
+ ]
12597
+ },
12598
+ Wrench: {
12599
+ name: "wrench",
12600
+ 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")]
12601
+ },
12602
+ X: {
12603
+ name: "x",
12604
+ nodes: [path("M18 6 6 18"), path("m6 6 12 12")]
12605
+ }
12606
+ };
12607
+ /**
12608
+ * Internal. The SVG data for every icon the chat components draw.
12609
+ *
12610
+ * Each framework's `CopilotIcon` component reads an entry and draws it:
12611
+ *
12612
+ * ```ts
12613
+ * const { name, nodes } = ɵcopilotIcons.ArrowUp;
12614
+ * // <svg {...ɵcopilotIconSvgAttributes} class="lucide lucide-arrow-up">
12615
+ * // one child element per node: <{node.tag} {...node.attributes} />
12616
+ * // </svg>
12617
+ * ```
12618
+ */
12619
+ const ɵcopilotIcons = icons;
12620
+ /**
12621
+ * Internal. The attributes to put on the `<svg>` of every chat icon.
12622
+ *
12623
+ * These are Lucide's default attributes, so a drawn icon matches the Lucide
12624
+ * icon. Set `width` and `height` to change the size.
12625
+ */
12626
+ const ɵcopilotIconSvgAttributes = {
12627
+ xmlns: "http://www.w3.org/2000/svg",
12628
+ width: "24",
12629
+ height: "24",
12630
+ viewBox: "0 0 24 24",
12631
+ fill: "none",
12632
+ stroke: "currentColor",
12633
+ "stroke-width": "2",
12634
+ "stroke-linecap": "round",
12635
+ "stroke-linejoin": "round"
12636
+ };
12637
+
12638
+ //#endregion
12639
+ //#region src/chat/message-feedback.ts
12640
+ /** Trajectory event name for a rating of one assistant message. */
12641
+ const ɵMESSAGE_FEEDBACK_EVENT_NAME = "message.feedback";
12642
+ /** Longest comment kept, in characters; the rest is cut so the event stays small. */
12643
+ const ɵMESSAGE_FEEDBACK_MAX_COMMENT_LENGTH = 1e3;
12644
+ /** Longest excerpt of the rated response sent with the rating, in characters. */
12645
+ const RESPONSE_EXCERPT_LENGTH = 500;
12646
+ /**
12647
+ * How long the pointer may be away from the rating and its comment before the
12648
+ * comment closes: enough to cross the gap between them, short enough that
12649
+ * passing over a rating does not leave it open.
12650
+ */
12651
+ const ɵFEEDBACK_COMMENT_CLOSE_DELAY_MS = 150;
12652
+ const ratings = /* @__PURE__ */ new Map();
12653
+ const listeners = /* @__PURE__ */ new Map();
12654
+ const threadKey = (agentId, threadId) => JSON.stringify([agentId, threadId]);
12655
+ const messageKey = (agentId, threadId, messageId) => JSON.stringify([
12656
+ agentId,
12657
+ threadId,
12658
+ messageId
12659
+ ]);
12660
+ /** Cuts `text` to `max` characters without splitting a surrogate pair. */
12661
+ const clip = (text, max) => {
12662
+ const characters = Array.from(text);
12663
+ return characters.length > max ? characters.slice(0, max).join("") : text;
12664
+ };
12665
+ /** The comment as kept and sent: trimmed and capped, or none. */
12666
+ const normalizeComment = (comment) => {
12667
+ if (comment === void 0) return void 0;
12668
+ const text = clip(comment.trim(), ɵMESSAGE_FEEDBACK_MAX_COMMENT_LENGTH);
12669
+ return text === "" ? void 0 : text;
12670
+ };
12671
+ /** The rating this page gave one message, if any. */
12672
+ function ɵgetMessageFeedback(agentId, threadId, messageId) {
12673
+ return ratings.get(messageKey(agentId, threadId, messageId));
12674
+ }
12675
+ /** Calls `listener` whenever a rating in this Thread changes. */
12676
+ function ɵsubscribeToMessageFeedback(agentId, threadId, listener) {
12677
+ const key = threadKey(agentId, threadId);
12678
+ let set = listeners.get(key);
12679
+ if (set === void 0) {
12680
+ set = /* @__PURE__ */ new Set();
12681
+ listeners.set(key, set);
12682
+ }
12683
+ const subscribed = set;
12684
+ subscribed.add(listener);
12685
+ return () => {
12686
+ subscribed.delete(listener);
12687
+ if (subscribed.size === 0) listeners.delete(key);
12688
+ };
12689
+ }
12690
+ /**
12691
+ * Sets (or, with `null`, clears) this page's rating of one message and sends
12692
+ * it to the active Trajectory. Every change is a new event; the newest event
12693
+ * for a `feedbackId` is the current one. Like any Trajectory event, a change
12694
+ * made while no Trajectory captures, for example during a reconnect, is not
12695
+ * sent; the page still shows it.
12696
+ */
12697
+ function ɵsetMessageFeedback(params) {
12698
+ const { copilotkit, agentId, threadId, message } = params;
12699
+ const comment = normalizeComment(params.feedback?.comment);
12700
+ const feedback = params.feedback && {
12701
+ rating: params.feedback.rating,
12702
+ ...comment ? { comment } : {}
12703
+ };
12704
+ const key = messageKey(agentId, threadId, message.id);
12705
+ if (feedback) ratings.set(key, feedback);
12706
+ else ratings.delete(key);
12707
+ const threadListeners = listeners.get(threadKey(agentId, threadId)) ?? [];
12708
+ for (const listener of threadListeners) listener();
12709
+ const runId = copilotkit.getRunIdForMessage(agentId, threadId, message.id);
12710
+ copilotkit.emitTrajectoryEvent(ɵMESSAGE_FEEDBACK_EVENT_NAME, {
12711
+ feedbackId: `${threadId}:${message.id}`,
12712
+ threadId,
12713
+ messageId: message.id,
12714
+ agentId,
12715
+ ...runId ? { runId } : {},
12716
+ rating: feedback?.rating ?? null,
12717
+ ...feedback?.comment ? { comment: feedback.comment } : {},
12718
+ ...copilotkit.ɵlearningCapturesAgentText ? { response: clip(message.content ?? "", RESPONSE_EXCERPT_LENGTH) } : {}
12719
+ });
12720
+ }
12721
+ /** @internal Forgets every rating, so each test starts empty. */
12722
+ function ɵresetMessageFeedbackCache() {
12723
+ ratings.clear();
12724
+ }
12725
+ const capturedCores = /* @__PURE__ */ new WeakSet();
12726
+ const rememberCapture = (copilotkit) => {
12727
+ if (capturedCores.has(copilotkit)) return;
12728
+ capturedCores.add(copilotkit);
12729
+ const unsubscribe = copilotkit.ɵsubscribeToLearningConfigured(() => {
12730
+ if (copilotkit.ɵlearningConfigured) return;
12731
+ capturedCores.delete(copilotkit);
12732
+ unsubscribe();
12733
+ });
12734
+ };
12735
+ /**
12736
+ * Whether the thumbs record feedback for Learning. True once a Trajectory of
12737
+ * this Core has started and as long as Learning stays configured, also while
12738
+ * capture reconnects or is stopped, so the buttons do not flicker. Ratings
12739
+ * given meanwhile still show but, like any Trajectory event, are not sent. A
12740
+ * capture that never starts (for example without a license) leaves it false.
12741
+ *
12742
+ * Re-read it when {@link ɵsubscribeToLearningFeedbackEnabled} notifies.
12743
+ */
12744
+ function ɵisLearningFeedbackEnabled(copilotkit) {
12745
+ const capturing = copilotkit.trajectoryId !== null;
12746
+ if (capturing) rememberCapture(copilotkit);
12747
+ return copilotkit.ɵlearningConfigured && (capturing || capturedCores.has(copilotkit));
12748
+ }
12749
+ /**
12750
+ * Calls `listener` when {@link ɵisLearningFeedbackEnabled} may have changed:
12751
+ * when Learning is configured or removed, and when the Trajectory changes.
12752
+ * Returns the unsubscribe function.
12753
+ */
12754
+ function ɵsubscribeToLearningFeedbackEnabled(copilotkit, listener) {
12755
+ const unsubscribeConfigured = copilotkit.ɵsubscribeToLearningConfigured(listener);
12756
+ const subscription = copilotkit.subscribe({ onTrajectoryChanged: listener });
12757
+ return () => {
12758
+ unsubscribeConfigured();
12759
+ subscription.unsubscribe();
12760
+ };
12761
+ }
12762
+ /**
12763
+ * The feedback this page gave `message` in `scope`, and how to change it.
12764
+ * Read it again when {@link ɵsubscribeToMessageFeedback} notifies for the
12765
+ * scope's Thread.
12766
+ */
12767
+ function ɵgetMessageFeedbackControls(scope, message) {
12768
+ const feedback = ɵgetMessageFeedback(scope.agentId, scope.threadId, message.id);
12769
+ const save = (next) => ɵsetMessageFeedback({
12770
+ ...scope,
12771
+ message,
12772
+ feedback: next
12773
+ });
12774
+ return {
12775
+ feedback,
12776
+ rate: (rating) => {
12777
+ if (feedback?.rating !== rating) save({ rating });
12778
+ },
12779
+ clear: () => {
12780
+ if (feedback) save(null);
12781
+ },
12782
+ comment: (comment) => {
12783
+ if (feedback) save({
12784
+ rating: feedback.rating,
12785
+ comment
12786
+ });
12787
+ }
12788
+ };
12789
+ }
12790
+ /**
12791
+ * Drives the comment popover of a rated message.
12792
+ *
12793
+ * It opens when a rating is given and whenever the pointer or keyboard focus
12794
+ * reaches the chosen thumb, with the saved comment in the field. It closes by
12795
+ * itself shortly after the pointer leaves the thumb and the popover, unless
12796
+ * focus is in the field: then it stays until focus moves away, Enter, or
12797
+ * Escape. Closing saves a changed comment; Escape, a click on a thumb, and
12798
+ * removing the rating discard it.
12799
+ *
12800
+ * Frameworks render from `getSnapshot()` and re-render when `subscribe()`
12801
+ * notifies. Call `dispose()` on unmount: it keeps an unsaved edit, for a
12802
+ * message that scrolls out of a virtual list. The controller stays usable
12803
+ * after `dispose()`, so a remount (React Strict Mode) can keep it.
12804
+ *
12805
+ * @example
12806
+ * ```ts
12807
+ * const comment = new ɵFeedbackCommentController({ getControls: () => controls });
12808
+ * comment.subscribe(() => render(comment.getSnapshot()));
12809
+ * comment.show({ comment: "", focus: false });
12810
+ * // On unmount:
12811
+ * comment.dispose();
12812
+ * ```
12813
+ */
12814
+ var ɵFeedbackCommentController = class {
12815
+ #getControls;
12816
+ #closeDelayMs;
12817
+ #listeners = /* @__PURE__ */ new Set();
12818
+ #state = {
12819
+ open: false,
12820
+ draft: "",
12821
+ focusRequest: 0
12822
+ };
12823
+ #timer;
12824
+ #editing = false;
12825
+ #focusWaiting = false;
12826
+ #pointerOver = false;
12827
+ #returning = false;
12828
+ constructor(options) {
12829
+ this.#getControls = options.getControls;
12830
+ this.#closeDelayMs = options.closeDelayMs ?? ɵFEEDBACK_COMMENT_CLOSE_DELAY_MS;
12831
+ }
12832
+ /** The current state. The same object until something changes. */
12833
+ getSnapshot = () => this.#state;
12834
+ /** Calls `listener` when the state changes. Returns the unsubscribe function. */
12835
+ subscribe = (listener) => {
12836
+ this.#listeners.add(listener);
12837
+ return () => {
12838
+ this.#listeners.delete(listener);
12839
+ };
12840
+ };
12841
+ /** Sets the comment being edited. */
12842
+ setDraft = (draft) => {
12843
+ this.#update({ draft });
12844
+ };
12845
+ /** Whether a focus request waits; reading it answers the request. */
12846
+ takeFocusRequest = () => {
12847
+ const waiting = this.#focusWaiting;
12848
+ this.#focusWaiting = false;
12849
+ return waiting;
12850
+ };
12851
+ /** Opens with `comment` in the field. */
12852
+ show = ({ comment, focus }) => {
12853
+ this.#cancelClose();
12854
+ if (focus) this.#focusWaiting = true;
12855
+ this.#update({
12856
+ open: true,
12857
+ draft: comment,
12858
+ focusRequest: this.#state.focusRequest + (focus ? 1 : 0)
12859
+ });
12860
+ };
12861
+ /** The pointer or focus reached the rating or the popover. */
12862
+ enter = (via = "focus") => {
12863
+ this.#cancelClose();
12864
+ if (via === "pointer") this.#pointerOver = true;
12865
+ if (this.#returning) return;
12866
+ if (!this.#state.open && this.#getControls()?.feedback) this.show({
12867
+ comment: this.#savedComment(),
12868
+ focus: false
12869
+ });
12870
+ };
12871
+ /**
12872
+ * It left them: close soon, unless the user is editing the comment or, when
12873
+ * focus left, the pointer is still on the rating or the popover.
12874
+ */
12875
+ leave = (via = "focus") => {
12876
+ if (via === "pointer") this.#pointerOver = false;
12877
+ else if (this.#pointerOver) return;
12878
+ this.#cancelClose();
12879
+ this.#timer = setTimeout(() => {
12880
+ this.#timer = void 0;
12881
+ if (!this.#editing) this.close();
12882
+ }, this.#closeDelayMs);
12883
+ };
12884
+ /** Tracks whether focus is in the comment form. */
12885
+ setEditing = (editing) => {
12886
+ this.#editing = editing;
12887
+ };
12888
+ /** Closes, saving a changed comment unless `save` is false. */
12889
+ close = ({ save = true } = {}) => {
12890
+ this.#cancelClose();
12891
+ this.#focusWaiting = false;
12892
+ this.#pointerOver = false;
12893
+ if (!this.#state.open) return;
12894
+ if (save) this.#saveDraft();
12895
+ this.#editing = false;
12896
+ this.#update({ open: false });
12897
+ };
12898
+ /** Moves focus back to the thumb without opening the comment again. */
12899
+ returnFocus = (target) => {
12900
+ this.#returning = true;
12901
+ try {
12902
+ target?.focus();
12903
+ } finally {
12904
+ this.#returning = false;
12905
+ }
12906
+ };
12907
+ /** Stops the close timer and saves a changed comment that is still open. */
12908
+ dispose = () => {
12909
+ this.#cancelClose();
12910
+ if (this.#state.open) this.#saveDraft();
12911
+ };
12912
+ #savedComment() {
12913
+ return this.#getControls()?.feedback?.comment ?? "";
12914
+ }
12915
+ #saveDraft() {
12916
+ const controls = this.#getControls();
12917
+ const draft = this.#state.draft;
12918
+ if (controls?.feedback && draft.trim() !== this.#savedComment()) controls.comment(draft);
12919
+ }
12920
+ #cancelClose() {
12921
+ if (this.#timer === void 0) return;
12922
+ clearTimeout(this.#timer);
12923
+ this.#timer = void 0;
12924
+ }
12925
+ #update(patch) {
12926
+ const next = {
12927
+ ...this.#state,
12928
+ ...patch
12929
+ };
12930
+ if (next.open === this.#state.open && next.draft === this.#state.draft && next.focusRequest === this.#state.focusRequest) return;
12931
+ this.#state = next;
12932
+ for (const listener of this.#listeners) listener();
12933
+ }
12934
+ };
12935
+
12936
+ //#endregion
12937
+ //#region src/chat/viewport.ts
12938
+ const AUTO_SCROLL_MODES = [
12939
+ "pin-to-bottom",
12940
+ "pin-to-send",
12941
+ "none"
12942
+ ];
12943
+ const isAutoScrollMode = (value) => AUTO_SCROLL_MODES.includes(value);
12944
+ /**
12945
+ * Turns the `autoScroll` prop into a mode. `true` and a missing value mean
12946
+ * `"pin-to-bottom"`, `false` means `"none"`, and an unknown string falls back
12947
+ * to `"pin-to-bottom"`.
12948
+ */
12949
+ function ɵnormalizeAutoScroll(value) {
12950
+ if (value === false) return "none";
12951
+ if (value === void 0 || value === true) return "pin-to-bottom";
12952
+ return isAutoScrollMode(value) ? value : "pin-to-bottom";
12953
+ }
12954
+ /**
12955
+ * Media query for the mobile range, where the threads drawer and the chat
12956
+ * modal are mutually exclusive.
12957
+ */
12958
+ const ɵMOBILE_MAX_WIDTH_QUERY = "(max-width: 767px)";
12959
+ /** `window.matchMedia` for the mobile query, or `null` without a DOM. */
12960
+ const mobileMediaQuery = () => {
12961
+ return typeof window !== "undefined" && typeof window.matchMedia === "function" ? window.matchMedia(ɵMOBILE_MAX_WIDTH_QUERY) : null;
12962
+ };
12963
+ /**
12964
+ * Whether the viewport is in the mobile range (`<768px`). `false` during SSR
12965
+ * and where `window.matchMedia` is missing (some test runners and webviews).
12966
+ */
12967
+ function ɵisMobileViewport() {
12968
+ return mobileMediaQuery()?.matches ?? false;
12969
+ }
12970
+ /**
12971
+ * Calls `listener` with {@link ɵisMobileViewport} now and each time the
12972
+ * viewport enters or leaves the mobile range. Does nothing without
12973
+ * `window.matchMedia`. Returns the unsubscribe function.
12974
+ */
12975
+ function ɵwatchMobileViewport(listener) {
12976
+ const query = mobileMediaQuery();
12977
+ if (query === null) return () => {};
12978
+ const update = () => listener(query.matches);
12979
+ update();
12980
+ query.addEventListener("change", update);
12981
+ return () => query.removeEventListener("change", update);
12982
+ }
12983
+ /**
12984
+ * The on-screen keyboard is treated as open once it covers more than this
12985
+ * many pixels of the layout viewport.
12986
+ */
12987
+ const ɵKEYBOARD_OPEN_THRESHOLD_PX = 150;
12988
+ /**
12989
+ * Reads the keyboard state with the Visual Viewport API: the keyboard height
12990
+ * is `innerHeight - visualViewport.height`, clamped to 0. Without the API (or
12991
+ * during SSR) it reports a closed keyboard and the full window height.
12992
+ */
12993
+ function ɵreadKeyboardState() {
12994
+ if (typeof window === "undefined") return closedKeyboard(0);
12995
+ const visualViewport = window.visualViewport;
12996
+ if (!visualViewport) return closedKeyboard(window.innerHeight);
12997
+ const layoutHeight = window.innerHeight;
12998
+ const keyboardHeight = Math.max(0, layoutHeight - visualViewport.height);
12999
+ return {
13000
+ isKeyboardOpen: keyboardHeight > ɵKEYBOARD_OPEN_THRESHOLD_PX,
13001
+ keyboardHeight,
13002
+ availableHeight: visualViewport.height,
13003
+ viewportHeight: layoutHeight
13004
+ };
13005
+ }
13006
+ const closedKeyboard = (height) => ({
13007
+ isKeyboardOpen: false,
13008
+ keyboardHeight: 0,
13009
+ availableHeight: height,
13010
+ viewportHeight: height
13011
+ });
13012
+ /**
13013
+ * The state for the first render, before {@link ɵwatchKeyboardState} reads
13014
+ * the visual viewport: a closed keyboard over the full window height (0
13015
+ * during SSR).
13016
+ */
13017
+ function ɵinitialKeyboardState() {
13018
+ return closedKeyboard(typeof window === "undefined" ? 0 : window.innerHeight);
13019
+ }
13020
+ /**
13021
+ * Calls `listener` with {@link ɵreadKeyboardState} now and on each visual
13022
+ * viewport resize or scroll. Does nothing during SSR or without the Visual
13023
+ * Viewport API. Returns the unsubscribe function.
13024
+ */
13025
+ function ɵwatchKeyboardState(listener) {
13026
+ if (typeof window === "undefined") return () => {};
13027
+ const visualViewport = window.visualViewport;
13028
+ if (!visualViewport) return () => {};
13029
+ const update = () => listener(ɵreadKeyboardState());
13030
+ update();
13031
+ visualViewport.addEventListener("resize", update);
13032
+ visualViewport.addEventListener("scroll", update);
13033
+ return () => {
13034
+ visualViewport.removeEventListener("resize", update);
13035
+ visualViewport.removeEventListener("scroll", update);
13036
+ };
13037
+ }
13038
+ /** Escapes `id` for a CSS attribute selector, also without `CSS.escape`. */
13039
+ const escapeSelectorValue = (id) => typeof CSS !== "undefined" && typeof CSS.escape === "function" ? CSS.escape(id) : id.replace(/[!"#$%&'()*+,./:;<=>?@[\\\]^`{|}~]/g, "\\$&");
13040
+ /**
13041
+ * Offset of `el` from the top of `stopAt`'s content, including `stopAt`'s
13042
+ * scroll. Uses `getBoundingClientRect`, so it works for any CSS position.
13043
+ */
13044
+ const offsetTopWithin = (el, stopAt) => el.getBoundingClientRect().top - stopAt.getBoundingClientRect().top + stopAt.scrollTop;
13045
+ /**
13046
+ * Pins a sent message to the top of the chat: sizes the spacer so the
13047
+ * message bubble can scroll to `topOffset` from the viewport top, scrolls
13048
+ * there on the next frame, and then shrinks the spacer as the reply below
13049
+ * grows, so the bubble stays put.
13050
+ *
13051
+ * The message element's top padding is scrolled off-screen: the bubble, not
13052
+ * its padded box, is pinned. Does nothing when no element in `contentEl` has
13053
+ * `data-message-id` equal to `messageId`. Skips the scroll without
13054
+ * `requestAnimationFrame` and the spacer updates without `ResizeObserver`.
13055
+ *
13056
+ * @returns A function that cancels the scroll and stops the spacer updates.
13057
+ * It returns `false` when it cancelled a scroll that had not run yet, so the
13058
+ * caller can pin the same send again. React's StrictMode tears an effect
13059
+ * down before the next frame, so the first run never scrolls.
13060
+ *
13061
+ * @example
13062
+ * ```ts
13063
+ * const unpin = ɵpinMessageToTop({ scrollEl, contentEl, spacerEl, messageId });
13064
+ * // On the next send or on unmount:
13065
+ * unpin();
13066
+ * ```
13067
+ */
13068
+ function ɵpinMessageToTop({ scrollEl, contentEl, spacerEl, messageId, topOffset = 16 }) {
13069
+ const targetEl = contentEl.querySelector(`[data-message-id="${escapeSelectorValue(messageId)}"]`);
13070
+ if (!targetEl) return () => true;
13071
+ const viewportHeight = scrollEl.clientHeight;
13072
+ const userMessageHeight = targetEl.getBoundingClientRect().height;
13073
+ const paddingTop = parseFloat(getComputedStyle(targetEl).paddingTop) || 0;
13074
+ const bubbleHeight = Math.max(0, userMessageHeight - paddingTop);
13075
+ const spacerHeight = Math.max(0, viewportHeight - bubbleHeight - topOffset);
13076
+ spacerEl.style.height = `${spacerHeight}px`;
13077
+ let scrolled = false;
13078
+ const frame = typeof requestAnimationFrame === "function" ? requestAnimationFrame(() => {
13079
+ scrolled = true;
13080
+ const targetTop = offsetTopWithin(targetEl, scrollEl) + paddingTop - topOffset;
13081
+ scrollEl.scrollTo({
13082
+ top: Math.max(0, targetTop),
13083
+ behavior: "smooth"
13084
+ });
13085
+ }) : null;
13086
+ const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(() => {
13087
+ const consumedBelow = contentEl.getBoundingClientRect().height - offsetTopWithin(targetEl, contentEl) - userMessageHeight;
13088
+ const remaining = Math.max(0, spacerHeight - consumedBelow);
13089
+ spacerEl.style.height = `${remaining}px`;
13090
+ });
13091
+ observer?.observe(contentEl);
13092
+ return () => {
13093
+ if (frame !== null && typeof cancelAnimationFrame === "function") cancelAnimationFrame(frame);
13094
+ observer?.disconnect();
13095
+ return frame === null || scrolled;
13096
+ };
13097
+ }
13098
+
13099
+ //#endregion
13100
+ //#region src/chat/message-display.ts
13101
+ /**
13102
+ * How long the model reasoned, as label text: "a few seconds", "4 seconds",
13103
+ * "2 minutes", or "1m 5s".
13104
+ *
13105
+ * @param seconds - The elapsed time in seconds. It may have a fraction.
13106
+ * @param labels - The chat labels that hold the duration texts.
13107
+ */
13108
+ function ɵformatReasoningDurationLabel(seconds, labels) {
13109
+ const duration = formatReasoningDuration(seconds);
13110
+ switch (duration.unit) {
13111
+ case "fewSeconds": return labels.reasoningMessageDurationFewSeconds;
13112
+ case "seconds": return ɵformatLabel(labels.reasoningMessageDurationSeconds, { count: duration.seconds });
13113
+ case "minutes": return ɵformatCountLabel(duration.minutes, {
13114
+ one: labels.reasoningMessageDurationMinutesOne,
13115
+ other: labels.reasoningMessageDurationMinutesOther
13116
+ });
13117
+ case "minutesSeconds": return ɵformatLabel(labels.reasoningMessageDurationMinutesSeconds, {
13118
+ minutes: duration.minutes,
13119
+ seconds: duration.seconds
13120
+ });
13121
+ }
13122
+ }
13123
+ /**
13124
+ * The text of the work summary line at the top of a reply in the `"turn"`
13125
+ * tool-call display.
13126
+ *
13127
+ * - While working: `label` is "Working" and `detail` the live timer ("4s"),
13128
+ * or `null` when the elapsed time is not known.
13129
+ * - When done with a known time: `label` is "Worked for 9s" (at least 1s)
13130
+ * and `detail` the tool count ("7 tools").
13131
+ * - When done without a time: `label` is "Used 7 tools" and `detail` `null`.
13132
+ * - `failed` is "2 failed" when tool calls failed, otherwise `null`. It is
13133
+ * always `null` while working.
13134
+ */
13135
+ function ɵgetWorkSummaryText({ isWorking, calls, elapsedMs, workingSince, now, labels }) {
13136
+ if (isWorking) {
13137
+ const isTimed = elapsedMs !== void 0 && workingSince !== void 0;
13138
+ return {
13139
+ label: labels.workSummaryWorkingLabel,
13140
+ detail: isTimed ? formatWorkDuration(elapsedMs + Math.max(0, now - workingSince)) : null,
13141
+ failed: null
13142
+ };
13143
+ }
13144
+ const failedCount = countFailedToolCalls(calls);
13145
+ const failed = failedCount > 0 ? ɵformatLabel(labels.toolCallFailedCountLabel, { count: failedCount }) : null;
13146
+ if (elapsedMs === void 0) return {
13147
+ label: ɵformatCountLabel(calls.length, {
13148
+ one: labels.toolCallUsedToolsOne,
13149
+ other: labels.toolCallUsedToolsOther
13150
+ }),
13151
+ detail: null,
13152
+ failed
13153
+ };
13154
+ const duration = formatWorkDuration(Math.max(1e3, elapsedMs));
13155
+ return {
13156
+ label: ɵformatLabel(labels.workSummaryWorkedForLabel, { duration }),
13157
+ detail: ɵformatCountLabel(calls.length, {
13158
+ one: labels.toolCallToolCountOne,
13159
+ other: labels.toolCallToolCountOther
13160
+ }),
13161
+ failed
13162
+ };
13163
+ }
13164
+ /**
13165
+ * The text of a user message: the string content, or its text parts joined
13166
+ * by newlines. Parts that are not text, and malformed parts from untyped
13167
+ * data, add nothing.
13168
+ */
13169
+ function ɵflattenUserMessageContent(content) {
13170
+ if (!content) return "";
13171
+ if (typeof content === "string") return content;
13172
+ return content.map((part) => part?.type === "text" && typeof part.text === "string" ? part.text : "").filter((text) => text.length > 0).join("\n");
13173
+ }
13174
+ const isMediaPart = (part) => part?.type === "image" || part?.type === "audio" || part?.type === "video" || part?.type === "document";
13175
+ /** The image, audio, video, and document parts of a user message. */
13176
+ function ɵgetUserMessageMediaParts(content) {
13177
+ if (!content || typeof content === "string") return [];
13178
+ return content.filter(isMediaPart);
13179
+ }
13180
+ /** The file name stored in an attachment's `metadata.filename`, if any. */
13181
+ function ɵgetUserMessageMediaFilename(part) {
13182
+ const meta = part.metadata;
13183
+ return meta != null && typeof meta === "object" && "filename" in meta && typeof meta.filename === "string" ? meta.filename : void 0;
13184
+ }
13185
+ /**
13186
+ * Whether a user message shows its branch navigation and which arrows work.
13187
+ * It shows only with more than one branch and a switch handler: without the
13188
+ * handler the arrows would do nothing.
13189
+ */
13190
+ function ɵgetBranchNavState({ branchIndex, numberOfBranches, canSwitch }) {
13191
+ const show = canSwitch && numberOfBranches > 1;
13192
+ return {
13193
+ show,
13194
+ canGoPrev: show && branchIndex > 0,
13195
+ canGoNext: show && branchIndex < numberOfBranches - 1
13196
+ };
13197
+ }
13198
+ /** Whether an assistant message has text beyond whitespace. */
13199
+ function ɵhasAssistantMessageText(content) {
13200
+ return !!content && content.trim().length > 0;
13201
+ }
13202
+ /**
13203
+ * Whether an assistant message shows its toolbar: when toolbars are on, the
13204
+ * message has text or the Inspector shortcut shows, and the message is not
13205
+ * the one still streaming (the latest while the agent runs).
13206
+ */
13207
+ function ɵshouldShowAssistantToolbar({ toolbarVisible, hasContent, showInspectorShortcut, isRunning, isLatest }) {
13208
+ return toolbarVisible && (hasContent || showInspectorShortcut) && !(isRunning && isLatest);
13209
+ }
13210
+ /** How long a copy button shows its "copied" check mark, in ms. */
13211
+ const ɵCOPY_FEEDBACK_RESET_MS = 2e3;
13212
+ /**
13213
+ * The "copied" state of a copy button. After a copy it is `true` for
13214
+ * {@link ɵCOPY_FEEDBACK_RESET_MS}; another copy in that time restarts the
13215
+ * wait, so rapid clicks do not flicker.
13216
+ *
13217
+ * Frameworks render from `getSnapshot()` and re-render when `subscribe()`
13218
+ * notifies. Call `dispose()` on unmount. The controller stays usable after
13219
+ * `dispose()`, so a remount (React Strict Mode) can keep it.
13220
+ *
13221
+ * @example
13222
+ * ```ts
13223
+ * const feedback = new ɵCopyFeedback();
13224
+ * feedback.subscribe(() => render(feedback.getSnapshot()));
13225
+ * await feedback.copy(text);
13226
+ * ```
13227
+ */
13228
+ var ɵCopyFeedback = class {
13229
+ #listeners = /* @__PURE__ */ new Set();
13230
+ #resetMs;
13231
+ #copied = false;
13232
+ #timer;
13233
+ constructor({ resetMs = ɵCOPY_FEEDBACK_RESET_MS } = {}) {
13234
+ this.#resetMs = resetMs;
13235
+ }
13236
+ /** Whether the check mark shows. */
13237
+ getSnapshot = () => this.#copied;
13238
+ /** Calls `listener` when the state changes. Returns the unsubscribe function. */
13239
+ subscribe = (listener) => {
13240
+ this.#listeners.add(listener);
13241
+ return () => {
13242
+ this.#listeners.delete(listener);
13243
+ };
13244
+ };
13245
+ /** Shows the check mark, or keeps it for the full time again. */
13246
+ markCopied = () => {
13247
+ this.#clearTimer();
13248
+ this.#set(true);
13249
+ this.#timer = setTimeout(() => {
13250
+ this.#timer = void 0;
13251
+ this.#set(false);
13252
+ }, this.#resetMs);
13253
+ };
13254
+ /**
13255
+ * Copies `text` to the clipboard and shows the check mark on success.
13256
+ * Empty text copies nothing.
13257
+ *
13258
+ * @returns Whether the text was copied.
13259
+ */
13260
+ copy = async (text) => {
13261
+ if (!text) return false;
13262
+ const copied = await (0, _copilotkit_shared.copyToClipboard)(text);
13263
+ if (copied) this.markCopied();
13264
+ return copied;
13265
+ };
13266
+ /** Stops the reset timer. */
13267
+ dispose = () => {
13268
+ this.#clearTimer();
13269
+ };
13270
+ #clearTimer() {
13271
+ if (this.#timer === void 0) return;
13272
+ clearTimeout(this.#timer);
13273
+ this.#timer = void 0;
13274
+ }
13275
+ #set(copied) {
13276
+ if (copied === this.#copied) return;
13277
+ this.#copied = copied;
13278
+ for (const listener of this.#listeners) listener();
13279
+ }
13280
+ };
13281
+
13282
+ //#endregion
13283
+ //#region src/chat/inspector-button.ts
13284
+ let shortcutsHidden = false;
13285
+ const shortcutListeners = /* @__PURE__ */ new Set();
13286
+ const notifyShortcutListeners = () => {
13287
+ for (const listener of shortcutListeners) listener();
13288
+ };
13289
+ /**
13290
+ * Whether the user hid the Inspector shortcuts in the message toolbars
13291
+ * ("Hide this icon"). It lasts until the page reloads and applies to every
13292
+ * chat on the page.
13293
+ *
13294
+ * @example
13295
+ * ```ts
13296
+ * ɵinspectorShortcuts.subscribe(() => render(ɵinspectorShortcuts.hidden));
13297
+ * ɵinspectorShortcuts.hide();
13298
+ * ```
13299
+ */
13300
+ const ɵinspectorShortcuts = {
13301
+ get hidden() {
13302
+ return shortcutsHidden;
13303
+ },
13304
+ hide() {
13305
+ if (shortcutsHidden) return;
13306
+ shortcutsHidden = true;
13307
+ notifyShortcutListeners();
13308
+ },
13309
+ subscribe(listener) {
13310
+ shortcutListeners.add(listener);
13311
+ return () => {
13312
+ shortcutListeners.delete(listener);
13313
+ };
13314
+ },
13315
+ reset() {
13316
+ if (!shortcutsHidden) return;
13317
+ shortcutsHidden = false;
13318
+ notifyShortcutListeners();
13319
+ }
13320
+ };
13321
+ const kiteStroke = (d, stroke, strokeWidth) => ({
13322
+ d,
13323
+ stroke,
13324
+ strokeWidth,
13325
+ strokeLinecap: "round"
13326
+ });
13327
+ /**
13328
+ * The Inspector kite artwork as data, as in
13329
+ * `web-inspector/src/assets/inspector-logo-kite.svg`. Render an `<svg>` with
13330
+ * `viewBox` and `fill="none"`, one `<path>` per entry of `paths`, and a
13331
+ * `<linearGradient gradientUnits="userSpaceOnUse">` per entry of `gradients`
13332
+ * in `<defs>`. Give each gradient the id `${prefix}-${gradient.id}` with a
13333
+ * prefix unique to the icon, and fill paths with
13334
+ * {@link ɵinspectorKiteFill}.
13335
+ */
13336
+ const ɵinspectorKiteIcon = {
13337
+ viewBox: "4.57 3.36 17.8 17.8",
13338
+ paths: [
13339
+ {
13340
+ d: "M6.36084 10.9855C8.34277 8.393 9.98843 5.82939 10.6204 3.75914C10.6382 3.70281 10.7043 3.67888 10.7534 3.7114C12.9536 5.16894 16.9635 6.12833 20.5086 6.15085C20.5703 6.15124 20.6124 6.2114 20.5895 6.26829C19.4109 9.25938 17.9705 14.6189 17.9148 20.7392C17.9148 20.8301 17.7873 20.8627 17.7419 20.7837C15.7236 17.2522 9.26021 12.2898 6.39414 11.1186C6.34112 11.0968 6.32556 11.0313 6.36084 10.9855Z",
13341
+ fillGradient: "paint0_linear"
13342
+ },
13343
+ {
13344
+ d: "M13.0475 9.39974C9.95016 10.3806 7.11935 10.9259 6.44331 11.0498C6.40027 11.0577 6.39115 11.1172 6.43152 11.134C9.3203 12.3347 15.7516 17.2826 17.7511 20.7998C17.7551 20.8075 17.7647 20.8103 17.7728 20.8068C17.7809 20.803 17.7853 20.793 17.7819 20.7844L13.0475 9.39974Z",
13345
+ fillGradient: "paint1_linear"
13346
+ },
13347
+ {
13348
+ d: "M10.762 3.705C13.4137 5.15161 16.4787 5.80132 20.545 6.14367C20.5703 6.14585 20.5787 6.18008 20.5557 6.19197C20.0359 6.45923 17.0574 7.97512 14.8455 8.78701C14.2524 9.00453 13.6564 9.20632 13.0692 9.39249C13.0562 9.39656 13.0419 9.39015 13.0369 9.37774L10.7005 3.75979C10.6849 3.72196 10.7257 3.68538 10.762 3.705Z",
13349
+ fillGradient: "paint2_linear"
13350
+ },
13351
+ kiteStroke("M10.7145 3.79041L17.8305 20.7659", "#513C9F", "0.17284"),
13352
+ kiteStroke("M6.44531 11.0476C6.44531 11.0476 10.375 10.3422 14.0686 9.06804C17.7623 7.7939 20.5122 6.23373 20.5122 6.23373", "#513C9F", "0.17284"),
13353
+ kiteStroke("M11.6914 5.93518L9.05534 14.7068M9.05534 14.7068H15.3203M9.05534 14.7068L0.15625 26.3646", "#ABABAB", "0.302474"),
13354
+ {
13355
+ d: "M6.02539 23.9646L4.85806 24.1287C5.46272 25.7287 6.70381 26.4276 8.18528 26.4276C11.8147 26.4276 10.707 22.3227 12.8103 22.3227C14.3358 22.3227 13.7155 25.6498 16.9992 25.6498C19.0029 25.6498 19.2028 23.631 18.8607 22.7625C18.8589 22.7572 18.8568 22.7524 18.8538 22.7476L18.3166 21.9253C18.2817 21.8706 18.1968 21.8912 18.1907 21.9562L18.0908 22.9529C18.0838 23.0222 18.0857 23.0913 18.0936 23.1605C18.1764 23.8491 18.2291 25.5202 16.9992 25.5202C15.7015 25.5202 15.3895 22.2362 12.8103 22.2362C9.78393 22.2362 10.1726 26.298 8.31487 26.298C7.08938 26.298 6.15447 24.9153 6.02539 23.9646Z",
13356
+ fillGradient: "paint3_linear"
13357
+ }
13358
+ ],
13359
+ gradients: [
13360
+ {
13361
+ id: "paint0_linear",
13362
+ x1: "15.5372",
13363
+ y1: "5.0278",
13364
+ x2: "12.0802",
13365
+ y2: "14.534",
13366
+ stops: [{ color: "#6430AB" }, {
13367
+ offset: "1",
13368
+ color: "#AA89D8"
13369
+ }]
13370
+ },
13371
+ {
13372
+ id: "paint1_linear",
13373
+ x1: "12.8583",
13374
+ y1: "10.3858",
13375
+ x2: "8.40764",
13376
+ y2: "18.9846",
13377
+ stops: [{ color: "#005DBB" }, {
13378
+ offset: "1",
13379
+ color: "#3D92E8"
13380
+ }]
13381
+ },
13382
+ {
13383
+ id: "paint2_linear",
13384
+ x1: "14.8452",
13385
+ y1: "5.02774",
13386
+ x2: "13.5047",
13387
+ y2: "9.21911",
13388
+ stops: [{ color: "#1B70C4" }, {
13389
+ offset: "1",
13390
+ color: "#54A4F2"
13391
+ }]
13392
+ },
13393
+ {
13394
+ id: "paint3_linear",
13395
+ x1: "4.85806",
13396
+ y1: "24.2455",
13397
+ x2: "18.9963",
13398
+ y2: "24.2455",
13399
+ stops: [
13400
+ { color: "#4497EA" },
13401
+ {
13402
+ offset: "0.254755",
13403
+ color: "#1463B2"
13404
+ },
13405
+ {
13406
+ offset: "0.498725",
13407
+ color: "#0A437D"
13408
+ },
13409
+ {
13410
+ offset: "0.666667",
13411
+ color: "#2476C8"
13412
+ },
13413
+ {
13414
+ offset: "0.972542",
13415
+ color: "#0C549A"
13416
+ }
13417
+ ]
13418
+ }
13419
+ ]
13420
+ };
13421
+ /**
13422
+ * The `fill` of a kite path: its gradient under the icon's id `prefix`, or
13423
+ * `undefined` for a stroke-only path.
13424
+ */
13425
+ function ɵinspectorKiteFill(prefix, path) {
13426
+ return path.fillGradient === void 0 ? void 0 : `url(#${prefix}-${path.fillGradient})`;
13427
+ }
13428
+ /** How long a hover-opened menu stays after the pointer leaves, in ms. */
13429
+ const ɵHOVER_MENU_CLOSE_DELAY_MS = 180;
13430
+ /**
13431
+ * The open state of a menu that opens when the pointer reaches its trigger,
13432
+ * like the Inspector shortcut's menu.
13433
+ *
13434
+ * - A mouse or pen over the trigger opens it; touch does not.
13435
+ * - Leaving the trigger or the menu closes it after `closeDelayMs`, unless
13436
+ * the pointer comes back first or the keyboard has used the menu since.
13437
+ * - Opening reads whether the trigger is inside a `.dark` element, so a menu
13438
+ * in a portal can match the theme.
13439
+ *
13440
+ * Frameworks render from `getSnapshot()` and re-render when `subscribe()`
13441
+ * notifies. Call `dispose()` on unmount; the controller stays usable.
13442
+ */
13443
+ var ɵHoverMenuController = class {
13444
+ #closeDelayMs;
13445
+ #listeners = /* @__PURE__ */ new Set();
13446
+ #state = {
13447
+ open: false,
13448
+ dark: false
13449
+ };
13450
+ #timer;
13451
+ #openedByHover = false;
13452
+ constructor({ closeDelayMs = ɵHOVER_MENU_CLOSE_DELAY_MS } = {}) {
13453
+ this.#closeDelayMs = closeDelayMs;
13454
+ }
13455
+ /** The current state. The same object until something changes. */
13456
+ getSnapshot = () => this.#state;
13457
+ /** Calls `listener` when the state changes. Returns the unsubscribe function. */
13458
+ subscribe = (listener) => {
13459
+ this.#listeners.add(listener);
13460
+ return () => {
13461
+ this.#listeners.delete(listener);
13462
+ };
13463
+ };
13464
+ /** Whether the pointer opened the menu and the keyboard has not used it. */
13465
+ get openedByHover() {
13466
+ return this.#openedByHover;
13467
+ }
13468
+ /**
13469
+ * Opens or closes the menu and stops a pending close. `trigger` is read on
13470
+ * open for the dark theme.
13471
+ */
13472
+ setOpen = (open, trigger) => {
13473
+ this.cancelClose();
13474
+ const dark = open ? !!trigger?.closest(".dark") : this.#state.dark;
13475
+ if (open === this.#state.open && dark === this.#state.dark) return;
13476
+ this.#state = {
13477
+ open,
13478
+ dark
13479
+ };
13480
+ for (const listener of this.#listeners) listener();
13481
+ };
13482
+ /** The pointer reached the trigger: opens, except for touch or disabled. */
13483
+ pointerEnter = ({ pointerType, disabled = false, trigger }) => {
13484
+ if (disabled || pointerType === "touch") return;
13485
+ this.#openedByHover = true;
13486
+ this.setOpen(true, trigger);
13487
+ };
13488
+ /** The keyboard used the trigger or the menu: keep it open on leave. */
13489
+ keyboardUsed = () => {
13490
+ this.#openedByHover = false;
13491
+ };
13492
+ /** The pointer left the trigger or the menu: close soon if hover opened it. */
13493
+ scheduleClose = () => {
13494
+ this.cancelClose();
13495
+ this.#timer = setTimeout(() => {
13496
+ this.#timer = void 0;
13497
+ if (this.#openedByHover) this.setOpen(false);
13498
+ }, this.#closeDelayMs);
13499
+ };
13500
+ /** The pointer came back: keep the menu open. */
13501
+ cancelClose = () => {
13502
+ if (this.#timer === void 0) return;
13503
+ clearTimeout(this.#timer);
13504
+ this.#timer = void 0;
13505
+ };
13506
+ /** Stops a pending close. */
13507
+ dispose = () => {
13508
+ this.cancelClose();
13509
+ };
13510
+ };
13511
+
13512
+ //#endregion
13513
+ //#region src/open-generative-ui/content.ts
13514
+ /**
13515
+ * Open Generative UI content: the activity the agent streams while it
13516
+ * generates a sandboxed UI, and the rules for when a new snapshot must reach
13517
+ * the sandbox at once.
13518
+ */
13519
+ /** The activity type of Open Generative UI messages. */
13520
+ const OPEN_GENERATIVE_UI_ACTIVITY_TYPE = "open-generative-ui";
13521
+ /** The name of the frontend tool the agent calls to generate a sandboxed UI. */
13522
+ const GENERATE_SANDBOXED_UI_TOOL_NAME = "generateSandboxedUi";
13523
+ /** The design guidance sent to the agent when no `designSkill` is set. */
13524
+ const DEFAULT_OPEN_GENERATIVE_UI_DESIGN_SKILL = `When generating UI with generateSandboxedUi, follow these design principles inspired by shadcn/ui:
13525
+
13526
+ - Use a minimal, flat aesthetic. Avoid drop shadows and gradients — rely on subtle borders (1px solid, light gray like #e5e7eb) to define surfaces.
13527
+ - Neutral base palette: white backgrounds, zinc/slate gray text (#09090b for headings, #71717a for secondary text). One accent color for interactive elements.
13528
+ - Use system font stacks (system-ui, -apple-system, sans-serif) at readable sizes (14px body, 600 weight for headings). Tight line-heights.
13529
+ - Small, consistent border-radius (6–8px). Cards and containers use border, not shadow, for separation.
13530
+ - Buttons: solid fill for primary (dark bg, white text), outline for secondary (border + transparent bg). Subtle hover state (slight opacity or background shift).
13531
+ - Use CSS Grid or Flexbox for layout. Ensure the UI looks good at any width.
13532
+ - Minimal transitions (150ms) for hover/focus states only. No decorative animations.
13533
+ - Keep the UI focused and dense — avoid excessive padding. Use compact spacing (8–12px gaps, 10–14px padding in controls).`;
13534
+ /** `true` when the content has HTML that a preview or final sandbox shows. */
13535
+ function hasRenderableContent(content) {
13536
+ if (!content) return false;
13537
+ const hasHtml = !!content.html?.join("").trim();
13538
+ const hasFinalHtml = content.htmlComplete && hasHtml;
13539
+ const hasPreviewHtml = content.cssComplete && !content.htmlComplete && hasHtml;
13540
+ return !!hasFinalHtml || !!hasPreviewHtml;
13541
+ }
13542
+ /**
13543
+ * `true` when `next` must replace `previous` at once instead of waiting for
13544
+ * the throttle window: the UI restarts, a stage completes, or new JavaScript
13545
+ * arrives.
13546
+ */
13547
+ function shouldFlushImmediately(previous, next) {
13548
+ if (hasRenderableContent(previous) && !hasRenderableContent(next)) return true;
13549
+ if (next.cssComplete && !previous?.cssComplete) return true;
13550
+ if (next.htmlComplete) return true;
13551
+ if (next.generating === false) return true;
13552
+ if (next.jsFunctions && !previous?.jsFunctions) return true;
13553
+ if ((next.jsExpressions?.length ?? 0) > (previous?.jsExpressions?.length ?? 0)) return true;
13554
+ if (next.html?.length && !previous?.html?.length) return true;
13555
+ return false;
13556
+ }
13557
+
13558
+ //#endregion
13559
+ //#region src/open-generative-ui/html.ts
13560
+ /**
13561
+ * Pure string helpers that turn streamed HTML into sandbox content.
13562
+ * No DOM access.
13563
+ */
13564
+ /**
13565
+ * Extracts all complete `<style>` blocks from the raw HTML.
13566
+ * Returns the concatenated style tags, suitable for injection into `<head>`.
13567
+ */
13568
+ function extractCompleteStyles(html) {
13569
+ const matches = html.match(/<style\b[^>]*>[\s\S]*?<\/style>/gi);
13570
+ return matches ? matches.join("") : "";
13571
+ }
13572
+ /**
13573
+ * Processes raw accumulated HTML for safe preview via innerHTML injection.
13574
+ *
13575
+ * Pipeline (order matters):
13576
+ * 1. Strip incomplete tag at end
13577
+ * 2. Strip complete <style>, <script>, and <head> blocks
13578
+ * 3. Strip incomplete <style>/<script>/<head> blocks
13579
+ * 4. Strip incomplete HTML entities
13580
+ * 5. Extract body content (or use full string if no <body>)
13581
+ */
13582
+ function processPartialHtml(html) {
13583
+ let result = html;
13584
+ result = result.replace(/<[^>]*$/, "");
13585
+ result = result.replace(/<(style|script|head)\b[^>]*>[\s\S]*?<\/\1>/gi, "");
13586
+ result = result.replace(/<(style|script|head)\b[^>]*>[\s\S]*$/gi, "");
13587
+ result = result.replace(/&[a-zA-Z0-9#]*$/, "");
13588
+ const bodyMatch = result.match(/<body[^>]*>([\s\S]*)/i);
13589
+ if (bodyMatch) {
13590
+ result = bodyMatch[1];
13591
+ result = result.replace(/<\/body>[\s\S]*/i, "");
13592
+ }
13593
+ return result;
13594
+ }
13595
+ /** Builds the final sandbox document: the HTML with the CSS in its `<head>`. */
13596
+ function buildFinalFrameContent(html, css) {
13597
+ const withCss = css ? injectCssIntoHtml(html, css) : html;
13598
+ return /<head[\s>]/i.test(withCss) ? withCss : `<head></head>${withCss}`;
13599
+ }
13600
+ function injectCssIntoHtml(html, css) {
13601
+ const headCloseIdx = html.indexOf("</head>");
13602
+ if (headCloseIdx !== -1) return html.slice(0, headCloseIdx) + `<style>${css}</style>` + html.slice(headCloseIdx);
13603
+ return `<head><style>${css}</style></head>${html}`;
13604
+ }
13605
+
13606
+ //#endregion
13607
+ //#region src/open-generative-ui/websandbox.ts
13608
+ /**
13609
+ * Imports `@jetbrains/websandbox` on demand. The import is dynamic because
13610
+ * the package touches `self` when it loads, which breaks server rendering.
13611
+ */
13612
+ const loadWebsandbox = async () => {
13613
+ const defaultExport = (await import("@jetbrains/websandbox")).default;
13614
+ return "default" in defaultExport ? defaultExport.default : defaultExport;
13615
+ };
13616
+
13617
+ //#endregion
13618
+ //#region src/open-generative-ui/controller.ts
13619
+ /** Non-immediate content updates reach the sandbox at most this often. */
13620
+ const OPEN_GENERATIVE_UI_THROTTLE_MS = 1e3;
13621
+ const DEFAULT_HEIGHT = 200;
13622
+ const HIDE_SCROLLBARS = `
13623
+ var s = document.createElement('style');
13624
+ s.textContent = 'html, body { overflow: hidden !important; }';
13625
+ document.head.appendChild(s);
13626
+ `;
13627
+ const HIDE_SCROLLBARS_STYLE = "<style>html, body { overflow: hidden !important; }</style>";
13628
+ const MEASURE_HEIGHT = `
13629
+ (function() {
13630
+ var s = document.createElement('style');
13631
+ s.textContent = 'body { height: auto !important; min-height: 0 !important; }';
13632
+ document.head.appendChild(s);
13633
+ var h = document.body.scrollHeight;
13634
+ var cs = getComputedStyle(document.body);
13635
+ h += parseFloat(cs.marginTop) || 0;
13636
+ h += parseFloat(cs.marginBottom) || 0;
13637
+ s.remove();
13638
+ parent.postMessage({ type: "__ck_resize", height: Math.ceil(h) }, "*");
13639
+ })();
13640
+ `;
13641
+ function deriveContent(content) {
13642
+ const html = content.html?.join("") || void 0;
13643
+ const css = content.cssComplete ? content.css : void 0;
13644
+ if (content.htmlComplete) return {
13645
+ fullHtml: html,
13646
+ css,
13647
+ previewStyles: ""
13648
+ };
13649
+ const previewBody = html && content.cssComplete ? processPartialHtml(html) : void 0;
13650
+ return {
13651
+ css,
13652
+ previewBody: previewBody?.trim() ? previewBody : void 0,
13653
+ previewStyles: html ? extractCompleteStyles(html) : ""
13654
+ };
13655
+ }
13656
+ function prepareIframe(iframe, testId) {
13657
+ iframe.setAttribute("data-testid", testId);
13658
+ iframe.style.width = "100%";
13659
+ iframe.style.height = "100%";
13660
+ iframe.style.border = "none";
13661
+ iframe.style.backgroundColor = "transparent";
13662
+ }
13663
+ function logLoadError(error) {
13664
+ console.error("[OpenGenerativeUI] Failed to load sandbox module:", error);
13665
+ }
13666
+ function sameFunctions(a, b) {
13667
+ return a.length === b.length && a.every((fn, i) => fn.name === b[i].name && fn.handler === b[i].handler);
13668
+ }
13669
+ /**
13670
+ * Runs Open Generative UI content in websandbox iframes inside a host element.
13671
+ *
13672
+ * Give it content snapshots with `setContent()` and a host element with
13673
+ * `setHost()`. It throttles the snapshots, streams a preview while HTML
13674
+ * arrives, swaps in the final sandbox once HTML is complete, runs
13675
+ * `jsFunctions` and `jsExpressions` in it once each, and measures the final
13676
+ * height. Frameworks render the container from `getState()` and re-render
13677
+ * when `subscribe()` notifies.
13678
+ *
13679
+ * @example
13680
+ * ```ts
13681
+ * const controller = new ɵOpenGenerativeUIController();
13682
+ * controller.subscribe(() => render(controller.getState()));
13683
+ * controller.setContent(content);
13684
+ * controller.setHost(containerElement);
13685
+ * // On unmount:
13686
+ * controller.destroy();
13687
+ * ```
13688
+ */
13689
+ var OpenGenerativeUIController = class {
13690
+ #load;
13691
+ #listeners = /* @__PURE__ */ new Set();
13692
+ #content;
13693
+ #latest;
13694
+ #derived = { previewStyles: "" };
13695
+ #timer;
13696
+ #host = null;
13697
+ #functions = [];
13698
+ #localApi = {};
13699
+ #preview;
13700
+ #final;
13701
+ #measuredHeight;
13702
+ #state = {
13703
+ phase: "placeholder",
13704
+ generating: true,
13705
+ height: DEFAULT_HEIGHT
13706
+ };
13707
+ constructor(options = {}) {
13708
+ this.#load = options.loadWebsandbox ?? loadWebsandbox;
13709
+ }
13710
+ /** The current state. The same object until something changes. */
13711
+ getState = () => this.#state;
13712
+ /** Calls `listener` when the state changes. Returns the unsubscribe function. */
13713
+ subscribe = (listener) => {
13714
+ this.#listeners.add(listener);
13715
+ return () => {
13716
+ this.#listeners.delete(listener);
13717
+ };
13718
+ };
13719
+ /**
13720
+ * Sets the latest content snapshot. The first snapshot and snapshots that
13721
+ * finish a stage apply at once; others apply at most once per second.
13722
+ */
13723
+ setContent(content) {
13724
+ this.#latest = content;
13725
+ if (this.#content === void 0 || shouldFlushImmediately(this.#content, content)) {
13726
+ this.#clearTimer();
13727
+ this.#commit(content);
13728
+ return;
13729
+ }
13730
+ if (content === this.#content || this.#timer !== void 0) return;
13731
+ this.#timer = setTimeout(() => {
13732
+ this.#timer = void 0;
13733
+ if (this.#latest) this.#commit(this.#latest);
13734
+ }, OPEN_GENERATIVE_UI_THROTTLE_MS);
13735
+ }
13736
+ /** Sets the element the sandbox iframes go into. `null` removes them. */
13737
+ setHost(host) {
13738
+ if (host === this.#host) return;
13739
+ this.#destroyPreview();
13740
+ this.#destroyFinal();
13741
+ this.#host = host;
13742
+ this.#reconcile();
13743
+ }
13744
+ /**
13745
+ * Sets the host functions sandboxed code can call. A change recreates the
13746
+ * final sandbox.
13747
+ */
13748
+ setSandboxFunctions(functions) {
13749
+ if (sameFunctions(functions, this.#functions)) return;
13750
+ this.#functions = functions;
13751
+ const localApi = {};
13752
+ for (const fn of functions) localApi[fn.name] = fn.handler;
13753
+ this.#localApi = localApi;
13754
+ this.#reconcile();
13755
+ }
13756
+ /**
13757
+ * Removes the sandboxes and stops pending work. A later `setHost()`
13758
+ * starts again from the current content.
13759
+ */
13760
+ destroy() {
13761
+ this.#clearTimer();
13762
+ this.#destroyPreview();
13763
+ this.#destroyFinal();
13764
+ this.#host = null;
13765
+ }
13766
+ #commit(content) {
13767
+ if (content === this.#content) return;
13768
+ this.#content = content;
13769
+ this.#derived = deriveContent(content);
13770
+ this.#reconcile();
13771
+ }
13772
+ #reconcile() {
13773
+ const host = this.#host;
13774
+ const content = this.#content;
13775
+ const derived = this.#derived;
13776
+ if (host && content) if (derived.fullHtml) {
13777
+ this.#destroyPreview();
13778
+ const frameContent = buildFinalFrameContent(derived.fullHtml, derived.css);
13779
+ let final = this.#final;
13780
+ if (final?.frameContent !== frameContent || final.localApi !== this.#localApi) {
13781
+ this.#destroyFinal();
13782
+ final = this.#final = this.#createFinal(host, frameContent);
13783
+ }
13784
+ this.#runScripts(final, content);
13785
+ } else {
13786
+ this.#destroyFinal();
13787
+ if (derived.previewBody) {
13788
+ this.#preview ??= this.#createPreview(host);
13789
+ this.#writePreview();
13790
+ } else this.#destroyPreview();
13791
+ }
13792
+ this.#updateState();
13793
+ }
13794
+ #createPreview(host) {
13795
+ const slot = {
13796
+ ready: false,
13797
+ cancelled: false
13798
+ };
13799
+ this.#load().then((Websandbox) => {
13800
+ if (slot.cancelled) return;
13801
+ const sandbox = Websandbox.create({}, {
13802
+ frameContainer: host,
13803
+ frameContent: "<head></head><body></body>",
13804
+ allowAdditionalAttributes: ""
13805
+ });
13806
+ slot.sandbox = sandbox;
13807
+ prepareIframe(sandbox.iframe, "open-generative-ui-preview-sandbox");
13808
+ sandbox.promise.then(() => {
13809
+ if (slot.cancelled) return;
13810
+ slot.ready = true;
13811
+ this.#writePreview();
13812
+ });
13813
+ }).catch(logLoadError);
13814
+ return slot;
13815
+ }
13816
+ #writePreview() {
13817
+ const slot = this.#preview;
13818
+ if (!slot?.sandbox || !slot.ready) return;
13819
+ const { css, previewStyles, previewBody } = this.#derived;
13820
+ const head = HIDE_SCROLLBARS_STYLE + (css ? `<style>${css}</style>` : "") + previewStyles;
13821
+ if (head !== slot.head) {
13822
+ slot.head = head;
13823
+ slot.sandbox.run(`document.head.innerHTML = ${JSON.stringify(head)}`);
13824
+ }
13825
+ if (previewBody && previewBody !== slot.body) {
13826
+ slot.body = previewBody;
13827
+ slot.sandbox.run(`document.body.innerHTML = ${JSON.stringify(previewBody)}`);
13828
+ }
13829
+ }
13830
+ #createFinal(host, frameContent) {
13831
+ const slot = {
13832
+ frameContent,
13833
+ localApi: this.#localApi,
13834
+ ready: false,
13835
+ cancelled: false,
13836
+ queue: [],
13837
+ jsFunctionsInjected: false,
13838
+ executedExpressions: 0,
13839
+ heightRequested: false
13840
+ };
13841
+ this.#load().then((Websandbox) => {
13842
+ if (slot.cancelled) return;
13843
+ const sandbox = Websandbox.create(slot.localApi, {
13844
+ frameContainer: host,
13845
+ frameContent,
13846
+ allowAdditionalAttributes: ""
13847
+ });
13848
+ slot.sandbox = sandbox;
13849
+ prepareIframe(sandbox.iframe, "open-generative-ui-final-sandbox");
13850
+ sandbox.promise.then(() => {
13851
+ if (slot.cancelled) return;
13852
+ slot.ready = true;
13853
+ sandbox.run(HIDE_SCROLLBARS);
13854
+ const queue = slot.queue;
13855
+ slot.queue = [];
13856
+ for (const code of queue) sandbox.run(code);
13857
+ });
13858
+ }).catch(logLoadError);
13859
+ return slot;
13860
+ }
13861
+ /** Runs new `jsFunctions`, new `jsExpressions`, and the height measurement. */
13862
+ #runScripts(slot, content) {
13863
+ if (content.jsFunctions && !slot.jsFunctionsInjected) {
13864
+ slot.jsFunctionsInjected = true;
13865
+ this.#runOrQueue(slot, content.jsFunctions);
13866
+ }
13867
+ const expressions = content.jsExpressions ?? [];
13868
+ if (expressions.length > slot.executedExpressions) {
13869
+ const newExpressions = expressions.slice(slot.executedExpressions);
13870
+ slot.executedExpressions = expressions.length;
13871
+ const sandbox = slot.sandbox;
13872
+ if (slot.ready && sandbox) (async () => {
13873
+ for (const expression of newExpressions) await sandbox.run(expression);
13874
+ })();
13875
+ else slot.queue.push(...newExpressions);
13876
+ }
13877
+ if (content.generating === false && !slot.heightRequested) {
13878
+ slot.heightRequested = true;
13879
+ this.#listenForHeight(slot);
13880
+ this.#runOrQueue(slot, MEASURE_HEIGHT);
13881
+ }
13882
+ }
13883
+ #runOrQueue(slot, code) {
13884
+ if (slot.ready && slot.sandbox) slot.sandbox.run(code);
13885
+ else slot.queue.push(code);
13886
+ }
13887
+ #listenForHeight(slot) {
13888
+ if (typeof window === "undefined") return;
13889
+ const onMessage = (event) => {
13890
+ const data = event.data;
13891
+ if (!slot.sandbox || event.source !== slot.sandbox.iframe.contentWindow || data?.type !== "__ck_resize" || typeof data.height !== "number") return;
13892
+ slot.stopHeightListener?.();
13893
+ this.#measuredHeight = data.height;
13894
+ this.#updateState();
13895
+ };
13896
+ window.addEventListener("message", onMessage);
13897
+ slot.stopHeightListener = () => {
13898
+ window.removeEventListener("message", onMessage);
13899
+ slot.stopHeightListener = void 0;
13900
+ };
13901
+ }
13902
+ #destroyPreview() {
13903
+ const slot = this.#preview;
13904
+ if (!slot) return;
13905
+ slot.cancelled = true;
13906
+ slot.sandbox?.destroy();
13907
+ this.#preview = void 0;
13908
+ }
13909
+ #destroyFinal() {
13910
+ const slot = this.#final;
13911
+ if (!slot) return;
13912
+ slot.cancelled = true;
13913
+ slot.stopHeightListener?.();
13914
+ slot.sandbox?.destroy();
13915
+ this.#final = void 0;
13916
+ this.#measuredHeight = void 0;
13917
+ }
13918
+ #clearTimer() {
13919
+ if (this.#timer === void 0) return;
13920
+ clearTimeout(this.#timer);
13921
+ this.#timer = void 0;
13922
+ }
13923
+ #updateState() {
13924
+ const content = this.#content ?? {};
13925
+ const derived = this.#derived;
13926
+ const next = {
13927
+ phase: derived.fullHtml ? "final" : derived.previewBody ? "preview" : "placeholder",
13928
+ generating: content.generating !== false,
13929
+ height: this.#measuredHeight ?? content.initialHeight ?? DEFAULT_HEIGHT
13930
+ };
13931
+ const current = this.#state;
13932
+ if (next.phase === current.phase && next.generating === current.generating && next.height === current.height) return;
13933
+ this.#state = next;
13934
+ for (const listener of this.#listeners) listener();
13935
+ }
13936
+ };
13937
+
13938
+ //#endregion
13939
+ //#region src/utils/class-names.ts
13940
+ /**
13941
+ * Joins class names, skipping falsy values. Takes the same inputs as `clsx`.
13942
+ * Classes are not merged: every rule CopilotKit ships sits in `:where()`, so a
13943
+ * class the app adds wins without removing ours.
13944
+ */
13945
+ function cn(...inputs) {
13946
+ const out = [];
13947
+ for (const input of inputs) {
13948
+ if (!input) continue;
13949
+ if (typeof input === "string" || typeof input === "number" || typeof input === "bigint") out.push(String(input));
13950
+ else if (Array.isArray(input)) {
13951
+ const nested = cn(...input);
13952
+ if (nested) out.push(nested);
13953
+ } else if (typeof input === "object") {
13954
+ for (const key in input) if (input[key]) out.push(key);
13955
+ }
13956
+ }
13957
+ return out.join(" ");
13958
+ }
13959
+
10774
13960
  //#endregion
10775
13961
  exports.A2UI_FENCE_LANGUAGE = A2UI_FENCE_LANGUAGE;
10776
13962
  exports.AgentRegistry = AgentRegistry;
10777
13963
  exports.AgentThreadLockedError = AgentThreadLockedError;
10778
13964
  exports.ContextStore = ContextStore;
13965
+ exports.CopilotChatDefaultLabels = CopilotChatDefaultLabels;
10779
13966
  exports.CopilotKitCore = CopilotKitCore;
10780
13967
  exports.CopilotKitCoreErrorCode = CopilotKitCoreErrorCode;
10781
13968
  exports.CopilotKitCoreRuntimeConnectionStatus = CopilotKitCoreRuntimeConnectionStatus;
10782
13969
  exports.CopilotKitHeaderResolutionError = CopilotKitHeaderResolutionError;
13970
+ exports.DEFAULT_OPEN_GENERATIVE_UI_DESIGN_SKILL = DEFAULT_OPEN_GENERATIVE_UI_DESIGN_SKILL;
13971
+ exports.GENERATE_SANDBOXED_UI_TOOL_NAME = GENERATE_SANDBOXED_UI_TOOL_NAME;
10783
13972
  exports.INSPECTOR_THREAD_BRIDGE_PLUGIN_ID = INSPECTOR_THREAD_BRIDGE_PLUGIN_ID;
13973
+ exports.INTERRUPT_EVENT_NAME = INTERRUPT_EVENT_NAME;
10784
13974
  exports.IntelligenceAgent = IntelligenceAgent;
10785
13975
  exports.MEMORY_ERROR_REGISTRY = MEMORY_ERROR_REGISTRY;
10786
13976
  exports.MemoryError = MemoryError;
13977
+ exports.OPEN_GENERATIVE_UI_ACTIVITY_TYPE = OPEN_GENERATIVE_UI_ACTIVITY_TYPE;
10787
13978
  exports.ProxiedCopilotRuntimeAgent = ProxiedCopilotRuntimeAgent;
10788
13979
  exports.RunHandler = RunHandler;
10789
13980
  exports.StateManager = StateManager;
10790
13981
  exports.SuggestionEngine = SuggestionEngine;
10791
13982
  exports.ToolCallStatus = ToolCallStatus;
13983
+ exports.TranscriptionError = TranscriptionError;
13984
+ exports.TranscriptionErrorCode = _copilotkit_shared.TranscriptionErrorCode;
10792
13985
  exports.WebMCPRegistry = WebMCPRegistry;
10793
13986
  exports.classifySurfaceCards = classifySurfaceCards;
10794
13987
  exports.completePartialMarkdown = completePartialMarkdown;
@@ -10819,7 +14012,6 @@ exports.onInspectorActiveThread = onInspectorActiveThread;
10819
14012
  exports.onInspectorStopViewing = onInspectorStopViewing;
10820
14013
  exports.onInspectorViewThread = onInspectorViewThread;
10821
14014
  exports.onInspectorViewThreadResult = onInspectorViewThreadResult;
10822
- exports.parseMarkdown = parseMarkdown;
10823
14015
  exports.parseToolArguments = parseToolArguments;
10824
14016
  exports.prepareSurfaceOperations = prepareSurfaceOperations;
10825
14017
  exports.props = props;
@@ -10827,30 +14019,100 @@ exports.segmentSurfaceProse = segmentSurfaceProse;
10827
14019
  exports.select = select;
10828
14020
  exports.splitA2UIMarkdown = splitA2UIMarkdown;
10829
14021
  exports.ɵCOPILOTKIT_FEATURES = ɵCOPILOTKIT_FEATURES;
14022
+ exports.ɵCOPY_FEEDBACK_RESET_MS = ɵCOPY_FEEDBACK_RESET_MS;
14023
+ exports.ɵCopyFeedback = ɵCopyFeedback;
14024
+ exports.ɵFEEDBACK_COMMENT_CLOSE_DELAY_MS = ɵFEEDBACK_COMMENT_CLOSE_DELAY_MS;
14025
+ exports.ɵFeedbackCommentController = ɵFeedbackCommentController;
14026
+ exports.ɵHOVER_MENU_CLOSE_DELAY_MS = ɵHOVER_MENU_CLOSE_DELAY_MS;
14027
+ exports.ɵHoverMenuController = ɵHoverMenuController;
14028
+ exports.ɵINLINE_FEATURE_WARNING_STYLE = ɵINLINE_FEATURE_WARNING_STYLE;
10830
14029
  exports.ɵInterruptState = ɵInterruptState;
14030
+ exports.ɵKEYBOARD_OPEN_THRESHOLD_PX = ɵKEYBOARD_OPEN_THRESHOLD_PX;
14031
+ exports.ɵLICENSE_BANNER_OFFSET = ɵLICENSE_BANNER_OFFSET;
14032
+ exports.ɵLICENSE_BANNER_STYLE = ɵLICENSE_BANNER_STYLE;
10831
14033
  exports.ɵMAX_SOCKET_RETRIES = ɵMAX_SOCKET_RETRIES;
14034
+ exports.ɵMESSAGE_FEEDBACK_EVENT_NAME = ɵMESSAGE_FEEDBACK_EVENT_NAME;
14035
+ exports.ɵMESSAGE_FEEDBACK_MAX_COMMENT_LENGTH = ɵMESSAGE_FEEDBACK_MAX_COMMENT_LENGTH;
14036
+ exports.ɵMOBILE_MAX_WIDTH_QUERY = ɵMOBILE_MAX_WIDTH_QUERY;
14037
+ exports.ɵOpenGenerativeUIController = OpenGenerativeUIController;
10832
14038
  exports.ɵRUNTIME_PROBE_TIMEOUT_MS = ɵRUNTIME_PROBE_TIMEOUT_MS;
10833
14039
  exports.ɵTHREAD_REQUEST_TIMEOUT_MS = ɵTHREAD_REQUEST_TIMEOUT_MS;
10834
14040
  exports.ɵclearAgentInterruptState = ɵclearAgentInterruptState;
14041
+ exports.ɵcn = cn;
14042
+ exports.ɵcomposerButtonState = ɵcomposerButtonState;
14043
+ exports.ɵcopilotIconSvgAttributes = ɵcopilotIconSvgAttributes;
14044
+ exports.ɵcopilotIcons = ɵcopilotIcons;
14045
+ exports.ɵcountFailedToolCalls = countFailedToolCalls;
10835
14046
  exports.ɵcreateMemoryStore = createMemoryStore;
10836
14047
  exports.ɵcreateThreadSelectors = ɵcreateThreadSelectors;
10837
14048
  exports.ɵcreateThreadStore = createThreadStore;
14049
+ exports.ɵdeduplicateMessages = ɵdeduplicateMessages;
14050
+ exports.ɵextractCompleteStyles = extractCompleteStyles;
14051
+ exports.ɵflattenUserMessageContent = ɵflattenUserMessageContent;
14052
+ exports.ɵformatCountLabel = ɵformatCountLabel;
14053
+ exports.ɵformatLabel = ɵformatLabel;
14054
+ exports.ɵformatReasoningDuration = formatReasoningDuration;
14055
+ exports.ɵformatReasoningDurationLabel = ɵformatReasoningDurationLabel;
14056
+ exports.ɵformatToolNames = formatToolNames;
14057
+ exports.ɵformatWorkDuration = formatWorkDuration;
10838
14058
  exports.ɵgetAgentInterruptState = ɵgetAgentInterruptState;
14059
+ exports.ɵgetArgumentPreview = getArgumentPreview;
14060
+ exports.ɵgetBranchNavState = ɵgetBranchNavState;
14061
+ exports.ɵgetInlineFeatureWarningSpec = ɵgetInlineFeatureWarningSpec;
14062
+ exports.ɵgetLatestTurnKey = getLatestTurnKey;
14063
+ exports.ɵgetLicenseBannerSpec = ɵgetLicenseBannerSpec;
14064
+ exports.ɵgetMessageFeedback = ɵgetMessageFeedback;
14065
+ exports.ɵgetMessageFeedbackControls = ɵgetMessageFeedbackControls;
14066
+ exports.ɵgetToolCallLayouts = getToolCallLayouts;
14067
+ exports.ɵgetToolCallPreview = getToolCallPreview;
14068
+ exports.ɵgetToolCallRendererNames = getToolCallRendererNames;
14069
+ exports.ɵgetToolCallRowStatus = getToolCallRowStatus;
14070
+ exports.ɵgetToolResults = getToolResults;
14071
+ exports.ɵgetTurnWork = getTurnWork;
14072
+ exports.ɵgetUserMessageMediaFilename = ɵgetUserMessageMediaFilename;
14073
+ exports.ɵgetUserMessageMediaParts = ɵgetUserMessageMediaParts;
14074
+ exports.ɵgetWorkOpenState = getWorkOpenState;
14075
+ exports.ɵgetWorkSummaryText = ɵgetWorkSummaryText;
14076
+ exports.ɵhasAssistantMessageText = ɵhasAssistantMessageText;
14077
+ exports.ɵinitialKeyboardState = ɵinitialKeyboardState;
14078
+ exports.ɵinspectorKiteFill = ɵinspectorKiteFill;
14079
+ exports.ɵinspectorKiteIcon = ɵinspectorKiteIcon;
14080
+ exports.ɵinspectorShortcuts = ɵinspectorShortcuts;
10839
14081
  exports.ɵisCopilotKitFeature = ɵisCopilotKitFeature;
10840
14082
  exports.ɵisHttpAgent = ɵisHttpAgent;
14083
+ exports.ɵisLearningFeedbackEnabled = ɵisLearningFeedbackEnabled;
14084
+ exports.ɵisMobileViewport = ɵisMobileViewport;
10841
14085
  exports.ɵisRetryableMemoryStatus = isRetryableStatus;
14086
+ exports.ɵisTurnWorkOpen = isTurnWorkOpen;
14087
+ exports.ɵisTurnWorking = isTurnWorking;
10842
14088
  exports.ɵjoinPhoenixChannel$ = ɵjoinPhoenixChannel$;
14089
+ exports.ɵloadWebsandbox = loadWebsandbox;
10843
14090
  exports.ɵmapMemoryMetadataEvent = ɵmapMemoryMetadataEvent;
10844
14091
  exports.ɵmemoryAdapterEvents = ɵmemoryAdapterEvents;
10845
14092
  exports.ɵmemoryDomainEvents = ɵmemoryDomainEvents;
10846
14093
  exports.ɵmemoryReducer = ɵmemoryReducer;
10847
14094
  exports.ɵmemoryRestEvents = ɵmemoryRestEvents;
14095
+ exports.ɵmessagesFingerprint = ɵmessagesFingerprint;
14096
+ exports.ɵnormalizeAutoScroll = ɵnormalizeAutoScroll;
10848
14097
  exports.ɵobservePhoenixEvent$ = ɵobservePhoenixEvent$;
10849
14098
  exports.ɵobservePhoenixJoinOutcome$ = ɵobservePhoenixJoinOutcome$;
10850
14099
  exports.ɵobservePhoenixSocketHealth$ = ɵobservePhoenixSocketHealth$;
10851
14100
  exports.ɵobservePhoenixSocketSignals$ = ɵobservePhoenixSocketSignals$;
10852
14101
  exports.ɵphoenixChannel$ = ɵphoenixChannel$;
10853
14102
  exports.ɵphoenixSocket$ = ɵphoenixSocket$;
14103
+ exports.ɵpinMessageToTop = ɵpinMessageToTop;
14104
+ exports.ɵpluralize = pluralize;
14105
+ exports.ɵprocessPartialHtml = processPartialHtml;
14106
+ exports.ɵreadKeyboardState = ɵreadKeyboardState;
14107
+ exports.ɵrecordWorkTime = recordWorkTime;
14108
+ exports.ɵreserveLicenseBannerOffset = ɵreserveLicenseBannerOffset;
14109
+ exports.ɵresetMessageFeedbackCache = ɵresetMessageFeedbackCache;
14110
+ exports.ɵresolveActivityRenderer = ɵresolveActivityRenderer;
14111
+ exports.ɵresolveComposerKey = ɵresolveComposerKey;
14112
+ exports.ɵresolveCustomMessageRenderers = ɵresolveCustomMessageRenderers;
14113
+ exports.ɵresolveLicenseState = ɵresolveLicenseState;
14114
+ exports.ɵresolveThreadsLicense = ɵresolveThreadsLicense;
14115
+ exports.ɵresolveToolCallRenderer = ɵresolveToolCallRenderer;
10854
14116
  exports.ɵselectFetchMoreError = ɵselectFetchMoreError;
10855
14117
  exports.ɵselectHasNextPage = ɵselectHasNextPage;
10856
14118
  exports.ɵselectIsFetchingNextPage = ɵselectIsFetchingNextPage;
@@ -10864,6 +14126,16 @@ exports.ɵselectMemoriesRealtimeStatus = ɵselectMemoriesRealtimeStatus;
10864
14126
  exports.ɵselectThreads = ɵselectThreads;
10865
14127
  exports.ɵselectThreadsError = ɵselectThreadsError;
10866
14128
  exports.ɵselectThreadsIsLoading = ɵselectThreadsIsLoading;
14129
+ exports.ɵsetMessageFeedback = ɵsetMessageFeedback;
14130
+ exports.ɵshallowEqualRecord = shallowEqualRecord;
14131
+ exports.ɵshouldShowAssistantToolbar = ɵshouldShowAssistantToolbar;
14132
+ exports.ɵstringifyToolCallPayload = stringifyToolCallPayload;
14133
+ exports.ɵsubscribeToLearningFeedbackEnabled = ɵsubscribeToLearningFeedbackEnabled;
14134
+ exports.ɵsubscribeToMessageFeedback = ɵsubscribeToMessageFeedback;
10867
14135
  exports.ɵthreadAdapterEvents = ɵthreadAdapterEvents;
14136
+ exports.ɵtranscribeAudio = ɵtranscribeAudio;
14137
+ exports.ɵtranscriptionErrorMessageKey = ɵtranscriptionErrorMessageKey;
14138
+ exports.ɵwatchKeyboardState = ɵwatchKeyboardState;
14139
+ exports.ɵwatchMobileViewport = ɵwatchMobileViewport;
10868
14140
  exports.ɵwithHeaderDefaults = ɵwithHeaderDefaults;
10869
14141
  //# sourceMappingURL=index.cjs.map