@copilotkit/core 2.0.0-rc.0 → 2.0.0-rc.10

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