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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,12 +1,11 @@
1
1
  import { Throttler } from "@tanstack/pacer";
2
2
  import { AGUIConnectNotImplementedError, AbstractAgent, CompatibilityBoundary, EventType, HttpAgent, buildResumeArray, isInterruptExpired, randomUUID, runHttpRequest, structuredClone_, transformChunks, transformHttpEventStream } from "@ag-ui/client";
3
- import { A2UI_VERSION, GENERATIVE_UI_ROOT_ID, RUNTIME_MODE_INTELLIGENCE, RUNTIME_MODE_SSE, THREAD_ALREADY_RUNNING_ERROR_CODE, logger, parseInspectorMetadataV1, partialJSONParse, phoenixExponentialBackoff, randomUUID as randomUUID$1, resolveDebugConfig, schemaToJsonSchema, stripIntelligenceRoutingFields } from "@copilotkit/shared";
3
+ import { A2UI_VERSION, GENERATIVE_UI_ROOT_ID, RUNTIME_MODE_INTELLIGENCE, RUNTIME_MODE_SSE, THREAD_ALREADY_RUNNING_ERROR_CODE, TranscriptionErrorCode, copyToClipboard, createLicenseContextValue, logger, parseInspectorMetadataV1, partialJSONParse, phoenixExponentialBackoff, randomUUID as randomUUID$1, resolveDebugConfig, schemaToJsonSchema, stripIntelligenceRoutingFields } from "@copilotkit/shared";
4
4
  import { BehaviorSubject, EMPTY, NEVER, Notification, Observable, Subject, Subscription, asapScheduler, combineLatest, concat, defer, dematerialize, firstValueFrom, from, lastValueFrom, merge, observeOn, of, switchMap, throwError } from "rxjs";
5
5
  import { catchError, concatMap, concatWith, delay, distinctUntilChanged, endWith, filter, finalize, ignoreElements, map, mergeMap, observeOn as observeOn$1, scan, share, shareReplay, startWith, switchMap as switchMap$1, take, takeUntil, tap, timeout, withLatestFrom } from "rxjs/operators";
6
6
  import { Socket } from "phoenix";
7
- import { zodToJsonSchema } from "zod-to-json-schema";
8
7
  import { createCollector, createTrajectoryCollector } from "@copilotkit/learning";
9
- import { marked } from "marked";
8
+ import { jsonrepair } from "jsonrepair";
10
9
 
11
10
  //#region src/utils/http-agent.ts
12
11
  /**
@@ -1764,6 +1763,20 @@ function isAbortError$1(error) {
1764
1763
  return typeof message === "string" && ABORT_MESSAGES.has(message);
1765
1764
  }
1766
1765
 
1766
+ //#endregion
1767
+ //#region src/utils/shallow-equal.ts
1768
+ /**
1769
+ * True when both records have the same own keys and each key holds the same
1770
+ * value (compared with `Object.is`). Key order does not matter. Nested
1771
+ * objects are compared by reference, not by content.
1772
+ */
1773
+ function shallowEqualRecord(a, b) {
1774
+ if (a === b) return true;
1775
+ const aKeys = Object.keys(a);
1776
+ if (aKeys.length !== Object.keys(b).length) return false;
1777
+ return aKeys.every((key) => Object.prototype.hasOwnProperty.call(b, key) && Object.is(a[key], b[key]));
1778
+ }
1779
+
1767
1780
  //#endregion
1768
1781
  //#region src/utils/runtime-request.ts
1769
1782
  const RUNTIME_REQUEST_WATCHDOG_MS = 1e4;
@@ -1866,13 +1879,6 @@ function isPromiseLike(value) {
1866
1879
  function normalizeHeaders(headers) {
1867
1880
  return Object.fromEntries(Object.entries(headers).filter((entry) => entry[1] != null));
1868
1881
  }
1869
- /** Same keys, same values (order-independent). */
1870
- function shallowEqualRecord(a, b) {
1871
- const aKeys = Object.keys(a);
1872
- const bKeys = Object.keys(b);
1873
- if (aKeys.length !== bKeys.length) return false;
1874
- return aKeys.every((key) => a[key] === b[key]);
1875
- }
1876
1882
  function isHeaderRecordInput(value) {
1877
1883
  return typeof value === "object" && value !== null && !Array.isArray(value);
1878
1884
  }
@@ -2041,6 +2047,13 @@ const RUNTIME_ENTITLEMENT_RETRY_DELAY_MS = 5e3;
2041
2047
  var AgentRegistry = class {
2042
2048
  _agents = {};
2043
2049
  localAgents = {};
2050
+ /**
2051
+ * Whether `onAgentsChanged` has run since {@link initialize}. Constructor
2052
+ * agents are not announced, so the first `setAgents__unsafe_dev_only` with
2053
+ * the same agents must still announce them (core subscribes to agents on
2054
+ * that notification).
2055
+ */
2056
+ agentsPublished = false;
2044
2057
  remoteAgents = {};
2045
2058
  mintedThreadIds = /* @__PURE__ */ new WeakMap();
2046
2059
  _runtimeUrl;
@@ -2087,6 +2100,12 @@ var AgentRegistry = class {
2087
2100
  runtimeRecoveryPending = false;
2088
2101
  runtimeHealthGeneration = 0;
2089
2102
  /**
2103
+ * Aborted by {@link dispose}. Runtime probes, recovery fetches and request
2104
+ * watchdogs listen to it so a disposed core leaves no timer or request
2105
+ * behind.
2106
+ */
2107
+ disposeController = new AbortController();
2108
+ /**
2090
2109
  * The headers each HttpAgent was constructed with, captured on the first
2091
2110
  * `applyHeadersToAgent` call for that agent (which, for agents the registry
2092
2111
  * owns, happens at registration before any core headers are applied). Core
@@ -2166,6 +2185,27 @@ var AgentRegistry = class {
2166
2185
  return this._telemetryDisabled;
2167
2186
  }
2168
2187
  /**
2188
+ * Stop runtime work this registry owns: the entitlement retry timer, the
2189
+ * inspector metadata request, runtime probes and recovery fetches with
2190
+ * their timeouts, and request watchdogs. In-flight `/info` connections are
2191
+ * detached so their late results change nothing. Called by
2192
+ * `CopilotKitCore.dispose`.
2193
+ */
2194
+ dispose() {
2195
+ if (this.disposeController.signal.aborted) return;
2196
+ this.disposeController.abort();
2197
+ this._activeRuntimeConnectionAttempt = void 0;
2198
+ this._connectionInFlight = void 0;
2199
+ this.resetRuntimeEntitlementRetry();
2200
+ this.inspectorMetadataGeneration += 1;
2201
+ this.inspectorMetadataAbortController?.abort();
2202
+ this.inspectorMetadataAbortController = void 0;
2203
+ this.abandonRuntimeHealthProbe();
2204
+ }
2205
+ get isDisposed() {
2206
+ return this.disposeController.signal.aborted;
2207
+ }
2208
+ /**
2169
2209
  * Initialize agents from configuration
2170
2210
  */
2171
2211
  initialize(agents) {
@@ -2251,9 +2291,12 @@ var AgentRegistry = class {
2251
2291
  this.runtimeProbeAbortController = void 0;
2252
2292
  }
2253
2293
  /**
2254
- * Set all agents at once (for development use)
2294
+ * Set all agents at once (for development use). Same ids mapped to the
2295
+ * same instances as the current local agents is a no-op once the agents
2296
+ * have been announced.
2255
2297
  */
2256
2298
  setAgents__unsafe_dev_only(agents) {
2299
+ if (this.agentsPublished && shallowEqualRecord(agents, this.localAgents)) return;
2257
2300
  Object.entries(agents).forEach(([id, agent]) => {
2258
2301
  if (agent) this.validateAndAssignAgentId(id, agent);
2259
2302
  });
@@ -2517,11 +2560,17 @@ var AgentRegistry = class {
2517
2560
  checked: () => false
2518
2561
  };
2519
2562
  let checked = false;
2563
+ const disposeSignal = this.disposeController.signal;
2520
2564
  const timeoutId = setTimeout(() => {
2521
2565
  checked = this.handleRuntimeRequestOutcome("failed");
2522
2566
  }, RUNTIME_REQUEST_WATCHDOG_MS);
2567
+ const clear = () => {
2568
+ clearTimeout(timeoutId);
2569
+ disposeSignal.removeEventListener("abort", clear);
2570
+ };
2571
+ disposeSignal.addEventListener("abort", clear, { once: true });
2523
2572
  return {
2524
- clear: () => clearTimeout(timeoutId),
2573
+ clear,
2525
2574
  checked: () => checked
2526
2575
  };
2527
2576
  }
@@ -2682,7 +2731,7 @@ var AgentRegistry = class {
2682
2731
  this.runtimeHealthGeneration += 1;
2683
2732
  }
2684
2733
  handleRuntimeRequestOutcome(outcome, alreadyChecked = () => false) {
2685
- if (outcome === "aborted" || outcome === "ignored") return false;
2734
+ if (outcome === "aborted" || outcome === "ignored" || this.isDisposed) return false;
2686
2735
  if (outcome === "failed" && alreadyChecked()) return false;
2687
2736
  if (typeof window === "undefined") return false;
2688
2737
  if (!this._runtimeUrl) return false;
@@ -2702,16 +2751,32 @@ var AgentRegistry = class {
2702
2751
  let timeoutId;
2703
2752
  const request = this.fetchRuntimeInfo(runtimeUrl, runtimeTransport, abortController.signal);
2704
2753
  request.catch(() => {});
2754
+ const disposeSignal = this.disposeController.signal;
2755
+ let rejectOnAbort;
2756
+ const abortOnDispose = () => abortController.abort();
2705
2757
  try {
2706
2758
  const timedOut = new Promise((_resolve, reject) => {
2707
2759
  timeoutId = setTimeout(() => {
2708
- abortController.abort();
2709
2760
  reject(/* @__PURE__ */ new Error(`Runtime did not answer within ${ɵRUNTIME_PROBE_TIMEOUT_MS}ms`));
2761
+ abortController.abort();
2710
2762
  }, ɵRUNTIME_PROBE_TIMEOUT_MS);
2711
2763
  });
2712
- return await Promise.race([request, timedOut]);
2764
+ const aborted = new Promise((_resolve, reject) => {
2765
+ rejectOnAbort = () => reject(/* @__PURE__ */ new Error("Runtime request aborted"));
2766
+ abortController.signal.addEventListener("abort", rejectOnAbort, { once: true });
2767
+ });
2768
+ aborted.catch(() => {});
2769
+ disposeSignal.addEventListener("abort", abortOnDispose, { once: true });
2770
+ if (disposeSignal.aborted) abortController.abort();
2771
+ return await Promise.race([
2772
+ request,
2773
+ timedOut,
2774
+ aborted
2775
+ ]);
2713
2776
  } finally {
2714
2777
  if (timeoutId !== void 0) clearTimeout(timeoutId);
2778
+ if (rejectOnAbort) abortController.signal.removeEventListener("abort", rejectOnAbort);
2779
+ disposeSignal.removeEventListener("abort", abortOnDispose);
2715
2780
  }
2716
2781
  }
2717
2782
  async probeRuntimeReachability() {
@@ -2772,7 +2837,7 @@ var AgentRegistry = class {
2772
2837
  * Update runtime connection and fetch remote agents
2773
2838
  */
2774
2839
  async updateRuntimeConnection(options) {
2775
- if (typeof window === "undefined") return;
2840
+ if (typeof window === "undefined" || this.isDisposed) return;
2776
2841
  const key = this.runtimeConnectionKey();
2777
2842
  const inFlight = this._connectionInFlight;
2778
2843
  if (inFlight && inFlight.attempt.key === key && this.isCurrentRuntimeConnection(inFlight.attempt)) return inFlight.promise;
@@ -2834,6 +2899,7 @@ var AgentRegistry = class {
2834
2899
  }
2835
2900
  this._runtimeEntitlementRetryAttemptedKey = key;
2836
2901
  this._runtimeEntitlementRetryPendingKey = key;
2902
+ if (this.isDisposed) return;
2837
2903
  this._runtimeEntitlementRetryTimer = setTimeout(() => {
2838
2904
  this._runtimeEntitlementRetryTimer = void 0;
2839
2905
  this.executeRuntimeEntitlementRetry(attempt).catch((error) => {
@@ -3088,6 +3154,7 @@ var AgentRegistry = class {
3088
3154
  * Notify subscribers of agent changes
3089
3155
  */
3090
3156
  async notifyAgentsChanged() {
3157
+ this.agentsPublished = true;
3091
3158
  await this.core.notifySubscribers((subscriber) => subscriber.onAgentsChanged?.({
3092
3159
  copilotkit: this.core,
3093
3160
  agents: this._agents
@@ -3183,6 +3250,13 @@ var SuggestionEngine = class {
3183
3250
  _suggestionsConfig = {};
3184
3251
  _suggestions = {};
3185
3252
  _runningSuggestions = {};
3253
+ /**
3254
+ * The last `getSuggestions` result per agent, with the per-generation
3255
+ * arrays it was built from. Each generation's array is replaced (never
3256
+ * mutated) on change, so comparing those references tells whether the
3257
+ * cached result is still current.
3258
+ */
3259
+ _snapshots = /* @__PURE__ */ new Map();
3186
3260
  constructor(core) {
3187
3261
  this.core = core;
3188
3262
  }
@@ -3245,13 +3319,29 @@ var SuggestionEngine = class {
3245
3319
  this.notifySuggestionsChanged(agentId, []);
3246
3320
  }
3247
3321
  /**
3248
- * Get current suggestions for an agent
3322
+ * Get current suggestions for an agent. Returns the same object until the
3323
+ * agent's suggestions or loading state change.
3249
3324
  */
3250
3325
  getSuggestions(agentId) {
3251
- return {
3252
- suggestions: Object.values(this._suggestions[agentId] ?? {}).flat(),
3253
- isLoading: (this._runningSuggestions[agentId]?.length ?? 0) > 0
3326
+ const parts = Object.values(this._suggestions[agentId] ?? {});
3327
+ const isLoading = (this._runningSuggestions[agentId]?.length ?? 0) > 0;
3328
+ const cached = this._snapshots.get(agentId);
3329
+ if (cached !== void 0 && cached.result.isLoading === isLoading && cached.parts.length === parts.length && parts.every((part, index) => part === cached.parts[index])) return cached.result;
3330
+ const result = {
3331
+ suggestions: parts.flat(),
3332
+ isLoading
3254
3333
  };
3334
+ this._snapshots.set(agentId, {
3335
+ parts,
3336
+ result
3337
+ });
3338
+ return result;
3339
+ }
3340
+ /** Abort every running suggestion generation. Called by `CopilotKitCore.dispose`. */
3341
+ dispose() {
3342
+ const runs = Object.values(this._runningSuggestions).flat();
3343
+ this._runningSuggestions = {};
3344
+ for (const run of runs) run.abortRun();
3255
3345
  }
3256
3346
  /**
3257
3347
  * Generate suggestions by running a provider agent and extracting the
@@ -3622,7 +3712,7 @@ const EMPTY_TOOL_SCHEMA = {
3622
3712
  */
3623
3713
  function createToolSchema(tool) {
3624
3714
  if (!tool.parameters) return { ...EMPTY_TOOL_SCHEMA };
3625
- const rawSchema = schemaToJsonSchema(tool.parameters, { zodToJsonSchema: (schema, options) => zodToJsonSchema(schema, options) });
3715
+ const rawSchema = schemaToJsonSchema(tool.parameters);
3626
3716
  if (!rawSchema || typeof rawSchema !== "object") return { ...EMPTY_TOOL_SCHEMA };
3627
3717
  const { $schema: _$schema, ...schema } = rawSchema;
3628
3718
  if (typeof schema.type !== "string") schema.type = "object";
@@ -3661,14 +3751,14 @@ var ɵInterruptState = class {
3661
3751
  #adoptedContent = /* @__PURE__ */ new Map();
3662
3752
  #pending = null;
3663
3753
  #sealed = false;
3664
- /** Return the active normalized interrupt without exposing mutable state. */
3754
+ /**
3755
+ * Return the active normalized interrupt. A standard interrupt set is a
3756
+ * frozen snapshot, and every read returns the same object until the
3757
+ * interrupt is replaced or cleared, so a framework can compare it by
3758
+ * reference.
3759
+ */
3665
3760
  get pending() {
3666
- const pending = this.#pending;
3667
- if (pending?.kind === "standard") return {
3668
- kind: "standard",
3669
- interrupts: [...pending.interrupts]
3670
- };
3671
- return pending;
3761
+ return this.#pending;
3672
3762
  }
3673
3763
  /** Replace the current interrupt with a legacy custom-event interrupt. */
3674
3764
  setLegacy(event) {
@@ -3689,10 +3779,10 @@ var ɵInterruptState = class {
3689
3779
  callIds.add(interrupt.toolCallId);
3690
3780
  }
3691
3781
  }
3692
- this.#replace({
3782
+ this.#replace(Object.freeze({
3693
3783
  kind: "standard",
3694
- interrupts: [...interrupts]
3695
- });
3784
+ interrupts: Object.freeze([...interrupts])
3785
+ }));
3696
3786
  }
3697
3787
  /** Clear all pending interrupt data and accumulated responses. */
3698
3788
  clear() {
@@ -4011,6 +4101,12 @@ var RunHandler = class {
4011
4101
  * one array before, so the `/info` response flipping `openGenerativeUI` (or
4012
4102
  * any other provider-prop change) silently dropped every hook-registered
4013
4103
  * tool (#4952). Key = `capabilityKey(name, agentId)`.
4104
+ *
4105
+ * Each key holds a stack of registrations. The last one is the active tool;
4106
+ * removing it (via the function `addTool` returns) brings back the one
4107
+ * below, and an empty stack lets the provider tool of that key show again.
4108
+ * A registration is its own object, so removing one never removes another
4109
+ * registration of the same tool object.
4014
4110
  */
4015
4111
  _hookTools = /* @__PURE__ */ new Map();
4016
4112
  /**
@@ -4067,6 +4163,13 @@ var RunHandler = class {
4067
4163
  */
4068
4164
  _runDepths = /* @__PURE__ */ new WeakMap();
4069
4165
  /**
4166
+ * Agents with at least one run in flight (depth above 0), so
4167
+ * {@link dispose} can stop them. Removed when the last run ends.
4168
+ */
4169
+ _runningAgents = /* @__PURE__ */ new Set();
4170
+ /** Set by {@link dispose}. Stops WebMCP from registering tools again. */
4171
+ _disposed = false;
4172
+ /**
4070
4173
  * Each agent's own `abortRun`, saved while RunHandler's intercept is
4071
4174
  * installed. Restored only once none of the agent's runs is in flight, so an
4072
4175
  * overlapping run keeps the intercept after an earlier run finishes.
@@ -4112,7 +4215,7 @@ var RunHandler = class {
4112
4215
  _executingToolCalls = /* @__PURE__ */ new WeakMap();
4113
4216
  _connectionGenerations = /* @__PURE__ */ new WeakMap();
4114
4217
  _runGenerations = /* @__PURE__ */ new WeakMap();
4115
- _interactionAbortControllers = /* @__PURE__ */ new WeakMap();
4218
+ _interactionAbortControllers = /* @__PURE__ */ new Map();
4116
4219
  constructor(core) {
4117
4220
  this.core = core;
4118
4221
  }
@@ -4130,6 +4233,29 @@ var RunHandler = class {
4130
4233
  this._executingToolCalls.delete(agent);
4131
4234
  }
4132
4235
  }
4236
+ /**
4237
+ * Stop every run chain and tool interaction this handler tracks, and every
4238
+ * agent in `agents` that reports a run in flight, the same way `stopAgent`
4239
+ * does. Then unregister all WebMCP tools. Called by `CopilotKitCore.dispose`.
4240
+ */
4241
+ dispose(agents) {
4242
+ this._disposed = true;
4243
+ const candidates = new Set([
4244
+ ...agents,
4245
+ ...this._runningAgents,
4246
+ ...this._interactionAbortControllers.keys()
4247
+ ]);
4248
+ for (const agent of candidates) {
4249
+ const hasActiveRun = agent.isRunning || this._runningAgents.has(agent);
4250
+ try {
4251
+ this.abortCurrentRun(agent);
4252
+ if (hasActiveRun) agent.abortRun();
4253
+ } catch (error) {
4254
+ logger.error(`Failed to stop agent '${agent.agentId ?? "(unknown agent)"}' on dispose:`, error);
4255
+ }
4256
+ }
4257
+ this._webmcpRegistry.sync(/* @__PURE__ */ new Map());
4258
+ }
4133
4259
  abortAgentRuns(agent) {
4134
4260
  for (const controller of this._runAbortControllers.get(agent) ?? []) controller.abort();
4135
4261
  }
@@ -4170,7 +4296,10 @@ var RunHandler = class {
4170
4296
  if (this._cachedMergedTools) return this._cachedMergedTools;
4171
4297
  const merged = /* @__PURE__ */ new Map();
4172
4298
  for (const tool of this._propTools) merged.set(this.capabilityKey(tool.name, tool.agentId), tool);
4173
- for (const [key, tool] of this._hookTools) merged.set(key, tool);
4299
+ for (const [key, stack] of this._hookTools) {
4300
+ const active = stack[stack.length - 1];
4301
+ if (active) merged.set(key, active.tool);
4302
+ }
4174
4303
  this._cachedMergedTools = Array.from(merged.values());
4175
4304
  return this._cachedMergedTools;
4176
4305
  }
@@ -4186,17 +4315,34 @@ var RunHandler = class {
4186
4315
  /**
4187
4316
  * Add a tool to the registry. Survives provider re-syncs ({@link setTools}),
4188
4317
  * and shadows a provider tool of the same name + agentId.
4318
+ *
4319
+ * Registrations of the same name + agentId stack: the most recent one is
4320
+ * active. Call the returned function to remove exactly this registration;
4321
+ * the previous registration (or the provider tool) becomes active again.
4322
+ * Calling it more than once does nothing.
4189
4323
  */
4190
4324
  addTool(tool) {
4191
4325
  const key = this.capabilityKey(tool.name, tool.agentId);
4192
- if (this._hookTools.has(key)) {
4193
- logger.warn(`Tool already exists: '${tool.name}' for agent '${tool.agentId || "global"}', skipping.`);
4194
- return;
4195
- }
4196
- this._hookTools.set(key, tool);
4326
+ const registration = { tool };
4327
+ const stack = this._hookTools.get(key);
4328
+ if (stack) {
4329
+ if (process.env.NODE_ENV !== "production") logger.warn(`Tool already exists: '${tool.name}' for agent '${tool.agentId || "global"}'. The new registration shadows it until the new one is removed.`);
4330
+ stack.push(registration);
4331
+ } else this._hookTools.set(key, [registration]);
4197
4332
  this._cachedMergedTools = null;
4198
4333
  this.warnOnMissingToolParameters([tool]);
4199
4334
  this.syncWebMCP();
4335
+ return () => this.unregisterHookTool(key, registration);
4336
+ }
4337
+ /** Remove one `addTool` registration. Unknown registrations are ignored. */
4338
+ unregisterHookTool(key, registration) {
4339
+ const stack = this._hookTools.get(key);
4340
+ const index = stack?.indexOf(registration) ?? -1;
4341
+ if (!stack || index === -1) return;
4342
+ stack.splice(index, 1);
4343
+ if (stack.length === 0) this._hookTools.delete(key);
4344
+ this._cachedMergedTools = null;
4345
+ this.syncWebMCP();
4200
4346
  }
4201
4347
  /**
4202
4348
  * Report, once per tool and at development time only, a tool registered with
@@ -4228,7 +4374,10 @@ var RunHandler = class {
4228
4374
  }
4229
4375
  }
4230
4376
  /**
4231
- * Remove a tool by name and optionally by agentId
4377
+ * Remove a tool by name and optionally by agentId: every `addTool`
4378
+ * registration of that key and the provider tool of that key. Without an
4379
+ * agentId only global tools are removed. To remove one `addTool`
4380
+ * registration and keep the others, call the function `addTool` returned.
4232
4381
  */
4233
4382
  removeTool(id, agentId) {
4234
4383
  this._hookTools.delete(this.capabilityKey(id, agentId));
@@ -4426,6 +4575,7 @@ var RunHandler = class {
4426
4575
  this._runAbortControllers.set(agent, controllers);
4427
4576
  }
4428
4577
  if (depth === 0) {
4578
+ this._runningAgents.add(agent);
4429
4579
  const originalAbortRun = agent.abortRun;
4430
4580
  this._originalAbortRuns.set(agent, originalAbortRun);
4431
4581
  agent.abortRun = () => {
@@ -4499,6 +4649,7 @@ var RunHandler = class {
4499
4649
  if (controllers?.size === 0) this._runAbortControllers.delete(agent);
4500
4650
  }
4501
4651
  if (remainingDepth === 0) {
4652
+ this._runningAgents.delete(agent);
4502
4653
  const originalAbortRun = this._originalAbortRuns.get(agent);
4503
4654
  if (originalAbortRun) {
4504
4655
  agent.abortRun = originalAbortRun;
@@ -5003,6 +5154,7 @@ var RunHandler = class {
5003
5154
  * agentId — a name collision across agentIds keeps the first registration.
5004
5155
  */
5005
5156
  syncWebMCP() {
5157
+ if (this._disposed) return;
5006
5158
  const desired = /* @__PURE__ */ new Map();
5007
5159
  const warnedCollisions = /* @__PURE__ */ new Set();
5008
5160
  for (const tool of this.tools) {
@@ -5332,6 +5484,11 @@ var StateManager = class {
5332
5484
  }
5333
5485
  this.rawEventByMessage.delete(agentId);
5334
5486
  }
5487
+ /** Unsubscribe from every agent. Called by `CopilotKitCore.dispose`. */
5488
+ dispose() {
5489
+ const agentIds = [...this.agentSubscriptions.keys()];
5490
+ for (const agentId of agentIds) this.unsubscribeFromAgent(agentId);
5491
+ }
5335
5492
  /**
5336
5493
  * Get state for a specific run
5337
5494
  * Returns a deep copy to prevent external mutations
@@ -7504,6 +7661,8 @@ var CopilotKitCore = class {
7504
7661
  _defaultThrottleMs;
7505
7662
  _debug;
7506
7663
  subscribers = /* @__PURE__ */ new Set();
7664
+ _disposed = false;
7665
+ waitForFrameworkUpdates;
7507
7666
  agentRegistry;
7508
7667
  contextStore;
7509
7668
  suggestionEngine;
@@ -7529,7 +7688,8 @@ var CopilotKitCore = class {
7529
7688
  * store that was registered prior to that initial notification.
7530
7689
  */
7531
7690
  previousAgentIds = /* @__PURE__ */ new Set();
7532
- constructor({ runtimeUrl, runtimeTransport = "auto", deferInitialConnection = false, headers = {}, credentials, messageFilter, properties = {}, agents__unsafe_dev_only = {}, tools = [], suggestionsConfig = [], debug, learning }) {
7691
+ constructor({ runtimeUrl, runtimeTransport = "auto", deferInitialConnection = false, headers = {}, credentials, messageFilter, properties = {}, agents__unsafe_dev_only = {}, tools = [], suggestionsConfig = [], debug, learning, ɵwaitForFrameworkUpdates }) {
7692
+ this.waitForFrameworkUpdates = ɵwaitForFrameworkUpdates;
7533
7693
  this.headerSource = new HeaderSourceResolver((error) => {
7534
7694
  this.emitError({
7535
7695
  error,
@@ -7583,6 +7743,7 @@ var CopilotKitCore = class {
7583
7743
  * Internal method used by delegate classes and subclasses to notify subscribers
7584
7744
  */
7585
7745
  async notifySubscribers(handler, errorMessage) {
7746
+ if (this._disposed) return;
7586
7747
  await Promise.all(Array.from(this.subscribers).map(async (subscriber) => {
7587
7748
  try {
7588
7749
  await handler(subscriber);
@@ -7832,7 +7993,12 @@ var CopilotKitCore = class {
7832
7993
  headers: this.headers
7833
7994
  }), "Subscriber onHeadersChanged error:");
7834
7995
  }
7996
+ /**
7997
+ * Set the credentials mode for runtime requests (for example `"include"`
7998
+ * to send HTTP-only cookies). Passing the current value does nothing.
7999
+ */
7835
8000
  setCredentials(credentials) {
8001
+ if (credentials === this._credentials) return;
7836
8002
  this._credentials = credentials;
7837
8003
  this.agentRegistry.applyCredentialsToAgents(this.agentRegistry.agents);
7838
8004
  this.agentRegistry.handleCredentialsChanged();
@@ -7842,9 +8008,11 @@ var CopilotKitCore = class {
7842
8008
  *
7843
8009
  * Applies to agents already discovered as well as ones discovered later, so
7844
8010
  * a filter set before `/info` lands is not lost. Pass `undefined` to go back
7845
- * to sending the full thread.
8011
+ * to sending the full thread. Passing the current filter function again
8012
+ * does nothing.
7846
8013
  */
7847
8014
  setMessageFilter(messageFilter) {
8015
+ if (messageFilter === this._messageFilter) return;
7848
8016
  this._messageFilter = messageFilter;
7849
8017
  this.agentRegistry.applyMessageFilterToAgents(this.agentRegistry.agents);
7850
8018
  }
@@ -7901,7 +8069,14 @@ var CopilotKitCore = class {
7901
8069
  }
7902
8070
  return merged;
7903
8071
  }
8072
+ /**
8073
+ * Replace the properties sent as `forwardedProps` with every run, and
8074
+ * notify `onPropertiesChanged`. Passing an object with the same keys and
8075
+ * values as the current one does nothing, so a fresh object literal on
8076
+ * every render is safe.
8077
+ */
7904
8078
  setProperties(properties) {
8079
+ if (shallowEqualRecord(properties, this._properties)) return;
7905
8080
  this._properties = properties;
7906
8081
  this.notifySubscribers((subscriber) => subscriber.onPropertiesChanged?.({
7907
8082
  copilotkit: this,
@@ -7909,7 +8084,10 @@ var CopilotKitCore = class {
7909
8084
  }), "Subscriber onPropertiesChanged error:");
7910
8085
  }
7911
8086
  /**
7912
- * Agent management (delegated to AgentRegistry)
8087
+ * Agent management (delegated to AgentRegistry).
8088
+ *
8089
+ * Replace the local (development) agents. Passing the same ids mapped to
8090
+ * the same agent instances does nothing.
7913
8091
  */
7914
8092
  setAgents__unsafe_dev_only(agents) {
7915
8093
  this.agentRegistry.setAgents__unsafe_dev_only(agents);
@@ -8188,11 +8366,34 @@ var CopilotKitCore = class {
8188
8366
  return this.suggestionEngine.getSuggestions(agentId);
8189
8367
  }
8190
8368
  /**
8191
- * Tool management (delegated to RunHandler)
8369
+ * Register a frontend tool. It shadows a provider tool (from the `tools`
8370
+ * config or `setTools`) with the same name and agentId.
8371
+ *
8372
+ * A second registration with the same name and agentId shadows the first.
8373
+ * Call the returned function to remove only this registration: the tool it
8374
+ * shadowed becomes active again. Calling it more than once does nothing.
8375
+ *
8376
+ * @param tool - The tool to register.
8377
+ * @returns A function that removes this registration.
8378
+ *
8379
+ * @example
8380
+ * const unregister = copilotkit.addTool({
8381
+ * name: "showWeather",
8382
+ * handler: async ({ city }) => `Sunny in ${city}`,
8383
+ * });
8384
+ * // later
8385
+ * unregister();
8192
8386
  */
8193
8387
  addTool(tool) {
8194
- this.runHandler.addTool(tool);
8388
+ return this.runHandler.addTool(tool);
8195
8389
  }
8390
+ /**
8391
+ * Remove a tool by name, and by agentId when given. This removes every
8392
+ * `addTool` registration with that name and agentId, and the provider tool
8393
+ * with that name and agentId. Without an agentId, only global tools are
8394
+ * removed. To remove one registration, call the function `addTool`
8395
+ * returned.
8396
+ */
8196
8397
  removeTool(id, agentId) {
8197
8398
  this.runHandler.removeTool(id, agentId);
8198
8399
  }
@@ -8436,11 +8637,52 @@ var CopilotKitCore = class {
8436
8637
  * synchronously while the deferred updates are still pending, producing stale
8437
8638
  * context for the next agent turn.
8438
8639
  *
8439
- * Override in framework-specific subclasses to yield to the framework
8440
- * scheduler before the follow-up run. The base implementation is a no-op
8441
- * because non-React environments have no deferred state to flush.
8640
+ * Awaits the `ɵwaitForFrameworkUpdates` config option when one is given.
8641
+ * Without it there is nothing to wait for, because a plain JavaScript
8642
+ * environment has no deferred state to flush. Framework subclasses that
8643
+ * still override this method keep working.
8442
8644
  */
8443
- async waitForPendingFrameworkUpdates() {}
8645
+ async waitForPendingFrameworkUpdates() {
8646
+ await this.waitForFrameworkUpdates?.();
8647
+ }
8648
+ /**
8649
+ * Stop everything this core started, so it can be dropped without leaks.
8650
+ *
8651
+ * Call it when you created a `CopilotKitCore` yourself and are done with it
8652
+ * (for example when a page or test tears down). Framework providers call it
8653
+ * for you.
8654
+ *
8655
+ * It does this, in order:
8656
+ *
8657
+ * - removes every subscriber, so no callback runs after this call;
8658
+ * - stops agent runs in flight and aborts running frontend tools;
8659
+ * - aborts suggestion generation;
8660
+ * - clears runtime timers and aborts runtime requests it can cancel;
8661
+ * - removes agent subscriptions, WebMCP tools, and the learning capture;
8662
+ * - stops the memory store and every registered thread store.
8663
+ *
8664
+ * Calling it again does nothing. Do not use the core after this call.
8665
+ *
8666
+ * @example
8667
+ * const copilotkit = new CopilotKitCore({ runtimeUrl: "/api/copilotkit" });
8668
+ * // ... use it ...
8669
+ * copilotkit.dispose();
8670
+ */
8671
+ dispose() {
8672
+ if (this._disposed) return;
8673
+ this._disposed = true;
8674
+ this.subscribers.clear();
8675
+ this.learningConfiguredListeners.clear();
8676
+ this.generativeUIDebugListeners.clear();
8677
+ this.runHandler.dispose(Object.values(this.agentRegistry.agents));
8678
+ this.suggestionEngine.dispose();
8679
+ this.agentRegistry.dispose();
8680
+ this.stateManager.dispose();
8681
+ this.stopTrajectory();
8682
+ this._memoryStore?.stop();
8683
+ const threadStores = Object.values(this.threadStoreRegistry.getAll());
8684
+ for (const store of threadStores) store.stop();
8685
+ }
8444
8686
  };
8445
8687
 
8446
8688
  //#endregion
@@ -8623,23 +8865,6 @@ function completePartialMarkdown(input) {
8623
8865
  return result;
8624
8866
  }
8625
8867
 
8626
- //#endregion
8627
- //#region src/utils/markdown/parse.ts
8628
- /**
8629
- * Parse a markdown string into a framework-agnostic token tree.
8630
- *
8631
- * Uses `marked`'s lexer (GFM enabled) so the result is DOM-free and can be
8632
- * walked into React, Vue, or React Native elements by each framework's
8633
- * built-in renderer.
8634
- */
8635
- function parseMarkdown(content, options = {}) {
8636
- const src = !content ? "" : options.complete === false ? content : completePartialMarkdown(content);
8637
- return marked.lexer(src, {
8638
- gfm: true,
8639
- breaks: true
8640
- });
8641
- }
8642
-
8643
8868
  //#endregion
8644
8869
  //#region src/threads.ts
8645
8870
  const THREADS_CHANNEL_EVENT = "thread_metadata";
@@ -10134,11 +10359,11 @@ function partialOperation(line) {
10134
10359
  return null;
10135
10360
  }
10136
10361
  /**
10137
- * A line that opens a new top-level operation: `{"version":"v…` or
10362
+ * A line that opens a new top-level operation: `{"version":"1…` or
10138
10363
  * `{"<operation>":{`. Seen at the start of a line while an earlier object is
10139
10364
  * still unbalanced, it means that object is malformed and has ended.
10140
10365
  */
10141
- const OPERATION_START = new RegExp(`^\\{\\s*"(?:version"\\s*:\\s*"v\\d|(?:${OP_KEYS.join("|")})"\\s*:\\s*\\{)`);
10366
+ const OPERATION_START = new RegExp(`^\\{\\s*"(?:version"\\s*:\\s*"\\d|(?:${OP_KEYS.join("|")})"\\s*:\\s*\\{)`);
10142
10367
  /**
10143
10368
  * Scan the top-level object whose "{" is at `start`. Returns the index just
10144
10369
  * past it and whether it balanced. An unbalanced object ends early (at the
@@ -10180,6 +10405,91 @@ function scanTopLevelObject(s, start) {
10180
10405
  balanced: false
10181
10406
  };
10182
10407
  }
10408
+ const OPERATION_NAMES = [
10409
+ "createSurface",
10410
+ "updateComponents",
10411
+ "updateDataModel",
10412
+ "deleteSurface",
10413
+ "callRendererFunction"
10414
+ ];
10415
+ /** Whether a value is shaped like one A2UI operation, with named components. */
10416
+ function isOperationShape(value) {
10417
+ if (!isRecord(value) || value.version !== A2UI_VERSION) return false;
10418
+ const names = OPERATION_NAMES.filter((name) => name in value);
10419
+ if (names.length !== 1 || Object.keys(value).length !== 2) return false;
10420
+ const body = value[names[0]];
10421
+ if (!isRecord(body)) return false;
10422
+ if (names[0] === "callRendererFunction") return true;
10423
+ if (typeof body.surfaceId !== "string") return false;
10424
+ const components = body.components;
10425
+ return components === void 0 || Array.isArray(components) && components.every((c) => isRecord(c) && typeof c.id === "string" && typeof c.component === "string");
10426
+ }
10427
+ /** Openers minus closers ({ and [ against } and ]) outside strings. */
10428
+ function closerImbalance(line) {
10429
+ let depth = 0;
10430
+ let inString = false;
10431
+ for (let i = 0; i < line.length; i++) {
10432
+ const c = line[i];
10433
+ if (inString) {
10434
+ if (c === "\\") i++;
10435
+ else if (c === "\"") inString = false;
10436
+ } else if (c === "\"") inString = true;
10437
+ else if (c === "{" || c === "[") depth++;
10438
+ else if (c === "}" || c === "]") depth--;
10439
+ }
10440
+ return depth;
10441
+ }
10442
+ /** The text with closers and whitespace removed, to compare a repair. */
10443
+ function withoutClosers(text) {
10444
+ return text.replace(/[\]}\s]/g, "");
10445
+ }
10446
+ /**
10447
+ * Whether a component of the operation holds a structural key (`id`,
10448
+ * `component`, `child`, `children`) in a nested object: a closer added at
10449
+ * the end instead of where it was dropped. The scan below repairs those.
10450
+ */
10451
+ function nestsStructuralKey(value) {
10452
+ const nests = (v) => isRecord(v) && Object.entries(v).some(([k, x]) => STRUCTURAL_KEYS.has(k) || nests(x));
10453
+ const components = (isRecord(value) ? Object.values(value).find(isRecord) : void 0)?.components;
10454
+ return Array.isArray(components) && components.some((c) => isRecord(c) && Object.values(c).some((prop) => nests(prop)));
10455
+ }
10456
+ /**
10457
+ * Repairs the complete lines of a fence that are not valid JSON (a missing
10458
+ * or extra brace) with jsonrepair, when the repair only adds or removes
10459
+ * closers and the result is shaped like an operation. A line still streaming in (no newline yet) is left alone.
10460
+ */
10461
+ function repairFenceLines(fenceText) {
10462
+ const repaired = [];
10463
+ const lines = fenceText.split("\n");
10464
+ if (fenceText.trimStart().startsWith("[")) return {
10465
+ text: fenceText,
10466
+ repaired
10467
+ };
10468
+ for (let n = 0; n < lines.length - 1; n++) {
10469
+ const line = lines[n];
10470
+ if (!line.trim().startsWith("{")) continue;
10471
+ try {
10472
+ JSON.parse(line);
10473
+ continue;
10474
+ } catch {}
10475
+ const imbalance = closerImbalance(line);
10476
+ if (Math.abs(imbalance) !== 1) continue;
10477
+ const next = lines.slice(n + 1).find((l) => l.trim() !== "");
10478
+ if (imbalance > 0 && next !== void 0 && !next.trim().startsWith("{")) continue;
10479
+ try {
10480
+ const fixed = jsonrepair(line);
10481
+ const value = JSON.parse(fixed);
10482
+ if (withoutClosers(fixed) === withoutClosers(line) && isOperationShape(value) && !nestsStructuralKey(value) && !(isRecord(value) && "callRendererFunction" in value)) {
10483
+ repaired.push(line.trim());
10484
+ lines[n] = JSON.stringify(value);
10485
+ }
10486
+ } catch {}
10487
+ }
10488
+ return {
10489
+ text: lines.join("\n"),
10490
+ repaired
10491
+ };
10492
+ }
10183
10493
  /**
10184
10494
  * Parse the body of an a2ui fence as a stream of top-level JSON values, so
10185
10495
  * operations may be one per line (the documented format), several per line,
@@ -10209,7 +10519,7 @@ function scanTopLevelObject(s, start) {
10209
10519
  * ```
10210
10520
  */
10211
10521
  function extractFenceOperations(fenceText) {
10212
- const s = fenceText;
10522
+ const { text: s, repaired: repairedLines } = repairFenceLines(fenceText);
10213
10523
  const operations = [];
10214
10524
  const invalidLines = [];
10215
10525
  const recovered = [];
@@ -10263,7 +10573,8 @@ function extractFenceOperations(fenceText) {
10263
10573
  partialObject,
10264
10574
  partialLine: partialObject,
10265
10575
  invalidLines,
10266
- recovered
10576
+ recovered,
10577
+ repairedLines
10267
10578
  };
10268
10579
  }
10269
10580
  /**
@@ -10771,5 +11082,2880 @@ function segmentSurfaceProse(components, options = {}) {
10771
11082
  }
10772
11083
 
10773
11084
  //#endregion
10774
- export { A2UI_FENCE_LANGUAGE, AgentRegistry, AgentThreadLockedError, ContextStore, CopilotKitCore, CopilotKitCoreErrorCode, CopilotKitCoreRuntimeConnectionStatus, CopilotKitHeaderResolutionError, INSPECTOR_THREAD_BRIDGE_PLUGIN_ID, IntelligenceAgent, MEMORY_ERROR_REGISTRY, MemoryError, ProxiedCopilotRuntimeAgent, RunHandler, StateManager, SuggestionEngine, ToolCallStatus, WebMCPRegistry, classifySurfaceCards, completePartialMarkdown, createActionGroup, createEffect, createInspectorThreadRequestId, createReducer, createSelector, createStore, emitInspectorActiveThread, emitInspectorStopViewing, emitInspectorViewThread, emitInspectorViewThreadResult, empty, ensureObjectArgs, extractCompleteArrayItems, extractFenceOperations, extractStringField, flattenInformationalCards, getMarkdownOperationSurfaceId, getWebMCPModelContext, isAbortError, isInspectorThreadBridgeEnabled, isRunCompletionAware, ofType, on, onInspectorActiveThread, onInspectorStopViewing, onInspectorViewThread, onInspectorViewThreadResult, parseMarkdown, parseToolArguments, prepareSurfaceOperations, props, segmentSurfaceProse, select, splitA2UIMarkdown, ɵCOPILOTKIT_FEATURES, ɵInterruptState, ɵMAX_SOCKET_RETRIES, ɵRUNTIME_PROBE_TIMEOUT_MS, ɵTHREAD_REQUEST_TIMEOUT_MS, ɵclearAgentInterruptState, createMemoryStore as ɵcreateMemoryStore, ɵcreateThreadSelectors, createThreadStore as ɵcreateThreadStore, ɵgetAgentInterruptState, ɵisCopilotKitFeature, ɵisHttpAgent, isRetryableStatus as ɵisRetryableMemoryStatus, ɵjoinPhoenixChannel$, ɵmapMemoryMetadataEvent, ɵmemoryAdapterEvents, ɵmemoryDomainEvents, ɵmemoryReducer, ɵmemoryRestEvents, ɵobservePhoenixEvent$, ɵobservePhoenixJoinOutcome$, ɵobservePhoenixSocketHealth$, ɵobservePhoenixSocketSignals$, ɵphoenixChannel$, ɵphoenixSocket$, ɵselectFetchMoreError, ɵselectHasNextPage, ɵselectIsFetchingNextPage, ɵselectIsMutating, ɵselectMemories, ɵselectMemoriesAvailable, ɵselectMemoriesError, ɵselectMemoriesIsLoading, ɵselectMemoriesIsMutating, ɵselectMemoriesRealtimeStatus, ɵselectThreads, ɵselectThreadsError, ɵselectThreadsIsLoading, ɵthreadAdapterEvents, ɵwithHeaderDefaults };
11085
+ //#region src/chat/labels.ts
11086
+ /**
11087
+ * The default English text for every word the chat UI shows. React, Vue and
11088
+ * Angular all read their chat text from this one set.
11089
+ *
11090
+ * To change or translate the text, pass a partial set to your framework's chat
11091
+ * configuration. Keys you leave out keep their default:
11092
+ *
11093
+ * ```ts
11094
+ * const labels = { ...CopilotChatDefaultLabels, chatInputPlaceholder: "Ask me" };
11095
+ * ```
11096
+ *
11097
+ * Some values are templates with `{name}` placeholders, such as
11098
+ * `"Thought for {duration}"`. Keep the placeholders when you translate them.
11099
+ *
11100
+ * Counts use two keys: `...One` for a count of 1, and `...Other` for any other
11101
+ * count.
11102
+ */
11103
+ const CopilotChatDefaultLabels = Object.freeze({
11104
+ chatInputPlaceholder: "Type a message...",
11105
+ chatInputToolbarStartTranscribeButtonLabel: "Transcribe",
11106
+ chatInputToolbarCancelTranscribeButtonLabel: "Cancel",
11107
+ chatInputToolbarFinishTranscribeButtonLabel: "Finish",
11108
+ chatInputToolbarAddButtonLabel: "Add attachments",
11109
+ chatInputToolbarToolsButtonLabel: "Tools",
11110
+ chatInputToolbarSendButtonLabel: "Send message",
11111
+ chatInputToolbarStopButtonLabel: "Stop",
11112
+ assistantMessageToolbarCopyCodeLabel: "Copy",
11113
+ assistantMessageToolbarCopyCodeCopiedLabel: "Copied",
11114
+ assistantMessageToolbarCopyMessageLabel: "Copy",
11115
+ assistantMessageToolbarInspectorLabel: "View in Inspector",
11116
+ assistantMessageToolbarInspectorDescription: "Open this message in the Inspector",
11117
+ assistantMessageToolbarInspectorLocalOnlyLabel: "Local only",
11118
+ assistantMessageToolbarInspectorLocalOnlyDescription: "Only visible on localhost or loopback hosts in development. Never shown in production.",
11119
+ assistantMessageToolbarInspectorTitle: "CopilotKit Inspector",
11120
+ assistantMessageToolbarInspectorHideLabel: "Hide this icon",
11121
+ assistantMessageToolbarInspectorHideDescription: "Until you reload this page",
11122
+ assistantMessageToolbarThumbsUpLabel: "Good response",
11123
+ assistantMessageToolbarThumbsDownLabel: "Bad response",
11124
+ assistantMessageFeedbackCommentPlaceholder: "Add a comment (optional)",
11125
+ assistantMessageFeedbackCommentSubmitLabel: "Send comment",
11126
+ assistantMessageToolbarReadAloudLabel: "Read aloud",
11127
+ assistantMessageToolbarRegenerateLabel: "Regenerate",
11128
+ userMessageToolbarCopyMessageLabel: "Copy",
11129
+ userMessageToolbarEditMessageLabel: "Edit",
11130
+ userMessageToolbarPreviousBranchLabel: "Previous branch",
11131
+ userMessageToolbarNextBranchLabel: "Next branch",
11132
+ chatDisclaimerText: "AI can make mistakes. Please verify important information.",
11133
+ chatToggleOpenLabel: "Open chat",
11134
+ chatToggleCloseLabel: "Close chat",
11135
+ chatScrollToBottomLabel: "Scroll to bottom",
11136
+ chatConnectingLabel: "Loading conversation",
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(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: 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: 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 TranscriptionErrorCode.RATE_LIMITED: return "transcriptionErrorRateLimitedText";
12118
+ case TranscriptionErrorCode.AUTH_FAILED: return "transcriptionErrorAuthFailedText";
12119
+ case TranscriptionErrorCode.AUDIO_TOO_LONG: return "transcriptionErrorAudioTooLongText";
12120
+ case TranscriptionErrorCode.AUDIO_TOO_SHORT: return "transcriptionErrorAudioTooShortText";
12121
+ case TranscriptionErrorCode.INVALID_AUDIO_FORMAT: return "transcriptionErrorInvalidAudioFormatText";
12122
+ case TranscriptionErrorCode.SERVICE_NOT_CONFIGURED: return "transcriptionErrorServiceNotConfiguredText";
12123
+ case TranscriptionErrorCode.NETWORK_ERROR: return "transcriptionErrorNetworkText";
12124
+ case TranscriptionErrorCode.PROVIDER_ERROR:
12125
+ case TranscriptionErrorCode.INVALID_REQUEST:
12126
+ default: return error.retryable ? "transcriptionErrorGenericText" : null;
12127
+ }
12128
+ }
12129
+ function toFormData(audioBlob, filename) {
12130
+ const formData = new FormData();
12131
+ formData.append("audio", audioBlob, filename);
12132
+ return formData;
12133
+ }
12134
+ function omitContentType(headers) {
12135
+ const entries = Object.entries(headers);
12136
+ return Object.fromEntries(entries.filter(([name]) => name.toLowerCase() !== "content-type"));
12137
+ }
12138
+ async function blobToBase64(blob) {
12139
+ const bytes = new Uint8Array(await blob.arrayBuffer());
12140
+ const chunkSize = 32768;
12141
+ let binary = "";
12142
+ for (let offset = 0; offset < bytes.length; offset += chunkSize) binary += String.fromCharCode(...bytes.subarray(offset, offset + chunkSize));
12143
+ return btoa(binary);
12144
+ }
12145
+ /** Build a typed error from a non-OK transcription response. */
12146
+ async function toTranscriptionError(response) {
12147
+ const retryable = response.status >= 500;
12148
+ let data;
12149
+ try {
12150
+ data = await response.json();
12151
+ } catch {
12152
+ return new TranscriptionError({
12153
+ code: TranscriptionErrorCode.PROVIDER_ERROR,
12154
+ message: `HTTP ${response.status}: ${response.statusText}`,
12155
+ retryable
12156
+ });
12157
+ }
12158
+ if (isTranscriptionErrorResponse(data)) return new TranscriptionError({
12159
+ code: data.error,
12160
+ message: data.message,
12161
+ retryable: data.retryable ?? false
12162
+ });
12163
+ const message = typeof data === "object" && data !== null && "message" in data ? String(data.message) : "Transcription failed";
12164
+ return new TranscriptionError({
12165
+ code: TranscriptionErrorCode.PROVIDER_ERROR,
12166
+ message,
12167
+ retryable
12168
+ });
12169
+ }
12170
+ function isTranscriptionErrorResponse(data) {
12171
+ return typeof data === "object" && data !== null && "error" in data && "message" in data && typeof data.error === "string" && typeof data.message === "string";
12172
+ }
12173
+
12174
+ //#endregion
12175
+ //#region src/chat/license.ts
12176
+ /**
12177
+ * Resolves the license context and the license banner from the runtime
12178
+ * license authority. React, Vue, and Angular call it with the values core
12179
+ * reports, then show the banner and provide the context.
12180
+ *
12181
+ * Rules:
12182
+ *
12183
+ * - A retryable entitlement failure that core is still retrying hides the
12184
+ * status, so no banner shows until the retry ends. A `valid` or `expiring`
12185
+ * legacy status stays in use during the retry.
12186
+ * - A terminal entitlement failure (not retryable, no `valid` or `expiring`
12187
+ * legacy status) keeps the reported status, but `checkFeature` returns
12188
+ * `false` and `getLimit` returns `null` for every feature.
12189
+ * - The `no_license` banner shows only when the status is `none` and no
12190
+ * public key is set.
12191
+ *
12192
+ * The banner text has no day count. No data source gives the days left.
12193
+ *
12194
+ * @param input - The runtime license values and the public key. See
12195
+ * {@link LicenseStateInput}.
12196
+ * @returns `context` for the license context, `warningStatus` (the status the
12197
+ * banner is based on, `undefined` while a retry runs), and `bannerType`
12198
+ * (`null` when no banner shows).
12199
+ *
12200
+ * @example
12201
+ * ```ts
12202
+ * const { context, bannerType } = ɵresolveLicenseState({
12203
+ * status: core.licenseStatus,
12204
+ * entitlements: core.runtimeEntitlements,
12205
+ * retryPending: core.runtimeEntitlementRetryPending,
12206
+ * publicKey,
12207
+ * });
12208
+ * ```
12209
+ */
12210
+ function ɵresolveLicenseState({ status, entitlements, retryPending, publicKey }) {
12211
+ const isRetryableFailure = entitlements?.status !== "ready" && entitlements?.error.retryable === true;
12212
+ const isNonReady = entitlements !== void 0 && entitlements.status !== "ready";
12213
+ const hasLegacyFallback = status === "valid" || status === "expiring";
12214
+ const isRetrying = isRetryableFailure && retryPending && !hasLegacyFallback;
12215
+ const isTerminalFailure = isNonReady && !isRetryableFailure && !hasLegacyFallback;
12216
+ const runtimeContext = createLicenseContextValue(isRetrying ? void 0 : status, entitlements);
12217
+ const context = isTerminalFailure ? {
12218
+ ...runtimeContext,
12219
+ checkFeature: () => false,
12220
+ getLimit: () => null
12221
+ } : runtimeContext;
12222
+ const warningStatus = isRetrying ? void 0 : context.status ?? void 0;
12223
+ return {
12224
+ context,
12225
+ warningStatus,
12226
+ bannerType: resolveLicenseBannerType(warningStatus, publicKey)
12227
+ };
12228
+ }
12229
+ function resolveLicenseBannerType(warningStatus, publicKey) {
12230
+ switch (warningStatus) {
12231
+ case "none": return publicKey ? null : "no_license";
12232
+ case "expired":
12233
+ case "invalid":
12234
+ case "expiring": return warningStatus;
12235
+ case "valid":
12236
+ case "unknown":
12237
+ case void 0: return null;
12238
+ }
12239
+ }
12240
+ /**
12241
+ * Resolves whether the threads drawer can load its thread list.
12242
+ *
12243
+ * - `licensed` is `true` when the status is `unknown` (an entitlement lookup
12244
+ * that did not recover, so the threads endpoint decides), or when the
12245
+ * status is `valid` or `expiring` and `checkFeature("threads")` is `true`.
12246
+ * - `licensePending` is `true` while the status is `null` (the runtime has
12247
+ * not reported yet). Show the loading state then, not the locked view.
12248
+ *
12249
+ * @param context - The license context from {@link ɵresolveLicenseState}.
12250
+ *
12251
+ * @example
12252
+ * ```ts
12253
+ * const { licensed, licensePending } = ɵresolveThreadsLicense(context);
12254
+ * ```
12255
+ */
12256
+ function ɵresolveThreadsLicense(context) {
12257
+ const { status } = context;
12258
+ return {
12259
+ licensed: status === "unknown" || (status === "valid" || status === "expiring") && context.checkFeature("threads"),
12260
+ licensePending: status === null
12261
+ };
12262
+ }
12263
+ const PRICING_URL = "https://copilotkit.ai/pricing";
12264
+ const DASHBOARD_URL = "https://dashboard.operations.copilotkit.ai";
12265
+ /**
12266
+ * What one license banner shows: its severity, text, and link. React, Vue,
12267
+ * and Angular render it with {@link ɵLICENSE_BANNER_STYLE}.
12268
+ *
12269
+ * @param type - The banner type, for example from
12270
+ * {@link ɵresolveLicenseState}'s `bannerType`.
12271
+ * @param labels - The chat labels in effect, so apps can translate the text.
12272
+ * @param details - The feature name, expiry date, or days left.
12273
+ *
12274
+ * @example
12275
+ * ```ts
12276
+ * const spec = ɵgetLicenseBannerSpec("expiring", labels, { graceRemaining: 3 });
12277
+ * // { severity: "warning", message: "… expires in 3 days …", actionLabel: "Renew", … }
12278
+ * ```
12279
+ */
12280
+ function ɵgetLicenseBannerSpec(type, labels, { featureName, expiryDate, graceRemaining } = {}) {
12281
+ switch (type) {
12282
+ case "no_license": return bannerSpec("info", labels.licensePoweredByText, labels.licenseGetLicenseLabel, PRICING_URL);
12283
+ case "feature_unlicensed": return bannerSpec("warning", ɵformatLabel(labels.licenseFeatureUnlicensedText, { feature: featureName ?? "" }), labels.licenseGetLicenseLabel, PRICING_URL);
12284
+ case "expiring": return bannerSpec("warning", expiringMessage(labels, graceRemaining), labels.licenseRenewLabel, DASHBOARD_URL);
12285
+ case "expired": return bannerSpec("critical", expiryDate ? ɵformatLabel(labels.licenseExpiredOnDateText, { date: expiryDate }) : labels.licenseExpiredText, labels.licenseRenewNowLabel, PRICING_URL);
12286
+ case "invalid": return bannerSpec("critical", labels.licenseInvalidText, labels.licenseGetLicenseLabel, PRICING_URL);
12287
+ }
12288
+ }
12289
+ const bannerSpec = (severity, message, actionLabel, actionUrl) => ({
12290
+ severity,
12291
+ message,
12292
+ actionLabel,
12293
+ actionUrl
12294
+ });
12295
+ /**
12296
+ * The "expires soon" text. Without a day count it says "soon", never "in
12297
+ * undefined days".
12298
+ */
12299
+ function expiringMessage(labels, graceRemaining) {
12300
+ if (graceRemaining === void 0) return labels.licenseExpiringText;
12301
+ return ɵformatLabel(graceRemaining === 1 ? labels.licenseExpiringInDaysOne : labels.licenseExpiringInDaysOther, { days: graceRemaining });
12302
+ }
12303
+ const FONT_FAMILY = "-apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif";
12304
+ /**
12305
+ * Inline styles of the fixed license banner, in camelCase, for React `style`
12306
+ * and Vue `:style`. `base` is the layout; `severity` holds the colours.
12307
+ */
12308
+ const ɵLICENSE_BANNER_STYLE = {
12309
+ base: {
12310
+ position: "fixed",
12311
+ bottom: "8px",
12312
+ left: "50%",
12313
+ transform: "translateX(-50%)",
12314
+ zIndex: 99999,
12315
+ display: "inline-flex",
12316
+ alignItems: "center",
12317
+ gap: "12px",
12318
+ whiteSpace: "nowrap",
12319
+ padding: "8px 16px",
12320
+ fontSize: "13px",
12321
+ fontFamily: FONT_FAMILY,
12322
+ borderRadius: "6px",
12323
+ boxShadow: "0 2px 8px rgba(0, 0, 0, 0.15)"
12324
+ },
12325
+ severity: {
12326
+ info: {
12327
+ backgroundColor: "#eff6ff",
12328
+ border: "1px solid #93c5fd",
12329
+ color: "#1e40af"
12330
+ },
12331
+ warning: {
12332
+ backgroundColor: "#fffbeb",
12333
+ border: "1px solid #fbbf24",
12334
+ color: "#92400e"
12335
+ },
12336
+ critical: {
12337
+ backgroundColor: "#fef2f2",
12338
+ border: "1px solid #fca5a5",
12339
+ color: "#991b1b"
12340
+ }
12341
+ },
12342
+ actions: {
12343
+ display: "flex",
12344
+ gap: "8px",
12345
+ alignItems: "center"
12346
+ },
12347
+ link: {
12348
+ fontWeight: 600,
12349
+ textDecoration: "underline",
12350
+ color: "inherit"
12351
+ },
12352
+ dismiss: {
12353
+ background: "none",
12354
+ border: "none",
12355
+ cursor: "pointer",
12356
+ color: "inherit",
12357
+ fontSize: "16px"
12358
+ }
12359
+ };
12360
+ /**
12361
+ * The bottom space the fixed banner takes: banner height (~36px) + bottom
12362
+ * offset (8px) + gap above the chat input (~8px). The chat input reads it
12363
+ * through `padding-bottom: var(--copilotkit-license-banner-offset)`.
12364
+ */
12365
+ const ɵLICENSE_BANNER_OFFSET = {
12366
+ cssVar: "--copilotkit-license-banner-offset",
12367
+ px: 52
12368
+ };
12369
+ /**
12370
+ * Publishes {@link ɵLICENSE_BANNER_OFFSET} on the root element while a
12371
+ * banner shows. Does nothing without a document (SSR).
12372
+ *
12373
+ * @returns A function that removes the offset again.
12374
+ */
12375
+ function ɵreserveLicenseBannerOffset() {
12376
+ if (typeof document === "undefined") return () => {};
12377
+ const root = document.documentElement;
12378
+ root.style.setProperty(ɵLICENSE_BANNER_OFFSET.cssVar, `${ɵLICENSE_BANNER_OFFSET.px}px`);
12379
+ return () => root.style.removeProperty(ɵLICENSE_BANNER_OFFSET.cssVar);
12380
+ }
12381
+ /**
12382
+ * What the inline warning shows when a chat component needs a license it
12383
+ * does not have: the `licenseFeatureUnlicensedText` label and a pricing
12384
+ * link. Render it with {@link ɵINLINE_FEATURE_WARNING_STYLE}.
12385
+ */
12386
+ function ɵgetInlineFeatureWarningSpec(featureName, labels) {
12387
+ return {
12388
+ message: ɵformatLabel(labels.licenseFeatureUnlicensedText, { feature: featureName }),
12389
+ actionLabel: "Get one at copilotkit.ai/pricing",
12390
+ actionUrl: PRICING_URL
12391
+ };
12392
+ }
12393
+ /** Inline styles of the inline feature warning, in camelCase. */
12394
+ const ɵINLINE_FEATURE_WARNING_STYLE = {
12395
+ container: {
12396
+ padding: "8px 12px",
12397
+ backgroundColor: "#fffbeb",
12398
+ border: "1px solid #fbbf24",
12399
+ borderRadius: "6px",
12400
+ fontSize: "13px",
12401
+ color: "#92400e",
12402
+ fontFamily: FONT_FAMILY
12403
+ },
12404
+ link: {
12405
+ color: "#b45309",
12406
+ textDecoration: "underline"
12407
+ }
12408
+ };
12409
+
12410
+ //#endregion
12411
+ //#region src/chat/icons.ts
12412
+ /*! @license
12413
+ * The icon data below is copied from Lucide v0.525.0 (https://lucide.dev).
12414
+ * The Lucide license follows. A copy is in LUCIDE-LICENSE.md next to this file.
12415
+ * This comment sits right above runtime code so the bundler keeps it in dist.
12416
+ *
12417
+ * ISC License
12418
+ *
12419
+ * 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.
12420
+ *
12421
+ * Permission to use, copy, modify, and/or distribute this software for any
12422
+ * purpose with or without fee is hereby granted, provided that the above
12423
+ * copyright notice and this permission notice appear in all copies.
12424
+ *
12425
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12426
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12427
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12428
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12429
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
12430
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
12431
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
12432
+ */
12433
+ function path(d) {
12434
+ return {
12435
+ tag: "path",
12436
+ attributes: { d }
12437
+ };
12438
+ }
12439
+ const icons = {
12440
+ ArrowUp: {
12441
+ name: "arrow-up",
12442
+ nodes: [path("m5 12 7-7 7 7"), path("M12 19V5")]
12443
+ },
12444
+ Check: {
12445
+ name: "check",
12446
+ nodes: [path("M20 6 9 17l-5-5")]
12447
+ },
12448
+ ChevronDown: {
12449
+ name: "chevron-down",
12450
+ nodes: [path("m6 9 6 6 6-6")]
12451
+ },
12452
+ ChevronLeft: {
12453
+ name: "chevron-left",
12454
+ nodes: [path("m15 18-6-6 6-6")]
12455
+ },
12456
+ ChevronRight: {
12457
+ name: "chevron-right",
12458
+ nodes: [path("m9 18 6-6-6-6")]
12459
+ },
12460
+ Circle: {
12461
+ name: "circle",
12462
+ nodes: [{
12463
+ tag: "circle",
12464
+ attributes: {
12465
+ cx: "12",
12466
+ cy: "12",
12467
+ r: "10"
12468
+ }
12469
+ }]
12470
+ },
12471
+ Copy: {
12472
+ name: "copy",
12473
+ nodes: [{
12474
+ tag: "rect",
12475
+ attributes: {
12476
+ width: "14",
12477
+ height: "14",
12478
+ x: "8",
12479
+ y: "8",
12480
+ rx: "2",
12481
+ ry: "2"
12482
+ }
12483
+ }, path("M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2")]
12484
+ },
12485
+ Edit: {
12486
+ name: "square-pen",
12487
+ 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")]
12488
+ },
12489
+ EyeOff: {
12490
+ name: "eye-off",
12491
+ nodes: [
12492
+ 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"),
12493
+ path("M14.084 14.158a3 3 0 0 1-4.242-4.242"),
12494
+ 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"),
12495
+ path("m2 2 20 20")
12496
+ ]
12497
+ },
12498
+ Loader2: {
12499
+ name: "loader-circle",
12500
+ nodes: [path("M21 12a9 9 0 1 1-6.219-8.56")]
12501
+ },
12502
+ MessageCircle: {
12503
+ name: "message-circle",
12504
+ nodes: [path("M7.9 20A9 9 0 1 0 4 16.1L2 22Z")]
12505
+ },
12506
+ Mic: {
12507
+ name: "mic",
12508
+ nodes: [
12509
+ path("M12 19v3"),
12510
+ path("M19 10v2a7 7 0 0 1-14 0v-2"),
12511
+ {
12512
+ tag: "rect",
12513
+ attributes: {
12514
+ x: "9",
12515
+ y: "2",
12516
+ width: "6",
12517
+ height: "13",
12518
+ rx: "3"
12519
+ }
12520
+ }
12521
+ ]
12522
+ },
12523
+ PanelLeftOpen: {
12524
+ name: "panel-left-open",
12525
+ nodes: [
12526
+ {
12527
+ tag: "rect",
12528
+ attributes: {
12529
+ width: "18",
12530
+ height: "18",
12531
+ x: "3",
12532
+ y: "3",
12533
+ rx: "2"
12534
+ }
12535
+ },
12536
+ path("M9 3v18"),
12537
+ path("m14 9 3 3-3 3")
12538
+ ]
12539
+ },
12540
+ Play: {
12541
+ name: "play",
12542
+ nodes: [{
12543
+ tag: "polygon",
12544
+ attributes: { points: "6 3 20 12 6 21 6 3" }
12545
+ }]
12546
+ },
12547
+ Plus: {
12548
+ name: "plus",
12549
+ nodes: [path("M5 12h14"), path("M12 5v14")]
12550
+ },
12551
+ RefreshCw: {
12552
+ name: "refresh-cw",
12553
+ nodes: [
12554
+ path("M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"),
12555
+ path("M21 3v5h-5"),
12556
+ path("M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"),
12557
+ path("M8 16H3v5")
12558
+ ]
12559
+ },
12560
+ Square: {
12561
+ name: "square",
12562
+ nodes: [{
12563
+ tag: "rect",
12564
+ attributes: {
12565
+ width: "18",
12566
+ height: "18",
12567
+ x: "3",
12568
+ y: "3",
12569
+ rx: "2"
12570
+ }
12571
+ }]
12572
+ },
12573
+ ThumbsDown: {
12574
+ name: "thumbs-down",
12575
+ 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")]
12576
+ },
12577
+ ThumbsUp: {
12578
+ name: "thumbs-up",
12579
+ 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")]
12580
+ },
12581
+ Upload: {
12582
+ name: "upload",
12583
+ nodes: [
12584
+ path("M12 3v12"),
12585
+ path("m17 8-5-5-5 5"),
12586
+ path("M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4")
12587
+ ]
12588
+ },
12589
+ Volume2: {
12590
+ name: "volume-2",
12591
+ nodes: [
12592
+ 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"),
12593
+ path("M16 9a5 5 0 0 1 0 6"),
12594
+ path("M19.364 18.364a9 9 0 0 0 0-12.728")
12595
+ ]
12596
+ },
12597
+ Wrench: {
12598
+ name: "wrench",
12599
+ 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")]
12600
+ },
12601
+ X: {
12602
+ name: "x",
12603
+ nodes: [path("M18 6 6 18"), path("m6 6 12 12")]
12604
+ }
12605
+ };
12606
+ /**
12607
+ * Internal. The SVG data for every icon the chat components draw.
12608
+ *
12609
+ * Each framework's `CopilotIcon` component reads an entry and draws it:
12610
+ *
12611
+ * ```ts
12612
+ * const { name, nodes } = ɵcopilotIcons.ArrowUp;
12613
+ * // <svg {...ɵcopilotIconSvgAttributes} class="lucide lucide-arrow-up">
12614
+ * // one child element per node: <{node.tag} {...node.attributes} />
12615
+ * // </svg>
12616
+ * ```
12617
+ */
12618
+ const ɵcopilotIcons = icons;
12619
+ /**
12620
+ * Internal. The attributes to put on the `<svg>` of every chat icon.
12621
+ *
12622
+ * These are Lucide's default attributes, so a drawn icon matches the Lucide
12623
+ * icon. Set `width` and `height` to change the size.
12624
+ */
12625
+ const ɵcopilotIconSvgAttributes = {
12626
+ xmlns: "http://www.w3.org/2000/svg",
12627
+ width: "24",
12628
+ height: "24",
12629
+ viewBox: "0 0 24 24",
12630
+ fill: "none",
12631
+ stroke: "currentColor",
12632
+ "stroke-width": "2",
12633
+ "stroke-linecap": "round",
12634
+ "stroke-linejoin": "round"
12635
+ };
12636
+
12637
+ //#endregion
12638
+ //#region src/chat/message-feedback.ts
12639
+ /** Trajectory event name for a rating of one assistant message. */
12640
+ const ɵMESSAGE_FEEDBACK_EVENT_NAME = "message.feedback";
12641
+ /** Longest comment kept, in characters; the rest is cut so the event stays small. */
12642
+ const ɵMESSAGE_FEEDBACK_MAX_COMMENT_LENGTH = 1e3;
12643
+ /** Longest excerpt of the rated response sent with the rating, in characters. */
12644
+ const RESPONSE_EXCERPT_LENGTH = 500;
12645
+ /**
12646
+ * How long the pointer may be away from the rating and its comment before the
12647
+ * comment closes: enough to cross the gap between them, short enough that
12648
+ * passing over a rating does not leave it open.
12649
+ */
12650
+ const ɵFEEDBACK_COMMENT_CLOSE_DELAY_MS = 150;
12651
+ const ratings = /* @__PURE__ */ new Map();
12652
+ const listeners = /* @__PURE__ */ new Map();
12653
+ const threadKey = (agentId, threadId) => JSON.stringify([agentId, threadId]);
12654
+ const messageKey = (agentId, threadId, messageId) => JSON.stringify([
12655
+ agentId,
12656
+ threadId,
12657
+ messageId
12658
+ ]);
12659
+ /** Cuts `text` to `max` characters without splitting a surrogate pair. */
12660
+ const clip = (text, max) => {
12661
+ const characters = Array.from(text);
12662
+ return characters.length > max ? characters.slice(0, max).join("") : text;
12663
+ };
12664
+ /** The comment as kept and sent: trimmed and capped, or none. */
12665
+ const normalizeComment = (comment) => {
12666
+ if (comment === void 0) return void 0;
12667
+ const text = clip(comment.trim(), ɵMESSAGE_FEEDBACK_MAX_COMMENT_LENGTH);
12668
+ return text === "" ? void 0 : text;
12669
+ };
12670
+ /** The rating this page gave one message, if any. */
12671
+ function ɵgetMessageFeedback(agentId, threadId, messageId) {
12672
+ return ratings.get(messageKey(agentId, threadId, messageId));
12673
+ }
12674
+ /** Calls `listener` whenever a rating in this Thread changes. */
12675
+ function ɵsubscribeToMessageFeedback(agentId, threadId, listener) {
12676
+ const key = threadKey(agentId, threadId);
12677
+ let set = listeners.get(key);
12678
+ if (set === void 0) {
12679
+ set = /* @__PURE__ */ new Set();
12680
+ listeners.set(key, set);
12681
+ }
12682
+ const subscribed = set;
12683
+ subscribed.add(listener);
12684
+ return () => {
12685
+ subscribed.delete(listener);
12686
+ if (subscribed.size === 0) listeners.delete(key);
12687
+ };
12688
+ }
12689
+ /**
12690
+ * Sets (or, with `null`, clears) this page's rating of one message and sends
12691
+ * it to the active Trajectory. Every change is a new event; the newest event
12692
+ * for a `feedbackId` is the current one. Like any Trajectory event, a change
12693
+ * made while no Trajectory captures, for example during a reconnect, is not
12694
+ * sent; the page still shows it.
12695
+ */
12696
+ function ɵsetMessageFeedback(params) {
12697
+ const { copilotkit, agentId, threadId, message } = params;
12698
+ const comment = normalizeComment(params.feedback?.comment);
12699
+ const feedback = params.feedback && {
12700
+ rating: params.feedback.rating,
12701
+ ...comment ? { comment } : {}
12702
+ };
12703
+ const key = messageKey(agentId, threadId, message.id);
12704
+ if (feedback) ratings.set(key, feedback);
12705
+ else ratings.delete(key);
12706
+ const threadListeners = listeners.get(threadKey(agentId, threadId)) ?? [];
12707
+ for (const listener of threadListeners) listener();
12708
+ const runId = copilotkit.getRunIdForMessage(agentId, threadId, message.id);
12709
+ copilotkit.emitTrajectoryEvent(ɵMESSAGE_FEEDBACK_EVENT_NAME, {
12710
+ feedbackId: `${threadId}:${message.id}`,
12711
+ threadId,
12712
+ messageId: message.id,
12713
+ agentId,
12714
+ ...runId ? { runId } : {},
12715
+ rating: feedback?.rating ?? null,
12716
+ ...feedback?.comment ? { comment: feedback.comment } : {},
12717
+ ...copilotkit.ɵlearningCapturesAgentText ? { response: clip(message.content ?? "", RESPONSE_EXCERPT_LENGTH) } : {}
12718
+ });
12719
+ }
12720
+ /** @internal Forgets every rating, so each test starts empty. */
12721
+ function ɵresetMessageFeedbackCache() {
12722
+ ratings.clear();
12723
+ }
12724
+ const capturedCores = /* @__PURE__ */ new WeakSet();
12725
+ const rememberCapture = (copilotkit) => {
12726
+ if (capturedCores.has(copilotkit)) return;
12727
+ capturedCores.add(copilotkit);
12728
+ const unsubscribe = copilotkit.ɵsubscribeToLearningConfigured(() => {
12729
+ if (copilotkit.ɵlearningConfigured) return;
12730
+ capturedCores.delete(copilotkit);
12731
+ unsubscribe();
12732
+ });
12733
+ };
12734
+ /**
12735
+ * Whether the thumbs record feedback for Learning. True once a Trajectory of
12736
+ * this Core has started and as long as Learning stays configured, also while
12737
+ * capture reconnects or is stopped, so the buttons do not flicker. Ratings
12738
+ * given meanwhile still show but, like any Trajectory event, are not sent. A
12739
+ * capture that never starts (for example without a license) leaves it false.
12740
+ *
12741
+ * Re-read it when {@link ɵsubscribeToLearningFeedbackEnabled} notifies.
12742
+ */
12743
+ function ɵisLearningFeedbackEnabled(copilotkit) {
12744
+ const capturing = copilotkit.trajectoryId !== null;
12745
+ if (capturing) rememberCapture(copilotkit);
12746
+ return copilotkit.ɵlearningConfigured && (capturing || capturedCores.has(copilotkit));
12747
+ }
12748
+ /**
12749
+ * Calls `listener` when {@link ɵisLearningFeedbackEnabled} may have changed:
12750
+ * when Learning is configured or removed, and when the Trajectory changes.
12751
+ * Returns the unsubscribe function.
12752
+ */
12753
+ function ɵsubscribeToLearningFeedbackEnabled(copilotkit, listener) {
12754
+ const unsubscribeConfigured = copilotkit.ɵsubscribeToLearningConfigured(listener);
12755
+ const subscription = copilotkit.subscribe({ onTrajectoryChanged: listener });
12756
+ return () => {
12757
+ unsubscribeConfigured();
12758
+ subscription.unsubscribe();
12759
+ };
12760
+ }
12761
+ /**
12762
+ * The feedback this page gave `message` in `scope`, and how to change it.
12763
+ * Read it again when {@link ɵsubscribeToMessageFeedback} notifies for the
12764
+ * scope's Thread.
12765
+ */
12766
+ function ɵgetMessageFeedbackControls(scope, message) {
12767
+ const feedback = ɵgetMessageFeedback(scope.agentId, scope.threadId, message.id);
12768
+ const save = (next) => ɵsetMessageFeedback({
12769
+ ...scope,
12770
+ message,
12771
+ feedback: next
12772
+ });
12773
+ return {
12774
+ feedback,
12775
+ rate: (rating) => {
12776
+ if (feedback?.rating !== rating) save({ rating });
12777
+ },
12778
+ clear: () => {
12779
+ if (feedback) save(null);
12780
+ },
12781
+ comment: (comment) => {
12782
+ if (feedback) save({
12783
+ rating: feedback.rating,
12784
+ comment
12785
+ });
12786
+ }
12787
+ };
12788
+ }
12789
+ /**
12790
+ * Drives the comment popover of a rated message.
12791
+ *
12792
+ * It opens when a rating is given and whenever the pointer or keyboard focus
12793
+ * reaches the chosen thumb, with the saved comment in the field. It closes by
12794
+ * itself shortly after the pointer leaves the thumb and the popover, unless
12795
+ * focus is in the field: then it stays until focus moves away, Enter, or
12796
+ * Escape. Closing saves a changed comment; Escape, a click on a thumb, and
12797
+ * removing the rating discard it.
12798
+ *
12799
+ * Frameworks render from `getSnapshot()` and re-render when `subscribe()`
12800
+ * notifies. Call `dispose()` on unmount: it keeps an unsaved edit, for a
12801
+ * message that scrolls out of a virtual list. The controller stays usable
12802
+ * after `dispose()`, so a remount (React Strict Mode) can keep it.
12803
+ *
12804
+ * @example
12805
+ * ```ts
12806
+ * const comment = new ɵFeedbackCommentController({ getControls: () => controls });
12807
+ * comment.subscribe(() => render(comment.getSnapshot()));
12808
+ * comment.show({ comment: "", focus: false });
12809
+ * // On unmount:
12810
+ * comment.dispose();
12811
+ * ```
12812
+ */
12813
+ var ɵFeedbackCommentController = class {
12814
+ #getControls;
12815
+ #closeDelayMs;
12816
+ #listeners = /* @__PURE__ */ new Set();
12817
+ #state = {
12818
+ open: false,
12819
+ draft: "",
12820
+ focusRequest: 0
12821
+ };
12822
+ #timer;
12823
+ #editing = false;
12824
+ #focusWaiting = false;
12825
+ #pointerOver = false;
12826
+ #returning = false;
12827
+ constructor(options) {
12828
+ this.#getControls = options.getControls;
12829
+ this.#closeDelayMs = options.closeDelayMs ?? ɵFEEDBACK_COMMENT_CLOSE_DELAY_MS;
12830
+ }
12831
+ /** The current state. The same object until something changes. */
12832
+ getSnapshot = () => this.#state;
12833
+ /** Calls `listener` when the state changes. Returns the unsubscribe function. */
12834
+ subscribe = (listener) => {
12835
+ this.#listeners.add(listener);
12836
+ return () => {
12837
+ this.#listeners.delete(listener);
12838
+ };
12839
+ };
12840
+ /** Sets the comment being edited. */
12841
+ setDraft = (draft) => {
12842
+ this.#update({ draft });
12843
+ };
12844
+ /** Whether a focus request waits; reading it answers the request. */
12845
+ takeFocusRequest = () => {
12846
+ const waiting = this.#focusWaiting;
12847
+ this.#focusWaiting = false;
12848
+ return waiting;
12849
+ };
12850
+ /** Opens with `comment` in the field. */
12851
+ show = ({ comment, focus }) => {
12852
+ this.#cancelClose();
12853
+ if (focus) this.#focusWaiting = true;
12854
+ this.#update({
12855
+ open: true,
12856
+ draft: comment,
12857
+ focusRequest: this.#state.focusRequest + (focus ? 1 : 0)
12858
+ });
12859
+ };
12860
+ /** The pointer or focus reached the rating or the popover. */
12861
+ enter = (via = "focus") => {
12862
+ this.#cancelClose();
12863
+ if (via === "pointer") this.#pointerOver = true;
12864
+ if (this.#returning) return;
12865
+ if (!this.#state.open && this.#getControls()?.feedback) this.show({
12866
+ comment: this.#savedComment(),
12867
+ focus: false
12868
+ });
12869
+ };
12870
+ /**
12871
+ * It left them: close soon, unless the user is editing the comment or, when
12872
+ * focus left, the pointer is still on the rating or the popover.
12873
+ */
12874
+ leave = (via = "focus") => {
12875
+ if (via === "pointer") this.#pointerOver = false;
12876
+ else if (this.#pointerOver) return;
12877
+ this.#cancelClose();
12878
+ this.#timer = setTimeout(() => {
12879
+ this.#timer = void 0;
12880
+ if (!this.#editing) this.close();
12881
+ }, this.#closeDelayMs);
12882
+ };
12883
+ /** Tracks whether focus is in the comment form. */
12884
+ setEditing = (editing) => {
12885
+ this.#editing = editing;
12886
+ };
12887
+ /** Closes, saving a changed comment unless `save` is false. */
12888
+ close = ({ save = true } = {}) => {
12889
+ this.#cancelClose();
12890
+ this.#focusWaiting = false;
12891
+ this.#pointerOver = false;
12892
+ if (!this.#state.open) return;
12893
+ if (save) this.#saveDraft();
12894
+ this.#editing = false;
12895
+ this.#update({ open: false });
12896
+ };
12897
+ /** Moves focus back to the thumb without opening the comment again. */
12898
+ returnFocus = (target) => {
12899
+ this.#returning = true;
12900
+ try {
12901
+ target?.focus();
12902
+ } finally {
12903
+ this.#returning = false;
12904
+ }
12905
+ };
12906
+ /** Stops the close timer and saves a changed comment that is still open. */
12907
+ dispose = () => {
12908
+ this.#cancelClose();
12909
+ if (this.#state.open) this.#saveDraft();
12910
+ };
12911
+ #savedComment() {
12912
+ return this.#getControls()?.feedback?.comment ?? "";
12913
+ }
12914
+ #saveDraft() {
12915
+ const controls = this.#getControls();
12916
+ const draft = this.#state.draft;
12917
+ if (controls?.feedback && draft.trim() !== this.#savedComment()) controls.comment(draft);
12918
+ }
12919
+ #cancelClose() {
12920
+ if (this.#timer === void 0) return;
12921
+ clearTimeout(this.#timer);
12922
+ this.#timer = void 0;
12923
+ }
12924
+ #update(patch) {
12925
+ const next = {
12926
+ ...this.#state,
12927
+ ...patch
12928
+ };
12929
+ if (next.open === this.#state.open && next.draft === this.#state.draft && next.focusRequest === this.#state.focusRequest) return;
12930
+ this.#state = next;
12931
+ for (const listener of this.#listeners) listener();
12932
+ }
12933
+ };
12934
+
12935
+ //#endregion
12936
+ //#region src/chat/viewport.ts
12937
+ const AUTO_SCROLL_MODES = [
12938
+ "pin-to-bottom",
12939
+ "pin-to-send",
12940
+ "none"
12941
+ ];
12942
+ const isAutoScrollMode = (value) => AUTO_SCROLL_MODES.includes(value);
12943
+ /**
12944
+ * Turns the `autoScroll` prop into a mode. `true` and a missing value mean
12945
+ * `"pin-to-bottom"`, `false` means `"none"`, and an unknown string falls back
12946
+ * to `"pin-to-bottom"`.
12947
+ */
12948
+ function ɵnormalizeAutoScroll(value) {
12949
+ if (value === false) return "none";
12950
+ if (value === void 0 || value === true) return "pin-to-bottom";
12951
+ return isAutoScrollMode(value) ? value : "pin-to-bottom";
12952
+ }
12953
+ /**
12954
+ * Media query for the mobile range, where the threads drawer and the chat
12955
+ * modal are mutually exclusive.
12956
+ */
12957
+ const ɵMOBILE_MAX_WIDTH_QUERY = "(max-width: 767px)";
12958
+ /** `window.matchMedia` for the mobile query, or `null` without a DOM. */
12959
+ const mobileMediaQuery = () => {
12960
+ return typeof window !== "undefined" && typeof window.matchMedia === "function" ? window.matchMedia(ɵMOBILE_MAX_WIDTH_QUERY) : null;
12961
+ };
12962
+ /**
12963
+ * Whether the viewport is in the mobile range (`<768px`). `false` during SSR
12964
+ * and where `window.matchMedia` is missing (some test runners and webviews).
12965
+ */
12966
+ function ɵisMobileViewport() {
12967
+ return mobileMediaQuery()?.matches ?? false;
12968
+ }
12969
+ /**
12970
+ * Calls `listener` with {@link ɵisMobileViewport} now and each time the
12971
+ * viewport enters or leaves the mobile range. Does nothing without
12972
+ * `window.matchMedia`. Returns the unsubscribe function.
12973
+ */
12974
+ function ɵwatchMobileViewport(listener) {
12975
+ const query = mobileMediaQuery();
12976
+ if (query === null) return () => {};
12977
+ const update = () => listener(query.matches);
12978
+ update();
12979
+ query.addEventListener("change", update);
12980
+ return () => query.removeEventListener("change", update);
12981
+ }
12982
+ /**
12983
+ * The on-screen keyboard is treated as open once it covers more than this
12984
+ * many pixels of the layout viewport.
12985
+ */
12986
+ const ɵKEYBOARD_OPEN_THRESHOLD_PX = 150;
12987
+ /**
12988
+ * Reads the keyboard state with the Visual Viewport API: the keyboard height
12989
+ * is `innerHeight - visualViewport.height`, clamped to 0. Without the API (or
12990
+ * during SSR) it reports a closed keyboard and the full window height.
12991
+ */
12992
+ function ɵreadKeyboardState() {
12993
+ if (typeof window === "undefined") return closedKeyboard(0);
12994
+ const visualViewport = window.visualViewport;
12995
+ if (!visualViewport) return closedKeyboard(window.innerHeight);
12996
+ const layoutHeight = window.innerHeight;
12997
+ const keyboardHeight = Math.max(0, layoutHeight - visualViewport.height);
12998
+ return {
12999
+ isKeyboardOpen: keyboardHeight > ɵKEYBOARD_OPEN_THRESHOLD_PX,
13000
+ keyboardHeight,
13001
+ availableHeight: visualViewport.height,
13002
+ viewportHeight: layoutHeight
13003
+ };
13004
+ }
13005
+ const closedKeyboard = (height) => ({
13006
+ isKeyboardOpen: false,
13007
+ keyboardHeight: 0,
13008
+ availableHeight: height,
13009
+ viewportHeight: height
13010
+ });
13011
+ /**
13012
+ * The state for the first render, before {@link ɵwatchKeyboardState} reads
13013
+ * the visual viewport: a closed keyboard over the full window height (0
13014
+ * during SSR).
13015
+ */
13016
+ function ɵinitialKeyboardState() {
13017
+ return closedKeyboard(typeof window === "undefined" ? 0 : window.innerHeight);
13018
+ }
13019
+ /**
13020
+ * Calls `listener` with {@link ɵreadKeyboardState} now and on each visual
13021
+ * viewport resize or scroll. Does nothing during SSR or without the Visual
13022
+ * Viewport API. Returns the unsubscribe function.
13023
+ */
13024
+ function ɵwatchKeyboardState(listener) {
13025
+ if (typeof window === "undefined") return () => {};
13026
+ const visualViewport = window.visualViewport;
13027
+ if (!visualViewport) return () => {};
13028
+ const update = () => listener(ɵreadKeyboardState());
13029
+ update();
13030
+ visualViewport.addEventListener("resize", update);
13031
+ visualViewport.addEventListener("scroll", update);
13032
+ return () => {
13033
+ visualViewport.removeEventListener("resize", update);
13034
+ visualViewport.removeEventListener("scroll", update);
13035
+ };
13036
+ }
13037
+ /** Escapes `id` for a CSS attribute selector, also without `CSS.escape`. */
13038
+ const escapeSelectorValue = (id) => typeof CSS !== "undefined" && typeof CSS.escape === "function" ? CSS.escape(id) : id.replace(/[!"#$%&'()*+,./:;<=>?@[\\\]^`{|}~]/g, "\\$&");
13039
+ /**
13040
+ * Offset of `el` from the top of `stopAt`'s content, including `stopAt`'s
13041
+ * scroll. Uses `getBoundingClientRect`, so it works for any CSS position.
13042
+ */
13043
+ const offsetTopWithin = (el, stopAt) => el.getBoundingClientRect().top - stopAt.getBoundingClientRect().top + stopAt.scrollTop;
13044
+ /**
13045
+ * Pins a sent message to the top of the chat: sizes the spacer so the
13046
+ * message bubble can scroll to `topOffset` from the viewport top, scrolls
13047
+ * there on the next frame, and then shrinks the spacer as the reply below
13048
+ * grows, so the bubble stays put.
13049
+ *
13050
+ * The message element's top padding is scrolled off-screen: the bubble, not
13051
+ * its padded box, is pinned. Does nothing when no element in `contentEl` has
13052
+ * `data-message-id` equal to `messageId`. Skips the scroll without
13053
+ * `requestAnimationFrame` and the spacer updates without `ResizeObserver`.
13054
+ *
13055
+ * @returns A function that cancels the scroll and stops the spacer updates.
13056
+ * It returns `false` when it cancelled a scroll that had not run yet, so the
13057
+ * caller can pin the same send again. React's StrictMode tears an effect
13058
+ * down before the next frame, so the first run never scrolls.
13059
+ *
13060
+ * @example
13061
+ * ```ts
13062
+ * const unpin = ɵpinMessageToTop({ scrollEl, contentEl, spacerEl, messageId });
13063
+ * // On the next send or on unmount:
13064
+ * unpin();
13065
+ * ```
13066
+ */
13067
+ function ɵpinMessageToTop({ scrollEl, contentEl, spacerEl, messageId, topOffset = 16 }) {
13068
+ const targetEl = contentEl.querySelector(`[data-message-id="${escapeSelectorValue(messageId)}"]`);
13069
+ if (!targetEl) return () => true;
13070
+ const viewportHeight = scrollEl.clientHeight;
13071
+ const userMessageHeight = targetEl.getBoundingClientRect().height;
13072
+ const paddingTop = parseFloat(getComputedStyle(targetEl).paddingTop) || 0;
13073
+ const bubbleHeight = Math.max(0, userMessageHeight - paddingTop);
13074
+ const spacerHeight = Math.max(0, viewportHeight - bubbleHeight - topOffset);
13075
+ spacerEl.style.height = `${spacerHeight}px`;
13076
+ let scrolled = false;
13077
+ const frame = typeof requestAnimationFrame === "function" ? requestAnimationFrame(() => {
13078
+ scrolled = true;
13079
+ const targetTop = offsetTopWithin(targetEl, scrollEl) + paddingTop - topOffset;
13080
+ scrollEl.scrollTo({
13081
+ top: Math.max(0, targetTop),
13082
+ behavior: "smooth"
13083
+ });
13084
+ }) : null;
13085
+ const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(() => {
13086
+ const consumedBelow = contentEl.getBoundingClientRect().height - offsetTopWithin(targetEl, contentEl) - userMessageHeight;
13087
+ const remaining = Math.max(0, spacerHeight - consumedBelow);
13088
+ spacerEl.style.height = `${remaining}px`;
13089
+ });
13090
+ observer?.observe(contentEl);
13091
+ return () => {
13092
+ if (frame !== null && typeof cancelAnimationFrame === "function") cancelAnimationFrame(frame);
13093
+ observer?.disconnect();
13094
+ return frame === null || scrolled;
13095
+ };
13096
+ }
13097
+
13098
+ //#endregion
13099
+ //#region src/chat/message-display.ts
13100
+ /**
13101
+ * How long the model reasoned, as label text: "a few seconds", "4 seconds",
13102
+ * "2 minutes", or "1m 5s".
13103
+ *
13104
+ * @param seconds - The elapsed time in seconds. It may have a fraction.
13105
+ * @param labels - The chat labels that hold the duration texts.
13106
+ */
13107
+ function ɵformatReasoningDurationLabel(seconds, labels) {
13108
+ const duration = formatReasoningDuration(seconds);
13109
+ switch (duration.unit) {
13110
+ case "fewSeconds": return labels.reasoningMessageDurationFewSeconds;
13111
+ case "seconds": return ɵformatLabel(labels.reasoningMessageDurationSeconds, { count: duration.seconds });
13112
+ case "minutes": return ɵformatCountLabel(duration.minutes, {
13113
+ one: labels.reasoningMessageDurationMinutesOne,
13114
+ other: labels.reasoningMessageDurationMinutesOther
13115
+ });
13116
+ case "minutesSeconds": return ɵformatLabel(labels.reasoningMessageDurationMinutesSeconds, {
13117
+ minutes: duration.minutes,
13118
+ seconds: duration.seconds
13119
+ });
13120
+ }
13121
+ }
13122
+ /**
13123
+ * The text of the work summary line at the top of a reply in the `"turn"`
13124
+ * tool-call display.
13125
+ *
13126
+ * - While working: `label` is "Working" and `detail` the live timer ("4s"),
13127
+ * or `null` when the elapsed time is not known.
13128
+ * - When done with a known time: `label` is "Worked for 9s" (at least 1s)
13129
+ * and `detail` the tool count ("7 tools").
13130
+ * - When done without a time: `label` is "Used 7 tools" and `detail` `null`.
13131
+ * - `failed` is "2 failed" when tool calls failed, otherwise `null`. It is
13132
+ * always `null` while working.
13133
+ */
13134
+ function ɵgetWorkSummaryText({ isWorking, calls, elapsedMs, workingSince, now, labels }) {
13135
+ if (isWorking) {
13136
+ const isTimed = elapsedMs !== void 0 && workingSince !== void 0;
13137
+ return {
13138
+ label: labels.workSummaryWorkingLabel,
13139
+ detail: isTimed ? formatWorkDuration(elapsedMs + Math.max(0, now - workingSince)) : null,
13140
+ failed: null
13141
+ };
13142
+ }
13143
+ const failedCount = countFailedToolCalls(calls);
13144
+ const failed = failedCount > 0 ? ɵformatLabel(labels.toolCallFailedCountLabel, { count: failedCount }) : null;
13145
+ if (elapsedMs === void 0) return {
13146
+ label: ɵformatCountLabel(calls.length, {
13147
+ one: labels.toolCallUsedToolsOne,
13148
+ other: labels.toolCallUsedToolsOther
13149
+ }),
13150
+ detail: null,
13151
+ failed
13152
+ };
13153
+ const duration = formatWorkDuration(Math.max(1e3, elapsedMs));
13154
+ return {
13155
+ label: ɵformatLabel(labels.workSummaryWorkedForLabel, { duration }),
13156
+ detail: ɵformatCountLabel(calls.length, {
13157
+ one: labels.toolCallToolCountOne,
13158
+ other: labels.toolCallToolCountOther
13159
+ }),
13160
+ failed
13161
+ };
13162
+ }
13163
+ /**
13164
+ * The text of a user message: the string content, or its text parts joined
13165
+ * by newlines. Parts that are not text, and malformed parts from untyped
13166
+ * data, add nothing.
13167
+ */
13168
+ function ɵflattenUserMessageContent(content) {
13169
+ if (!content) return "";
13170
+ if (typeof content === "string") return content;
13171
+ return content.map((part) => part?.type === "text" && typeof part.text === "string" ? part.text : "").filter((text) => text.length > 0).join("\n");
13172
+ }
13173
+ const isMediaPart = (part) => part?.type === "image" || part?.type === "audio" || part?.type === "video" || part?.type === "document";
13174
+ /** The image, audio, video, and document parts of a user message. */
13175
+ function ɵgetUserMessageMediaParts(content) {
13176
+ if (!content || typeof content === "string") return [];
13177
+ return content.filter(isMediaPart);
13178
+ }
13179
+ /** The file name stored in an attachment's `metadata.filename`, if any. */
13180
+ function ɵgetUserMessageMediaFilename(part) {
13181
+ const meta = part.metadata;
13182
+ return meta != null && typeof meta === "object" && "filename" in meta && typeof meta.filename === "string" ? meta.filename : void 0;
13183
+ }
13184
+ /**
13185
+ * Whether a user message shows its branch navigation and which arrows work.
13186
+ * It shows only with more than one branch and a switch handler: without the
13187
+ * handler the arrows would do nothing.
13188
+ */
13189
+ function ɵgetBranchNavState({ branchIndex, numberOfBranches, canSwitch }) {
13190
+ const show = canSwitch && numberOfBranches > 1;
13191
+ return {
13192
+ show,
13193
+ canGoPrev: show && branchIndex > 0,
13194
+ canGoNext: show && branchIndex < numberOfBranches - 1
13195
+ };
13196
+ }
13197
+ /** Whether an assistant message has text beyond whitespace. */
13198
+ function ɵhasAssistantMessageText(content) {
13199
+ return !!content && content.trim().length > 0;
13200
+ }
13201
+ /**
13202
+ * Whether an assistant message shows its toolbar: when toolbars are on, the
13203
+ * message has text or the Inspector shortcut shows, and the message is not
13204
+ * the one still streaming (the latest while the agent runs).
13205
+ */
13206
+ function ɵshouldShowAssistantToolbar({ toolbarVisible, hasContent, showInspectorShortcut, isRunning, isLatest }) {
13207
+ return toolbarVisible && (hasContent || showInspectorShortcut) && !(isRunning && isLatest);
13208
+ }
13209
+ /** How long a copy button shows its "copied" check mark, in ms. */
13210
+ const ɵCOPY_FEEDBACK_RESET_MS = 2e3;
13211
+ /**
13212
+ * The "copied" state of a copy button. After a copy it is `true` for
13213
+ * {@link ɵCOPY_FEEDBACK_RESET_MS}; another copy in that time restarts the
13214
+ * wait, so rapid clicks do not flicker.
13215
+ *
13216
+ * Frameworks render from `getSnapshot()` and re-render when `subscribe()`
13217
+ * notifies. Call `dispose()` on unmount. The controller stays usable after
13218
+ * `dispose()`, so a remount (React Strict Mode) can keep it.
13219
+ *
13220
+ * @example
13221
+ * ```ts
13222
+ * const feedback = new ɵCopyFeedback();
13223
+ * feedback.subscribe(() => render(feedback.getSnapshot()));
13224
+ * await feedback.copy(text);
13225
+ * ```
13226
+ */
13227
+ var ɵCopyFeedback = class {
13228
+ #listeners = /* @__PURE__ */ new Set();
13229
+ #resetMs;
13230
+ #copied = false;
13231
+ #timer;
13232
+ constructor({ resetMs = ɵCOPY_FEEDBACK_RESET_MS } = {}) {
13233
+ this.#resetMs = resetMs;
13234
+ }
13235
+ /** Whether the check mark shows. */
13236
+ getSnapshot = () => this.#copied;
13237
+ /** Calls `listener` when the state changes. Returns the unsubscribe function. */
13238
+ subscribe = (listener) => {
13239
+ this.#listeners.add(listener);
13240
+ return () => {
13241
+ this.#listeners.delete(listener);
13242
+ };
13243
+ };
13244
+ /** Shows the check mark, or keeps it for the full time again. */
13245
+ markCopied = () => {
13246
+ this.#clearTimer();
13247
+ this.#set(true);
13248
+ this.#timer = setTimeout(() => {
13249
+ this.#timer = void 0;
13250
+ this.#set(false);
13251
+ }, this.#resetMs);
13252
+ };
13253
+ /**
13254
+ * Copies `text` to the clipboard and shows the check mark on success.
13255
+ * Empty text copies nothing.
13256
+ *
13257
+ * @returns Whether the text was copied.
13258
+ */
13259
+ copy = async (text) => {
13260
+ if (!text) return false;
13261
+ const copied = await copyToClipboard(text);
13262
+ if (copied) this.markCopied();
13263
+ return copied;
13264
+ };
13265
+ /** Stops the reset timer. */
13266
+ dispose = () => {
13267
+ this.#clearTimer();
13268
+ };
13269
+ #clearTimer() {
13270
+ if (this.#timer === void 0) return;
13271
+ clearTimeout(this.#timer);
13272
+ this.#timer = void 0;
13273
+ }
13274
+ #set(copied) {
13275
+ if (copied === this.#copied) return;
13276
+ this.#copied = copied;
13277
+ for (const listener of this.#listeners) listener();
13278
+ }
13279
+ };
13280
+
13281
+ //#endregion
13282
+ //#region src/chat/inspector-button.ts
13283
+ let shortcutsHidden = false;
13284
+ const shortcutListeners = /* @__PURE__ */ new Set();
13285
+ const notifyShortcutListeners = () => {
13286
+ for (const listener of shortcutListeners) listener();
13287
+ };
13288
+ /**
13289
+ * Whether the user hid the Inspector shortcuts in the message toolbars
13290
+ * ("Hide this icon"). It lasts until the page reloads and applies to every
13291
+ * chat on the page.
13292
+ *
13293
+ * @example
13294
+ * ```ts
13295
+ * ɵinspectorShortcuts.subscribe(() => render(ɵinspectorShortcuts.hidden));
13296
+ * ɵinspectorShortcuts.hide();
13297
+ * ```
13298
+ */
13299
+ const ɵinspectorShortcuts = {
13300
+ get hidden() {
13301
+ return shortcutsHidden;
13302
+ },
13303
+ hide() {
13304
+ if (shortcutsHidden) return;
13305
+ shortcutsHidden = true;
13306
+ notifyShortcutListeners();
13307
+ },
13308
+ subscribe(listener) {
13309
+ shortcutListeners.add(listener);
13310
+ return () => {
13311
+ shortcutListeners.delete(listener);
13312
+ };
13313
+ },
13314
+ reset() {
13315
+ if (!shortcutsHidden) return;
13316
+ shortcutsHidden = false;
13317
+ notifyShortcutListeners();
13318
+ }
13319
+ };
13320
+ const kiteStroke = (d, stroke, strokeWidth) => ({
13321
+ d,
13322
+ stroke,
13323
+ strokeWidth,
13324
+ strokeLinecap: "round"
13325
+ });
13326
+ /**
13327
+ * The Inspector kite artwork as data, as in
13328
+ * `web-inspector/src/assets/inspector-logo-kite.svg`. Render an `<svg>` with
13329
+ * `viewBox` and `fill="none"`, one `<path>` per entry of `paths`, and a
13330
+ * `<linearGradient gradientUnits="userSpaceOnUse">` per entry of `gradients`
13331
+ * in `<defs>`. Give each gradient the id `${prefix}-${gradient.id}` with a
13332
+ * prefix unique to the icon, and fill paths with
13333
+ * {@link ɵinspectorKiteFill}.
13334
+ */
13335
+ const ɵinspectorKiteIcon = {
13336
+ viewBox: "4.57 3.36 17.8 17.8",
13337
+ paths: [
13338
+ {
13339
+ d: "M6.36084 10.9855C8.34277 8.393 9.98843 5.82939 10.6204 3.75914C10.6382 3.70281 10.7043 3.67888 10.7534 3.7114C12.9536 5.16894 16.9635 6.12833 20.5086 6.15085C20.5703 6.15124 20.6124 6.2114 20.5895 6.26829C19.4109 9.25938 17.9705 14.6189 17.9148 20.7392C17.9148 20.8301 17.7873 20.8627 17.7419 20.7837C15.7236 17.2522 9.26021 12.2898 6.39414 11.1186C6.34112 11.0968 6.32556 11.0313 6.36084 10.9855Z",
13340
+ fillGradient: "paint0_linear"
13341
+ },
13342
+ {
13343
+ d: "M13.0475 9.39974C9.95016 10.3806 7.11935 10.9259 6.44331 11.0498C6.40027 11.0577 6.39115 11.1172 6.43152 11.134C9.3203 12.3347 15.7516 17.2826 17.7511 20.7998C17.7551 20.8075 17.7647 20.8103 17.7728 20.8068C17.7809 20.803 17.7853 20.793 17.7819 20.7844L13.0475 9.39974Z",
13344
+ fillGradient: "paint1_linear"
13345
+ },
13346
+ {
13347
+ d: "M10.762 3.705C13.4137 5.15161 16.4787 5.80132 20.545 6.14367C20.5703 6.14585 20.5787 6.18008 20.5557 6.19197C20.0359 6.45923 17.0574 7.97512 14.8455 8.78701C14.2524 9.00453 13.6564 9.20632 13.0692 9.39249C13.0562 9.39656 13.0419 9.39015 13.0369 9.37774L10.7005 3.75979C10.6849 3.72196 10.7257 3.68538 10.762 3.705Z",
13348
+ fillGradient: "paint2_linear"
13349
+ },
13350
+ kiteStroke("M10.7145 3.79041L17.8305 20.7659", "#513C9F", "0.17284"),
13351
+ kiteStroke("M6.44531 11.0476C6.44531 11.0476 10.375 10.3422 14.0686 9.06804C17.7623 7.7939 20.5122 6.23373 20.5122 6.23373", "#513C9F", "0.17284"),
13352
+ kiteStroke("M11.6914 5.93518L9.05534 14.7068M9.05534 14.7068H15.3203M9.05534 14.7068L0.15625 26.3646", "#ABABAB", "0.302474"),
13353
+ {
13354
+ d: "M6.02539 23.9646L4.85806 24.1287C5.46272 25.7287 6.70381 26.4276 8.18528 26.4276C11.8147 26.4276 10.707 22.3227 12.8103 22.3227C14.3358 22.3227 13.7155 25.6498 16.9992 25.6498C19.0029 25.6498 19.2028 23.631 18.8607 22.7625C18.8589 22.7572 18.8568 22.7524 18.8538 22.7476L18.3166 21.9253C18.2817 21.8706 18.1968 21.8912 18.1907 21.9562L18.0908 22.9529C18.0838 23.0222 18.0857 23.0913 18.0936 23.1605C18.1764 23.8491 18.2291 25.5202 16.9992 25.5202C15.7015 25.5202 15.3895 22.2362 12.8103 22.2362C9.78393 22.2362 10.1726 26.298 8.31487 26.298C7.08938 26.298 6.15447 24.9153 6.02539 23.9646Z",
13355
+ fillGradient: "paint3_linear"
13356
+ }
13357
+ ],
13358
+ gradients: [
13359
+ {
13360
+ id: "paint0_linear",
13361
+ x1: "15.5372",
13362
+ y1: "5.0278",
13363
+ x2: "12.0802",
13364
+ y2: "14.534",
13365
+ stops: [{ color: "#6430AB" }, {
13366
+ offset: "1",
13367
+ color: "#AA89D8"
13368
+ }]
13369
+ },
13370
+ {
13371
+ id: "paint1_linear",
13372
+ x1: "12.8583",
13373
+ y1: "10.3858",
13374
+ x2: "8.40764",
13375
+ y2: "18.9846",
13376
+ stops: [{ color: "#005DBB" }, {
13377
+ offset: "1",
13378
+ color: "#3D92E8"
13379
+ }]
13380
+ },
13381
+ {
13382
+ id: "paint2_linear",
13383
+ x1: "14.8452",
13384
+ y1: "5.02774",
13385
+ x2: "13.5047",
13386
+ y2: "9.21911",
13387
+ stops: [{ color: "#1B70C4" }, {
13388
+ offset: "1",
13389
+ color: "#54A4F2"
13390
+ }]
13391
+ },
13392
+ {
13393
+ id: "paint3_linear",
13394
+ x1: "4.85806",
13395
+ y1: "24.2455",
13396
+ x2: "18.9963",
13397
+ y2: "24.2455",
13398
+ stops: [
13399
+ { color: "#4497EA" },
13400
+ {
13401
+ offset: "0.254755",
13402
+ color: "#1463B2"
13403
+ },
13404
+ {
13405
+ offset: "0.498725",
13406
+ color: "#0A437D"
13407
+ },
13408
+ {
13409
+ offset: "0.666667",
13410
+ color: "#2476C8"
13411
+ },
13412
+ {
13413
+ offset: "0.972542",
13414
+ color: "#0C549A"
13415
+ }
13416
+ ]
13417
+ }
13418
+ ]
13419
+ };
13420
+ /**
13421
+ * The `fill` of a kite path: its gradient under the icon's id `prefix`, or
13422
+ * `undefined` for a stroke-only path.
13423
+ */
13424
+ function ɵinspectorKiteFill(prefix, path) {
13425
+ return path.fillGradient === void 0 ? void 0 : `url(#${prefix}-${path.fillGradient})`;
13426
+ }
13427
+ /** How long a hover-opened menu stays after the pointer leaves, in ms. */
13428
+ const ɵHOVER_MENU_CLOSE_DELAY_MS = 180;
13429
+ /**
13430
+ * The open state of a menu that opens when the pointer reaches its trigger,
13431
+ * like the Inspector shortcut's menu.
13432
+ *
13433
+ * - A mouse or pen over the trigger opens it; touch does not.
13434
+ * - Leaving the trigger or the menu closes it after `closeDelayMs`, unless
13435
+ * the pointer comes back first or the keyboard has used the menu since.
13436
+ * - Opening reads whether the trigger is inside a `.dark` element, so a menu
13437
+ * in a portal can match the theme.
13438
+ *
13439
+ * Frameworks render from `getSnapshot()` and re-render when `subscribe()`
13440
+ * notifies. Call `dispose()` on unmount; the controller stays usable.
13441
+ */
13442
+ var ɵHoverMenuController = class {
13443
+ #closeDelayMs;
13444
+ #listeners = /* @__PURE__ */ new Set();
13445
+ #state = {
13446
+ open: false,
13447
+ dark: false
13448
+ };
13449
+ #timer;
13450
+ #openedByHover = false;
13451
+ constructor({ closeDelayMs = ɵHOVER_MENU_CLOSE_DELAY_MS } = {}) {
13452
+ this.#closeDelayMs = closeDelayMs;
13453
+ }
13454
+ /** The current state. The same object until something changes. */
13455
+ getSnapshot = () => this.#state;
13456
+ /** Calls `listener` when the state changes. Returns the unsubscribe function. */
13457
+ subscribe = (listener) => {
13458
+ this.#listeners.add(listener);
13459
+ return () => {
13460
+ this.#listeners.delete(listener);
13461
+ };
13462
+ };
13463
+ /** Whether the pointer opened the menu and the keyboard has not used it. */
13464
+ get openedByHover() {
13465
+ return this.#openedByHover;
13466
+ }
13467
+ /**
13468
+ * Opens or closes the menu and stops a pending close. `trigger` is read on
13469
+ * open for the dark theme.
13470
+ */
13471
+ setOpen = (open, trigger) => {
13472
+ this.cancelClose();
13473
+ const dark = open ? !!trigger?.closest(".dark") : this.#state.dark;
13474
+ if (open === this.#state.open && dark === this.#state.dark) return;
13475
+ this.#state = {
13476
+ open,
13477
+ dark
13478
+ };
13479
+ for (const listener of this.#listeners) listener();
13480
+ };
13481
+ /** The pointer reached the trigger: opens, except for touch or disabled. */
13482
+ pointerEnter = ({ pointerType, disabled = false, trigger }) => {
13483
+ if (disabled || pointerType === "touch") return;
13484
+ this.#openedByHover = true;
13485
+ this.setOpen(true, trigger);
13486
+ };
13487
+ /** The keyboard used the trigger or the menu: keep it open on leave. */
13488
+ keyboardUsed = () => {
13489
+ this.#openedByHover = false;
13490
+ };
13491
+ /** The pointer left the trigger or the menu: close soon if hover opened it. */
13492
+ scheduleClose = () => {
13493
+ this.cancelClose();
13494
+ this.#timer = setTimeout(() => {
13495
+ this.#timer = void 0;
13496
+ if (this.#openedByHover) this.setOpen(false);
13497
+ }, this.#closeDelayMs);
13498
+ };
13499
+ /** The pointer came back: keep the menu open. */
13500
+ cancelClose = () => {
13501
+ if (this.#timer === void 0) return;
13502
+ clearTimeout(this.#timer);
13503
+ this.#timer = void 0;
13504
+ };
13505
+ /** Stops a pending close. */
13506
+ dispose = () => {
13507
+ this.cancelClose();
13508
+ };
13509
+ };
13510
+
13511
+ //#endregion
13512
+ //#region src/open-generative-ui/content.ts
13513
+ /**
13514
+ * Open Generative UI content: the activity the agent streams while it
13515
+ * generates a sandboxed UI, and the rules for when a new snapshot must reach
13516
+ * the sandbox at once.
13517
+ */
13518
+ /** The activity type of Open Generative UI messages. */
13519
+ const OPEN_GENERATIVE_UI_ACTIVITY_TYPE = "open-generative-ui";
13520
+ /** The name of the frontend tool the agent calls to generate a sandboxed UI. */
13521
+ const GENERATE_SANDBOXED_UI_TOOL_NAME = "generateSandboxedUi";
13522
+ /** The design guidance sent to the agent when no `designSkill` is set. */
13523
+ const DEFAULT_OPEN_GENERATIVE_UI_DESIGN_SKILL = `When generating UI with generateSandboxedUi, follow these design principles inspired by shadcn/ui:
13524
+
13525
+ - Use a minimal, flat aesthetic. Avoid drop shadows and gradients — rely on subtle borders (1px solid, light gray like #e5e7eb) to define surfaces.
13526
+ - Neutral base palette: white backgrounds, zinc/slate gray text (#09090b for headings, #71717a for secondary text). One accent color for interactive elements.
13527
+ - Use system font stacks (system-ui, -apple-system, sans-serif) at readable sizes (14px body, 600 weight for headings). Tight line-heights.
13528
+ - Small, consistent border-radius (6–8px). Cards and containers use border, not shadow, for separation.
13529
+ - Buttons: solid fill for primary (dark bg, white text), outline for secondary (border + transparent bg). Subtle hover state (slight opacity or background shift).
13530
+ - Use CSS Grid or Flexbox for layout. Ensure the UI looks good at any width.
13531
+ - Minimal transitions (150ms) for hover/focus states only. No decorative animations.
13532
+ - Keep the UI focused and dense — avoid excessive padding. Use compact spacing (8–12px gaps, 10–14px padding in controls).`;
13533
+ /** `true` when the content has HTML that a preview or final sandbox shows. */
13534
+ function hasRenderableContent(content) {
13535
+ if (!content) return false;
13536
+ const hasHtml = !!content.html?.join("").trim();
13537
+ const hasFinalHtml = content.htmlComplete && hasHtml;
13538
+ const hasPreviewHtml = content.cssComplete && !content.htmlComplete && hasHtml;
13539
+ return !!hasFinalHtml || !!hasPreviewHtml;
13540
+ }
13541
+ /**
13542
+ * `true` when `next` must replace `previous` at once instead of waiting for
13543
+ * the throttle window: the UI restarts, a stage completes, or new JavaScript
13544
+ * arrives.
13545
+ */
13546
+ function shouldFlushImmediately(previous, next) {
13547
+ if (hasRenderableContent(previous) && !hasRenderableContent(next)) return true;
13548
+ if (next.cssComplete && !previous?.cssComplete) return true;
13549
+ if (next.htmlComplete) return true;
13550
+ if (next.generating === false) return true;
13551
+ if (next.jsFunctions && !previous?.jsFunctions) return true;
13552
+ if ((next.jsExpressions?.length ?? 0) > (previous?.jsExpressions?.length ?? 0)) return true;
13553
+ if (next.html?.length && !previous?.html?.length) return true;
13554
+ return false;
13555
+ }
13556
+
13557
+ //#endregion
13558
+ //#region src/open-generative-ui/html.ts
13559
+ /**
13560
+ * Pure string helpers that turn streamed HTML into sandbox content.
13561
+ * No DOM access.
13562
+ */
13563
+ /**
13564
+ * Extracts all complete `<style>` blocks from the raw HTML.
13565
+ * Returns the concatenated style tags, suitable for injection into `<head>`.
13566
+ */
13567
+ function extractCompleteStyles(html) {
13568
+ const matches = html.match(/<style\b[^>]*>[\s\S]*?<\/style>/gi);
13569
+ return matches ? matches.join("") : "";
13570
+ }
13571
+ /**
13572
+ * Processes raw accumulated HTML for safe preview via innerHTML injection.
13573
+ *
13574
+ * Pipeline (order matters):
13575
+ * 1. Strip incomplete tag at end
13576
+ * 2. Strip complete <style>, <script>, and <head> blocks
13577
+ * 3. Strip incomplete <style>/<script>/<head> blocks
13578
+ * 4. Strip incomplete HTML entities
13579
+ * 5. Extract body content (or use full string if no <body>)
13580
+ */
13581
+ function processPartialHtml(html) {
13582
+ let result = html;
13583
+ result = result.replace(/<[^>]*$/, "");
13584
+ result = result.replace(/<(style|script|head)\b[^>]*>[\s\S]*?<\/\1>/gi, "");
13585
+ result = result.replace(/<(style|script|head)\b[^>]*>[\s\S]*$/gi, "");
13586
+ result = result.replace(/&[a-zA-Z0-9#]*$/, "");
13587
+ const bodyMatch = result.match(/<body[^>]*>([\s\S]*)/i);
13588
+ if (bodyMatch) {
13589
+ result = bodyMatch[1];
13590
+ result = result.replace(/<\/body>[\s\S]*/i, "");
13591
+ }
13592
+ return result;
13593
+ }
13594
+ /** Builds the final sandbox document: the HTML with the CSS in its `<head>`. */
13595
+ function buildFinalFrameContent(html, css) {
13596
+ const withCss = css ? injectCssIntoHtml(html, css) : html;
13597
+ return /<head[\s>]/i.test(withCss) ? withCss : `<head></head>${withCss}`;
13598
+ }
13599
+ function injectCssIntoHtml(html, css) {
13600
+ const headCloseIdx = html.indexOf("</head>");
13601
+ if (headCloseIdx !== -1) return html.slice(0, headCloseIdx) + `<style>${css}</style>` + html.slice(headCloseIdx);
13602
+ return `<head><style>${css}</style></head>${html}`;
13603
+ }
13604
+
13605
+ //#endregion
13606
+ //#region src/open-generative-ui/websandbox.ts
13607
+ /**
13608
+ * Imports `@jetbrains/websandbox` on demand. The import is dynamic because
13609
+ * the package touches `self` when it loads, which breaks server rendering.
13610
+ */
13611
+ const loadWebsandbox = async () => {
13612
+ const defaultExport = (await import("@jetbrains/websandbox")).default;
13613
+ return "default" in defaultExport ? defaultExport.default : defaultExport;
13614
+ };
13615
+
13616
+ //#endregion
13617
+ //#region src/open-generative-ui/controller.ts
13618
+ /** Non-immediate content updates reach the sandbox at most this often. */
13619
+ const OPEN_GENERATIVE_UI_THROTTLE_MS = 1e3;
13620
+ const DEFAULT_HEIGHT = 200;
13621
+ const HIDE_SCROLLBARS = `
13622
+ var s = document.createElement('style');
13623
+ s.textContent = 'html, body { overflow: hidden !important; }';
13624
+ document.head.appendChild(s);
13625
+ `;
13626
+ const HIDE_SCROLLBARS_STYLE = "<style>html, body { overflow: hidden !important; }</style>";
13627
+ const MEASURE_HEIGHT = `
13628
+ (function() {
13629
+ var s = document.createElement('style');
13630
+ s.textContent = 'body { height: auto !important; min-height: 0 !important; }';
13631
+ document.head.appendChild(s);
13632
+ var h = document.body.scrollHeight;
13633
+ var cs = getComputedStyle(document.body);
13634
+ h += parseFloat(cs.marginTop) || 0;
13635
+ h += parseFloat(cs.marginBottom) || 0;
13636
+ s.remove();
13637
+ parent.postMessage({ type: "__ck_resize", height: Math.ceil(h) }, "*");
13638
+ })();
13639
+ `;
13640
+ function deriveContent(content) {
13641
+ const html = content.html?.join("") || void 0;
13642
+ const css = content.cssComplete ? content.css : void 0;
13643
+ if (content.htmlComplete) return {
13644
+ fullHtml: html,
13645
+ css,
13646
+ previewStyles: ""
13647
+ };
13648
+ const previewBody = html && content.cssComplete ? processPartialHtml(html) : void 0;
13649
+ return {
13650
+ css,
13651
+ previewBody: previewBody?.trim() ? previewBody : void 0,
13652
+ previewStyles: html ? extractCompleteStyles(html) : ""
13653
+ };
13654
+ }
13655
+ function prepareIframe(iframe, testId) {
13656
+ iframe.setAttribute("data-testid", testId);
13657
+ iframe.style.width = "100%";
13658
+ iframe.style.height = "100%";
13659
+ iframe.style.border = "none";
13660
+ iframe.style.backgroundColor = "transparent";
13661
+ }
13662
+ function logLoadError(error) {
13663
+ console.error("[OpenGenerativeUI] Failed to load sandbox module:", error);
13664
+ }
13665
+ function sameFunctions(a, b) {
13666
+ return a.length === b.length && a.every((fn, i) => fn.name === b[i].name && fn.handler === b[i].handler);
13667
+ }
13668
+ /**
13669
+ * Runs Open Generative UI content in websandbox iframes inside a host element.
13670
+ *
13671
+ * Give it content snapshots with `setContent()` and a host element with
13672
+ * `setHost()`. It throttles the snapshots, streams a preview while HTML
13673
+ * arrives, swaps in the final sandbox once HTML is complete, runs
13674
+ * `jsFunctions` and `jsExpressions` in it once each, and measures the final
13675
+ * height. Frameworks render the container from `getState()` and re-render
13676
+ * when `subscribe()` notifies.
13677
+ *
13678
+ * @example
13679
+ * ```ts
13680
+ * const controller = new ɵOpenGenerativeUIController();
13681
+ * controller.subscribe(() => render(controller.getState()));
13682
+ * controller.setContent(content);
13683
+ * controller.setHost(containerElement);
13684
+ * // On unmount:
13685
+ * controller.destroy();
13686
+ * ```
13687
+ */
13688
+ var OpenGenerativeUIController = class {
13689
+ #load;
13690
+ #listeners = /* @__PURE__ */ new Set();
13691
+ #content;
13692
+ #latest;
13693
+ #derived = { previewStyles: "" };
13694
+ #timer;
13695
+ #host = null;
13696
+ #functions = [];
13697
+ #localApi = {};
13698
+ #preview;
13699
+ #final;
13700
+ #measuredHeight;
13701
+ #state = {
13702
+ phase: "placeholder",
13703
+ generating: true,
13704
+ height: DEFAULT_HEIGHT
13705
+ };
13706
+ constructor(options = {}) {
13707
+ this.#load = options.loadWebsandbox ?? loadWebsandbox;
13708
+ }
13709
+ /** The current state. The same object until something changes. */
13710
+ getState = () => this.#state;
13711
+ /** Calls `listener` when the state changes. Returns the unsubscribe function. */
13712
+ subscribe = (listener) => {
13713
+ this.#listeners.add(listener);
13714
+ return () => {
13715
+ this.#listeners.delete(listener);
13716
+ };
13717
+ };
13718
+ /**
13719
+ * Sets the latest content snapshot. The first snapshot and snapshots that
13720
+ * finish a stage apply at once; others apply at most once per second.
13721
+ */
13722
+ setContent(content) {
13723
+ this.#latest = content;
13724
+ if (this.#content === void 0 || shouldFlushImmediately(this.#content, content)) {
13725
+ this.#clearTimer();
13726
+ this.#commit(content);
13727
+ return;
13728
+ }
13729
+ if (content === this.#content || this.#timer !== void 0) return;
13730
+ this.#timer = setTimeout(() => {
13731
+ this.#timer = void 0;
13732
+ if (this.#latest) this.#commit(this.#latest);
13733
+ }, OPEN_GENERATIVE_UI_THROTTLE_MS);
13734
+ }
13735
+ /** Sets the element the sandbox iframes go into. `null` removes them. */
13736
+ setHost(host) {
13737
+ if (host === this.#host) return;
13738
+ this.#destroyPreview();
13739
+ this.#destroyFinal();
13740
+ this.#host = host;
13741
+ this.#reconcile();
13742
+ }
13743
+ /**
13744
+ * Sets the host functions sandboxed code can call. A change recreates the
13745
+ * final sandbox.
13746
+ */
13747
+ setSandboxFunctions(functions) {
13748
+ if (sameFunctions(functions, this.#functions)) return;
13749
+ this.#functions = functions;
13750
+ const localApi = {};
13751
+ for (const fn of functions) localApi[fn.name] = fn.handler;
13752
+ this.#localApi = localApi;
13753
+ this.#reconcile();
13754
+ }
13755
+ /**
13756
+ * Removes the sandboxes and stops pending work. A later `setHost()`
13757
+ * starts again from the current content.
13758
+ */
13759
+ destroy() {
13760
+ this.#clearTimer();
13761
+ this.#destroyPreview();
13762
+ this.#destroyFinal();
13763
+ this.#host = null;
13764
+ }
13765
+ #commit(content) {
13766
+ if (content === this.#content) return;
13767
+ this.#content = content;
13768
+ this.#derived = deriveContent(content);
13769
+ this.#reconcile();
13770
+ }
13771
+ #reconcile() {
13772
+ const host = this.#host;
13773
+ const content = this.#content;
13774
+ const derived = this.#derived;
13775
+ if (host && content) if (derived.fullHtml) {
13776
+ this.#destroyPreview();
13777
+ const frameContent = buildFinalFrameContent(derived.fullHtml, derived.css);
13778
+ let final = this.#final;
13779
+ if (final?.frameContent !== frameContent || final.localApi !== this.#localApi) {
13780
+ this.#destroyFinal();
13781
+ final = this.#final = this.#createFinal(host, frameContent);
13782
+ }
13783
+ this.#runScripts(final, content);
13784
+ } else {
13785
+ this.#destroyFinal();
13786
+ if (derived.previewBody) {
13787
+ this.#preview ??= this.#createPreview(host);
13788
+ this.#writePreview();
13789
+ } else this.#destroyPreview();
13790
+ }
13791
+ this.#updateState();
13792
+ }
13793
+ #createPreview(host) {
13794
+ const slot = {
13795
+ ready: false,
13796
+ cancelled: false
13797
+ };
13798
+ this.#load().then((Websandbox) => {
13799
+ if (slot.cancelled) return;
13800
+ const sandbox = Websandbox.create({}, {
13801
+ frameContainer: host,
13802
+ frameContent: "<head></head><body></body>",
13803
+ allowAdditionalAttributes: ""
13804
+ });
13805
+ slot.sandbox = sandbox;
13806
+ prepareIframe(sandbox.iframe, "open-generative-ui-preview-sandbox");
13807
+ sandbox.promise.then(() => {
13808
+ if (slot.cancelled) return;
13809
+ slot.ready = true;
13810
+ this.#writePreview();
13811
+ });
13812
+ }).catch(logLoadError);
13813
+ return slot;
13814
+ }
13815
+ #writePreview() {
13816
+ const slot = this.#preview;
13817
+ if (!slot?.sandbox || !slot.ready) return;
13818
+ const { css, previewStyles, previewBody } = this.#derived;
13819
+ const head = HIDE_SCROLLBARS_STYLE + (css ? `<style>${css}</style>` : "") + previewStyles;
13820
+ if (head !== slot.head) {
13821
+ slot.head = head;
13822
+ slot.sandbox.run(`document.head.innerHTML = ${JSON.stringify(head)}`);
13823
+ }
13824
+ if (previewBody && previewBody !== slot.body) {
13825
+ slot.body = previewBody;
13826
+ slot.sandbox.run(`document.body.innerHTML = ${JSON.stringify(previewBody)}`);
13827
+ }
13828
+ }
13829
+ #createFinal(host, frameContent) {
13830
+ const slot = {
13831
+ frameContent,
13832
+ localApi: this.#localApi,
13833
+ ready: false,
13834
+ cancelled: false,
13835
+ queue: [],
13836
+ jsFunctionsInjected: false,
13837
+ executedExpressions: 0,
13838
+ heightRequested: false
13839
+ };
13840
+ this.#load().then((Websandbox) => {
13841
+ if (slot.cancelled) return;
13842
+ const sandbox = Websandbox.create(slot.localApi, {
13843
+ frameContainer: host,
13844
+ frameContent,
13845
+ allowAdditionalAttributes: ""
13846
+ });
13847
+ slot.sandbox = sandbox;
13848
+ prepareIframe(sandbox.iframe, "open-generative-ui-final-sandbox");
13849
+ sandbox.promise.then(() => {
13850
+ if (slot.cancelled) return;
13851
+ slot.ready = true;
13852
+ sandbox.run(HIDE_SCROLLBARS);
13853
+ const queue = slot.queue;
13854
+ slot.queue = [];
13855
+ for (const code of queue) sandbox.run(code);
13856
+ });
13857
+ }).catch(logLoadError);
13858
+ return slot;
13859
+ }
13860
+ /** Runs new `jsFunctions`, new `jsExpressions`, and the height measurement. */
13861
+ #runScripts(slot, content) {
13862
+ if (content.jsFunctions && !slot.jsFunctionsInjected) {
13863
+ slot.jsFunctionsInjected = true;
13864
+ this.#runOrQueue(slot, content.jsFunctions);
13865
+ }
13866
+ const expressions = content.jsExpressions ?? [];
13867
+ if (expressions.length > slot.executedExpressions) {
13868
+ const newExpressions = expressions.slice(slot.executedExpressions);
13869
+ slot.executedExpressions = expressions.length;
13870
+ const sandbox = slot.sandbox;
13871
+ if (slot.ready && sandbox) (async () => {
13872
+ for (const expression of newExpressions) await sandbox.run(expression);
13873
+ })();
13874
+ else slot.queue.push(...newExpressions);
13875
+ }
13876
+ if (content.generating === false && !slot.heightRequested) {
13877
+ slot.heightRequested = true;
13878
+ this.#listenForHeight(slot);
13879
+ this.#runOrQueue(slot, MEASURE_HEIGHT);
13880
+ }
13881
+ }
13882
+ #runOrQueue(slot, code) {
13883
+ if (slot.ready && slot.sandbox) slot.sandbox.run(code);
13884
+ else slot.queue.push(code);
13885
+ }
13886
+ #listenForHeight(slot) {
13887
+ if (typeof window === "undefined") return;
13888
+ const onMessage = (event) => {
13889
+ const data = event.data;
13890
+ if (!slot.sandbox || event.source !== slot.sandbox.iframe.contentWindow || data?.type !== "__ck_resize" || typeof data.height !== "number") return;
13891
+ slot.stopHeightListener?.();
13892
+ this.#measuredHeight = data.height;
13893
+ this.#updateState();
13894
+ };
13895
+ window.addEventListener("message", onMessage);
13896
+ slot.stopHeightListener = () => {
13897
+ window.removeEventListener("message", onMessage);
13898
+ slot.stopHeightListener = void 0;
13899
+ };
13900
+ }
13901
+ #destroyPreview() {
13902
+ const slot = this.#preview;
13903
+ if (!slot) return;
13904
+ slot.cancelled = true;
13905
+ slot.sandbox?.destroy();
13906
+ this.#preview = void 0;
13907
+ }
13908
+ #destroyFinal() {
13909
+ const slot = this.#final;
13910
+ if (!slot) return;
13911
+ slot.cancelled = true;
13912
+ slot.stopHeightListener?.();
13913
+ slot.sandbox?.destroy();
13914
+ this.#final = void 0;
13915
+ this.#measuredHeight = void 0;
13916
+ }
13917
+ #clearTimer() {
13918
+ if (this.#timer === void 0) return;
13919
+ clearTimeout(this.#timer);
13920
+ this.#timer = void 0;
13921
+ }
13922
+ #updateState() {
13923
+ const content = this.#content ?? {};
13924
+ const derived = this.#derived;
13925
+ const next = {
13926
+ phase: derived.fullHtml ? "final" : derived.previewBody ? "preview" : "placeholder",
13927
+ generating: content.generating !== false,
13928
+ height: this.#measuredHeight ?? content.initialHeight ?? DEFAULT_HEIGHT
13929
+ };
13930
+ const current = this.#state;
13931
+ if (next.phase === current.phase && next.generating === current.generating && next.height === current.height) return;
13932
+ this.#state = next;
13933
+ for (const listener of this.#listeners) listener();
13934
+ }
13935
+ };
13936
+
13937
+ //#endregion
13938
+ //#region src/utils/class-names.ts
13939
+ /**
13940
+ * Joins class names, skipping falsy values. Takes the same inputs as `clsx`.
13941
+ * Classes are not merged: every rule CopilotKit ships sits in `:where()`, so a
13942
+ * class the app adds wins without removing ours.
13943
+ */
13944
+ function cn(...inputs) {
13945
+ const out = [];
13946
+ for (const input of inputs) {
13947
+ if (!input) continue;
13948
+ if (typeof input === "string" || typeof input === "number" || typeof input === "bigint") out.push(String(input));
13949
+ else if (Array.isArray(input)) {
13950
+ const nested = cn(...input);
13951
+ if (nested) out.push(nested);
13952
+ } else if (typeof input === "object") {
13953
+ for (const key in input) if (input[key]) out.push(key);
13954
+ }
13955
+ }
13956
+ return out.join(" ");
13957
+ }
13958
+
13959
+ //#endregion
13960
+ export { A2UI_FENCE_LANGUAGE, AgentRegistry, AgentThreadLockedError, ContextStore, CopilotChatDefaultLabels, CopilotKitCore, CopilotKitCoreErrorCode, CopilotKitCoreRuntimeConnectionStatus, CopilotKitHeaderResolutionError, DEFAULT_OPEN_GENERATIVE_UI_DESIGN_SKILL, GENERATE_SANDBOXED_UI_TOOL_NAME, INSPECTOR_THREAD_BRIDGE_PLUGIN_ID, INTERRUPT_EVENT_NAME, IntelligenceAgent, MEMORY_ERROR_REGISTRY, MemoryError, OPEN_GENERATIVE_UI_ACTIVITY_TYPE, ProxiedCopilotRuntimeAgent, RunHandler, StateManager, SuggestionEngine, ToolCallStatus, TranscriptionError, TranscriptionErrorCode, WebMCPRegistry, classifySurfaceCards, completePartialMarkdown, createActionGroup, createEffect, createInspectorThreadRequestId, createReducer, createSelector, createStore, emitInspectorActiveThread, emitInspectorStopViewing, emitInspectorViewThread, emitInspectorViewThreadResult, empty, ensureObjectArgs, extractCompleteArrayItems, extractFenceOperations, extractStringField, flattenInformationalCards, getMarkdownOperationSurfaceId, getWebMCPModelContext, isAbortError, isInspectorThreadBridgeEnabled, isRunCompletionAware, ofType, on, onInspectorActiveThread, onInspectorStopViewing, onInspectorViewThread, onInspectorViewThreadResult, parseToolArguments, prepareSurfaceOperations, props, segmentSurfaceProse, select, splitA2UIMarkdown, ɵCOPILOTKIT_FEATURES, ɵCOPY_FEEDBACK_RESET_MS, ɵCopyFeedback, ɵFEEDBACK_COMMENT_CLOSE_DELAY_MS, ɵFeedbackCommentController, ɵHOVER_MENU_CLOSE_DELAY_MS, ɵHoverMenuController, ɵINLINE_FEATURE_WARNING_STYLE, ɵInterruptState, ɵKEYBOARD_OPEN_THRESHOLD_PX, ɵLICENSE_BANNER_OFFSET, ɵLICENSE_BANNER_STYLE, ɵMAX_SOCKET_RETRIES, ɵMESSAGE_FEEDBACK_EVENT_NAME, ɵMESSAGE_FEEDBACK_MAX_COMMENT_LENGTH, ɵMOBILE_MAX_WIDTH_QUERY, OpenGenerativeUIController as ɵOpenGenerativeUIController, ɵRUNTIME_PROBE_TIMEOUT_MS, ɵTHREAD_REQUEST_TIMEOUT_MS, ɵclearAgentInterruptState, cn as ɵcn, ɵcomposerButtonState, ɵcopilotIconSvgAttributes, ɵcopilotIcons, countFailedToolCalls as ɵcountFailedToolCalls, createMemoryStore as ɵcreateMemoryStore, ɵcreateThreadSelectors, createThreadStore as ɵcreateThreadStore, ɵdeduplicateMessages, extractCompleteStyles as ɵextractCompleteStyles, ɵflattenUserMessageContent, ɵformatCountLabel, ɵformatLabel, formatReasoningDuration as ɵformatReasoningDuration, ɵformatReasoningDurationLabel, formatToolNames as ɵformatToolNames, formatWorkDuration as ɵformatWorkDuration, ɵgetAgentInterruptState, getArgumentPreview as ɵgetArgumentPreview, ɵgetBranchNavState, ɵgetInlineFeatureWarningSpec, getLatestTurnKey as ɵgetLatestTurnKey, ɵgetLicenseBannerSpec, ɵgetMessageFeedback, ɵgetMessageFeedbackControls, getToolCallLayouts as ɵgetToolCallLayouts, getToolCallPreview as ɵgetToolCallPreview, getToolCallRendererNames as ɵgetToolCallRendererNames, getToolCallRowStatus as ɵgetToolCallRowStatus, getToolResults as ɵgetToolResults, getTurnWork as ɵgetTurnWork, ɵgetUserMessageMediaFilename, ɵgetUserMessageMediaParts, getWorkOpenState as ɵgetWorkOpenState, ɵgetWorkSummaryText, ɵhasAssistantMessageText, ɵinitialKeyboardState, ɵinspectorKiteFill, ɵinspectorKiteIcon, ɵinspectorShortcuts, ɵisCopilotKitFeature, ɵisHttpAgent, ɵisLearningFeedbackEnabled, ɵisMobileViewport, isRetryableStatus as ɵisRetryableMemoryStatus, isTurnWorkOpen as ɵisTurnWorkOpen, isTurnWorking as ɵisTurnWorking, ɵjoinPhoenixChannel$, loadWebsandbox as ɵloadWebsandbox, ɵmapMemoryMetadataEvent, ɵmemoryAdapterEvents, ɵmemoryDomainEvents, ɵmemoryReducer, ɵmemoryRestEvents, ɵmessagesFingerprint, ɵnormalizeAutoScroll, ɵobservePhoenixEvent$, ɵobservePhoenixJoinOutcome$, ɵobservePhoenixSocketHealth$, ɵobservePhoenixSocketSignals$, ɵphoenixChannel$, ɵphoenixSocket$, ɵpinMessageToTop, pluralize as ɵpluralize, processPartialHtml as ɵprocessPartialHtml, ɵreadKeyboardState, recordWorkTime as ɵrecordWorkTime, ɵreserveLicenseBannerOffset, ɵresetMessageFeedbackCache, ɵresolveActivityRenderer, ɵresolveComposerKey, ɵresolveCustomMessageRenderers, ɵresolveLicenseState, ɵresolveThreadsLicense, ɵresolveToolCallRenderer, ɵselectFetchMoreError, ɵselectHasNextPage, ɵselectIsFetchingNextPage, ɵselectIsMutating, ɵselectMemories, ɵselectMemoriesAvailable, ɵselectMemoriesError, ɵselectMemoriesIsLoading, ɵselectMemoriesIsMutating, ɵselectMemoriesRealtimeStatus, ɵselectThreads, ɵselectThreadsError, ɵselectThreadsIsLoading, ɵsetMessageFeedback, shallowEqualRecord as ɵshallowEqualRecord, ɵshouldShowAssistantToolbar, stringifyToolCallPayload as ɵstringifyToolCallPayload, ɵsubscribeToLearningFeedbackEnabled, ɵsubscribeToMessageFeedback, ɵthreadAdapterEvents, ɵtranscribeAudio, ɵtranscriptionErrorMessageKey, ɵwatchKeyboardState, ɵwatchMobileViewport, ɵwithHeaderDefaults };
10775
13961
  //# sourceMappingURL=index.mjs.map