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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.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";
@@ -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 !== "v1.0") 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,1861 @@ 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
+ modalHeaderTitle: "CopilotKit Chat",
11138
+ welcomeMessageText: "How can I help you today?",
11139
+ reasoningMessageThinkingLabel: "Thinking…",
11140
+ chatInputSlashMenuLabel: "Slash commands",
11141
+ chatInputSlashMenuEmptyText: "No commands found",
11142
+ attachmentRemoveButtonLabel: "Remove attachment",
11143
+ attachmentPlayVideoButtonLabel: "Play video",
11144
+ attachmentPreviewCloseButtonLabel: "Close preview",
11145
+ modalHeaderCloseButtonLabel: "Close",
11146
+ modalHeaderThreadsButtonLabel: "Open threads",
11147
+ sidebarLabel: "Copilot chat sidebar",
11148
+ chatDropFilesLabel: "Drop files here",
11149
+ threadLoadErrorText: "Could not load saved conversation. Reopen the thread and try again.",
11150
+ reasoningMessageThoughtForLabel: "Thought for {duration}",
11151
+ reasoningMessageDurationFewSeconds: "a few seconds",
11152
+ reasoningMessageDurationSeconds: "{count} seconds",
11153
+ reasoningMessageDurationMinutesOne: "{count} minute",
11154
+ reasoningMessageDurationMinutesOther: "{count} minutes",
11155
+ reasoningMessageDurationMinutesSeconds: "{minutes}m {seconds}s",
11156
+ toolCallStatusRunningLabel: "Running",
11157
+ toolCallStatusDoneLabel: "Done",
11158
+ toolCallStatusFailedLabel: "Failed",
11159
+ toolCallStatusStoppedLabel: "Stopped",
11160
+ toolCallRunningLabel: "Running {name}",
11161
+ toolCallFailedCountLabel: "{count} failed",
11162
+ toolCallDoneCountLabel: "{count} done",
11163
+ toolCallArgumentsLabel: "Arguments",
11164
+ toolCallResultLabel: "Result",
11165
+ toolCallCollapseLabel: "Collapse",
11166
+ toolCallUsedToolsOne: "Used {count} tool",
11167
+ toolCallUsedToolsOther: "Used {count} tools",
11168
+ toolCallToolCountOne: "{count} tool",
11169
+ toolCallToolCountOther: "{count} tools",
11170
+ toolCallToolCallCountOne: "{count} tool call",
11171
+ toolCallToolCallCountOther: "{count} tool calls",
11172
+ toolCallCallCountOne: "{count} call",
11173
+ toolCallCallCountOther: "{count} calls",
11174
+ workSummaryWorkingLabel: "Working",
11175
+ workSummaryWorkedForLabel: "Worked for {duration}",
11176
+ attachmentImageLoadErrorText: "Failed to load image",
11177
+ attachmentImageAltText: "Image attachment",
11178
+ attachmentUnknownTypeText: "Unknown type",
11179
+ attachmentDocumentLabel: "Document",
11180
+ attachmentDocumentAltText: "Document attachment",
11181
+ attachmentNoPreviewText: "No preview available for this file type",
11182
+ chatAttachmentsUploadingText: "Cannot send while attachments are uploading.",
11183
+ transcriptionErrorRateLimitedText: "Too many requests. Please wait a moment.",
11184
+ transcriptionErrorAuthFailedText: "Authentication error. Please check your configuration.",
11185
+ transcriptionErrorAudioTooLongText: "Recording is too long. Please try a shorter recording.",
11186
+ transcriptionErrorAudioTooShortText: "Recording is too short. Please try again.",
11187
+ transcriptionErrorInvalidAudioFormatText: "Audio format not supported.",
11188
+ transcriptionErrorServiceNotConfiguredText: "Transcription service is not available.",
11189
+ transcriptionErrorNetworkText: "Network error. Please check your connection.",
11190
+ transcriptionErrorGenericText: "Transcription failed. Please try again.",
11191
+ licensePoweredByText: "Powered by CopilotKit",
11192
+ licenseGetLicenseLabel: "Get a license",
11193
+ licenseFeatureUnlicensedText: "⚠ The \"{feature}\" feature requires a CopilotKit license.",
11194
+ licenseExpiringText: "Your CopilotKit license expires soon. Please renew.",
11195
+ licenseExpiringInDaysOne: "Your CopilotKit license expires in {days} day. Please renew.",
11196
+ licenseExpiringInDaysOther: "Your CopilotKit license expires in {days} days. Please renew.",
11197
+ licenseExpiredText: "Your CopilotKit license expired. Please renew at copilotkit.ai/pricing",
11198
+ licenseExpiredOnDateText: "Your CopilotKit license expired on {date}. Please renew at copilotkit.ai/pricing",
11199
+ licenseInvalidText: "Invalid CopilotKit license token. Please check your configuration.",
11200
+ licenseRenewLabel: "Renew",
11201
+ licenseRenewNowLabel: "Renew now"
11202
+ });
11203
+ /**
11204
+ * Puts values into a label template. Each `{name}` in the template is replaced
11205
+ * by `values[name]`. A placeholder with no value stays in the text as is.
11206
+ *
11207
+ * @param template - A label value, such as `"Running {name}"`.
11208
+ * @param values - The value for each placeholder.
11209
+ *
11210
+ * ```ts
11211
+ * ɵformatLabel(labels.toolCallRunningLabel, { name: "read_file" });
11212
+ * // "Running read_file"
11213
+ * ```
11214
+ */
11215
+ function ɵformatLabel(template, values) {
11216
+ return template.replace(/\{(\w+)\}/g, (placeholder, name) => Object.hasOwn(values, name) ? String(values[name]) : placeholder);
11217
+ }
11218
+ /**
11219
+ * Fills a counted label pair: the `one` template for a count of 1, the
11220
+ * `other` template for any other count. Both templates take `{count}`.
11221
+ *
11222
+ * @param count - The number to show.
11223
+ * @param templates - The `...One` and `...Other` label templates.
11224
+ *
11225
+ * ```ts
11226
+ * ɵformatCountLabel(3, {
11227
+ * one: labels.toolCallToolCountOne,
11228
+ * other: labels.toolCallToolCountOther,
11229
+ * }); // "3 tools"
11230
+ * ```
11231
+ */
11232
+ function ɵformatCountLabel(count, templates) {
11233
+ return ɵformatLabel(count === 1 ? templates.one : templates.other, { count });
11234
+ }
11235
+
11236
+ //#endregion
11237
+ //#region src/chat/renderers.ts
11238
+ /** Name or activity type that matches anything. */
11239
+ const WILDCARD = "*";
11240
+ /**
11241
+ * Find the renderer that draws a tool call.
11242
+ *
11243
+ * The first rule that matches wins:
11244
+ *
11245
+ * 1. A renderer for `toolName` with `agentId` equal to the current agent.
11246
+ * 2. A renderer for `toolName` with no `agentId`.
11247
+ * 3. The first renderer for `toolName` from any other agent.
11248
+ * 4. The first `"*"` renderer, from any agent.
11249
+ *
11250
+ * Inside each rule, the earlier renderer in the list wins.
11251
+ *
11252
+ * @param renderers - Registered renderers in registration order. If you
11253
+ * build tiers (for example app renderers before built-in ones), flatten
11254
+ * them into one ordered list first.
11255
+ * @param toolName - Name of the tool the agent called.
11256
+ * @param agentId - The agent that owns the chat. The caller picks the
11257
+ * default: React and Vue pass `DEFAULT_AGENT_ID` when the chat has no
11258
+ * agent. With `undefined`, rule 1 matches the same renderers as rule 2.
11259
+ * @returns The renderer, or `null` when no renderer matches. Draw nothing
11260
+ * for `null`.
11261
+ *
11262
+ * @example
11263
+ * ```ts
11264
+ * const renderer = ɵresolveToolCallRenderer(
11265
+ * core.renderToolCalls,
11266
+ * toolCall.function.name,
11267
+ * chatAgentId ?? DEFAULT_AGENT_ID,
11268
+ * );
11269
+ * ```
11270
+ */
11271
+ function ɵresolveToolCallRenderer(renderers, toolName, agentId) {
11272
+ const named = renderers.filter((renderer) => renderer.name === toolName);
11273
+ return named.find((renderer) => renderer.agentId === agentId) ?? named.find((renderer) => !renderer.agentId) ?? named[0] ?? renderers.find((renderer) => renderer.name === WILDCARD) ?? null;
11274
+ }
11275
+ /**
11276
+ * Find the renderer that draws an activity message, and validate the
11277
+ * message content with that renderer's `content` schema.
11278
+ *
11279
+ * The first rule that matches picks the renderer:
11280
+ *
11281
+ * 1. A renderer for `activityType` with `agentId` equal to the current agent.
11282
+ * 2. A renderer for `activityType` with no `agentId`.
11283
+ * 3. The first `"*"` renderer, from any agent.
11284
+ *
11285
+ * A renderer for `activityType` that belongs to a different agent never
11286
+ * matches. Inside each rule, the earlier renderer in the list wins.
11287
+ *
11288
+ * Only the picked renderer validates the content. When validation fails, or
11289
+ * the schema validates asynchronously, the result is `null`. The function
11290
+ * does not try the next renderer.
11291
+ *
11292
+ * @param renderers - Registered renderers in registration order.
11293
+ * @param query - The activity type, the current agent, and the raw content.
11294
+ * @returns `{ renderer, content }`, where `content` is the value the schema
11295
+ * returned. Pass that value to `render`, not the raw content. Returns
11296
+ * `null` when no renderer matches or validation does not pass.
11297
+ *
11298
+ * @example
11299
+ * ```ts
11300
+ * const match = ɵresolveActivityRenderer(core.renderActivityMessages, {
11301
+ * activityType: message.activityType,
11302
+ * agentId,
11303
+ * content: message.content,
11304
+ * });
11305
+ * if (match) draw(match.renderer.render, match.content);
11306
+ * ```
11307
+ */
11308
+ function ɵresolveActivityRenderer(renderers, query) {
11309
+ const { activityType, agentId, content } = query;
11310
+ const sameType = renderers.filter((renderer) => renderer.activityType === activityType);
11311
+ const renderer = sameType.find((candidate) => candidate.agentId === agentId) ?? sameType.find((candidate) => candidate.agentId === void 0) ?? renderers.find((candidate) => candidate.activityType === WILDCARD);
11312
+ if (renderer === void 0) return null;
11313
+ const result = renderer.content["~standard"].validate(content);
11314
+ if (result instanceof Promise) return null;
11315
+ if (result.issues) return null;
11316
+ return {
11317
+ renderer,
11318
+ content: result.value
11319
+ };
11320
+ }
11321
+ /**
11322
+ * List the custom message renderers that apply to an agent, in the order to
11323
+ * try them.
11324
+ *
11325
+ * The list keeps renderers with no `agentId` and renderers for `agentId`.
11326
+ * Renderers for `agentId` come first. Inside each group, registration order
11327
+ * stays the same.
11328
+ *
11329
+ * The framework tries each renderer in this order and shows the first one
11330
+ * that draws something (a non-null result).
11331
+ *
11332
+ * @param renderers - Registered renderers in registration order.
11333
+ * @param agentId - The agent that owns the chat.
11334
+ * @returns A new array. Empty when no renderer applies.
11335
+ *
11336
+ * @example
11337
+ * ```ts
11338
+ * const candidates = ɵresolveCustomMessageRenderers(
11339
+ * core.renderCustomMessages,
11340
+ * agentId,
11341
+ * );
11342
+ * ```
11343
+ */
11344
+ function ɵresolveCustomMessageRenderers(renderers, agentId) {
11345
+ const scoped = renderers.filter((renderer) => renderer.agentId === agentId);
11346
+ const unscoped = renderers.filter((renderer) => renderer.agentId === void 0);
11347
+ return [...scoped, ...unscoped];
11348
+ }
11349
+
11350
+ //#endregion
11351
+ //#region src/chat/interrupt-types.ts
11352
+ /** Name of the legacy custom event agents emit to signal an interrupt. */
11353
+ const INTERRUPT_EVENT_NAME = "on_interrupt";
11354
+
11355
+ //#endregion
11356
+ //#region src/chat/tool-call-layout.ts
11357
+ function contentLength(content) {
11358
+ return typeof content === "string" ? content.length : JSON.stringify(content ?? "").length;
11359
+ }
11360
+ const entrySignature = ({ toolCall, toolMessage }) => [
11361
+ toolCall.id,
11362
+ toolCall.function.name,
11363
+ toolCall.function.arguments.length,
11364
+ toolMessage ? `${contentLength(toolMessage.content)}${toolMessage.error ? "!" : ""}` : "-"
11365
+ ].join(":");
11366
+ function signatureOf(segments) {
11367
+ return segments.map((segment) => segment.kind === "call" ? `c(${entrySignature(segment.call)})` : `g${segment.trailing ? "*" : ""}(${segment.calls.map(entrySignature).join(",")})`).join("|");
11368
+ }
11369
+ /**
11370
+ * Indexes tool results by the id of the call they answer.
11371
+ *
11372
+ * @param messages - The messages to search. Only `role: "tool"` messages count.
11373
+ */
11374
+ function getToolResults(messages) {
11375
+ const results = /* @__PURE__ */ new Map();
11376
+ for (const message of messages) if (message.role === "tool") results.set(message.toolCallId, message);
11377
+ return results;
11378
+ }
11379
+ /**
11380
+ * Lays out the tool calls of every assistant message in `rendered`.
11381
+ *
11382
+ * Calls drawn by a renderer that opted into grouping join the group that is
11383
+ * open. Anything else that shows between them closes it: assistant text, a
11384
+ * user, reasoning or activity message, or a call drawn by any other renderer.
11385
+ * A group belongs to the message where it starts, so later messages whose
11386
+ * calls joined it render no tool calls themselves.
11387
+ *
11388
+ * @param rendered - The messages as the chat renders them, in order.
11389
+ * @param all - Every message, for finding tool results (a transform may hide them).
11390
+ * @param renderers - The registered renderers, from `getToolCallRendererNames`.
11391
+ * @returns A map from assistant message id to its layout.
11392
+ *
11393
+ * @example
11394
+ * ```ts
11395
+ * const names = getToolCallRendererNames(core.renderToolCalls);
11396
+ * const layouts = getToolCallLayouts(renderedMessages, messages, names);
11397
+ * layouts.get(message.id)?.segments;
11398
+ * ```
11399
+ */
11400
+ function getToolCallLayouts(rendered, all, renderers) {
11401
+ const results = getToolResults(all);
11402
+ const layouts = /* @__PURE__ */ new Map();
11403
+ let open;
11404
+ for (const message of rendered) {
11405
+ if (message.role === "tool") continue;
11406
+ if (message.role !== "assistant") {
11407
+ open = void 0;
11408
+ continue;
11409
+ }
11410
+ if (typeof message.content === "string" && message.content.trim() !== "") open = void 0;
11411
+ const segments = [];
11412
+ layouts.set(message.id, segments);
11413
+ const toolCalls = /* @__PURE__ */ new Map();
11414
+ const messageToolCalls = message.toolCalls ?? [];
11415
+ for (const toolCall of messageToolCalls) toolCalls.set(toolCall.id, toolCall);
11416
+ const uniqueToolCalls = toolCalls.values();
11417
+ for (const toolCall of uniqueToolCalls) {
11418
+ const entry = {
11419
+ toolCall,
11420
+ toolMessage: results.get(toolCall.id)
11421
+ };
11422
+ const name = toolCall.function.name;
11423
+ const named = renderers.named.has(name);
11424
+ const isRendered = named || renderers.wildcard;
11425
+ const groups = named ? renderers.groupedNames.has(name) : renderers.wildcardGroups;
11426
+ if (!isRendered || !groups) {
11427
+ if (isRendered) open = void 0;
11428
+ segments.push({
11429
+ kind: "call",
11430
+ id: toolCall.id,
11431
+ call: entry,
11432
+ rendered: isRendered
11433
+ });
11434
+ } else if (open) open.calls.push(entry);
11435
+ else {
11436
+ open = {
11437
+ kind: "group",
11438
+ id: toolCall.id,
11439
+ calls: [entry],
11440
+ trailing: false
11441
+ };
11442
+ segments.push(open);
11443
+ }
11444
+ }
11445
+ }
11446
+ if (open) open.trailing = true;
11447
+ const layout = /* @__PURE__ */ new Map();
11448
+ for (const [id, segments] of layouts) layout.set(id, {
11449
+ segments,
11450
+ signature: signatureOf(segments)
11451
+ });
11452
+ return layout;
11453
+ }
11454
+ const TOOL_CALL_SLOT_PREFIX = "tool-call-";
11455
+ const WILDCARD_TOOL_CALL_SLOT = "tool-call";
11456
+ /**
11457
+ * Works out which tool calls have a renderer and which of those group, for
11458
+ * `getToolCallLayouts`.
11459
+ *
11460
+ * @param renderers - The registered renderers. A renderer named `"*"` is the
11461
+ * wildcard. `group: true` opts the renderer into grouping.
11462
+ * @param options - Slots, extra named tools, and a built-in wildcard card.
11463
+ * See `ToolCallRendererNamesOptions`.
11464
+ *
11465
+ * @example
11466
+ * ```ts
11467
+ * // React: only registered renderers.
11468
+ * getToolCallRendererNames(core.renderToolCalls);
11469
+ * // Vue: the view's slots count too.
11470
+ * getToolCallRendererNames(core.renderToolCalls, { slotNames: Object.keys(slots) });
11471
+ * // Angular: client and human-in-the-loop renderers, and the built-in card.
11472
+ * getToolCallRendererNames(appRenderers, {
11473
+ * extraNamed: [...clientNames, ...hitlNames],
11474
+ * builtInWildcard: { enabled: defaultToolRenderingEnabled, groups: true },
11475
+ * });
11476
+ * ```
11477
+ */
11478
+ function getToolCallRendererNames(renderers, options = {}) {
11479
+ const { slotNames = [], extraNamed = [], builtInWildcard } = options;
11480
+ const hasWildcardSlot = slotNames.includes(WILDCARD_TOOL_CALL_SLOT);
11481
+ const slotTools = slotNames.filter((name) => name.startsWith(TOOL_CALL_SLOT_PREFIX)).map((name) => name.slice(10));
11482
+ const named = renderers.filter((renderer) => renderer.name !== "*");
11483
+ const wildcards = renderers.filter((renderer) => renderer.name === "*");
11484
+ const hasAppWildcard = wildcards.length > 0;
11485
+ const isBuiltInEnabled = builtInWildcard?.enabled ?? false;
11486
+ const builtInGroups = isBuiltInEnabled && (builtInWildcard?.groups ?? false);
11487
+ const groupedNames = hasWildcardSlot ? [] : named.filter((renderer) => renderer.group && !slotTools.includes(renderer.name)).map((renderer) => renderer.name);
11488
+ const appWildcardGroups = wildcards.some((renderer) => renderer.group);
11489
+ return {
11490
+ named: new Set([
11491
+ ...named.map((renderer) => renderer.name),
11492
+ ...slotTools,
11493
+ ...extraNamed
11494
+ ]),
11495
+ groupedNames: new Set(groupedNames),
11496
+ wildcard: hasAppWildcard || hasWildcardSlot || isBuiltInEnabled,
11497
+ wildcardGroups: !hasWildcardSlot && (hasAppWildcard ? appWildcardGroups : builtInGroups)
11498
+ };
11499
+ }
11500
+ /** The turn key of a reply that no user message starts. */
11501
+ const FIRST_TURN_KEY = "start";
11502
+ /**
11503
+ * Finds the working phase of every reply in `rendered`: its messages up to the
11504
+ * last one that calls a tool. Text in there was narration. What follows is the
11505
+ * reply itself. Replies that called no tools are left out, except the latest,
11506
+ * which may be about to.
11507
+ *
11508
+ * @param rendered - The messages as the chat renders them, in order.
11509
+ * @param layouts - The layouts from `getToolCallLayouts` for the same messages.
11510
+ * @returns A map from turn key (see `TurnWork.key`) to the turn's work.
11511
+ */
11512
+ function getTurnWork(rendered, layouts) {
11513
+ const turns = /* @__PURE__ */ new Map();
11514
+ let start = 0;
11515
+ while (start < rendered.length) {
11516
+ let end = start;
11517
+ while (end < rendered.length && rendered[end].role !== "user") end++;
11518
+ const key = start > 0 ? rendered[start - 1].id : FIRST_TURN_KEY;
11519
+ const visible = rendered.slice(start, end).filter((message) => message.role !== "tool");
11520
+ const isLatest = end === rendered.length;
11521
+ const calls = [];
11522
+ for (const message of visible) {
11523
+ const segments = layouts.get(message.id)?.segments ?? [];
11524
+ for (const segment of segments) if (segment.kind === "group") calls.push(...segment.calls);
11525
+ else if (segment.rendered) calls.push(segment.call);
11526
+ }
11527
+ const shown = new Set(calls.map((entry) => entry.toolCall.id));
11528
+ let lastWork = -1;
11529
+ visible.forEach((message, index) => {
11530
+ if (message.role === "assistant" && message.toolCalls?.some((call) => shown.has(call.id))) lastWork = index;
11531
+ });
11532
+ const first = visible[0];
11533
+ if (first && (calls.length > 0 || isLatest)) {
11534
+ let lastAssistant = -1;
11535
+ visible.forEach((message, index) => {
11536
+ if (message.role === "assistant") lastAssistant = index;
11537
+ });
11538
+ const replyText = visible[lastAssistant]?.content;
11539
+ const endsWithWork = lastAssistant >= 0 && lastAssistant <= lastWork && typeof replyText === "string" && replyText.trim().length > 0;
11540
+ turns.set(key, {
11541
+ key,
11542
+ firstMessageId: first.id,
11543
+ workMessageIds: new Set(visible.slice(0, lastWork + 1).map((message) => message.id)),
11544
+ replyTextMessageId: endsWithWork ? visible[lastAssistant].id : void 0,
11545
+ calls,
11546
+ isLatest
11547
+ });
11548
+ }
11549
+ start = end + 1;
11550
+ }
11551
+ return turns;
11552
+ }
11553
+ /**
11554
+ * The key of the latest reply (see `TurnWork.key`): the id of the last user
11555
+ * message, or `"start"` when there is none.
11556
+ *
11557
+ * @param rendered - The messages as the chat renders them, in order.
11558
+ */
11559
+ function getLatestTurnKey(rendered) {
11560
+ for (let i = rendered.length - 1; i >= 0; i--) {
11561
+ const message = rendered[i];
11562
+ if (message.role === "user") return message.id;
11563
+ }
11564
+ return FIRST_TURN_KEY;
11565
+ }
11566
+ /**
11567
+ * Whether the agent is working on this reply now: it is the latest one and a
11568
+ * run is going.
11569
+ *
11570
+ * @param turnKey - The reply's `TurnWork.key`.
11571
+ * @param state - The run state and the latest turn key.
11572
+ */
11573
+ function isTurnWorking(turnKey, state) {
11574
+ return state.isRunning && turnKey === state.latestTurnKey;
11575
+ }
11576
+ /**
11577
+ * Whether a reply's work shows. It shows while the agent works on the reply
11578
+ * and folds once the reply is done, unless the user opened or closed it.
11579
+ *
11580
+ * @param turnKey - The reply's `TurnWork.key`.
11581
+ * @param state - The user's toggles, the run state, and the latest turn key.
11582
+ */
11583
+ function isTurnWorkOpen(turnKey, state) {
11584
+ return state.toggledTurns.get(turnKey) ?? isTurnWorking(turnKey, state);
11585
+ }
11586
+ /**
11587
+ * For each message in a reply's working phase, whether its work and its text
11588
+ * show. Text that ends the reply stays out of `workTextOpen` even when its
11589
+ * message also calls a tool, because it is the answer.
11590
+ *
11591
+ * @param turns - The turns from `getTurnWork`.
11592
+ * @param state - The user's toggles, the run state, and the latest turn key.
11593
+ * @returns The `workOpen` and `workTextOpen` maps of `ToolCallDisplayContextValue`.
11594
+ */
11595
+ function getWorkOpenState(turns, state) {
11596
+ const workOpen = /* @__PURE__ */ new Map();
11597
+ const workTextOpen = /* @__PURE__ */ new Map();
11598
+ for (const turn of turns) {
11599
+ const turnOpen = isTurnWorkOpen(turn.key, state);
11600
+ for (const id of turn.workMessageIds) {
11601
+ workOpen.set(id, turnOpen);
11602
+ if (id !== turn.replyTextMessageId) workTextOpen.set(id, turnOpen);
11603
+ }
11604
+ }
11605
+ return {
11606
+ workOpen,
11607
+ workTextOpen
11608
+ };
11609
+ }
11610
+ /**
11611
+ * Records run starts and ends in `workTimes`, for "Worked for 9s". Time spent
11612
+ * between runs (say, waiting for an approval) does not count. A reply is only
11613
+ * timed when this client saw it start from the user's message, so a restored
11614
+ * thread gets no entry. Calling it again with the same state changes nothing.
11615
+ *
11616
+ * @param workTimes - The times by turn key. This function updates it in place.
11617
+ * @param state - The run state now.
11618
+ * @param state.lastMessageRole - The role of the last rendered message.
11619
+ * @param state.now - The current time, in epoch ms.
11620
+ */
11621
+ function recordWorkTime(workTimes, state) {
11622
+ const { isRunning, latestTurnKey, lastMessageRole, now } = state;
11623
+ if (isRunning) {
11624
+ const times = workTimes.get(latestTurnKey);
11625
+ if (times) times.workingSince ??= now;
11626
+ else if (lastMessageRole === "user") workTimes.set(latestTurnKey, {
11627
+ elapsedMs: 0,
11628
+ workingSince: now
11629
+ });
11630
+ return;
11631
+ }
11632
+ const allTimes = workTimes.values();
11633
+ for (const times of allTimes) {
11634
+ if (times.workingSince === void 0) continue;
11635
+ times.elapsedMs += now - times.workingSince;
11636
+ times.workingSince = void 0;
11637
+ }
11638
+ }
11639
+ /**
11640
+ * The status of one call in a group. A call without a result is running only
11641
+ * while the group is active: once the run has moved on or ended, its result
11642
+ * is never coming.
11643
+ *
11644
+ * @param entry - The call and its result, if any.
11645
+ * @param active - The agent may still finish the group's calls.
11646
+ */
11647
+ function getToolCallRowStatus(entry, active) {
11648
+ const { toolMessage } = entry;
11649
+ let status;
11650
+ if (toolMessage) status = toolMessage.error ? "failed" : "done";
11651
+ else status = active ? "running" : "stopped";
11652
+ return status;
11653
+ }
11654
+ /**
11655
+ * The first non-empty string argument, with runs of whitespace collapsed to
11656
+ * one space. This is usually a command, path or query.
11657
+ *
11658
+ * @param parameters - The call's parsed arguments.
11659
+ * @returns The preview, or `undefined` when no argument is a non-empty string.
11660
+ */
11661
+ function getArgumentPreview(parameters) {
11662
+ if (!parameters || typeof parameters !== "object") return void 0;
11663
+ return Object.values(parameters).find((v) => typeof v === "string" && v.trim().length > 0)?.replace(/\s+/g, " ");
11664
+ }
11665
+ /**
11666
+ * `getArgumentPreview` for a call whose arguments may still be streaming in
11667
+ * as partial JSON.
11668
+ *
11669
+ * @param entry - The call.
11670
+ */
11671
+ function getToolCallPreview(entry) {
11672
+ return getArgumentPreview((0, _copilotkit_shared.partialJSONParse)(entry.toolCall.function.arguments));
11673
+ }
11674
+ /**
11675
+ * The names of the tools the calls used, in first-use order, with a count
11676
+ * for repeats: `"run_command ×2, read_file"`.
11677
+ *
11678
+ * @param calls - The calls to name.
11679
+ */
11680
+ function formatToolNames(calls) {
11681
+ const counts = /* @__PURE__ */ new Map();
11682
+ for (const { toolCall } of calls) {
11683
+ const name = toolCall.function.name;
11684
+ counts.set(name, (counts.get(name) ?? 0) + 1);
11685
+ }
11686
+ return [...counts].map(([name, count]) => count > 1 ? `${name} ×${count}` : name).join(", ");
11687
+ }
11688
+ /**
11689
+ * How many of the calls finished with an error.
11690
+ *
11691
+ * @param calls - The calls to count.
11692
+ */
11693
+ function countFailedToolCalls(calls) {
11694
+ return calls.filter((call) => call.toolMessage?.error).length;
11695
+ }
11696
+ /**
11697
+ * A count followed by the word that fits it: `"1 tool"`, `"3 tools"`.
11698
+ *
11699
+ * @param count - The number to show.
11700
+ * @param words - The word for exactly one (`one`) and for any other count (`other`).
11701
+ *
11702
+ * @example
11703
+ * ```ts
11704
+ * pluralize(3, { one: "tool", other: "tools" }); // "3 tools"
11705
+ * ```
11706
+ */
11707
+ function pluralize(count, words) {
11708
+ return `${count} ${count === 1 ? words.one : words.other}`;
11709
+ }
11710
+ /**
11711
+ * A tool call's arguments or result as display text. Strings pass through.
11712
+ * Other values are pretty-printed JSON. A value JSON cannot encode (say, a
11713
+ * circular reference) falls back to `String(value)`, then to
11714
+ * `"[unserializable]"`, so it never throws during a render.
11715
+ *
11716
+ * @param value - The arguments or the result.
11717
+ */
11718
+ function stringifyToolCallPayload(value) {
11719
+ if (typeof value === "string") return value;
11720
+ try {
11721
+ return JSON.stringify(value, null, 2);
11722
+ } catch (err) {
11723
+ console.warn("[CopilotKit] Failed to JSON.stringify tool-call payload; falling back to String():", err);
11724
+ try {
11725
+ return String(value);
11726
+ } catch {
11727
+ return "[unserializable]";
11728
+ }
11729
+ }
11730
+ }
11731
+ /**
11732
+ * How long a `"turn"` reply worked, as short text: `"45s"`, `"1m 5s"`, `"2m"`.
11733
+ * Used for the live timer and the final duration. Partial seconds round down,
11734
+ * and a negative time reads `"0s"`.
11735
+ *
11736
+ * @param ms - The time in milliseconds.
11737
+ */
11738
+ function formatWorkDuration(ms) {
11739
+ const seconds = Math.max(0, Math.floor(ms / 1e3));
11740
+ if (seconds < 60) return `${seconds}s`;
11741
+ const minutes = Math.floor(seconds / 60);
11742
+ const rest = seconds % 60;
11743
+ return rest ? `${minutes}m ${rest}s` : `${minutes}m`;
11744
+ }
11745
+ /**
11746
+ * Splits a reasoning time into the unit and counts the "Thought for ..."
11747
+ * header shows. See `ReasoningDuration` for the text each unit maps to.
11748
+ *
11749
+ * - Under 1 second: `fewSeconds`.
11750
+ * - Under 60 seconds: `seconds`, rounded to the nearest second.
11751
+ * - Whole minutes after rounding the seconds: `minutes`.
11752
+ * - Otherwise: `minutesSeconds`.
11753
+ *
11754
+ * @param seconds - The elapsed time in seconds. It may have a fraction.
11755
+ */
11756
+ function formatReasoningDuration(seconds) {
11757
+ if (seconds < 1) return { unit: "fewSeconds" };
11758
+ if (seconds < 60) return {
11759
+ unit: "seconds",
11760
+ seconds: Math.round(seconds)
11761
+ };
11762
+ const minutes = Math.floor(seconds / 60);
11763
+ const rest = Math.round(seconds % 60);
11764
+ if (rest === 0) return {
11765
+ unit: "minutes",
11766
+ minutes
11767
+ };
11768
+ return {
11769
+ unit: "minutesSeconds",
11770
+ minutes,
11771
+ seconds: rest
11772
+ };
11773
+ }
11774
+
11775
+ //#endregion
11776
+ //#region src/chat/messages.ts
11777
+ /**
11778
+ * Collapses tool calls that share an id, keeping first-seen order.
11779
+ *
11780
+ * AG-UI's TOOL_CALL_START handler appends to the parent message's `toolCalls`
11781
+ * without checking whether that id is already present. When a start event is
11782
+ * applied twice (the human-in-the-loop flow does this when the run syncs after
11783
+ * `respond()`), the message carries the same call twice. The second copy has
11784
+ * empty `arguments`, because a start event carries none. The args arrive later
11785
+ * as TOOL_CALL_ARGS deltas addressed to the first copy.
11786
+ *
11787
+ * Left alone, the same tool call renders twice: once populated and once blank.
11788
+ * The blank copy is the redundant one, so the copy that carries arguments wins,
11789
+ * whatever order the two arrive in.
11790
+ *
11791
+ * @param toolCalls - The tool calls of one assistant message.
11792
+ * @returns The same array when no id repeats, so memoized consumers keep a
11793
+ * stable reference. Otherwise a new array with one entry per id.
11794
+ */
11795
+ function dedupeToolCalls(toolCalls) {
11796
+ const byId = /* @__PURE__ */ new Map();
11797
+ for (const toolCall of toolCalls) {
11798
+ const existing = byId.get(toolCall.id);
11799
+ if (!existing) {
11800
+ byId.set(toolCall.id, toolCall);
11801
+ continue;
11802
+ }
11803
+ if (!existing.function?.arguments && Boolean(toolCall.function?.arguments)) byId.set(toolCall.id, toolCall);
11804
+ }
11805
+ return byId.size === toolCalls.length ? toolCalls : [...byId.values()];
11806
+ }
11807
+ /**
11808
+ * Merges two snapshots of the same assistant message.
11809
+ *
11810
+ * - Empty `content` means a streaming update cleared the field, so the earlier
11811
+ * non-empty content is kept.
11812
+ * - `toolCalls: undefined` means the later chunk had no tool-call activity, so
11813
+ * the earlier tool calls are kept. An explicit `[]` is kept as-is.
11814
+ * - Fields that only the earlier snapshot has are kept.
11815
+ */
11816
+ function mergeAssistantMessages(existing, message) {
11817
+ const content = message.content || existing.content;
11818
+ const toolCalls = message.toolCalls ?? existing.toolCalls;
11819
+ return {
11820
+ ...existing,
11821
+ ...message,
11822
+ content,
11823
+ toolCalls: toolCalls ? dedupeToolCalls(toolCalls) : toolCalls
11824
+ };
11825
+ }
11826
+ /**
11827
+ * Returns the assistant message with repeated tool-call ids collapsed. Returns
11828
+ * the same object when nothing collapsed.
11829
+ */
11830
+ function withDedupedToolCalls(message) {
11831
+ if (!message.toolCalls) return message;
11832
+ const toolCalls = dedupeToolCalls(message.toolCalls);
11833
+ return toolCalls === message.toolCalls ? message : {
11834
+ ...message,
11835
+ toolCalls
11836
+ };
11837
+ }
11838
+ /**
11839
+ * De-duplicates chat messages by id, for rendering.
11840
+ *
11841
+ * A message list from an agent can hold the same message id more than once
11842
+ * while it streams. This keeps one entry per id, at the position the id first
11843
+ * appears:
11844
+ *
11845
+ * - **Assistant messages** are merged. Later fields win, but empty `content`
11846
+ * falls back to earlier non-empty content, and `toolCalls: undefined` falls
11847
+ * back to earlier tool calls (an explicit `[]` is kept).
11848
+ * - **Tool calls** on an assistant message are de-duplicated by id, also
11849
+ * when the message itself is not repeated. The copy that has arguments
11850
+ * wins, and the first-seen order is kept.
11851
+ * - **Other roles** keep the last copy.
11852
+ *
11853
+ * @param messages - The agent's messages, in order.
11854
+ * @returns A new array. A message that needed no change is returned as the
11855
+ * same object.
11856
+ *
11857
+ * @example
11858
+ * ```ts
11859
+ * const visible = ɵdeduplicateMessages(agent.messages);
11860
+ * ```
11861
+ */
11862
+ function ɵdeduplicateMessages(messages) {
11863
+ const byId = /* @__PURE__ */ new Map();
11864
+ for (const message of messages) {
11865
+ if (message.role !== "assistant") {
11866
+ byId.set(message.id, message);
11867
+ continue;
11868
+ }
11869
+ const existing = byId.get(message.id);
11870
+ const merged = existing?.role === "assistant" ? mergeAssistantMessages(existing, message) : withDedupedToolCalls(message);
11871
+ byId.set(message.id, merged);
11872
+ }
11873
+ return [...byId.values()];
11874
+ }
11875
+ /**
11876
+ * Serializes object content for {@link ɵmessagesFingerprint}.
11877
+ *
11878
+ * `JSON.stringify` throws on a circular structure (and on a `BigInt`). The
11879
+ * fingerprint runs on every render, so a throw would take the chat down. A
11880
+ * value that cannot be serialized gets a constant key instead: it does not
11881
+ * trigger a change on its own, but every other part of the fingerprint still
11882
+ * does.
11883
+ */
11884
+ function objectContentKey(content) {
11885
+ try {
11886
+ return JSON.stringify(content) ?? "";
11887
+ } catch {
11888
+ return "[unserializable]";
11889
+ }
11890
+ }
11891
+ /**
11892
+ * Gives the part of the fingerprint that tracks a message's content:
11893
+ * - string content: its length, so streamed text changes it.
11894
+ * - array content: the part count, so an added attachment changes it. The
11895
+ * parts are not serialized, which keeps base64 uploads out of the key.
11896
+ * - object content (activity messages): its JSON, so a snapshot that replaces
11897
+ * the content under the same message id changes it.
11898
+ */
11899
+ function contentKey(content) {
11900
+ if (typeof content === "string" || Array.isArray(content)) return String(content.length);
11901
+ if (content !== null && typeof content === "object") return objectContentKey(content);
11902
+ return "0";
11903
+ }
11904
+ /**
11905
+ * Builds a string that changes whenever a render of the message list could
11906
+ * change. Use it as a cheap memo key in place of a deep comparison.
11907
+ *
11908
+ * The key covers, per message:
11909
+ * - the id and the role.
11910
+ * - the content: text length, part count, or the JSON of object content.
11911
+ * - the `toolCallId` of a tool message.
11912
+ * - each tool call's id and the length of its arguments, so streamed
11913
+ * arguments change the key.
11914
+ *
11915
+ * It never throws. Object content that cannot be serialized (for example a
11916
+ * circular tool result) gets a constant key.
11917
+ *
11918
+ * @param messages - The agent's messages, in order.
11919
+ * @returns The fingerprint string.
11920
+ *
11921
+ * @example
11922
+ * ```ts
11923
+ * const key = ɵmessagesFingerprint(agent.messages);
11924
+ * if (key !== previousKey) rerender();
11925
+ * ```
11926
+ */
11927
+ function ɵmessagesFingerprint(messages) {
11928
+ return messages.map((message) => {
11929
+ const toolCallId = "toolCallId" in message ? message.toolCallId : "";
11930
+ const toolCallsKey = ("toolCalls" in message && Array.isArray(message.toolCalls) ? message.toolCalls : []).map((tc) => `${tc.id}:${tc.function?.arguments?.length ?? 0}`).join(";");
11931
+ return `${message.id}:${message.role}:${contentKey(message.content)}:${toolCallId}:${toolCallsKey}`;
11932
+ }).join(",");
11933
+ }
11934
+
11935
+ //#endregion
11936
+ //#region src/chat/composer.ts
11937
+ /**
11938
+ * Get the state of the send/stop button in the chat input.
11939
+ *
11940
+ * @param input - The current state of the chat input.
11941
+ * @returns
11942
+ * - `isProcessing`: the agent runs and the input does not record audio.
11943
+ * - `canSend`: the text is not empty and nothing blocks a send.
11944
+ * - `action`: `"stop"` when the button stops the run, else `"send"`.
11945
+ * Use it for the icon, the label, and the click.
11946
+ * - `disabled`: `true` when a click does nothing.
11947
+ *
11948
+ * @example
11949
+ * ```ts
11950
+ * const button = ɵcomposerButtonState({
11951
+ * mode: "input",
11952
+ * isRunning: agent.isRunning,
11953
+ * value: text,
11954
+ * canSubmit: true,
11955
+ * canStop: true,
11956
+ * });
11957
+ * // On click:
11958
+ * if (button.action === "stop") stopRun();
11959
+ * else if (button.canSend) sendMessage(text.trim());
11960
+ * ```
11961
+ */
11962
+ function ɵcomposerButtonState(input) {
11963
+ const isProcessing = input.mode !== "transcribe" && input.isRunning;
11964
+ const isSendBlocked = input.disabled === true || input.attachmentsUploading === true;
11965
+ const canSend = input.canSubmit && !isSendBlocked && input.value.trim().length > 0;
11966
+ return {
11967
+ isProcessing,
11968
+ canSend,
11969
+ action: isProcessing && input.canStop ? "stop" : "send",
11970
+ disabled: isProcessing ? !input.canStop : !canSend
11971
+ };
11972
+ }
11973
+ /**
11974
+ * Decide what a key press in the chat input does.
11975
+ *
11976
+ * This handles Enter only. Keys for the slash-command menu stay in each
11977
+ * framework, and the framework handles them before it calls this function.
11978
+ *
11979
+ * Results:
11980
+ * - `"send"`: send the trimmed text.
11981
+ * - `"stop"`: stop the run. This happens for Enter in an empty input while
11982
+ * the agent runs. Text in the input always means send, not stop.
11983
+ * - `"newline"`: Shift+Enter. Let the browser add the line break.
11984
+ * - `"none"`: do nothing. Returned during IME composition, while the input
11985
+ * is disabled, for keys other than Enter, and for an Enter that has
11986
+ * nothing to send or stop.
11987
+ *
11988
+ * Call `preventDefault()` for every Enter without Shift that is not part of
11989
+ * IME composition, including when the result is `"none"`. This stops Enter
11990
+ * from adding a line break that the user cannot send.
11991
+ *
11992
+ * @param event - The keyboard event, or an object with the same fields.
11993
+ * @param input - The current state of the chat input.
11994
+ *
11995
+ * @example
11996
+ * ```ts
11997
+ * function onKeyDown(event: KeyboardEvent) {
11998
+ * if (event.isComposing || event.keyCode === 229) return;
11999
+ * // ...slash-command menu keys...
12000
+ * const result = ɵresolveComposerKey(event, composerInput);
12001
+ * if (event.key === "Enter" && !event.shiftKey) event.preventDefault();
12002
+ * if (result === "send") sendMessage(composerInput.value.trim());
12003
+ * if (result === "stop") stopRun();
12004
+ * }
12005
+ * ```
12006
+ */
12007
+ function ɵresolveComposerKey(event, input) {
12008
+ if (event.isComposing || event.keyCode === 229 || input.disabled === true || event.key !== "Enter") return "none";
12009
+ if (event.shiftKey) return "newline";
12010
+ const button = ɵcomposerButtonState(input);
12011
+ const isEmpty = input.value.trim().length === 0;
12012
+ if (button.isProcessing && isEmpty) return input.canStop ? "stop" : "none";
12013
+ return button.canSend ? "send" : "none";
12014
+ }
12015
+
12016
+ //#endregion
12017
+ //#region src/chat/transcription.ts
12018
+ /**
12019
+ * The error `ɵtranscribeAudio` throws. Read `error.info.code` to pick a
12020
+ * message for the user, or pass `error.info` to
12021
+ * `ɵtranscriptionErrorMessageKey`.
12022
+ */
12023
+ var TranscriptionError = class extends Error {
12024
+ info;
12025
+ constructor(info) {
12026
+ super(info.message);
12027
+ this.name = "TranscriptionError";
12028
+ this.info = info;
12029
+ }
12030
+ };
12031
+ /**
12032
+ * Send a recording to the CopilotKit runtime and get its text back.
12033
+ *
12034
+ * The request follows the transport set on the core:
12035
+ * - `"single"`: one JSON POST to `runtimeUrl`, with the audio as base64.
12036
+ * - any other transport: a multipart POST to `${runtimeUrl}/transcribe`.
12037
+ *
12038
+ * Headers are resolved on each call. The core's `credentials` are sent when
12039
+ * they are set, the same as for agent requests.
12040
+ *
12041
+ * @param core - The `CopilotKitCore` (or a framework subclass) to send through.
12042
+ * @param audioBlob - The recorded audio.
12043
+ * @param filename - The file name the runtime sees. Defaults to `"recording.webm"`.
12044
+ * @returns The transcription result, with the text in `result.text`.
12045
+ * @throws {TranscriptionError} When the runtime URL is not set, the request
12046
+ * fails, or the runtime returns an error. `error.info` has the code.
12047
+ *
12048
+ * @example
12049
+ * ```ts
12050
+ * try {
12051
+ * const { text } = await ɵtranscribeAudio(core, blob);
12052
+ * } catch (error) {
12053
+ * if (error instanceof TranscriptionError) {
12054
+ * const key = ɵtranscriptionErrorMessageKey(error.info);
12055
+ * showError(key ? labels[key] : error.info.message);
12056
+ * }
12057
+ * }
12058
+ * ```
12059
+ */
12060
+ async function ɵtranscribeAudio(core, audioBlob, filename = "recording.webm") {
12061
+ const { runtimeUrl, credentials } = core;
12062
+ if (!runtimeUrl) throw new TranscriptionError({
12063
+ code: _copilotkit_shared.TranscriptionErrorCode.INVALID_REQUEST,
12064
+ message: "Runtime URL is not configured",
12065
+ retryable: false
12066
+ });
12067
+ const resolvedHeaders = await core.resolveHeaders();
12068
+ const credentialsInit = credentials ? { credentials } : {};
12069
+ let response;
12070
+ try {
12071
+ response = core.runtimeTransport === "single" ? await fetch(runtimeUrl, {
12072
+ method: "POST",
12073
+ headers: {
12074
+ ...omitContentType(resolvedHeaders),
12075
+ "Content-Type": "application/json"
12076
+ },
12077
+ body: JSON.stringify({
12078
+ method: "transcribe",
12079
+ body: {
12080
+ audio: await blobToBase64(audioBlob),
12081
+ mimeType: audioBlob.type || "audio/webm",
12082
+ filename
12083
+ }
12084
+ }),
12085
+ ...credentialsInit
12086
+ }) : await fetch(`${runtimeUrl}/transcribe`, {
12087
+ method: "POST",
12088
+ headers: omitContentType(resolvedHeaders),
12089
+ body: toFormData(audioBlob, filename),
12090
+ ...credentialsInit
12091
+ });
12092
+ } catch (error) {
12093
+ throw new TranscriptionError({
12094
+ code: _copilotkit_shared.TranscriptionErrorCode.NETWORK_ERROR,
12095
+ message: error instanceof Error ? error.message : "Network request failed",
12096
+ retryable: true
12097
+ });
12098
+ }
12099
+ if (!response.ok) throw await toTranscriptionError(response);
12100
+ return await response.json();
12101
+ }
12102
+ /**
12103
+ * Pick the chat label to show the user for a transcription error.
12104
+ *
12105
+ * @param error - The `info` of a `TranscriptionError`.
12106
+ * @returns A key of the chat labels, or `null`. `null` means no label fits:
12107
+ * show `error.message` instead.
12108
+ *
12109
+ * @example
12110
+ * ```ts
12111
+ * const key = ɵtranscriptionErrorMessageKey(error.info);
12112
+ * const text = key ? labels[key] : error.info.message;
12113
+ * ```
12114
+ */
12115
+ function ɵtranscriptionErrorMessageKey(error) {
12116
+ switch (error.code) {
12117
+ case _copilotkit_shared.TranscriptionErrorCode.RATE_LIMITED: return "transcriptionErrorRateLimitedText";
12118
+ case _copilotkit_shared.TranscriptionErrorCode.AUTH_FAILED: return "transcriptionErrorAuthFailedText";
12119
+ case _copilotkit_shared.TranscriptionErrorCode.AUDIO_TOO_LONG: return "transcriptionErrorAudioTooLongText";
12120
+ case _copilotkit_shared.TranscriptionErrorCode.AUDIO_TOO_SHORT: return "transcriptionErrorAudioTooShortText";
12121
+ case _copilotkit_shared.TranscriptionErrorCode.INVALID_AUDIO_FORMAT: return "transcriptionErrorInvalidAudioFormatText";
12122
+ case _copilotkit_shared.TranscriptionErrorCode.SERVICE_NOT_CONFIGURED: return "transcriptionErrorServiceNotConfiguredText";
12123
+ case _copilotkit_shared.TranscriptionErrorCode.NETWORK_ERROR: return "transcriptionErrorNetworkText";
12124
+ default: return error.retryable ? "transcriptionErrorGenericText" : null;
12125
+ }
12126
+ }
12127
+ function toFormData(audioBlob, filename) {
12128
+ const formData = new FormData();
12129
+ formData.append("audio", audioBlob, filename);
12130
+ return formData;
12131
+ }
12132
+ function omitContentType(headers) {
12133
+ const entries = Object.entries(headers);
12134
+ return Object.fromEntries(entries.filter(([name]) => name.toLowerCase() !== "content-type"));
12135
+ }
12136
+ async function blobToBase64(blob) {
12137
+ const bytes = new Uint8Array(await blob.arrayBuffer());
12138
+ const chunkSize = 32768;
12139
+ let binary = "";
12140
+ for (let offset = 0; offset < bytes.length; offset += chunkSize) binary += String.fromCharCode(...bytes.subarray(offset, offset + chunkSize));
12141
+ return btoa(binary);
12142
+ }
12143
+ /** Build a typed error from a non-OK transcription response. */
12144
+ async function toTranscriptionError(response) {
12145
+ const retryable = response.status >= 500;
12146
+ let data;
12147
+ try {
12148
+ data = await response.json();
12149
+ } catch {
12150
+ return new TranscriptionError({
12151
+ code: _copilotkit_shared.TranscriptionErrorCode.PROVIDER_ERROR,
12152
+ message: `HTTP ${response.status}: ${response.statusText}`,
12153
+ retryable
12154
+ });
12155
+ }
12156
+ if (isTranscriptionErrorResponse(data)) return new TranscriptionError({
12157
+ code: data.error,
12158
+ message: data.message,
12159
+ retryable: data.retryable ?? false
12160
+ });
12161
+ const message = typeof data === "object" && data !== null && "message" in data ? String(data.message) : "Transcription failed";
12162
+ return new TranscriptionError({
12163
+ code: _copilotkit_shared.TranscriptionErrorCode.PROVIDER_ERROR,
12164
+ message,
12165
+ retryable
12166
+ });
12167
+ }
12168
+ function isTranscriptionErrorResponse(data) {
12169
+ return typeof data === "object" && data !== null && "error" in data && "message" in data && typeof data.error === "string" && typeof data.message === "string";
12170
+ }
12171
+
12172
+ //#endregion
12173
+ //#region src/chat/license.ts
12174
+ /**
12175
+ * Resolves the license context and the license banner from the runtime
12176
+ * license authority. React, Vue, and Angular call it with the values core
12177
+ * reports, then show the banner and provide the context.
12178
+ *
12179
+ * Rules:
12180
+ *
12181
+ * - A retryable entitlement failure that core is still retrying hides the
12182
+ * status, so no banner shows until the retry ends. A `valid` or `expiring`
12183
+ * legacy status stays in use during the retry.
12184
+ * - A terminal entitlement failure (not retryable, no `valid` or `expiring`
12185
+ * legacy status) keeps the reported status, but `checkFeature` returns
12186
+ * `false` and `getLimit` returns `null` for every feature.
12187
+ * - The `no_license` banner shows only when the status is `none` and no
12188
+ * public key is set.
12189
+ *
12190
+ * The banner text has no day count. No data source gives the days left.
12191
+ *
12192
+ * @param input - The runtime license values and the public key. See
12193
+ * {@link LicenseStateInput}.
12194
+ * @returns `context` for the license context, `warningStatus` (the status the
12195
+ * banner is based on, `undefined` while a retry runs), and `bannerType`
12196
+ * (`null` when no banner shows).
12197
+ *
12198
+ * @example
12199
+ * ```ts
12200
+ * const { context, bannerType } = ɵresolveLicenseState({
12201
+ * status: core.licenseStatus,
12202
+ * entitlements: core.runtimeEntitlements,
12203
+ * retryPending: core.runtimeEntitlementRetryPending,
12204
+ * publicKey,
12205
+ * });
12206
+ * ```
12207
+ */
12208
+ function ɵresolveLicenseState({ status, entitlements, retryPending, publicKey }) {
12209
+ const isRetryableFailure = entitlements?.status !== "ready" && entitlements?.error.retryable === true;
12210
+ const isNonReady = entitlements !== void 0 && entitlements.status !== "ready";
12211
+ const hasLegacyFallback = status === "valid" || status === "expiring";
12212
+ const isRetrying = isRetryableFailure && retryPending && !hasLegacyFallback;
12213
+ const isTerminalFailure = isNonReady && !isRetryableFailure && !hasLegacyFallback;
12214
+ const runtimeContext = (0, _copilotkit_shared.createLicenseContextValue)(isRetrying ? void 0 : status, entitlements);
12215
+ const context = isTerminalFailure ? {
12216
+ ...runtimeContext,
12217
+ checkFeature: () => false,
12218
+ getLimit: () => null
12219
+ } : runtimeContext;
12220
+ const warningStatus = isRetrying ? void 0 : context.status ?? void 0;
12221
+ return {
12222
+ context,
12223
+ warningStatus,
12224
+ bannerType: resolveLicenseBannerType(warningStatus, publicKey)
12225
+ };
12226
+ }
12227
+ function resolveLicenseBannerType(warningStatus, publicKey) {
12228
+ switch (warningStatus) {
12229
+ case "none": return publicKey ? null : "no_license";
12230
+ case "expired":
12231
+ case "invalid":
12232
+ case "expiring": return warningStatus;
12233
+ case "valid":
12234
+ case "unknown":
12235
+ case void 0: return null;
12236
+ }
12237
+ }
12238
+ /**
12239
+ * Resolves whether the threads drawer can load its thread list.
12240
+ *
12241
+ * - `licensed` is `true` when the status is `unknown` (an entitlement lookup
12242
+ * that did not recover, so the threads endpoint decides), or when the
12243
+ * status is `valid` or `expiring` and `checkFeature("threads")` is `true`.
12244
+ * - `licensePending` is `true` while the status is `null` (the runtime has
12245
+ * not reported yet). Show the loading state then, not the locked view.
12246
+ *
12247
+ * @param context - The license context from {@link ɵresolveLicenseState}.
12248
+ *
12249
+ * @example
12250
+ * ```ts
12251
+ * const { licensed, licensePending } = ɵresolveThreadsLicense(context);
12252
+ * ```
12253
+ */
12254
+ function ɵresolveThreadsLicense(context) {
12255
+ const { status } = context;
12256
+ return {
12257
+ licensed: status === "unknown" || (status === "valid" || status === "expiring") && context.checkFeature("threads"),
12258
+ licensePending: status === null
12259
+ };
12260
+ }
12261
+
12262
+ //#endregion
12263
+ //#region src/chat/icons.ts
12264
+ /*! @license
12265
+ * The icon data below is copied from Lucide v0.525.0 (https://lucide.dev).
12266
+ * The Lucide license follows. A copy is in LUCIDE-LICENSE.md next to this file.
12267
+ * This comment sits right above runtime code so the bundler keeps it in dist.
12268
+ *
12269
+ * ISC License
12270
+ *
12271
+ * 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.
12272
+ *
12273
+ * Permission to use, copy, modify, and/or distribute this software for any
12274
+ * purpose with or without fee is hereby granted, provided that the above
12275
+ * copyright notice and this permission notice appear in all copies.
12276
+ *
12277
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12278
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12279
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12280
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12281
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
12282
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
12283
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
12284
+ */
12285
+ function path(d) {
12286
+ return {
12287
+ tag: "path",
12288
+ attributes: { d }
12289
+ };
12290
+ }
12291
+ const icons = {
12292
+ ArrowUp: {
12293
+ name: "arrow-up",
12294
+ nodes: [path("m5 12 7-7 7 7"), path("M12 19V5")]
12295
+ },
12296
+ Check: {
12297
+ name: "check",
12298
+ nodes: [path("M20 6 9 17l-5-5")]
12299
+ },
12300
+ ChevronDown: {
12301
+ name: "chevron-down",
12302
+ nodes: [path("m6 9 6 6 6-6")]
12303
+ },
12304
+ ChevronLeft: {
12305
+ name: "chevron-left",
12306
+ nodes: [path("m15 18-6-6 6-6")]
12307
+ },
12308
+ ChevronRight: {
12309
+ name: "chevron-right",
12310
+ nodes: [path("m9 18 6-6-6-6")]
12311
+ },
12312
+ Circle: {
12313
+ name: "circle",
12314
+ nodes: [{
12315
+ tag: "circle",
12316
+ attributes: {
12317
+ cx: "12",
12318
+ cy: "12",
12319
+ r: "10"
12320
+ }
12321
+ }]
12322
+ },
12323
+ Copy: {
12324
+ name: "copy",
12325
+ nodes: [{
12326
+ tag: "rect",
12327
+ attributes: {
12328
+ width: "14",
12329
+ height: "14",
12330
+ x: "8",
12331
+ y: "8",
12332
+ rx: "2",
12333
+ ry: "2"
12334
+ }
12335
+ }, path("M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2")]
12336
+ },
12337
+ Edit: {
12338
+ name: "square-pen",
12339
+ 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")]
12340
+ },
12341
+ EyeOff: {
12342
+ name: "eye-off",
12343
+ nodes: [
12344
+ 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"),
12345
+ path("M14.084 14.158a3 3 0 0 1-4.242-4.242"),
12346
+ 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"),
12347
+ path("m2 2 20 20")
12348
+ ]
12349
+ },
12350
+ Loader2: {
12351
+ name: "loader-circle",
12352
+ nodes: [path("M21 12a9 9 0 1 1-6.219-8.56")]
12353
+ },
12354
+ MessageCircle: {
12355
+ name: "message-circle",
12356
+ nodes: [path("M7.9 20A9 9 0 1 0 4 16.1L2 22Z")]
12357
+ },
12358
+ Mic: {
12359
+ name: "mic",
12360
+ nodes: [
12361
+ path("M12 19v3"),
12362
+ path("M19 10v2a7 7 0 0 1-14 0v-2"),
12363
+ {
12364
+ tag: "rect",
12365
+ attributes: {
12366
+ x: "9",
12367
+ y: "2",
12368
+ width: "6",
12369
+ height: "13",
12370
+ rx: "3"
12371
+ }
12372
+ }
12373
+ ]
12374
+ },
12375
+ PanelLeftOpen: {
12376
+ name: "panel-left-open",
12377
+ nodes: [
12378
+ {
12379
+ tag: "rect",
12380
+ attributes: {
12381
+ width: "18",
12382
+ height: "18",
12383
+ x: "3",
12384
+ y: "3",
12385
+ rx: "2"
12386
+ }
12387
+ },
12388
+ path("M9 3v18"),
12389
+ path("m14 9 3 3-3 3")
12390
+ ]
12391
+ },
12392
+ Play: {
12393
+ name: "play",
12394
+ nodes: [{
12395
+ tag: "polygon",
12396
+ attributes: { points: "6 3 20 12 6 21 6 3" }
12397
+ }]
12398
+ },
12399
+ Plus: {
12400
+ name: "plus",
12401
+ nodes: [path("M5 12h14"), path("M12 5v14")]
12402
+ },
12403
+ RefreshCw: {
12404
+ name: "refresh-cw",
12405
+ nodes: [
12406
+ path("M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"),
12407
+ path("M21 3v5h-5"),
12408
+ path("M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"),
12409
+ path("M8 16H3v5")
12410
+ ]
12411
+ },
12412
+ Square: {
12413
+ name: "square",
12414
+ nodes: [{
12415
+ tag: "rect",
12416
+ attributes: {
12417
+ width: "18",
12418
+ height: "18",
12419
+ x: "3",
12420
+ y: "3",
12421
+ rx: "2"
12422
+ }
12423
+ }]
12424
+ },
12425
+ ThumbsDown: {
12426
+ name: "thumbs-down",
12427
+ 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")]
12428
+ },
12429
+ ThumbsUp: {
12430
+ name: "thumbs-up",
12431
+ 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")]
12432
+ },
12433
+ Upload: {
12434
+ name: "upload",
12435
+ nodes: [
12436
+ path("M12 3v12"),
12437
+ path("m17 8-5-5-5 5"),
12438
+ path("M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4")
12439
+ ]
12440
+ },
12441
+ Volume2: {
12442
+ name: "volume-2",
12443
+ nodes: [
12444
+ 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"),
12445
+ path("M16 9a5 5 0 0 1 0 6"),
12446
+ path("M19.364 18.364a9 9 0 0 0 0-12.728")
12447
+ ]
12448
+ },
12449
+ Wrench: {
12450
+ name: "wrench",
12451
+ 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")]
12452
+ },
12453
+ X: {
12454
+ name: "x",
12455
+ nodes: [path("M18 6 6 18"), path("m6 6 12 12")]
12456
+ }
12457
+ };
12458
+ /**
12459
+ * Internal. The SVG data for every icon the chat components draw.
12460
+ *
12461
+ * Each framework's `CopilotIcon` component reads an entry and draws it:
12462
+ *
12463
+ * ```ts
12464
+ * const { name, nodes } = ɵcopilotIcons.ArrowUp;
12465
+ * // <svg {...ɵcopilotIconSvgAttributes} class="lucide lucide-arrow-up">
12466
+ * // one child element per node: <{node.tag} {...node.attributes} />
12467
+ * // </svg>
12468
+ * ```
12469
+ */
12470
+ const ɵcopilotIcons = icons;
12471
+ /**
12472
+ * Internal. The attributes to put on the `<svg>` of every chat icon.
12473
+ *
12474
+ * These are Lucide's default attributes, so a drawn icon matches the Lucide
12475
+ * icon. Set `width` and `height` to change the size.
12476
+ */
12477
+ const ɵcopilotIconSvgAttributes = {
12478
+ xmlns: "http://www.w3.org/2000/svg",
12479
+ width: "24",
12480
+ height: "24",
12481
+ viewBox: "0 0 24 24",
12482
+ fill: "none",
12483
+ stroke: "currentColor",
12484
+ "stroke-width": "2",
12485
+ "stroke-linecap": "round",
12486
+ "stroke-linejoin": "round"
12487
+ };
12488
+
12489
+ //#endregion
12490
+ //#region src/open-generative-ui/content.ts
12491
+ /**
12492
+ * Open Generative UI content: the activity the agent streams while it
12493
+ * generates a sandboxed UI, and the rules for when a new snapshot must reach
12494
+ * the sandbox at once.
12495
+ */
12496
+ /** The activity type of Open Generative UI messages. */
12497
+ const OPEN_GENERATIVE_UI_ACTIVITY_TYPE = "open-generative-ui";
12498
+ /** The name of the frontend tool the agent calls to generate a sandboxed UI. */
12499
+ const GENERATE_SANDBOXED_UI_TOOL_NAME = "generateSandboxedUi";
12500
+ /** The design guidance sent to the agent when no `designSkill` is set. */
12501
+ const DEFAULT_OPEN_GENERATIVE_UI_DESIGN_SKILL = `When generating UI with generateSandboxedUi, follow these design principles inspired by shadcn/ui:
12502
+
12503
+ - Use a minimal, flat aesthetic. Avoid drop shadows and gradients — rely on subtle borders (1px solid, light gray like #e5e7eb) to define surfaces.
12504
+ - Neutral base palette: white backgrounds, zinc/slate gray text (#09090b for headings, #71717a for secondary text). One accent color for interactive elements.
12505
+ - Use system font stacks (system-ui, -apple-system, sans-serif) at readable sizes (14px body, 600 weight for headings). Tight line-heights.
12506
+ - Small, consistent border-radius (6–8px). Cards and containers use border, not shadow, for separation.
12507
+ - Buttons: solid fill for primary (dark bg, white text), outline for secondary (border + transparent bg). Subtle hover state (slight opacity or background shift).
12508
+ - Use CSS Grid or Flexbox for layout. Ensure the UI looks good at any width.
12509
+ - Minimal transitions (150ms) for hover/focus states only. No decorative animations.
12510
+ - Keep the UI focused and dense — avoid excessive padding. Use compact spacing (8–12px gaps, 10–14px padding in controls).`;
12511
+ /** `true` when the content has HTML that a preview or final sandbox shows. */
12512
+ function hasRenderableContent(content) {
12513
+ if (!content) return false;
12514
+ const hasHtml = !!content.html?.join("").trim();
12515
+ const hasFinalHtml = content.htmlComplete && hasHtml;
12516
+ const hasPreviewHtml = content.cssComplete && !content.htmlComplete && hasHtml;
12517
+ return !!hasFinalHtml || !!hasPreviewHtml;
12518
+ }
12519
+ /**
12520
+ * `true` when `next` must replace `previous` at once instead of waiting for
12521
+ * the throttle window: the UI restarts, a stage completes, or new JavaScript
12522
+ * arrives.
12523
+ */
12524
+ function shouldFlushImmediately(previous, next) {
12525
+ if (hasRenderableContent(previous) && !hasRenderableContent(next)) return true;
12526
+ if (next.cssComplete && !previous?.cssComplete) return true;
12527
+ if (next.htmlComplete) return true;
12528
+ if (next.generating === false) return true;
12529
+ if (next.jsFunctions && !previous?.jsFunctions) return true;
12530
+ if ((next.jsExpressions?.length ?? 0) > (previous?.jsExpressions?.length ?? 0)) return true;
12531
+ if (next.html?.length && !previous?.html?.length) return true;
12532
+ return false;
12533
+ }
12534
+
12535
+ //#endregion
12536
+ //#region src/open-generative-ui/html.ts
12537
+ /**
12538
+ * Pure string helpers that turn streamed HTML into sandbox content.
12539
+ * No DOM access.
12540
+ */
12541
+ /**
12542
+ * Extracts all complete `<style>` blocks from the raw HTML.
12543
+ * Returns the concatenated style tags, suitable for injection into `<head>`.
12544
+ */
12545
+ function extractCompleteStyles(html) {
12546
+ const matches = html.match(/<style\b[^>]*>[\s\S]*?<\/style>/gi);
12547
+ return matches ? matches.join("") : "";
12548
+ }
12549
+ /**
12550
+ * Processes raw accumulated HTML for safe preview via innerHTML injection.
12551
+ *
12552
+ * Pipeline (order matters):
12553
+ * 1. Strip incomplete tag at end
12554
+ * 2. Strip complete <style>, <script>, and <head> blocks
12555
+ * 3. Strip incomplete <style>/<script>/<head> blocks
12556
+ * 4. Strip incomplete HTML entities
12557
+ * 5. Extract body content (or use full string if no <body>)
12558
+ */
12559
+ function processPartialHtml(html) {
12560
+ let result = html;
12561
+ result = result.replace(/<[^>]*$/, "");
12562
+ result = result.replace(/<(style|script|head)\b[^>]*>[\s\S]*?<\/\1>/gi, "");
12563
+ result = result.replace(/<(style|script|head)\b[^>]*>[\s\S]*$/gi, "");
12564
+ result = result.replace(/&[a-zA-Z0-9#]*$/, "");
12565
+ const bodyMatch = result.match(/<body[^>]*>([\s\S]*)/i);
12566
+ if (bodyMatch) {
12567
+ result = bodyMatch[1];
12568
+ result = result.replace(/<\/body>[\s\S]*/i, "");
12569
+ }
12570
+ return result;
12571
+ }
12572
+ /** Builds the final sandbox document: the HTML with the CSS in its `<head>`. */
12573
+ function buildFinalFrameContent(html, css) {
12574
+ const withCss = css ? injectCssIntoHtml(html, css) : html;
12575
+ return /<head[\s>]/i.test(withCss) ? withCss : `<head></head>${withCss}`;
12576
+ }
12577
+ function injectCssIntoHtml(html, css) {
12578
+ const headCloseIdx = html.indexOf("</head>");
12579
+ if (headCloseIdx !== -1) return html.slice(0, headCloseIdx) + `<style>${css}</style>` + html.slice(headCloseIdx);
12580
+ return `<head><style>${css}</style></head>${html}`;
12581
+ }
12582
+
12583
+ //#endregion
12584
+ //#region src/open-generative-ui/websandbox.ts
12585
+ /**
12586
+ * Imports `@jetbrains/websandbox` on demand. The import is dynamic because
12587
+ * the package touches `self` when it loads, which breaks server rendering.
12588
+ */
12589
+ const loadWebsandbox = async () => {
12590
+ const defaultExport = (await import("@jetbrains/websandbox")).default;
12591
+ return "default" in defaultExport ? defaultExport.default : defaultExport;
12592
+ };
12593
+
12594
+ //#endregion
12595
+ //#region src/open-generative-ui/controller.ts
12596
+ /** Non-immediate content updates reach the sandbox at most this often. */
12597
+ const OPEN_GENERATIVE_UI_THROTTLE_MS = 1e3;
12598
+ const DEFAULT_HEIGHT = 200;
12599
+ const HIDE_SCROLLBARS = `
12600
+ var s = document.createElement('style');
12601
+ s.textContent = 'html, body { overflow: hidden !important; }';
12602
+ document.head.appendChild(s);
12603
+ `;
12604
+ const HIDE_SCROLLBARS_STYLE = "<style>html, body { overflow: hidden !important; }</style>";
12605
+ const MEASURE_HEIGHT = `
12606
+ (function() {
12607
+ var s = document.createElement('style');
12608
+ s.textContent = 'body { height: auto !important; min-height: 0 !important; }';
12609
+ document.head.appendChild(s);
12610
+ var h = document.body.scrollHeight;
12611
+ var cs = getComputedStyle(document.body);
12612
+ h += parseFloat(cs.marginTop) || 0;
12613
+ h += parseFloat(cs.marginBottom) || 0;
12614
+ s.remove();
12615
+ parent.postMessage({ type: "__ck_resize", height: Math.ceil(h) }, "*");
12616
+ })();
12617
+ `;
12618
+ function deriveContent(content) {
12619
+ const html = content.html?.join("") || void 0;
12620
+ const css = content.cssComplete ? content.css : void 0;
12621
+ if (content.htmlComplete) return {
12622
+ fullHtml: html,
12623
+ css,
12624
+ previewStyles: ""
12625
+ };
12626
+ const previewBody = html && content.cssComplete ? processPartialHtml(html) : void 0;
12627
+ return {
12628
+ css,
12629
+ previewBody: previewBody?.trim() ? previewBody : void 0,
12630
+ previewStyles: html ? extractCompleteStyles(html) : ""
12631
+ };
12632
+ }
12633
+ function prepareIframe(iframe, testId) {
12634
+ iframe.setAttribute("data-testid", testId);
12635
+ iframe.style.width = "100%";
12636
+ iframe.style.height = "100%";
12637
+ iframe.style.border = "none";
12638
+ iframe.style.backgroundColor = "transparent";
12639
+ }
12640
+ function logLoadError(error) {
12641
+ console.error("[OpenGenerativeUI] Failed to load sandbox module:", error);
12642
+ }
12643
+ function sameFunctions(a, b) {
12644
+ return a.length === b.length && a.every((fn, i) => fn.name === b[i].name && fn.handler === b[i].handler);
12645
+ }
12646
+ /**
12647
+ * Runs Open Generative UI content in websandbox iframes inside a host element.
12648
+ *
12649
+ * Give it content snapshots with `setContent()` and a host element with
12650
+ * `setHost()`. It throttles the snapshots, streams a preview while HTML
12651
+ * arrives, swaps in the final sandbox once HTML is complete, runs
12652
+ * `jsFunctions` and `jsExpressions` in it once each, and measures the final
12653
+ * height. Frameworks render the container from `getState()` and re-render
12654
+ * when `subscribe()` notifies.
12655
+ *
12656
+ * @example
12657
+ * ```ts
12658
+ * const controller = new ɵOpenGenerativeUIController();
12659
+ * controller.subscribe(() => render(controller.getState()));
12660
+ * controller.setContent(content);
12661
+ * controller.setHost(containerElement);
12662
+ * // On unmount:
12663
+ * controller.destroy();
12664
+ * ```
12665
+ */
12666
+ var OpenGenerativeUIController = class {
12667
+ #load;
12668
+ #listeners = /* @__PURE__ */ new Set();
12669
+ #content;
12670
+ #latest;
12671
+ #derived = { previewStyles: "" };
12672
+ #timer;
12673
+ #host = null;
12674
+ #functions = [];
12675
+ #localApi = {};
12676
+ #preview;
12677
+ #final;
12678
+ #measuredHeight;
12679
+ #state = {
12680
+ phase: "placeholder",
12681
+ generating: true,
12682
+ height: DEFAULT_HEIGHT
12683
+ };
12684
+ constructor(options = {}) {
12685
+ this.#load = options.loadWebsandbox ?? loadWebsandbox;
12686
+ }
12687
+ /** The current state. The same object until something changes. */
12688
+ getState = () => this.#state;
12689
+ /** Calls `listener` when the state changes. Returns the unsubscribe function. */
12690
+ subscribe = (listener) => {
12691
+ this.#listeners.add(listener);
12692
+ return () => {
12693
+ this.#listeners.delete(listener);
12694
+ };
12695
+ };
12696
+ /**
12697
+ * Sets the latest content snapshot. The first snapshot and snapshots that
12698
+ * finish a stage apply at once; others apply at most once per second.
12699
+ */
12700
+ setContent(content) {
12701
+ this.#latest = content;
12702
+ if (this.#content === void 0 || shouldFlushImmediately(this.#content, content)) {
12703
+ this.#clearTimer();
12704
+ this.#commit(content);
12705
+ return;
12706
+ }
12707
+ if (content === this.#content || this.#timer !== void 0) return;
12708
+ this.#timer = setTimeout(() => {
12709
+ this.#timer = void 0;
12710
+ if (this.#latest) this.#commit(this.#latest);
12711
+ }, OPEN_GENERATIVE_UI_THROTTLE_MS);
12712
+ }
12713
+ /** Sets the element the sandbox iframes go into. `null` removes them. */
12714
+ setHost(host) {
12715
+ if (host === this.#host) return;
12716
+ this.#destroyPreview();
12717
+ this.#destroyFinal();
12718
+ this.#host = host;
12719
+ this.#reconcile();
12720
+ }
12721
+ /**
12722
+ * Sets the host functions sandboxed code can call. A change recreates the
12723
+ * final sandbox.
12724
+ */
12725
+ setSandboxFunctions(functions) {
12726
+ if (sameFunctions(functions, this.#functions)) return;
12727
+ this.#functions = functions;
12728
+ const localApi = {};
12729
+ for (const fn of functions) localApi[fn.name] = fn.handler;
12730
+ this.#localApi = localApi;
12731
+ this.#reconcile();
12732
+ }
12733
+ /**
12734
+ * Removes the sandboxes and stops pending work. A later `setHost()`
12735
+ * starts again from the current content.
12736
+ */
12737
+ destroy() {
12738
+ this.#clearTimer();
12739
+ this.#destroyPreview();
12740
+ this.#destroyFinal();
12741
+ this.#host = null;
12742
+ }
12743
+ #commit(content) {
12744
+ if (content === this.#content) return;
12745
+ this.#content = content;
12746
+ this.#derived = deriveContent(content);
12747
+ this.#reconcile();
12748
+ }
12749
+ #reconcile() {
12750
+ const host = this.#host;
12751
+ const content = this.#content;
12752
+ const derived = this.#derived;
12753
+ if (host && content) if (derived.fullHtml) {
12754
+ this.#destroyPreview();
12755
+ const frameContent = buildFinalFrameContent(derived.fullHtml, derived.css);
12756
+ let final = this.#final;
12757
+ if (final?.frameContent !== frameContent || final.localApi !== this.#localApi) {
12758
+ this.#destroyFinal();
12759
+ final = this.#final = this.#createFinal(host, frameContent);
12760
+ }
12761
+ this.#runScripts(final, content);
12762
+ } else {
12763
+ this.#destroyFinal();
12764
+ if (derived.previewBody) {
12765
+ this.#preview ??= this.#createPreview(host);
12766
+ this.#writePreview();
12767
+ } else this.#destroyPreview();
12768
+ }
12769
+ this.#updateState();
12770
+ }
12771
+ #createPreview(host) {
12772
+ const slot = {
12773
+ ready: false,
12774
+ cancelled: false
12775
+ };
12776
+ this.#load().then((Websandbox) => {
12777
+ if (slot.cancelled) return;
12778
+ const sandbox = Websandbox.create({}, {
12779
+ frameContainer: host,
12780
+ frameContent: "<head></head><body></body>",
12781
+ allowAdditionalAttributes: ""
12782
+ });
12783
+ slot.sandbox = sandbox;
12784
+ prepareIframe(sandbox.iframe, "open-generative-ui-preview-sandbox");
12785
+ sandbox.promise.then(() => {
12786
+ if (slot.cancelled) return;
12787
+ slot.ready = true;
12788
+ this.#writePreview();
12789
+ });
12790
+ }).catch(logLoadError);
12791
+ return slot;
12792
+ }
12793
+ #writePreview() {
12794
+ const slot = this.#preview;
12795
+ if (!slot?.sandbox || !slot.ready) return;
12796
+ const { css, previewStyles, previewBody } = this.#derived;
12797
+ const head = HIDE_SCROLLBARS_STYLE + (css ? `<style>${css}</style>` : "") + previewStyles;
12798
+ if (head !== slot.head) {
12799
+ slot.head = head;
12800
+ slot.sandbox.run(`document.head.innerHTML = ${JSON.stringify(head)}`);
12801
+ }
12802
+ if (previewBody && previewBody !== slot.body) {
12803
+ slot.body = previewBody;
12804
+ slot.sandbox.run(`document.body.innerHTML = ${JSON.stringify(previewBody)}`);
12805
+ }
12806
+ }
12807
+ #createFinal(host, frameContent) {
12808
+ const slot = {
12809
+ frameContent,
12810
+ localApi: this.#localApi,
12811
+ ready: false,
12812
+ cancelled: false,
12813
+ queue: [],
12814
+ jsFunctionsInjected: false,
12815
+ executedExpressions: 0,
12816
+ heightRequested: false
12817
+ };
12818
+ this.#load().then((Websandbox) => {
12819
+ if (slot.cancelled) return;
12820
+ const sandbox = Websandbox.create(slot.localApi, {
12821
+ frameContainer: host,
12822
+ frameContent,
12823
+ allowAdditionalAttributes: ""
12824
+ });
12825
+ slot.sandbox = sandbox;
12826
+ prepareIframe(sandbox.iframe, "open-generative-ui-final-sandbox");
12827
+ sandbox.promise.then(() => {
12828
+ if (slot.cancelled) return;
12829
+ slot.ready = true;
12830
+ sandbox.run(HIDE_SCROLLBARS);
12831
+ const queue = slot.queue;
12832
+ slot.queue = [];
12833
+ for (const code of queue) sandbox.run(code);
12834
+ });
12835
+ }).catch(logLoadError);
12836
+ return slot;
12837
+ }
12838
+ /** Runs new `jsFunctions`, new `jsExpressions`, and the height measurement. */
12839
+ #runScripts(slot, content) {
12840
+ if (content.jsFunctions && !slot.jsFunctionsInjected) {
12841
+ slot.jsFunctionsInjected = true;
12842
+ this.#runOrQueue(slot, content.jsFunctions);
12843
+ }
12844
+ const expressions = content.jsExpressions ?? [];
12845
+ if (expressions.length > slot.executedExpressions) {
12846
+ const newExpressions = expressions.slice(slot.executedExpressions);
12847
+ slot.executedExpressions = expressions.length;
12848
+ const sandbox = slot.sandbox;
12849
+ if (slot.ready && sandbox) (async () => {
12850
+ for (const expression of newExpressions) await sandbox.run(expression);
12851
+ })();
12852
+ else slot.queue.push(...newExpressions);
12853
+ }
12854
+ if (content.generating === false && !slot.heightRequested) {
12855
+ slot.heightRequested = true;
12856
+ this.#listenForHeight(slot);
12857
+ this.#runOrQueue(slot, MEASURE_HEIGHT);
12858
+ }
12859
+ }
12860
+ #runOrQueue(slot, code) {
12861
+ if (slot.ready && slot.sandbox) slot.sandbox.run(code);
12862
+ else slot.queue.push(code);
12863
+ }
12864
+ #listenForHeight(slot) {
12865
+ if (typeof window === "undefined") return;
12866
+ const onMessage = (event) => {
12867
+ const data = event.data;
12868
+ if (!slot.sandbox || event.source !== slot.sandbox.iframe.contentWindow || data?.type !== "__ck_resize" || typeof data.height !== "number") return;
12869
+ slot.stopHeightListener?.();
12870
+ this.#measuredHeight = data.height;
12871
+ this.#updateState();
12872
+ };
12873
+ window.addEventListener("message", onMessage);
12874
+ slot.stopHeightListener = () => {
12875
+ window.removeEventListener("message", onMessage);
12876
+ slot.stopHeightListener = void 0;
12877
+ };
12878
+ }
12879
+ #destroyPreview() {
12880
+ const slot = this.#preview;
12881
+ if (!slot) return;
12882
+ slot.cancelled = true;
12883
+ slot.sandbox?.destroy();
12884
+ this.#preview = void 0;
12885
+ }
12886
+ #destroyFinal() {
12887
+ const slot = this.#final;
12888
+ if (!slot) return;
12889
+ slot.cancelled = true;
12890
+ slot.stopHeightListener?.();
12891
+ slot.sandbox?.destroy();
12892
+ this.#final = void 0;
12893
+ this.#measuredHeight = void 0;
12894
+ }
12895
+ #clearTimer() {
12896
+ if (this.#timer === void 0) return;
12897
+ clearTimeout(this.#timer);
12898
+ this.#timer = void 0;
12899
+ }
12900
+ #updateState() {
12901
+ const content = this.#content ?? {};
12902
+ const derived = this.#derived;
12903
+ const next = {
12904
+ phase: derived.fullHtml ? "final" : derived.previewBody ? "preview" : "placeholder",
12905
+ generating: content.generating !== false,
12906
+ height: this.#measuredHeight ?? content.initialHeight ?? DEFAULT_HEIGHT
12907
+ };
12908
+ const current = this.#state;
12909
+ if (next.phase === current.phase && next.generating === current.generating && next.height === current.height) return;
12910
+ this.#state = next;
12911
+ for (const listener of this.#listeners) listener();
12912
+ }
12913
+ };
12914
+
10774
12915
  //#endregion
10775
12916
  exports.A2UI_FENCE_LANGUAGE = A2UI_FENCE_LANGUAGE;
10776
12917
  exports.AgentRegistry = AgentRegistry;
10777
12918
  exports.AgentThreadLockedError = AgentThreadLockedError;
10778
12919
  exports.ContextStore = ContextStore;
12920
+ exports.CopilotChatDefaultLabels = CopilotChatDefaultLabels;
10779
12921
  exports.CopilotKitCore = CopilotKitCore;
10780
12922
  exports.CopilotKitCoreErrorCode = CopilotKitCoreErrorCode;
10781
12923
  exports.CopilotKitCoreRuntimeConnectionStatus = CopilotKitCoreRuntimeConnectionStatus;
10782
12924
  exports.CopilotKitHeaderResolutionError = CopilotKitHeaderResolutionError;
12925
+ exports.DEFAULT_OPEN_GENERATIVE_UI_DESIGN_SKILL = DEFAULT_OPEN_GENERATIVE_UI_DESIGN_SKILL;
12926
+ exports.GENERATE_SANDBOXED_UI_TOOL_NAME = GENERATE_SANDBOXED_UI_TOOL_NAME;
10783
12927
  exports.INSPECTOR_THREAD_BRIDGE_PLUGIN_ID = INSPECTOR_THREAD_BRIDGE_PLUGIN_ID;
12928
+ exports.INTERRUPT_EVENT_NAME = INTERRUPT_EVENT_NAME;
10784
12929
  exports.IntelligenceAgent = IntelligenceAgent;
10785
12930
  exports.MEMORY_ERROR_REGISTRY = MEMORY_ERROR_REGISTRY;
10786
12931
  exports.MemoryError = MemoryError;
12932
+ exports.OPEN_GENERATIVE_UI_ACTIVITY_TYPE = OPEN_GENERATIVE_UI_ACTIVITY_TYPE;
10787
12933
  exports.ProxiedCopilotRuntimeAgent = ProxiedCopilotRuntimeAgent;
10788
12934
  exports.RunHandler = RunHandler;
10789
12935
  exports.StateManager = StateManager;
10790
12936
  exports.SuggestionEngine = SuggestionEngine;
10791
12937
  exports.ToolCallStatus = ToolCallStatus;
12938
+ exports.TranscriptionError = TranscriptionError;
12939
+ exports.TranscriptionErrorCode = _copilotkit_shared.TranscriptionErrorCode;
10792
12940
  exports.WebMCPRegistry = WebMCPRegistry;
10793
12941
  exports.classifySurfaceCards = classifySurfaceCards;
10794
12942
  exports.completePartialMarkdown = completePartialMarkdown;
@@ -10819,7 +12967,6 @@ exports.onInspectorActiveThread = onInspectorActiveThread;
10819
12967
  exports.onInspectorStopViewing = onInspectorStopViewing;
10820
12968
  exports.onInspectorViewThread = onInspectorViewThread;
10821
12969
  exports.onInspectorViewThreadResult = onInspectorViewThreadResult;
10822
- exports.parseMarkdown = parseMarkdown;
10823
12970
  exports.parseToolArguments = parseToolArguments;
10824
12971
  exports.prepareSurfaceOperations = prepareSurfaceOperations;
10825
12972
  exports.props = props;
@@ -10829,28 +12976,62 @@ exports.splitA2UIMarkdown = splitA2UIMarkdown;
10829
12976
  exports.ɵCOPILOTKIT_FEATURES = ɵCOPILOTKIT_FEATURES;
10830
12977
  exports.ɵInterruptState = ɵInterruptState;
10831
12978
  exports.ɵMAX_SOCKET_RETRIES = ɵMAX_SOCKET_RETRIES;
12979
+ exports.ɵOpenGenerativeUIController = OpenGenerativeUIController;
10832
12980
  exports.ɵRUNTIME_PROBE_TIMEOUT_MS = ɵRUNTIME_PROBE_TIMEOUT_MS;
10833
12981
  exports.ɵTHREAD_REQUEST_TIMEOUT_MS = ɵTHREAD_REQUEST_TIMEOUT_MS;
10834
12982
  exports.ɵclearAgentInterruptState = ɵclearAgentInterruptState;
12983
+ exports.ɵcomposerButtonState = ɵcomposerButtonState;
12984
+ exports.ɵcopilotIconSvgAttributes = ɵcopilotIconSvgAttributes;
12985
+ exports.ɵcopilotIcons = ɵcopilotIcons;
12986
+ exports.ɵcountFailedToolCalls = countFailedToolCalls;
10835
12987
  exports.ɵcreateMemoryStore = createMemoryStore;
10836
12988
  exports.ɵcreateThreadSelectors = ɵcreateThreadSelectors;
10837
12989
  exports.ɵcreateThreadStore = createThreadStore;
12990
+ exports.ɵdeduplicateMessages = ɵdeduplicateMessages;
12991
+ exports.ɵextractCompleteStyles = extractCompleteStyles;
12992
+ exports.ɵformatCountLabel = ɵformatCountLabel;
12993
+ exports.ɵformatLabel = ɵformatLabel;
12994
+ exports.ɵformatReasoningDuration = formatReasoningDuration;
12995
+ exports.ɵformatToolNames = formatToolNames;
12996
+ exports.ɵformatWorkDuration = formatWorkDuration;
10838
12997
  exports.ɵgetAgentInterruptState = ɵgetAgentInterruptState;
12998
+ exports.ɵgetArgumentPreview = getArgumentPreview;
12999
+ exports.ɵgetLatestTurnKey = getLatestTurnKey;
13000
+ exports.ɵgetToolCallLayouts = getToolCallLayouts;
13001
+ exports.ɵgetToolCallPreview = getToolCallPreview;
13002
+ exports.ɵgetToolCallRendererNames = getToolCallRendererNames;
13003
+ exports.ɵgetToolCallRowStatus = getToolCallRowStatus;
13004
+ exports.ɵgetToolResults = getToolResults;
13005
+ exports.ɵgetTurnWork = getTurnWork;
13006
+ exports.ɵgetWorkOpenState = getWorkOpenState;
10839
13007
  exports.ɵisCopilotKitFeature = ɵisCopilotKitFeature;
10840
13008
  exports.ɵisHttpAgent = ɵisHttpAgent;
10841
13009
  exports.ɵisRetryableMemoryStatus = isRetryableStatus;
13010
+ exports.ɵisTurnWorkOpen = isTurnWorkOpen;
13011
+ exports.ɵisTurnWorking = isTurnWorking;
10842
13012
  exports.ɵjoinPhoenixChannel$ = ɵjoinPhoenixChannel$;
13013
+ exports.ɵloadWebsandbox = loadWebsandbox;
10843
13014
  exports.ɵmapMemoryMetadataEvent = ɵmapMemoryMetadataEvent;
10844
13015
  exports.ɵmemoryAdapterEvents = ɵmemoryAdapterEvents;
10845
13016
  exports.ɵmemoryDomainEvents = ɵmemoryDomainEvents;
10846
13017
  exports.ɵmemoryReducer = ɵmemoryReducer;
10847
13018
  exports.ɵmemoryRestEvents = ɵmemoryRestEvents;
13019
+ exports.ɵmessagesFingerprint = ɵmessagesFingerprint;
10848
13020
  exports.ɵobservePhoenixEvent$ = ɵobservePhoenixEvent$;
10849
13021
  exports.ɵobservePhoenixJoinOutcome$ = ɵobservePhoenixJoinOutcome$;
10850
13022
  exports.ɵobservePhoenixSocketHealth$ = ɵobservePhoenixSocketHealth$;
10851
13023
  exports.ɵobservePhoenixSocketSignals$ = ɵobservePhoenixSocketSignals$;
10852
13024
  exports.ɵphoenixChannel$ = ɵphoenixChannel$;
10853
13025
  exports.ɵphoenixSocket$ = ɵphoenixSocket$;
13026
+ exports.ɵpluralize = pluralize;
13027
+ exports.ɵprocessPartialHtml = processPartialHtml;
13028
+ exports.ɵrecordWorkTime = recordWorkTime;
13029
+ exports.ɵresolveActivityRenderer = ɵresolveActivityRenderer;
13030
+ exports.ɵresolveComposerKey = ɵresolveComposerKey;
13031
+ exports.ɵresolveCustomMessageRenderers = ɵresolveCustomMessageRenderers;
13032
+ exports.ɵresolveLicenseState = ɵresolveLicenseState;
13033
+ exports.ɵresolveThreadsLicense = ɵresolveThreadsLicense;
13034
+ exports.ɵresolveToolCallRenderer = ɵresolveToolCallRenderer;
10854
13035
  exports.ɵselectFetchMoreError = ɵselectFetchMoreError;
10855
13036
  exports.ɵselectHasNextPage = ɵselectHasNextPage;
10856
13037
  exports.ɵselectIsFetchingNextPage = ɵselectIsFetchingNextPage;
@@ -10864,6 +13045,9 @@ exports.ɵselectMemoriesRealtimeStatus = ɵselectMemoriesRealtimeStatus;
10864
13045
  exports.ɵselectThreads = ɵselectThreads;
10865
13046
  exports.ɵselectThreadsError = ɵselectThreadsError;
10866
13047
  exports.ɵselectThreadsIsLoading = ɵselectThreadsIsLoading;
13048
+ exports.ɵstringifyToolCallPayload = stringifyToolCallPayload;
10867
13049
  exports.ɵthreadAdapterEvents = ɵthreadAdapterEvents;
13050
+ exports.ɵtranscribeAudio = ɵtranscribeAudio;
13051
+ exports.ɵtranscriptionErrorMessageKey = ɵtranscriptionErrorMessageKey;
10868
13052
  exports.ɵwithHeaderDefaults = ɵwithHeaderDefaults;
10869
13053
  //# sourceMappingURL=index.cjs.map