@copilotkit/core 2.0.0-rc.25 → 2.0.0-rc.27

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,8 +1,8 @@
1
- import { a as ɵnormalizeAutoScroll, c as ɵwatchKeyboardState, i as ɵisMobileViewport, l as ɵwatchMobileViewport, n as ɵMOBILE_MAX_WIDTH_QUERY, o as ɵpinMessageToTop, r as ɵinitialKeyboardState, s as ɵreadKeyboardState, t as ɵKEYBOARD_OPEN_THRESHOLD_PX } from "./viewport-BkM_3mlk.mjs";
1
+ import { A as ɵdimensionToCss, C as ɵbindDialogFocus, D as ɵcreateExitPresence, E as ɵcreateDockedSidebar, F as ɵmorphViewTransition, I as ɵnextTabStop, L as ɵwatchElementHeight, M as ɵisContentScrolledToBottom, N as ɵisFocusVisible, O as ɵcreateObjectUrlFromSource, P as ɵisScrolledToBottom, R as ɵwatchElementWidth, S as ɵTAB_STOP_SELECTOR, T as ɵcanPreviewDocument, _ as ɵPOPUP_DEFAULT_WIDTH, a as ɵinitialKeyboardState, b as ɵSIDEBAR_DEFAULT_WIDTH, c as ɵpinMessageToTop, d as ɵwatchMobileViewport, f as ɵDockedSidebar, g as ɵPOPUP_DEFAULT_HEIGHT, h as ɵPOPUP_ANIMATION_MS, i as ɵcreateStickToBottom, j as ɵdockedSidebarRegistryFor, k as ɵdecodeTextSource, l as ɵreadKeyboardState, m as ɵExitPresence, n as ɵMOBILE_MAX_WIDTH_QUERY, o as ɵisMobileViewport, p as ɵDockedSidebarRegistry, r as ɵStickToBottom, s as ɵnormalizeAutoScroll, t as ɵKEYBOARD_OPEN_THRESHOLD_PX, u as ɵwatchKeyboardState, v as ɵRESIZE_SETTLE_MS, w as ɵbindPopupDismiss, x as ɵSIDEBAR_TRANSITION_MS, y as ɵSCROLL_BOTTOM_THRESHOLD_PX } from "./viewport-D9ZX0xqz.mjs";
2
2
  import { ɵChatConfigurationStore } from "./chat-configuration.mjs";
3
3
  import { Throttler } from "@tanstack/pacer";
4
4
  import { AGUIConnectNotImplementedError, AbstractAgent, CompatibilityBoundary, EventType, HttpAgent, buildResumeArray, isInterruptExpired, randomUUID, runHttpRequest, structuredClone_, transformChunks, transformHttpEventStream } from "@ag-ui/client";
5
- import { A2UI_VERSION, COPILOT_CLOUD_CHAT_URL, COPILOT_CLOUD_PUBLIC_API_KEY_HEADER, DEFAULT_AGENT_ID, GENERATE_SANDBOXED_UI_DESCRIPTION, GENERATIVE_UI_ROOT_ID, RUNTIME_MODE_INTELLIGENCE, RUNTIME_MODE_SSE, THREAD_ALREADY_RUNNING_ERROR_CODE, TranscriptionErrorCode, copyToClipboard, createAttachmentContent, createLicenseContextValue, exceedsMaxSize, formatFileSize, generateVideoThumbnail, getModalityFromMimeType, logger, matchesAcceptFilter, parseInspectorMetadataV1, partialJSONParse, phoenixExponentialBackoff, randomUUID as randomUUID$1, readFileAsBase64, resolveDebugConfig, schemaToJsonSchema, stripIntelligenceRoutingFields } from "@copilotkit/shared";
5
+ import { A2UI_VERSION, COPILOT_CLOUD_CHAT_URL, COPILOT_CLOUD_PUBLIC_API_KEY_HEADER, DEFAULT_AGENT_ID, GENERATE_SANDBOXED_UI_DESCRIPTION, GENERATIVE_UI_ROOT_ID, RUNTIME_MODE_INTELLIGENCE, RUNTIME_MODE_SSE, THREAD_ALREADY_RUNNING_ERROR_CODE, TranscriptionErrorCode, copyToClipboard, createAttachmentContent, createLicenseContextValue, exceedsMaxSize, formatFileSize, generateVideoThumbnail, getModalityFromMimeType, logger, matchesAcceptFilter, parseInspectorMetadataV1, partialJSONParse, phoenixExponentialBackoff, randomUUID as randomUUID$1, readFileAsBase64, resolveDebugConfig, schemaToJsonSchema, stripIntelligenceRoutingFields, ɵanySchema } from "@copilotkit/shared";
6
6
  import { BehaviorSubject, EMPTY, NEVER, Notification, Observable, Subject, Subscription, asapScheduler, combineLatest, concat, defer, dematerialize, firstValueFrom, from, lastValueFrom, merge, observeOn, of, switchMap, throwError } from "rxjs";
7
7
  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";
8
8
  import { Socket } from "phoenix";
@@ -9597,12 +9597,15 @@ function toolCallKey(entry) {
9597
9597
  * Holds the renderers of one provider and tells subscribers when a list
9598
9598
  * changes.
9599
9599
  *
9600
- * Tool-call renderers come from two places. Prop renderers are the list the
9600
+ * Tool-call renderers come from three places. Prop renderers are the list the
9601
9601
  * provider was given (`setPropToolCalls`). Hook renderers are added one at a
9602
- * time (`addHookToolCall`), for example by `useRenderTool`. Each renderer has
9603
- * a key made of its `agentId` and `name`. A hook renderer replaces a prop
9604
- * renderer with the same key, and a later hook renderer replaces an earlier
9605
- * one with the same key, so the latest registration wins.
9602
+ * time (`addHookToolCall`), for example by `useRenderTool`. Built-in
9603
+ * renderers are added by CopilotKit features such as A2UI
9604
+ * (`addBuiltInToolCall`). Each renderer has a key made of its `agentId` and
9605
+ * `name`. A hook renderer replaces a prop renderer with the same key, and a
9606
+ * later hook renderer replaces an earlier one with the same key, so the
9607
+ * latest registration wins. A built-in renderer shows only when no prop or
9608
+ * hook renderer has its key, so an app can always replace it.
9606
9609
  *
9607
9610
  * Fields are TypeScript `private`, not `#private`, so the registry keeps
9608
9611
  * working behind a Vue reactive proxy.
@@ -9626,6 +9629,7 @@ function toolCallKey(entry) {
9626
9629
  var ɵRendererRegistry = class {
9627
9630
  _propToolCalls;
9628
9631
  _hookToolCalls = /* @__PURE__ */ new Map();
9632
+ _builtInToolCalls = /* @__PURE__ */ new Map();
9629
9633
  _mergedToolCalls = null;
9630
9634
  _activity;
9631
9635
  _custom;
@@ -9640,16 +9644,18 @@ var ɵRendererRegistry = class {
9640
9644
  return this._propToolCalls;
9641
9645
  }
9642
9646
  /**
9643
- * Every tool-call renderer: prop renderers, then hook renderers, with one
9644
- * entry per `agentId` + `name` key. A prop renderer that a hook renderer
9645
- * replaces keeps its position in the list.
9647
+ * Every tool-call renderer: prop renderers, then hook renderers, then
9648
+ * built-in renderers, with one entry per `agentId` + `name` key. A prop
9649
+ * renderer that a hook renderer replaces keeps its position in the list. A
9650
+ * built-in renderer is left out when a prop or hook renderer has its key.
9646
9651
  */
9647
9652
  get toolCalls() {
9648
- if (this._hookToolCalls.size === 0) return this._propToolCalls;
9653
+ if (this._hookToolCalls.size === 0 && this._builtInToolCalls.size === 0) return this._propToolCalls;
9649
9654
  if (this._mergedToolCalls) return this._mergedToolCalls;
9650
9655
  const merged = /* @__PURE__ */ new Map();
9651
9656
  for (const entry of this._propToolCalls) merged.set(toolCallKey(entry), entry);
9652
9657
  for (const [key, entry] of this._hookToolCalls) merged.set(key, entry);
9658
+ for (const [key, entry] of this._builtInToolCalls) if (!merged.has(key)) merged.set(key, entry);
9653
9659
  this._mergedToolCalls = [...merged.values()];
9654
9660
  return this._mergedToolCalls;
9655
9661
  }
@@ -9704,6 +9710,55 @@ var ɵRendererRegistry = class {
9704
9710
  this.emit("toolCalls");
9705
9711
  }
9706
9712
  /**
9713
+ * Remove the prop and hook renderers for `name` and `agentId`. Built-in
9714
+ * renderers stay. Does nothing when no such renderer exists.
9715
+ *
9716
+ * @param name - The tool name.
9717
+ * @param agentId - The agent the renderers belong to. Omit it for
9718
+ * renderers with no `agentId`.
9719
+ */
9720
+ removeToolCall(name, agentId) {
9721
+ const key = toolCallKey({
9722
+ name,
9723
+ agentId
9724
+ });
9725
+ const props = this._propToolCalls.filter((entry) => toolCallKey(entry) !== key);
9726
+ if (!this._hookToolCalls.delete(key) && props.length === this._propToolCalls.length) return;
9727
+ this._propToolCalls = props;
9728
+ this._mergedToolCalls = null;
9729
+ this.emit("toolCalls");
9730
+ }
9731
+ /**
9732
+ * Add a built-in renderer, for a tool that a CopilotKit feature owns (for
9733
+ * example the A2UI render tool). Prop and hook renderers with the same
9734
+ * `agentId` and `name` win over it, and setting the prop renderers never
9735
+ * removes it.
9736
+ *
9737
+ * @param entry - The renderer to add. It replaces an earlier built-in
9738
+ * renderer with the same key.
9739
+ * @returns A function that removes this renderer, if it is still the
9740
+ * built-in renderer for its key. Calling it more than once does nothing.
9741
+ *
9742
+ * @example
9743
+ * ```ts
9744
+ * const remove = registry.addBuiltInToolCall({ name: "render_a2ui", render: Nothing });
9745
+ * // when the feature turns off
9746
+ * remove();
9747
+ * ```
9748
+ */
9749
+ addBuiltInToolCall(entry) {
9750
+ const key = toolCallKey(entry);
9751
+ this._builtInToolCalls.set(key, entry);
9752
+ this._mergedToolCalls = null;
9753
+ this.emit("toolCalls");
9754
+ return () => {
9755
+ if (this._builtInToolCalls.get(key) !== entry) return;
9756
+ this._builtInToolCalls.delete(key);
9757
+ this._mergedToolCalls = null;
9758
+ this.emit("toolCalls");
9759
+ };
9760
+ }
9761
+ /**
9707
9762
  * Replace the activity message renderers.
9708
9763
  *
9709
9764
  * @param renderers - The renderers. The registry keeps a copy.
@@ -10615,6 +10670,229 @@ function ɵtoolRendererShapeChanged(previous, next) {
10615
10670
  for (const key of previousKeys) if (!nextKeys.has(key)) return true;
10616
10671
  return false;
10617
10672
  }
10673
+ function isToolRendererShape(value) {
10674
+ return typeof value === "object" && value !== null;
10675
+ }
10676
+ /**
10677
+ * @internal The warning for a provider array prop that changed after mount,
10678
+ * or `undefined` when the change is fine.
10679
+ *
10680
+ * `renderToolCalls` warns only when its shape changes (see
10681
+ * {@link ɵtoolRendererShapeChanged}), so new render closures for the same
10682
+ * tools are fine. Every other prop warns on a new array.
10683
+ *
10684
+ * @param prop - Which prop changed.
10685
+ * @param initial - The value at mount. `undefined` counts as an empty list.
10686
+ * @param next - The new value.
10687
+ *
10688
+ * @example
10689
+ * const warning = ɵstableArrayPropWarning("frontendTools", initial, next);
10690
+ * if (warning) console.error(warning);
10691
+ */
10692
+ function ɵstableArrayPropWarning(prop, initial, next) {
10693
+ if (next === initial) return void 0;
10694
+ if (prop === "renderToolCalls" && !ɵtoolRendererShapeChanged((initial ?? []).filter(isToolRendererShape), (next ?? []).filter(isToolRendererShape))) return;
10695
+ return ɵSTABLE_ARRAY_WARNINGS[prop];
10696
+ }
10697
+ /**
10698
+ * @internal Build the tool list and the tool-call renderer list of a
10699
+ * provider from its props.
10700
+ *
10701
+ * - Tools: `frontendTools`, then `builtInFrontendTools`, then one tool per
10702
+ * `humanInTheLoop` entry (see `ɵbuildHumanInTheLoopTool`).
10703
+ * - Renderers: `renderToolCalls`, then one renderer per frontend tool with a
10704
+ * `render`, then one per human-in-the-loop entry with a `render`. A tool
10705
+ * renderer keeps the tool's `agentId`. A frontend tool without
10706
+ * `parameters` gets a renderer only when it is the `"*"` wildcard, which
10707
+ * then accepts any arguments.
10708
+ *
10709
+ * @example
10710
+ * const { tools, renderToolCalls } = ɵassembleProviderRegistry({
10711
+ * renderToolCalls: props.renderToolCalls,
10712
+ * frontendTools: props.frontendTools,
10713
+ * humanInTheLoop: props.humanInTheLoop,
10714
+ * humanInTheLoopRegistry: () => core.ɵhumanInTheLoop,
10715
+ * wrapHumanInTheLoopRender: (Render, tool, registry) => (props) =>
10716
+ * <Render {...ɵhitlRenderProps(props, tool, registry())} />,
10717
+ * });
10718
+ */
10719
+ function ɵassembleProviderRegistry(input) {
10720
+ const humanInTheLoop = ɵassembleHumanInTheLoop(input);
10721
+ return {
10722
+ tools: ɵassembleProviderTools({
10723
+ ...input,
10724
+ humanInTheLoop
10725
+ }),
10726
+ renderToolCalls: ɵassembleProviderToolRenderers({
10727
+ ...input,
10728
+ humanInTheLoop
10729
+ })
10730
+ };
10731
+ }
10732
+ /**
10733
+ * @internal The human-in-the-loop part of {@link ɵassembleProviderRegistry}:
10734
+ * one tool per `humanInTheLoop` entry, and one renderer per entry with a
10735
+ * `render`.
10736
+ *
10737
+ * Each call wraps every render again, and a new wrapper is a new component
10738
+ * type to React and Vue, so the card remounts. Adapters memoize this result
10739
+ * on `humanInTheLoop` alone, and pass it to {@link ɵassembleProviderTools}
10740
+ * and {@link ɵassembleProviderToolRenderers}.
10741
+ */
10742
+ function ɵassembleHumanInTheLoop(input) {
10743
+ const registryInput = input.humanInTheLoopRegistry;
10744
+ const registry = typeof registryInput === "function" ? registryInput : () => registryInput;
10745
+ const tools = [];
10746
+ const renderToolCalls = [];
10747
+ for (const entry of input.humanInTheLoop ?? []) {
10748
+ const { render, ...config } = entry;
10749
+ tools.push(ɵbuildHumanInTheLoopTool(config, registry));
10750
+ if (!render) continue;
10751
+ renderToolCalls.push({
10752
+ name: entry.name,
10753
+ args: entry.parameters,
10754
+ render: input.wrapHumanInTheLoopRender(render, entry, registry),
10755
+ ...entry.agentId && { agentId: entry.agentId }
10756
+ });
10757
+ }
10758
+ return {
10759
+ tools,
10760
+ renderToolCalls
10761
+ };
10762
+ }
10763
+ /**
10764
+ * @internal The tool list of {@link ɵassembleProviderRegistry}:
10765
+ * `frontendTools`, then `builtInFrontendTools`, then the human-in-the-loop
10766
+ * tools. It does not read `renderToolCalls`.
10767
+ */
10768
+ function ɵassembleProviderTools(input) {
10769
+ return [
10770
+ ...input.frontendTools ?? [],
10771
+ ...input.builtInFrontendTools ?? [],
10772
+ ...input.humanInTheLoop.tools
10773
+ ];
10774
+ }
10775
+ /**
10776
+ * @internal The renderer list of {@link ɵassembleProviderRegistry}:
10777
+ * `renderToolCalls`, then one renderer per frontend tool with a `render`,
10778
+ * then the human-in-the-loop renderers, which keep their identity.
10779
+ */
10780
+ function ɵassembleProviderToolRenderers(input) {
10781
+ const renderToolCalls = [...input.renderToolCalls ?? []];
10782
+ for (const tool of [...input.frontendTools ?? [], ...input.builtInFrontendTools ?? []]) {
10783
+ if (!tool.render) continue;
10784
+ const args = tool.parameters ?? (tool.name === "*" ? ɵanySchema : void 0);
10785
+ if (!args) continue;
10786
+ renderToolCalls.push({
10787
+ name: tool.name,
10788
+ args,
10789
+ render: tool.render,
10790
+ ...tool.agentId && { agentId: tool.agentId }
10791
+ });
10792
+ }
10793
+ renderToolCalls.push(...input.humanInTheLoop.renderToolCalls);
10794
+ return renderToolCalls;
10795
+ }
10796
+ /**
10797
+ * @internal Whether the provider turns on A2UI: its built-in renderers and
10798
+ * its agent context.
10799
+ *
10800
+ * A2UI is active when the runtime enables it or the provider has a catalog.
10801
+ * With `requireCatalog`, only a catalog turns it on. `missingCatalog` is
10802
+ * true when the runtime enables A2UI but `requireCatalog` keeps it off;
10803
+ * the provider should tell the developer to configure a catalog.
10804
+ *
10805
+ * @example
10806
+ * ɵresolveA2UIActivation({ runtimeEnabled: true, hasCatalog: false });
10807
+ * // { active: true, missingCatalog: false }
10808
+ * ɵresolveA2UIActivation({ runtimeEnabled: true, hasCatalog: false, requireCatalog: true });
10809
+ * // { active: false, missingCatalog: true }
10810
+ */
10811
+ function ɵresolveA2UIActivation({ runtimeEnabled, hasCatalog, requireCatalog = false }) {
10812
+ if (requireCatalog) return {
10813
+ active: hasCatalog,
10814
+ missingCatalog: runtimeEnabled && !hasCatalog
10815
+ };
10816
+ return {
10817
+ active: runtimeEnabled || hasCatalog,
10818
+ missingCatalog: false
10819
+ };
10820
+ }
10821
+ /**
10822
+ * @internal The provider's activity renderer list: the app's renderers, then
10823
+ * the A2UI renderer, then the other built-in renderers. Missing entries are
10824
+ * left out.
10825
+ *
10826
+ * @example
10827
+ * ɵassembleActivityRenderers({
10828
+ * app: props.renderActivityMessages,
10829
+ * a2ui: a2uiActive ? a2uiRenderer : undefined,
10830
+ * builtIns: [mcpAppsRenderer, openGenUIActive && openGenUIRenderer],
10831
+ * });
10832
+ */
10833
+ function ɵassembleActivityRenderers({ app = [], a2ui, builtIns = [] }) {
10834
+ const renderers = [...app];
10835
+ if (a2ui) renderers.push(a2ui);
10836
+ for (const renderer of builtIns) if (renderer) renderers.push(renderer);
10837
+ return renderers;
10838
+ }
10839
+
10840
+ //#endregion
10841
+ //#region src/core/frontend-tool-registration.ts
10842
+ function toolKey(tool) {
10843
+ return `${tool.agentId ?? ""}:${tool.name}`;
10844
+ }
10845
+ /**
10846
+ * @internal Register frontend tools from a hook (`useFrontendTool`,
10847
+ * `useFrontendTools`) and their renderers.
10848
+ *
10849
+ * - Tools with the same `name` and `agentId` in `tools` collapse to the last
10850
+ * one, with a warning.
10851
+ * - A tool that hides an already registered tool (a provider tool or another
10852
+ * hook) logs a warning. Core runs the newest registration until it is
10853
+ * removed, and then the hidden tool runs again.
10854
+ * - A tool with a `render` gets a renderer through `addRenderer`, also when
10855
+ * it has no `parameters` (for example a confirm dialog). The returned
10856
+ * function does not remove renderers, so past calls still render in the
10857
+ * chat history.
10858
+ *
10859
+ * @param core - The core to register the tools with.
10860
+ * @param tools - The tools, in order.
10861
+ * @param addRenderer - Adds a hook renderer in the framework's registry.
10862
+ * @returns A function that removes exactly the tools this call registered.
10863
+ *
10864
+ * @example
10865
+ * const unregister = ɵregisterFrontendTools(core, [tool], (renderer) =>
10866
+ * core.addHookRenderToolCall(renderer),
10867
+ * );
10868
+ * // on unmount
10869
+ * unregister();
10870
+ */
10871
+ function ɵregisterFrontendTools(core, tools, addRenderer) {
10872
+ const deduped = /* @__PURE__ */ new Map();
10873
+ for (const tool of tools) {
10874
+ const key = toolKey(tool);
10875
+ if (deduped.has(key)) console.warn(`Tool '${tool.name}' is listed more than once for agent '${tool.agentId || "global"}' in the same useFrontendTools call. Using the last entry.`);
10876
+ deduped.set(key, tool);
10877
+ }
10878
+ const unregisters = [];
10879
+ for (const tool of deduped.values()) {
10880
+ if (core.getTool({
10881
+ toolName: tool.name,
10882
+ agentId: tool.agentId
10883
+ })) console.warn(`Tool '${tool.name}' already exists for agent '${tool.agentId || "global"}'. Overriding with latest registration.`);
10884
+ unregisters.push(core.addTool(tool));
10885
+ if (tool.render) addRenderer({
10886
+ name: tool.name,
10887
+ args: tool.parameters,
10888
+ agentId: tool.agentId,
10889
+ render: tool.render
10890
+ });
10891
+ }
10892
+ return () => {
10893
+ for (const unregister of unregisters) unregister();
10894
+ };
10895
+ }
10618
10896
 
10619
10897
  //#endregion
10620
10898
  //#region src/utils/markdown/complete-partial-markdown.ts
@@ -10840,10 +11118,11 @@ const threadDomainEvents = createActionGroup("Thread Domain", {
10840
11118
  threadDeleted: props()
10841
11119
  });
10842
11120
  function sortThreadsByRecency(threads) {
10843
- return [...threads].sort((left, right) => {
10844
- const leftKey = left.lastRunAt ?? left.updatedAt ?? left.createdAt;
10845
- return (right.lastRunAt ?? right.updatedAt ?? right.createdAt).localeCompare(leftKey);
10846
- });
11121
+ return [...threads].sort((left, right) => recencyOf(right) - recencyOf(left));
11122
+ }
11123
+ function recencyOf(thread) {
11124
+ const time = Date.parse(thread.lastRunAt ?? thread.updatedAt ?? thread.createdAt);
11125
+ return Number.isNaN(time) ? Number.NEGATIVE_INFINITY : time;
10847
11126
  }
10848
11127
  function upsertThread(threads, thread) {
10849
11128
  const existingIndex = threads.findIndex((item) => item.id === thread.id);
@@ -14162,6 +14441,31 @@ function ɵresolveCustomMessageRenderContext(renderers, chatAgentId) {
14162
14441
  renderers: ɵresolveCustomMessageRenderers(renderers, agentId)
14163
14442
  };
14164
14443
  }
14444
+ /** The run that produced a message, else the thread's latest run. */
14445
+ function resolveMessageRunId(core, agentId, threadId, messageId) {
14446
+ return core.getRunIdForMessage(agentId, threadId, messageId) ?? core.getRunIdsForThread(agentId, threadId).at(-1);
14447
+ }
14448
+ /**
14449
+ * The agent state of the run that produced a message: the same value as
14450
+ * {@link ɵgetCustomMessageRenderProps}'s `stateSnapshot`, without the work of
14451
+ * placing the message in its run. Adapters use it to tell when a custom
14452
+ * message renderer must draw again.
14453
+ *
14454
+ * It clones the run state on each call. With no run at all it returns
14455
+ * `undefined`.
14456
+ *
14457
+ * @example
14458
+ * ```ts
14459
+ * const snapshot = ɵgetMessageRunStateSnapshot(core, {
14460
+ * agentId, threadId, messageId: message.id,
14461
+ * });
14462
+ * ```
14463
+ */
14464
+ function ɵgetMessageRunStateSnapshot(core, params) {
14465
+ const { agentId, threadId, messageId } = params;
14466
+ const runId = resolveMessageRunId(core, agentId, threadId, messageId);
14467
+ return runId === void 0 ? void 0 : core.getStateByRun(agentId, threadId, runId);
14468
+ }
14165
14469
  /**
14166
14470
  * The props a custom message renderer gets for one message: the run that
14167
14471
  * produced it, its place in the conversation and in the run, and the agent
@@ -14190,7 +14494,7 @@ function ɵresolveCustomMessageRenderContext(renderers, chatAgentId) {
14190
14494
  */
14191
14495
  function ɵgetCustomMessageRenderProps(core, params) {
14192
14496
  const { agentId, threadId, agent, message, position } = params;
14193
- const resolvedRunId = core.getRunIdForMessage(agentId, threadId, message.id) ?? core.getRunIdsForThread(agentId, threadId).at(-1);
14497
+ const resolvedRunId = resolveMessageRunId(core, agentId, threadId, message.id);
14194
14498
  const messages = agent?.messages ?? [];
14195
14499
  const messageIdsInRun = resolvedRunId === void 0 ? [message.id] : messages.filter((candidate) => core.getRunIdForMessage(agentId, threadId, candidate.id) === resolvedRunId).map((candidate) => candidate.id);
14196
14500
  const messageIndex = Math.max(0, messages.findIndex((candidate) => candidate.id === message.id));
@@ -14301,7 +14605,7 @@ function ɵbuildToolCallRenderProps(toolCall, toolMessage, options) {
14301
14605
  if (toolMessage !== void 0) return {
14302
14606
  ...base,
14303
14607
  status: ToolCallStatus.Complete,
14304
- result: contentToText(toolMessage.content)
14608
+ result: toolResultText(toolMessage)
14305
14609
  };
14306
14610
  if (status === ToolCallStatus.Executing) return {
14307
14611
  ...base,
@@ -14314,6 +14618,35 @@ function ɵbuildToolCallRenderProps(toolCall, toolMessage, options) {
14314
14618
  result: void 0
14315
14619
  };
14316
14620
  }
14621
+ const warnedToolMessages = /* @__PURE__ */ new WeakSet();
14622
+ /**
14623
+ * The tool result as renderers take it, `result: string`. AG-UI 1.0 lets a
14624
+ * tool result carry content parts: renderers get the text parts, and the
14625
+ * message keeps the media.
14626
+ *
14627
+ * Other content only comes from a producer that skipped validation: restored
14628
+ * thread history, a non-SSE transport, or app code casting on `addMessage`.
14629
+ * It is serialized as JSON, not dropped, because an empty string is a
14630
+ * legitimate tool result and a dropped one would look the same. `null` gives
14631
+ * `""`. It warns once per message outside production, and never throws, also
14632
+ * not on circular content.
14633
+ */
14634
+ function toolResultText(toolMessage) {
14635
+ const content = toolMessage.content;
14636
+ if (typeof content === "string") return content;
14637
+ if (Array.isArray(content) && content.every(isContentPart)) return contentToText(content);
14638
+ let serialized = "";
14639
+ if (content !== null && content !== void 0) try {
14640
+ serialized = JSON.stringify(content) ?? Object.prototype.toString.call(content);
14641
+ } catch {
14642
+ serialized = Object.prototype.toString.call(content);
14643
+ }
14644
+ if (process.env.NODE_ENV !== "production" && !warnedToolMessages.has(toolMessage)) {
14645
+ warnedToolMessages.add(toolMessage);
14646
+ console.warn(`[CopilotChat] Tool message for tool call "${toolMessage.toolCallId}" had content outside the AG-UI protocol (${content === null ? "null" : typeof content}), but renderers receive \`result: string\`. Rendering a serialized form instead of dropping it: ${serialized === "" ? "<empty>" : serialized}`);
14647
+ }
14648
+ return serialized;
14649
+ }
14317
14650
  /**
14318
14651
  * The agent to look up tool-call renderers for: the chat's agent, else the
14319
14652
  * agent that wrote the message, else the default agent.
@@ -14406,6 +14739,41 @@ function ɵcomponentToolDescription(name, description) {
14406
14739
  const prefix = `Use this tool to display the "${name}" component in the chat. This tool renders a visual UI component for the user.`;
14407
14740
  return description ? `${prefix}\n\n${description}` : prefix;
14408
14741
  }
14742
+ const warnedUnknownStatuses = /* @__PURE__ */ new Set();
14743
+ /**
14744
+ * The status the default tool-call renderer shows. A status this version
14745
+ * does not know (a newer runtime could send one) reads `"inProgress"`, and
14746
+ * logs one warning per distinct value.
14747
+ *
14748
+ * @param status - A `ToolCallStatus`, or any framework's spelling of one.
14749
+ */
14750
+ function ɵtoDefaultToolCallStatus(status) {
14751
+ const key = String(status);
14752
+ const normalized = ɵnormalizeToolCallStatus(key);
14753
+ if (normalized !== "unknown") return normalized;
14754
+ if (!warnedUnknownStatuses.has(key)) {
14755
+ warnedUnknownStatuses.add(key);
14756
+ console.warn(`[CopilotKit] Unknown ToolCallStatus "${key}" in default tool-call renderer; falling back to "inProgress".`);
14757
+ }
14758
+ return "inProgress";
14759
+ }
14760
+ /**
14761
+ * Turns the props a `"*"` renderer is called with into the documented
14762
+ * {@link ɵDefaultToolCallRenderProps}: `args` becomes `parameters`, and the
14763
+ * status goes through {@link ɵtoDefaultToolCallStatus}. Props already in the
14764
+ * documented shape stay as they are.
14765
+ *
14766
+ * @param raw - The props the renderer was called with.
14767
+ */
14768
+ function ɵadaptDefaultToolCallRenderProps(raw) {
14769
+ return {
14770
+ name: raw.name,
14771
+ toolCallId: raw.toolCallId,
14772
+ parameters: raw.parameters !== void 0 ? raw.parameters : raw.args,
14773
+ status: ɵtoDefaultToolCallStatus(raw.status),
14774
+ result: raw.result
14775
+ };
14776
+ }
14409
14777
 
14410
14778
  //#endregion
14411
14779
  //#region src/chat/tool-call-layout.ts
@@ -15300,7 +15668,7 @@ var ɵAttachmentQueue = class {
15300
15668
  value: await readFileAsBase64(file),
15301
15669
  mimeType: file.type
15302
15670
  };
15303
- const thumbnail = placeholder.type === "video" ? await generateVideoThumbnail(file) : void 0;
15671
+ const thumbnail = placeholder.type === "video" ? await generateVideoThumbnail(file).catch(() => {}) : void 0;
15304
15672
  const isStillQueued = this.attachments.some((attachment) => attachment.id === placeholder.id);
15305
15673
  if (this.disposed || !isStillQueued) return;
15306
15674
  this.update(this.attachments.map((attachment) => attachment.id === placeholder.id ? {
@@ -16028,6 +16396,287 @@ var ɵThreadSwitchCoordinator = class {
16028
16396
  }
16029
16397
  };
16030
16398
 
16399
+ //#endregion
16400
+ //#region src/chat/chat-connection.ts
16401
+ /**
16402
+ * Calls `handler` for every core error that belongs to `agentId`, and for
16403
+ * errors that name no agent. Core awaits its subscribers, so the handler's
16404
+ * promise is not awaited: a slow handler must not hold up the run that
16405
+ * reported the error. Returns the unsubscribe.
16406
+ */
16407
+ function ɵsubscribeToAgentErrors(core, agentId, handler) {
16408
+ const subscription = core.subscribe({ onError: (event) => {
16409
+ const eventAgentId = event.context.agentId;
16410
+ if (eventAgentId && eventAgentId !== agentId) return;
16411
+ handler({
16412
+ error: event.error,
16413
+ code: event.code,
16414
+ context: event.context
16415
+ });
16416
+ } });
16417
+ return () => subscription.unsubscribe();
16418
+ }
16419
+ /**
16420
+ * The thread a chat shows when no caller picked one: a locally minted id.
16421
+ * The id stays the same while no thread is provided, and a new one is minted
16422
+ * each time a provided thread goes away, so removing a thread starts a fresh
16423
+ * one instead of returning to an older fresh thread.
16424
+ *
16425
+ * {@link resolve} returns the same id for the same input, so a framework can
16426
+ * call it while it renders.
16427
+ */
16428
+ var ɵFreshThreadId = class {
16429
+ generated = randomUUID$1();
16430
+ lastProvided;
16431
+ /** `providedThreadId` when set, else the fresh thread's id. */
16432
+ resolve(providedThreadId) {
16433
+ if (providedThreadId) {
16434
+ this.lastProvided = providedThreadId;
16435
+ return providedThreadId;
16436
+ }
16437
+ if (this.lastProvided !== void 0) {
16438
+ this.lastProvided = void 0;
16439
+ this.generated = randomUUID$1();
16440
+ }
16441
+ return this.generated;
16442
+ }
16443
+ };
16444
+ /**
16445
+ * Whether `agent` can load a thread from its backend: it overrides AG-UI's
16446
+ * `connect` or `connectAgent`. The base versions only throw
16447
+ * `AGUIConnectNotImplementedError`.
16448
+ */
16449
+ function ɵimplementsConnect(agent) {
16450
+ const base = AbstractAgent.prototype;
16451
+ return Reflect.get(agent, "connect") !== Reflect.get(base, "connect") || Reflect.get(agent, "connectAgent") !== Reflect.get(base, "connectAgent");
16452
+ }
16453
+ function defaultAfterPaint(callback) {
16454
+ if (typeof requestAnimationFrame === "function") requestAnimationFrame(() => callback());
16455
+ else setTimeout(callback, 16);
16456
+ }
16457
+ /**
16458
+ * The connect side of a chat: keeps the agent on the thread the chat shows
16459
+ * and loads that thread from the backend. Owns the rules all three
16460
+ * frameworks share:
16461
+ *
16462
+ * - Only a thread a caller picked (explicit) is connected. A locally minted
16463
+ * thread has never reached the backend, so `/connect` would 404.
16464
+ * - A connect waits for the previous thread's teardown, and a send waits for
16465
+ * the connect ({@link threads}).
16466
+ * - An `HttpAgent` connect gets its own `AbortController`, aborted when the
16467
+ * chat leaves the thread before the connect settles.
16468
+ * - Leaving a thread detaches the agent's run only while that run is the
16469
+ * connect's own. A run the user started after the connect keeps running.
16470
+ * - An agent that does not implement connect is not connected, and its
16471
+ * thread counts as loaded at once. On the agent's first thread its
16472
+ * messages stay, so a message sent right after mount survives. A move
16473
+ * from another thread detaches the old thread's run and empties the agent,
16474
+ * as a connect would. An `AGUIConnectNotImplementedError` from a connect
16475
+ * is not an error.
16476
+ * - A failed connect of an Inspector override ends the override.
16477
+ * - The chat shows "connecting" for an explicit thread until its connect has
16478
+ * settled and painted ({@link isConnecting}).
16479
+ *
16480
+ * @example
16481
+ * ```ts
16482
+ * const connection = new ɵChatConnection({ core, onInspectorOverrideFailed });
16483
+ * const handle = connection.open({ agent, threadId, explicit: true });
16484
+ * connection.isConnecting({ threadId, explicit: true }); // true until settled
16485
+ * // cleanup:
16486
+ * handle.release();
16487
+ * ```
16488
+ */
16489
+ var ɵChatConnection = class {
16490
+ /** The thread coordinator; a chat submitter waits on its connections. */
16491
+ threads;
16492
+ snapshot = { connectedThreadId: null };
16493
+ listeners = /* @__PURE__ */ new Set();
16494
+ afterPaint;
16495
+ /** The thread each agent showed last, to tell a thread switch from a first open. */
16496
+ openedThreads = /* @__PURE__ */ new WeakMap();
16497
+ constructor(options) {
16498
+ this.options = options;
16499
+ this.threads = new ɵThreadSwitchCoordinator(options.core);
16500
+ this.afterPaint = options.afterPaint ?? defaultAfterPaint;
16501
+ }
16502
+ /** The last connected thread. Keeps its identity until it changes. */
16503
+ getSnapshot() {
16504
+ return this.snapshot;
16505
+ }
16506
+ /** Calls `listener` after every snapshot change. Returns the unsubscribe. */
16507
+ subscribe(listener) {
16508
+ this.listeners.add(listener);
16509
+ return () => {
16510
+ this.listeners.delete(listener);
16511
+ };
16512
+ }
16513
+ /**
16514
+ * Whether the chat waits for `threadId` to load: an explicit thread whose
16515
+ * connect has not settled yet. Pure, so a framework can call it while it
16516
+ * renders, before {@link open} has run for a new thread.
16517
+ */
16518
+ isConnecting({ threadId, explicit }) {
16519
+ return explicit && this.snapshot.connectedThreadId !== threadId;
16520
+ }
16521
+ /**
16522
+ * Shows a thread: selects it on the coordinator (pinning `agent.threadId`)
16523
+ * and, for an explicit thread, connects it. Release the handle when the
16524
+ * chat moves on or unmounts.
16525
+ */
16526
+ open(input, hooks = {}) {
16527
+ const previousThreadId = this.openedThreads.get(input.agent);
16528
+ const selection = this.threads.select(input);
16529
+ this.openedThreads.set(selection.agent, selection.threadId);
16530
+ if (!selection.shouldConnect) return {
16531
+ selection,
16532
+ release: () => selection.release()
16533
+ };
16534
+ if (!ɵimplementsConnect(selection.agent)) {
16535
+ if (previousThreadId !== void 0 && previousThreadId !== input.threadId) this.clearSwitchedThread(selection);
16536
+ this.setConnectedThreadId(selection.threadId);
16537
+ return {
16538
+ selection,
16539
+ release: () => selection.release()
16540
+ };
16541
+ }
16542
+ return this.connect(selection, hooks);
16543
+ }
16544
+ /**
16545
+ * Runs `connect` as a connection of the current thread, so a send waits for
16546
+ * it. With no current thread it just runs, and a failure is logged.
16547
+ */
16548
+ track(connect) {
16549
+ const selection = this.threads.current;
16550
+ if (selection) return this.threads.trackConnection(selection, connect);
16551
+ return connect().then(() => {}).catch((error) => {
16552
+ console.error("CopilotChat: connection failed", error);
16553
+ });
16554
+ }
16555
+ /** Releases the current thread and drops the listeners. */
16556
+ dispose() {
16557
+ this.threads.dispose();
16558
+ this.listeners.clear();
16559
+ }
16560
+ /**
16561
+ * What a connect does when an agent without `connect` moves to another
16562
+ * thread: detaches the old thread's run and empties the agent. The reset
16563
+ * runs again once the detach and every earlier teardown finished, and a
16564
+ * send waits for it, so nothing of the old thread lands on the new one.
16565
+ */
16566
+ clearSwitchedThread(selection) {
16567
+ const { agent, threadId } = selection;
16568
+ const reset = () => {
16569
+ if (selection.isCurrent) ɵresetAgentThreadBaseline(agent, { cursorThreadId: threadId });
16570
+ };
16571
+ this.threads.detach(agent);
16572
+ reset();
16573
+ this.threads.trackConnection(selection, async () => {
16574
+ await this.threads.whenTornDown();
16575
+ reset();
16576
+ });
16577
+ }
16578
+ setConnectedThreadId(threadId) {
16579
+ if (this.snapshot.connectedThreadId === threadId) return;
16580
+ this.snapshot = { connectedThreadId: threadId };
16581
+ for (const listener of this.listeners) listener();
16582
+ }
16583
+ connect(selection, hooks) {
16584
+ const { core, onInspectorOverrideFailed } = this.options;
16585
+ const { agent, threadId, inspectorRequestId } = selection;
16586
+ const controller = new AbortController();
16587
+ let ownership;
16588
+ let released = false;
16589
+ let settled = false;
16590
+ const failInspectorOverride = () => {
16591
+ if (inspectorRequestId) onInspectorOverrideFailed?.(inspectorRequestId);
16592
+ };
16593
+ const inspectorErrors = inspectorRequestId ? core.subscribe({ onError: (event) => {
16594
+ if (event.code === CopilotKitCoreErrorCode.AGENT_CONNECT_FAILED && event.context.agentId === agent.agentId && event.context.threadId === threadId && !released) failInspectorOverride();
16595
+ } }) : void 0;
16596
+ hooks.onStart?.();
16597
+ this.threads.trackConnection(selection, async () => {
16598
+ try {
16599
+ await this.threads.whenTornDown();
16600
+ if (released) return;
16601
+ if (ɵisHttpAgent(agent)) agent.abortController = controller;
16602
+ ownership = new ConnectOwnership(agent);
16603
+ await core.connectAgent({ agent });
16604
+ } catch (error) {
16605
+ if (released || error instanceof AGUIConnectNotImplementedError) return;
16606
+ failInspectorOverride();
16607
+ throw error;
16608
+ }
16609
+ }).finally(() => {
16610
+ settled = true;
16611
+ ownership?.stopWatching();
16612
+ if (released) selection.clearDiscardedBaseline();
16613
+ else this.afterPaint(() => {
16614
+ if (!released) this.setConnectedThreadId(threadId);
16615
+ });
16616
+ hooks.onSettled?.(!released);
16617
+ });
16618
+ return {
16619
+ selection,
16620
+ release: () => {
16621
+ if (released) return;
16622
+ released = true;
16623
+ selection.release();
16624
+ inspectorErrors?.unsubscribe();
16625
+ const ownsRun = !settled && ownership?.ownsActiveRun() === true;
16626
+ if (ownership?.replaced !== true && (!settled || ɵisHttpAgent(agent) && agent.abortController !== controller)) controller.abort();
16627
+ ownership?.stopWatching();
16628
+ if (ownsRun) this.threads.detach(agent);
16629
+ }
16630
+ };
16631
+ }
16632
+ };
16633
+ /**
16634
+ * Tells whether the agent's active run is still the pipeline a connect
16635
+ * started, or whether another run replaced it. It watches from the moment it
16636
+ * is created, and takes the first run that initializes after that for the
16637
+ * connect's own, so create it right before the connect starts.
16638
+ */
16639
+ var ConnectOwnership = class {
16640
+ /** Set when another run initialized on the agent after the connect's own. */
16641
+ replaced = false;
16642
+ initialized;
16643
+ completion;
16644
+ refresh;
16645
+ subscription;
16646
+ constructor(agent) {
16647
+ this.agent = agent;
16648
+ this.subscription = agent.subscribe({
16649
+ onRunInitialized: ({ input }) => {
16650
+ if (this.initialized && input !== this.initialized) {
16651
+ this.replaced = true;
16652
+ return;
16653
+ }
16654
+ this.initialized = input;
16655
+ this.refresh = setTimeout(() => this.isOwnPipeline(), 0);
16656
+ },
16657
+ onRunStartedEvent: () => {
16658
+ this.isOwnPipeline();
16659
+ }
16660
+ });
16661
+ }
16662
+ /** Whether detaching the agent stops only the connect's own run. */
16663
+ ownsActiveRun() {
16664
+ return this.isOwnPipeline() || !this.initialized;
16665
+ }
16666
+ stopWatching() {
16667
+ clearTimeout(this.refresh);
16668
+ this.subscription.unsubscribe();
16669
+ }
16670
+ isOwnPipeline() {
16671
+ if (!this.initialized || this.replaced) return false;
16672
+ const candidate = this.agent;
16673
+ const current = isRunCompletionAware(candidate) ? candidate.activeRunCompletionPromise : void 0;
16674
+ if (!current) return false;
16675
+ this.completion ??= current;
16676
+ return current === this.completion;
16677
+ }
16678
+ };
16679
+
16031
16680
  //#endregion
16032
16681
  //#region src/chat/message-view.ts
16033
16682
  const NO_LAYOUTS = /* @__PURE__ */ new Map();
@@ -16322,7 +16971,7 @@ function ɵcomposerButtonState(input) {
16322
16971
  * This handles Enter only. Keys for the slash-command menu stay in each
16323
16972
  * framework, and the framework handles them before it calls this function.
16324
16973
  *
16325
- * Results:
16974
+ * `action`:
16326
16975
  * - `"send"`: send the trimmed text.
16327
16976
  * - `"stop"`: stop the run. This happens for Enter in an empty input while
16328
16977
  * the agent runs. Text in the input always means send, not stop.
@@ -16331,9 +16980,9 @@ function ɵcomposerButtonState(input) {
16331
16980
  * is disabled, for keys other than Enter, and for an Enter that has
16332
16981
  * nothing to send or stop.
16333
16982
  *
16334
- * Call `preventDefault()` for every Enter without Shift that is not part of
16335
- * IME composition, including when the result is `"none"`. This stops Enter
16336
- * from adding a line break that the user cannot send.
16983
+ * `preventDefault` is `true` for every Enter without Shift that is not part
16984
+ * of IME composition, also when `action` is `"none"`: Enter never adds a line
16985
+ * break that the user cannot send.
16337
16986
  *
16338
16987
  * @param event - The keyboard event, or an object with the same fields.
16339
16988
  * @param input - The current state of the chat input.
@@ -16341,18 +16990,35 @@ function ɵcomposerButtonState(input) {
16341
16990
  * @example
16342
16991
  * ```ts
16343
16992
  * function onKeyDown(event: KeyboardEvent) {
16344
- * if (event.isComposing || event.keyCode === 229) return;
16345
16993
  * // ...slash-command menu keys...
16346
- * const result = ɵresolveComposerKey(event, composerInput);
16347
- * if (event.key === "Enter" && !event.shiftKey) event.preventDefault();
16348
- * if (result === "send") sendMessage(composerInput.value.trim());
16349
- * if (result === "stop") stopRun();
16994
+ * const { action, preventDefault } = ɵresolveComposerKey(event, composerInput);
16995
+ * if (preventDefault) event.preventDefault();
16996
+ * if (action === "send") sendMessage(composerInput.value.trim());
16997
+ * if (action === "stop") stopRun();
16350
16998
  * }
16351
16999
  * ```
16352
17000
  */
16353
17001
  function ɵresolveComposerKey(event, input) {
16354
- if (event.isComposing || event.keyCode === 229 || input.disabled === true || event.key !== "Enter") return "none";
16355
- if (event.shiftKey) return "newline";
17002
+ if (isImeComposition(event) || event.key !== "Enter") return {
17003
+ action: "none",
17004
+ preventDefault: false
17005
+ };
17006
+ if (event.shiftKey) return {
17007
+ action: "newline",
17008
+ preventDefault: false
17009
+ };
17010
+ return {
17011
+ action: resolveEnter(input),
17012
+ preventDefault: true
17013
+ };
17014
+ }
17015
+ /** `true` while the key is part of IME composition (for example CJK input). */
17016
+ function isImeComposition(event) {
17017
+ return event.isComposing || event.keyCode === 229;
17018
+ }
17019
+ /** What Enter without Shift does. */
17020
+ function resolveEnter(input) {
17021
+ if (input.disabled === true) return "none";
16356
17022
  const button = ɵcomposerButtonState(input);
16357
17023
  const isEmpty = input.value.trim().length === 0;
16358
17024
  if (button.isProcessing && isEmpty) return input.canStop ? "stop" : "none";
@@ -16507,6 +17173,255 @@ function ɵresolveSlashKey(event, state) {
16507
17173
  default: return none;
16508
17174
  }
16509
17175
  }
17176
+ /**
17177
+ * The tools menu the "+" button opens: the default "Add file" item first,
17178
+ * then the app's items. A separator goes between the two parts. Separators
17179
+ * next to each other become one, and separators at the start or end are
17180
+ * dropped. Nested groups stay as they are.
17181
+ *
17182
+ * @param toolsMenu - The app's items. `"-"` is a separator.
17183
+ * @param addFileItem - The default "Add file" item, or `undefined` when the
17184
+ * chat takes no files.
17185
+ *
17186
+ * @example
17187
+ * ```ts
17188
+ * ɵnormalizeToolsMenu(["-", search, "-", "-", summarize, "-"], addFile);
17189
+ * // → [addFile, "-", search, "-", summarize]
17190
+ * ```
17191
+ */
17192
+ function ɵnormalizeToolsMenu(toolsMenu, addFileItem) {
17193
+ const items = [];
17194
+ if (addFileItem !== void 0) items.push(addFileItem, "-");
17195
+ for (const item of toolsMenu ?? []) if (!(item === "-" && (items.length === 0 || items[items.length - 1] === "-"))) items.push(item);
17196
+ while (items[items.length - 1] === "-") items.pop();
17197
+ return items;
17198
+ }
17199
+ /**
17200
+ * The tools menu as a flat list of rows, for a menu that draws groups inline
17201
+ * instead of as submenus. A group becomes a label row followed by its items
17202
+ * one level deeper. Leaf items without an `action` are dropped. Each row has
17203
+ * a `key` that stays the same while the menu does.
17204
+ *
17205
+ * @param menu - The menu from {@link ɵnormalizeToolsMenu}.
17206
+ */
17207
+ function ɵflattenToolsMenuForDisplay(menu) {
17208
+ const walk = (items, depth, prefix) => items.flatMap((item, index) => {
17209
+ const key = `${prefix}-${index}`;
17210
+ if (item === "-") return [{
17211
+ type: "separator",
17212
+ key: `sep-${key}`
17213
+ }];
17214
+ if (item.items && item.items.length > 0) return [{
17215
+ type: "label",
17216
+ key: `label-${key}`,
17217
+ label: item.label,
17218
+ depth
17219
+ }, ...walk(item.items, depth + 1, key)];
17220
+ if (!item.action) return [];
17221
+ return [{
17222
+ type: "item",
17223
+ key: `item-${key}`,
17224
+ label: item.label,
17225
+ depth,
17226
+ action: item.action
17227
+ }];
17228
+ });
17229
+ return walk(menu, 0, "root");
17230
+ }
17231
+ /**
17232
+ * Make the recorder follow the chat input's mode: it starts recording when
17233
+ * the mode is `"transcribe"` and it is idle, and it stops when the mode
17234
+ * changes while it records. Call it when the mode or the recorder changes.
17235
+ * Errors are logged, not thrown.
17236
+ *
17237
+ * @param recorder - The recorder, or `null` before it renders.
17238
+ * @param mode - The chat input's mode.
17239
+ */
17240
+ async function ɵsyncRecorderToMode(recorder, mode) {
17241
+ if (!recorder) return;
17242
+ try {
17243
+ if (mode === "transcribe") {
17244
+ if (recorder.state === "idle") await recorder.start();
17245
+ } else if (recorder.state === "recording") await recorder.stop();
17246
+ } catch (error) {
17247
+ console.error(error);
17248
+ }
17249
+ }
17250
+ /**
17251
+ * Whether the chat input shows its disclaimer: as `showDisclaimer` says, or,
17252
+ * when it is not set, only when the input is pinned with absolute
17253
+ * positioning.
17254
+ */
17255
+ function ɵshowsComposerDisclaimer(options) {
17256
+ return options.showDisclaimer ?? options.positioning === "absolute";
17257
+ }
17258
+ /**
17259
+ * The text and slash-command menu of one chat input.
17260
+ *
17261
+ * - The text is the app's `value` when it sets one (controlled), else the
17262
+ * controller keeps it. Every change calls `onChange`, in both cases.
17263
+ * - The slash menu opens while the text starts with `/` in input mode and
17264
+ * the menu has commands. Escape, running a command, and leaving input mode
17265
+ * close it until the text changes.
17266
+ * - The highlight goes to the first row when the query changes and stays on
17267
+ * a row that exists when the list changes.
17268
+ *
17269
+ * Frameworks render from `getSnapshot()` and re-render when `subscribe()`
17270
+ * notifies. Call `setInputs()` whenever the app's value, the mode, or the
17271
+ * tools menu changes.
17272
+ *
17273
+ * @example
17274
+ * ```ts
17275
+ * const composer = new ɵComposerController({ onChange: emitChange });
17276
+ * composer.setInputs({ value: undefined, mode: "input", menu });
17277
+ * textarea.oninput = () => composer.setValue(textarea.value);
17278
+ * textarea.onkeydown = (event) => {
17279
+ * const { preventDefault, action } = composer.keyDown(event, composerInput);
17280
+ * if (preventDefault) event.preventDefault();
17281
+ * if (action === "send") composer.submit(sendMessage);
17282
+ * };
17283
+ * ```
17284
+ */
17285
+ var ɵComposerController = class {
17286
+ #listeners = /* @__PURE__ */ new Set();
17287
+ #onChange;
17288
+ #internalValue;
17289
+ #controlledValue;
17290
+ #mode = "input";
17291
+ #menu = [];
17292
+ #commands = [];
17293
+ #closedFor = null;
17294
+ #state;
17295
+ constructor({ initialValue = "", onChange } = {}) {
17296
+ this.#internalValue = initialValue;
17297
+ this.#onChange = onChange;
17298
+ this.#state = {
17299
+ value: initialValue,
17300
+ slashQuery: null,
17301
+ slashCommands: [],
17302
+ slashHighlightIndex: 0
17303
+ };
17304
+ }
17305
+ /** The current state. The same object until something changes. */
17306
+ getSnapshot = () => this.#state;
17307
+ /** Calls `listener` when the state changes. Returns the unsubscribe function. */
17308
+ subscribe = (listener) => {
17309
+ this.#listeners.add(listener);
17310
+ return () => {
17311
+ this.#listeners.delete(listener);
17312
+ };
17313
+ };
17314
+ /** Takes the app's value, the mode, and the tools menu. */
17315
+ setInputs = ({ value, mode, menu }) => {
17316
+ this.#controlledValue = value;
17317
+ if (menu !== this.#menu) {
17318
+ this.#menu = menu;
17319
+ this.#commands = ɵflattenCommandItems(menu);
17320
+ }
17321
+ if (mode !== this.#mode) {
17322
+ this.#mode = mode;
17323
+ if (mode !== "input") this.#closedFor = this.#value();
17324
+ }
17325
+ this.#refresh();
17326
+ };
17327
+ /** The user changed the text. */
17328
+ setValue = (value) => {
17329
+ if (this.#controlledValue === void 0) this.#internalValue = value;
17330
+ this.#onChange?.(value);
17331
+ this.#refresh();
17332
+ };
17333
+ /** Highlights row `index` of the slash menu, for example on hover. */
17334
+ highlight = (index) => {
17335
+ this.#refresh(index);
17336
+ };
17337
+ /** Closes the slash menu and keeps the text. */
17338
+ closeSlashMenu = () => {
17339
+ this.#closedFor = this.#value();
17340
+ this.#refresh();
17341
+ };
17342
+ /** Clears the text, closes the slash menu, and runs `command`. */
17343
+ runCommand = (command) => {
17344
+ this.#closedFor = this.#value();
17345
+ this.setValue("");
17346
+ command.action?.();
17347
+ };
17348
+ /**
17349
+ * Sends the trimmed text with `send` and then clears the input. Does
17350
+ * nothing for text that is only whitespace.
17351
+ *
17352
+ * @param send - Receives the trimmed text.
17353
+ * @param options.value - The text to send, when the framework has a newer
17354
+ * one than the snapshot (a controlled value can lag a tick).
17355
+ * @param options.clear - Clear the input after sending. Default: `true`.
17356
+ * @returns Whether `send` was called.
17357
+ */
17358
+ submit = (send, { value = this.#value(), clear = true } = {}) => {
17359
+ const trimmed = value.trim();
17360
+ if (!trimmed) return false;
17361
+ send(trimmed);
17362
+ if (clear) this.setValue("");
17363
+ return true;
17364
+ };
17365
+ /**
17366
+ * Handles a key press in the text box: the slash-menu keys first, then
17367
+ * Enter as {@link ɵresolveComposerKey} decides.
17368
+ *
17369
+ * @param event - The keyboard event, or an object with the same fields.
17370
+ * @param input - The chat input's state for the send or stop decision.
17371
+ */
17372
+ keyDown = (event, input) => {
17373
+ if (isImeComposition(event)) return {
17374
+ preventDefault: false,
17375
+ action: "none"
17376
+ };
17377
+ const slash = ɵresolveSlashKey(event, {
17378
+ query: this.#state.slashQuery,
17379
+ commands: this.#state.slashCommands,
17380
+ highlightIndex: this.#state.slashHighlightIndex
17381
+ });
17382
+ switch (slash.type) {
17383
+ case "highlight":
17384
+ this.highlight(slash.index);
17385
+ return {
17386
+ preventDefault: true,
17387
+ action: "none"
17388
+ };
17389
+ case "run":
17390
+ this.runCommand(slash.command);
17391
+ return {
17392
+ preventDefault: true,
17393
+ action: "command"
17394
+ };
17395
+ case "close":
17396
+ this.closeSlashMenu();
17397
+ return {
17398
+ preventDefault: true,
17399
+ action: "none"
17400
+ };
17401
+ case "none": return ɵresolveComposerKey(event, input);
17402
+ }
17403
+ };
17404
+ #value() {
17405
+ return this.#controlledValue ?? this.#internalValue;
17406
+ }
17407
+ #refresh(highlight = this.#state.slashHighlightIndex) {
17408
+ const value = this.#value();
17409
+ if (this.#closedFor !== null && this.#closedFor !== value) this.#closedFor = null;
17410
+ const slashQuery = this.#mode === "input" && this.#closedFor === null ? ɵparseSlashQuery(value, this.#commands.length > 0) : null;
17411
+ const slashCommands = ɵfilterCommands(this.#commands, slashQuery);
17412
+ const queryChanged = slashQuery !== this.#state.slashQuery;
17413
+ const slashHighlightIndex = slashQuery === null || queryChanged && slashCommands.length > 0 ? 0 : ɵclampSlashIndex(highlight, slashCommands.length);
17414
+ const previous = this.#state;
17415
+ if (value === previous.value && slashQuery === previous.slashQuery && slashHighlightIndex === previous.slashHighlightIndex && slashCommands.length === previous.slashCommands.length && slashCommands.every((command, i) => command === previous.slashCommands[i])) return;
17416
+ this.#state = {
17417
+ value,
17418
+ slashQuery,
17419
+ slashCommands,
17420
+ slashHighlightIndex
17421
+ };
17422
+ for (const listener of this.#listeners) listener();
17423
+ }
17424
+ };
16510
17425
 
16511
17426
  //#endregion
16512
17427
  //#region src/chat/composer-layout.ts
@@ -17097,375 +18012,6 @@ function ɵcreateWaveformRenderer(canvas, recorder) {
17097
18012
  } };
17098
18013
  }
17099
18014
 
17100
- //#endregion
17101
- //#region src/chat/dom.ts
17102
- /**
17103
- * Turn a width or height prop into a CSS value.
17104
- *
17105
- * @param value - A number of pixels, or a CSS length such as `"30rem"`.
17106
- * @param fallback - The pixels to use when `value` is missing, not finite,
17107
- * or an empty string.
17108
- *
17109
- * @example
17110
- * ```ts
17111
- * ɵdimensionToCss(420, 480); // "420px"
17112
- * ɵdimensionToCss(" 30rem ", 480); // "30rem"
17113
- * ɵdimensionToCss(undefined, 480); // "480px"
17114
- * ```
17115
- */
17116
- function ɵdimensionToCss(value, fallback) {
17117
- if (typeof value === "number" && Number.isFinite(value)) return `${value}px`;
17118
- if (typeof value === "string" && value.trim().length > 0) return value.trim();
17119
- return `${fallback}px`;
17120
- }
17121
- const ONLY_ONE_DOCKED_SIDEBAR = "[CopilotKit] Only one docked CopilotSidebar may be open per document.";
17122
- /**
17123
- * Gives one docked sidebar at a time the page's inline margin on its side,
17124
- * and puts back the margins the page had before when it lets go.
17125
- *
17126
- * Get the registry of a document with {@link ɵdockedSidebarRegistryFor}.
17127
- */
17128
- var ɵDockedSidebarRegistry = class {
17129
- owner;
17130
- original = {
17131
- start: "",
17132
- end: "",
17133
- transition: ""
17134
- };
17135
- restoreTimer;
17136
- warned = /* @__PURE__ */ new Set();
17137
- constructor(document) {
17138
- this.document = document;
17139
- }
17140
- /**
17141
- * Take the page margins for `owner`.
17142
- *
17143
- * @returns `true` when `owner` now has them. `false`, with a warning, when
17144
- * another sidebar has them.
17145
- */
17146
- acquire(owner) {
17147
- if (this.owner === owner) return true;
17148
- if (this.owner !== void 0) {
17149
- if (!this.warned.has(owner)) {
17150
- this.warned.add(owner);
17151
- console.warn(ONLY_ONE_DOCKED_SIDEBAR);
17152
- }
17153
- return false;
17154
- }
17155
- const style = this.document.body.style;
17156
- const transition = this.restoreTimer === void 0 ? style.transition : this.original.transition;
17157
- this.original = {
17158
- start: style.marginInlineStart,
17159
- end: style.marginInlineEnd,
17160
- transition
17161
- };
17162
- this.cancelRestore();
17163
- this.owner = owner;
17164
- return true;
17165
- }
17166
- /** Set the margin on the sidebar's side. Does nothing unless `owner` has it. */
17167
- update(owner, placement, options = {}) {
17168
- if (this.owner !== owner) return;
17169
- const style = this.document.body.style;
17170
- this.applyTransition(options.transitionMs);
17171
- style.marginInlineStart = placement.position === "left" ? placement.width : this.original.start;
17172
- style.marginInlineEnd = placement.position === "right" ? placement.width : this.original.end;
17173
- }
17174
- /**
17175
- * Put back the page's own margins and let go. Does nothing unless `owner`
17176
- * has the margins.
17177
- */
17178
- release(owner, options = {}) {
17179
- this.warned.delete(owner);
17180
- if (this.owner !== owner) return;
17181
- const style = this.document.body.style;
17182
- this.applyTransition(options.transitionMs);
17183
- style.marginInlineStart = this.original.start;
17184
- style.marginInlineEnd = this.original.end;
17185
- this.owner = void 0;
17186
- if (options.transitionMs === void 0) return;
17187
- this.restoreTimer = setTimeout(() => {
17188
- this.restoreTimer = void 0;
17189
- if (this.owner === void 0) style.transition = this.original.transition;
17190
- }, options.transitionMs);
17191
- }
17192
- applyTransition(transitionMs) {
17193
- const style = this.document.body.style;
17194
- this.cancelRestore();
17195
- style.transition = transitionMs === void 0 ? this.original.transition : `margin-inline-start ${transitionMs}ms ease, margin-inline-end ${transitionMs}ms ease`;
17196
- }
17197
- cancelRestore() {
17198
- if (this.restoreTimer === void 0) return;
17199
- clearTimeout(this.restoreTimer);
17200
- this.restoreTimer = void 0;
17201
- }
17202
- };
17203
- const registries = /* @__PURE__ */ new WeakMap();
17204
- /** The one {@link ɵDockedSidebarRegistry} of `document`. */
17205
- function ɵdockedSidebarRegistryFor(document) {
17206
- let registry = registries.get(document);
17207
- if (!registry) {
17208
- registry = new ɵDockedSidebarRegistry(document);
17209
- registries.set(document, registry);
17210
- }
17211
- return registry;
17212
- }
17213
- /**
17214
- * Makes room on the page for an open sidebar, on desktop viewports only
17215
- * (wider than 767px). It follows viewport changes, animates every change
17216
- * after the first, and gives the page its margins back on `dispose()`.
17217
- *
17218
- * Create it with {@link ɵcreateDockedSidebar}.
17219
- */
17220
- var ɵDockedSidebar = class {
17221
- owner = Symbol("copilot-sidebar");
17222
- registry;
17223
- media;
17224
- state;
17225
- owns = false;
17226
- hasApplied = false;
17227
- constructor(document, transitionMs) {
17228
- this.transitionMs = transitionMs;
17229
- this.registry = ɵdockedSidebarRegistryFor(document);
17230
- this.media = document.defaultView?.matchMedia?.(ɵMOBILE_MAX_WIDTH_QUERY);
17231
- this.media?.addEventListener("change", this.apply);
17232
- }
17233
- /** Apply the sidebar's open state, side, and width. */
17234
- set(state) {
17235
- this.state = state;
17236
- this.apply();
17237
- }
17238
- /** Give the margins back at once and stop following the viewport. */
17239
- dispose() {
17240
- this.media?.removeEventListener("change", this.apply);
17241
- this.registry.release(this.owner);
17242
- this.owns = false;
17243
- }
17244
- apply = () => {
17245
- const state = this.state;
17246
- if (!state) return;
17247
- const transition = this.hasApplied ? { transitionMs: this.transitionMs } : {};
17248
- this.hasApplied = true;
17249
- if (!(state.open && !this.media?.matches)) {
17250
- if (this.owns) this.registry.release(this.owner, transition);
17251
- this.owns = false;
17252
- return;
17253
- }
17254
- this.owns = this.owns || this.registry.acquire(this.owner);
17255
- if (this.owns) this.registry.update(this.owner, state, transition);
17256
- };
17257
- };
17258
- /**
17259
- * Create the controller that reserves the page margin for a docked sidebar.
17260
- *
17261
- * @param document - The page.
17262
- * @param options - `transitionMs`: how long margin changes animate.
17263
- *
17264
- * @example
17265
- * ```ts
17266
- * const dock = ɵcreateDockedSidebar(document, { transitionMs: 260 });
17267
- * dock.set({ open: true, position: "right", width: "480px" });
17268
- * dock.dispose(); // on unmount
17269
- * ```
17270
- */
17271
- function ɵcreateDockedSidebar(document, options) {
17272
- return new ɵDockedSidebar(document, options.transitionMs);
17273
- }
17274
- /** How long the popup's open animation runs, in ms. */
17275
- const ɵPOPUP_ANIMATION_MS = 200;
17276
- /**
17277
- * Close an open popup on Escape and, when asked, on a pointer down outside
17278
- * it, and move focus into it once its open animation ends.
17279
- *
17280
- * A pointer down on the chat toggle button, or in a chat popover (which
17281
- * renders in a portal, outside the panel), does not close the popup. Focus
17282
- * moves to the panel only when nothing inside it has focus yet.
17283
- *
17284
- * Call it when the popup opens, and call the returned function when it
17285
- * closes or unmounts.
17286
- *
17287
- * @param options - The panel, the close callback, and whether a click
17288
- * outside closes.
17289
- */
17290
- function ɵbindPopupDismiss(options) {
17291
- if (typeof window === "undefined") return () => {};
17292
- const handleKeyDown = (event) => {
17293
- if (event.key !== "Escape") return;
17294
- event.preventDefault();
17295
- options.onDismiss();
17296
- };
17297
- const handlePointerDown = (event) => {
17298
- const target = event.target;
17299
- if (!(target instanceof Node)) return;
17300
- if (options.getContainer()?.contains(target)) return;
17301
- if ((target instanceof Element ? target : target.parentElement)?.closest("[data-slot='chat-toggle-button'], [data-copilotkit-popover]")) return;
17302
- options.onDismiss();
17303
- };
17304
- const focusTimer = setTimeout(() => {
17305
- const container = options.getContainer();
17306
- if (container && !container.contains(container.ownerDocument.activeElement)) container.focus({ preventScroll: true });
17307
- }, ɵPOPUP_ANIMATION_MS);
17308
- window.addEventListener("keydown", handleKeyDown);
17309
- if (options.clickOutsideToClose) document.addEventListener("pointerdown", handlePointerDown);
17310
- return () => {
17311
- clearTimeout(focusTimer);
17312
- window.removeEventListener("keydown", handleKeyDown);
17313
- document.removeEventListener("pointerdown", handlePointerDown);
17314
- };
17315
- }
17316
- /**
17317
- * Open or close a lightbox with the View Transition API, so the thumbnail
17318
- * morphs into the preview and back.
17319
- *
17320
- * `view-transition-name` must be on one element at a time: on the
17321
- * thumbnail before the change and on the preview after it. Bind `name` to
17322
- * the preview element. Without the API, or without a thumbnail, `apply`
17323
- * runs with no animation.
17324
- *
17325
- * @param thumbnail - The element the preview grows from.
17326
- * @param name - A `view-transition-name`, unique on the page.
17327
- * @param apply - Renders the change. It must finish the DOM update before
17328
- * it returns or resolves (React: `flushSync`; Vue: `await nextTick()`).
17329
- * @param direction - `"open"` or `"close"`.
17330
- */
17331
- function ɵmorphViewTransition(thumbnail, name, apply, direction) {
17332
- const doc = typeof document === "undefined" ? void 0 : document;
17333
- if (!(!!thumbnail && typeof doc?.startViewTransition === "function") || !thumbnail || !doc) {
17334
- apply();
17335
- return;
17336
- }
17337
- if (direction === "open") {
17338
- thumbnail.style.viewTransitionName = name;
17339
- doc.startViewTransition(async () => {
17340
- thumbnail.style.viewTransitionName = "";
17341
- await apply();
17342
- });
17343
- return;
17344
- }
17345
- const transition = doc.startViewTransition(async () => {
17346
- await apply();
17347
- thumbnail.style.viewTransitionName = name;
17348
- });
17349
- const clear = () => {
17350
- thumbnail.style.viewTransitionName = "";
17351
- };
17352
- transition.finished.then(clear, clear);
17353
- }
17354
- const FOCUSABLE = "a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), audio[controls], video[controls], iframe, [tabindex]:not([tabindex=\"-1\"])";
17355
- /**
17356
- * Make `root` behave as a modal dialog for keyboard users: focus moves into
17357
- * it, Tab and Shift+Tab wrap inside it, and focus goes back to the opener
17358
- * when the returned function runs.
17359
- *
17360
- * @param root - The dialog element.
17361
- * @param options - Where focus goes on open and on close.
17362
- * @returns A function that removes the trap and returns focus.
17363
- */
17364
- function ɵbindDialogFocus(root, options = {}) {
17365
- const doc = root.ownerDocument;
17366
- const active = doc.activeElement;
17367
- const opener = active instanceof HTMLElement ? active : null;
17368
- const focusables = () => Array.from(root.querySelectorAll(FOCUSABLE));
17369
- const handleKeyDown = (event) => {
17370
- if (event.key !== "Tab") return;
17371
- const elements = focusables();
17372
- const first = elements[0];
17373
- const last = elements[elements.length - 1];
17374
- if (!first || !last) {
17375
- event.preventDefault();
17376
- return;
17377
- }
17378
- const current = doc.activeElement;
17379
- const isOutside = !root.contains(current);
17380
- if (event.shiftKey && (current === first || isOutside)) {
17381
- event.preventDefault();
17382
- last.focus();
17383
- } else if (!event.shiftKey && (current === last || isOutside)) {
17384
- event.preventDefault();
17385
- first.focus();
17386
- }
17387
- };
17388
- root.addEventListener("keydown", handleKeyDown);
17389
- (options.initialFocus ?? focusables()[0])?.focus();
17390
- return () => {
17391
- root.removeEventListener("keydown", handleKeyDown);
17392
- const target = options.returnFocusTo ?? opener;
17393
- if (target?.isConnected) target.focus();
17394
- };
17395
- }
17396
- /**
17397
- * Which in-browser preview a document gets.
17398
- *
17399
- * @param mimeType - The document's MIME type.
17400
- * @returns `"pdf"`, `"text"` (for `text/*`), or `null` when the browser
17401
- * cannot preview it.
17402
- */
17403
- function ɵcanPreviewDocument(mimeType) {
17404
- if (!mimeType) return null;
17405
- if (mimeType.includes("pdf")) return "pdf";
17406
- if (mimeType.startsWith("text/")) return "text";
17407
- return null;
17408
- }
17409
- function decodeBase64(value) {
17410
- const binary = atob(value);
17411
- const bytes = new Uint8Array(binary.length);
17412
- for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
17413
- return bytes;
17414
- }
17415
- /**
17416
- * A URL a browser can show in an `<iframe>` for an attachment's source.
17417
- *
17418
- * Browsers block `data:` URLs for PDFs in frames, so base64 data becomes a
17419
- * `blob:` URL. Call `revoke()` when the preview closes.
17420
- *
17421
- * @param source - The attachment's source.
17422
- * @returns `{ url, revoke }`, or `null` when the data is not valid base64.
17423
- */
17424
- function ɵcreateObjectUrlFromSource(source) {
17425
- if (source.type === "url") return {
17426
- url: source.value,
17427
- revoke: () => {}
17428
- };
17429
- try {
17430
- const blob = new Blob([decodeBase64(source.value)], { type: source.mimeType || "application/octet-stream" });
17431
- const url = URL.createObjectURL(blob);
17432
- return {
17433
- url,
17434
- revoke: () => URL.revokeObjectURL(url)
17435
- };
17436
- } catch (error) {
17437
- console.error("[CopilotKit] Failed to decode attachment data:", error);
17438
- return null;
17439
- }
17440
- }
17441
- /**
17442
- * The text of a text attachment, for a `<pre>` preview.
17443
- *
17444
- * @param source - The attachment's source.
17445
- * @returns The base64 data decoded as UTF-8, the raw value when it is not
17446
- * valid base64, or `null` for a URL source (show it in a frame instead).
17447
- */
17448
- function ɵdecodeTextSource(source) {
17449
- if (source.type !== "data") return null;
17450
- try {
17451
- return new TextDecoder().decode(decodeBase64(source.value));
17452
- } catch {
17453
- return source.value;
17454
- }
17455
- }
17456
- /** How close to the end, in pixels, still counts as scrolled to the bottom. */
17457
- const ɵSCROLL_BOTTOM_THRESHOLD_PX = 12;
17458
- /**
17459
- * Whether a scroll container shows the end of its content.
17460
- *
17461
- * @param element - The scroll container.
17462
- * @param threshold - The pixels from the end that still count. Default:
17463
- * {@link ɵSCROLL_BOTTOM_THRESHOLD_PX}.
17464
- */
17465
- function ɵisScrolledToBottom(element, threshold = ɵSCROLL_BOTTOM_THRESHOLD_PX) {
17466
- return element.scrollHeight - element.scrollTop - element.clientHeight <= threshold;
17467
- }
17468
-
17469
18015
  //#endregion
17470
18016
  //#region src/chat/license.ts
17471
18017
  /**
@@ -18184,6 +18730,19 @@ function ɵgetMessageFeedbackControls(scope, message) {
18184
18730
  }
18185
18731
  };
18186
18732
  }
18733
+ /** Selects a thumb of a rated message by its rating. */
18734
+ const thumbSelector = (rating) => `[data-copilotkit-rating="${rating}"]`;
18735
+ const HIDDEN_TOO = {
18736
+ checkVisibilityCSS: true,
18737
+ visibilityProperty: true
18738
+ };
18739
+ /**
18740
+ * Whether `target` is a thumb of message `messageId`. A click on one decides
18741
+ * itself what happens to the comment, so the popover ignores it.
18742
+ */
18743
+ function ɵisOwnFeedbackThumb(target, messageId) {
18744
+ return (target instanceof Element ? target.closest("[data-copilotkit-rating]") : null)?.closest("[data-message-id]")?.getAttribute("data-message-id") === messageId;
18745
+ }
18187
18746
  /**
18188
18747
  * Drives the comment popover of a rated message.
18189
18748
  *
@@ -18194,6 +18753,12 @@ function ɵgetMessageFeedbackControls(scope, message) {
18194
18753
  * Escape. Closing saves a changed comment; Escape, a click on a thumb, and
18195
18754
  * removing the rating discard it.
18196
18755
  *
18756
+ * The thumbs are toggles (see `rate()`), and `thumb()` gives each thumb its
18757
+ * attributes and handlers. The popover lives in a portal, so it keeps the
18758
+ * keyboard order by hand (see `popoverKeyDown()` and `popoverEscape()`):
18759
+ * Shift+Tab from its start returns to the thumb, Tab from its end moves on
18760
+ * to the control after the thumb, and Enter or Escape returns to the thumb.
18761
+ *
18197
18762
  * Frameworks render from `getSnapshot()` and re-render when `subscribe()`
18198
18763
  * notifies. Call `dispose()` on unmount: it keeps an unsaved edit, for a
18199
18764
  * message that scrolls out of a virtual list. The controller stays usable
@@ -18210,13 +18775,16 @@ function ɵgetMessageFeedbackControls(scope, message) {
18210
18775
  */
18211
18776
  var ɵFeedbackCommentController = class {
18212
18777
  #getControls;
18778
+ #getInput;
18213
18779
  #closeDelayMs;
18214
18780
  #listeners = /* @__PURE__ */ new Set();
18215
18781
  #state = {
18216
18782
  open: false,
18217
18783
  draft: "",
18218
- focusRequest: 0
18784
+ focusRequest: 0,
18785
+ anchor: null
18219
18786
  };
18787
+ #commentRating;
18220
18788
  #timer;
18221
18789
  #editing = false;
18222
18790
  #focusWaiting = false;
@@ -18224,6 +18792,8 @@ var ɵFeedbackCommentController = class {
18224
18792
  #returning = false;
18225
18793
  constructor(options) {
18226
18794
  this.#getControls = options.getControls;
18795
+ this.#getInput = options.getInput ?? (() => null);
18796
+ this.#commentRating = options.getControls()?.feedback?.rating;
18227
18797
  this.#closeDelayMs = options.closeDelayMs ?? ɵFEEDBACK_COMMENT_CLOSE_DELAY_MS;
18228
18798
  }
18229
18799
  /** The current state. The same object until something changes. */
@@ -18301,6 +18871,157 @@ var ɵFeedbackCommentController = class {
18301
18871
  this.#returning = false;
18302
18872
  }
18303
18873
  };
18874
+ /**
18875
+ * A click on thumb `value`. Thumbs are toggles: a new rating is saved and
18876
+ * opens its comment, and clicking the chosen thumb again removes the
18877
+ * rating. A keyboard click moves focus into the comment, as there is no
18878
+ * pointer.
18879
+ *
18880
+ * @param options.target - The clicked thumb, if the click gave one.
18881
+ * @param options.keyboard - The click came from the keyboard (`detail` 0).
18882
+ * @returns Whether the app's handler should run: true for a new rating and
18883
+ * whenever this chat does not record ratings, false when one is removed.
18884
+ */
18885
+ rate = (value, options = {}) => {
18886
+ const controls = this.#getControls();
18887
+ if (!controls) return true;
18888
+ if (controls.feedback?.rating === value) {
18889
+ this.close({ save: false });
18890
+ controls.clear();
18891
+ return false;
18892
+ }
18893
+ controls.rate(value);
18894
+ this.#commentRating = value;
18895
+ this.#update({ anchor: options.target ?? null });
18896
+ this.show({
18897
+ comment: "",
18898
+ focus: options.keyboard === true
18899
+ });
18900
+ return true;
18901
+ };
18902
+ /**
18903
+ * The attributes and handlers of thumb `value`, or `null` while this chat
18904
+ * records no ratings. The chosen thumb opens its comment when the pointer
18905
+ * or keyboard focus reaches it, and Tab from it moves into the comment.
18906
+ */
18907
+ thumb = (value) => {
18908
+ const controls = this.#getControls();
18909
+ if (!controls) return null;
18910
+ if (controls.feedback?.rating !== value) return {
18911
+ attributes: {
18912
+ "data-copilotkit-rating": value,
18913
+ "aria-pressed": false
18914
+ },
18915
+ handlers: null
18916
+ };
18917
+ const enter = (target, via) => {
18918
+ if (!this.#state.open) this.#commentRating = value;
18919
+ if (target instanceof HTMLElement) this.#update({ anchor: target });
18920
+ this.enter(via);
18921
+ };
18922
+ return {
18923
+ attributes: {
18924
+ "data-copilotkit-rating": value,
18925
+ "aria-pressed": true,
18926
+ "aria-haspopup": "dialog",
18927
+ "aria-expanded": this.#state.open
18928
+ },
18929
+ handlers: {
18930
+ pointerEnter: (event) => {
18931
+ if (event.pointerType !== "touch") enter(event.currentTarget, "pointer");
18932
+ },
18933
+ pointerLeave: (event) => {
18934
+ if (event.pointerType !== "touch") this.leave("pointer");
18935
+ },
18936
+ focus: (event) => {
18937
+ const target = event.currentTarget;
18938
+ if (target instanceof Element && ɵisFocusVisible(target)) enter(target, "focus");
18939
+ },
18940
+ blur: () => this.leave(),
18941
+ keyDown: (event) => {
18942
+ const input = this.#getInput();
18943
+ const visible = input?.checkVisibility?.(HIDDEN_TOO) !== false;
18944
+ if (event.key === "Tab" && !event.shiftKey && this.#state.open && input && visible) {
18945
+ event.preventDefault();
18946
+ input.focus();
18947
+ }
18948
+ }
18949
+ }
18950
+ };
18951
+ };
18952
+ /**
18953
+ * Points the popover at the chosen thumb inside `root` when no thumb was
18954
+ * given: a custom thumb can call its click handler without an event. Call
18955
+ * it after each render.
18956
+ */
18957
+ findAnchor = (root) => {
18958
+ const rating = this.#getControls()?.feedback?.rating;
18959
+ if (!this.#state.open || this.#state.anchor?.isConnected || !rating) return;
18960
+ const anchor = root?.querySelector(thumbSelector(rating)) ?? root?.querySelector("button[aria-pressed=\"true\"]") ?? null;
18961
+ this.#update({ anchor });
18962
+ };
18963
+ /**
18964
+ * Closes a comment that no longer fits: discards it when the rating was
18965
+ * changed or removed elsewhere, and saves it when the toolbar hides. Call
18966
+ * it when the rating or `showsToolbar` changes.
18967
+ */
18968
+ sync = ({ showsToolbar }) => {
18969
+ if (!this.#state.open) return;
18970
+ if (this.#getControls()?.feedback?.rating !== this.#commentRating) this.close({ save: false });
18971
+ else if (!showsToolbar) this.close();
18972
+ };
18973
+ /** Moves focus into the comment field when a keyboard rating asked for it. */
18974
+ focusField = () => {
18975
+ const input = this.#getInput();
18976
+ if (input && this.takeFocusRequest()) input.focus();
18977
+ };
18978
+ /** Saves the comment, closes, and moves focus back to the thumb. */
18979
+ submit = () => {
18980
+ this.close();
18981
+ this.returnFocus(this.#state.anchor);
18982
+ };
18983
+ /**
18984
+ * Escape in the popover: closes without saving, and moves focus back to
18985
+ * the thumb when it was in the popover.
18986
+ *
18987
+ * @param content - The popover element.
18988
+ * @returns Whether focus was in the popover. Then stop the event, so it
18989
+ * does not also close a chat popup around the message.
18990
+ */
18991
+ popoverEscape = (content) => {
18992
+ const focusInside = content?.contains(content.ownerDocument.activeElement);
18993
+ this.close({ save: false });
18994
+ if (focusInside) this.returnFocus(this.#state.anchor);
18995
+ return focusInside === true;
18996
+ };
18997
+ /**
18998
+ * A key press in the popover: Tab past its last control or Shift+Tab past
18999
+ * its first one leaves it, as if it sat right after the thumb.
19000
+ *
19001
+ * @param content - The popover element.
19002
+ */
19003
+ popoverKeyDown = (event, content) => {
19004
+ if (event.key !== "Tab" || !content) return;
19005
+ const anchor = this.#state.anchor;
19006
+ const stops = Array.from(content.querySelectorAll(ɵTAB_STOP_SELECTOR));
19007
+ const active = content.ownerDocument.activeElement;
19008
+ if (!(event.shiftKey ? active === stops[0] : active === stops[stops.length - 1]) || !anchor?.isConnected) return;
19009
+ event.preventDefault();
19010
+ const target = event.shiftKey ? anchor : ɵnextTabStop(anchor, content) ?? anchor;
19011
+ this.close();
19012
+ if (target === anchor) this.returnFocus(target);
19013
+ else target.focus();
19014
+ };
19015
+ /**
19016
+ * Focus left the comment form for `next`. Moving within the popover or to
19017
+ * a thumb of the message, where the pointer still is, keeps it open.
19018
+ *
19019
+ * @param content - The popover element.
19020
+ */
19021
+ popoverFocusLeave = (next, content, messageId) => {
19022
+ if (next && (content?.contains(next) || ɵisOwnFeedbackThumb(next, messageId))) return;
19023
+ this.leave();
19024
+ };
18304
19025
  /** Stops the close timer and saves a changed comment that is still open. */
18305
19026
  dispose = () => {
18306
19027
  this.#cancelClose();
@@ -18324,7 +19045,7 @@ var ɵFeedbackCommentController = class {
18324
19045
  ...this.#state,
18325
19046
  ...patch
18326
19047
  };
18327
- if (next.open === this.#state.open && next.draft === this.#state.draft && next.focusRequest === this.#state.focusRequest) return;
19048
+ if (next.open === this.#state.open && next.draft === this.#state.draft && next.focusRequest === this.#state.focusRequest && next.anchor === this.#state.anchor) return;
18328
19049
  this.#state = next;
18329
19050
  for (const listener of this.#listeners) listener();
18330
19051
  }
@@ -18355,6 +19076,119 @@ function ɵformatReasoningDurationLabel(seconds, labels) {
18355
19076
  }
18356
19077
  }
18357
19078
  /**
19079
+ * The header text of a reasoning message: `labels.reasoningMessageThinkingLabel`
19080
+ * while the model reasons, then `labels.reasoningMessageThoughtForLabel`
19081
+ * ("Thought for 4 seconds").
19082
+ *
19083
+ * @param state - Whether the model still reasons, and for how long it did.
19084
+ * @param labels - The chat labels.
19085
+ */
19086
+ function ɵgetReasoningHeaderLabel(state, labels) {
19087
+ if (state.isStreaming) return labels.reasoningMessageThinkingLabel;
19088
+ return ɵformatLabel(labels.reasoningMessageThoughtForLabel, { duration: ɵformatReasoningDurationLabel(state.elapsedSeconds, labels) });
19089
+ }
19090
+ /**
19091
+ * The open state and reasoning timer of one reasoning message.
19092
+ *
19093
+ * - It opens when streaming starts and closes by itself when it ends,
19094
+ * unless the user toggled it during that stream: then their choice stays.
19095
+ * Each new stream starts open again and forgets the earlier toggle.
19096
+ * - The elapsed time counts from the first stream start and updates every
19097
+ * tick while streaming. When streaming ends it takes the final time.
19098
+ *
19099
+ * Frameworks render from `getSnapshot()` and re-render when `subscribe()`
19100
+ * notifies. Call `setStreaming()` whenever the streaming state may have
19101
+ * changed, including once after mount. Call `dispose()` on unmount. The
19102
+ * controller stays usable after `dispose()`, so a remount (React Strict
19103
+ * Mode) can keep it: the next `setStreaming(true)` starts the timer again.
19104
+ *
19105
+ * @example
19106
+ * ```ts
19107
+ * const disclosure = new ɵReasoningDisclosure({ isStreaming });
19108
+ * disclosure.subscribe(() => render(disclosure.getSnapshot()));
19109
+ * disclosure.setStreaming(isStreaming);
19110
+ * // Header click, when the message has text:
19111
+ * disclosure.toggle();
19112
+ * ```
19113
+ */
19114
+ var ɵReasoningDisclosure = class {
19115
+ #listeners = /* @__PURE__ */ new Set();
19116
+ #tickMs;
19117
+ #state;
19118
+ #startedAt = null;
19119
+ #userToggled = false;
19120
+ #timer;
19121
+ constructor({ isStreaming = false, tickMs = 1e3 } = {}) {
19122
+ this.#tickMs = tickMs;
19123
+ this.#state = {
19124
+ isStreaming: false,
19125
+ isOpen: isStreaming,
19126
+ elapsedSeconds: 0
19127
+ };
19128
+ }
19129
+ /** The current state. The same object until something changes. */
19130
+ getSnapshot = () => this.#state;
19131
+ /** Calls `listener` when the state changes. Returns the unsubscribe function. */
19132
+ subscribe = (listener) => {
19133
+ this.#listeners.add(listener);
19134
+ return () => {
19135
+ this.#listeners.delete(listener);
19136
+ };
19137
+ };
19138
+ /** Tells the controller whether the model reasons in this message now. */
19139
+ setStreaming = (isStreaming) => {
19140
+ if (isStreaming) {
19141
+ if (this.#timer === void 0) this.#startTimer();
19142
+ if (this.#state.isStreaming) return;
19143
+ this.#startedAt ??= Date.now();
19144
+ this.#userToggled = false;
19145
+ this.#update({
19146
+ isStreaming: true,
19147
+ isOpen: true
19148
+ });
19149
+ return;
19150
+ }
19151
+ if (!this.#state.isStreaming) return;
19152
+ this.#stopTimer();
19153
+ this.#update({
19154
+ isStreaming: false,
19155
+ elapsedSeconds: this.#elapsed(),
19156
+ isOpen: this.#userToggled ? this.#state.isOpen : false
19157
+ });
19158
+ };
19159
+ /** Opens or closes the reasoning text, and keeps that after the stream. */
19160
+ toggle = () => {
19161
+ this.#userToggled = true;
19162
+ this.#update({ isOpen: !this.#state.isOpen });
19163
+ };
19164
+ /** Stops the timer. */
19165
+ dispose = () => {
19166
+ this.#stopTimer();
19167
+ };
19168
+ #elapsed() {
19169
+ return this.#startedAt === null ? 0 : (Date.now() - this.#startedAt) / 1e3;
19170
+ }
19171
+ #startTimer() {
19172
+ this.#timer = setInterval(() => {
19173
+ this.#update({ elapsedSeconds: this.#elapsed() });
19174
+ }, this.#tickMs);
19175
+ }
19176
+ #stopTimer() {
19177
+ if (this.#timer === void 0) return;
19178
+ clearInterval(this.#timer);
19179
+ this.#timer = void 0;
19180
+ }
19181
+ #update(patch) {
19182
+ const next = {
19183
+ ...this.#state,
19184
+ ...patch
19185
+ };
19186
+ if (next.isStreaming === this.#state.isStreaming && next.isOpen === this.#state.isOpen && next.elapsedSeconds === this.#state.elapsedSeconds) return;
19187
+ this.#state = next;
19188
+ for (const listener of this.#listeners) listener();
19189
+ }
19190
+ };
19191
+ /**
18358
19192
  * The text of the work summary line at the top of a reply in the `"turn"`
18359
19193
  * tool-call display.
18360
19194
  *
@@ -18397,18 +19231,18 @@ function ɵgetWorkSummaryText({ isWorking, calls, elapsedMs, workingSince, now,
18397
19231
  }
18398
19232
  /**
18399
19233
  * The text of a user message: the string content, or its text parts joined
18400
- * by newlines. Parts that are not text, and malformed parts from untyped
18401
- * data, add nothing.
19234
+ * by newlines. Parts that are not text, and malformed parts or content
19235
+ * that is not a list from untyped data, add nothing.
18402
19236
  */
18403
19237
  function ɵflattenUserMessageContent(content) {
18404
- if (!content) return "";
18405
19238
  if (typeof content === "string") return content;
19239
+ if (!Array.isArray(content)) return "";
18406
19240
  return content.map((part) => part?.type === "text" && typeof part.text === "string" ? part.text : "").filter((text) => text.length > 0).join("\n");
18407
19241
  }
18408
19242
  const isMediaPart = (part) => part?.type === "image" || part?.type === "audio" || part?.type === "video" || part?.type === "document";
18409
19243
  /** The image, audio, video, and document parts of a user message. */
18410
19244
  function ɵgetUserMessageMediaParts(content) {
18411
- if (!content || typeof content === "string") return [];
19245
+ if (!Array.isArray(content)) return [];
18412
19246
  return content.filter(isMediaPart);
18413
19247
  }
18414
19248
  /** The file name stored in an attachment's `metadata.filename`, if any. */
@@ -19309,6 +20143,25 @@ function buildOpenGenerativeUIContexts({ designSkill, sandboxFunctions }) {
19309
20143
  });
19310
20144
  return entries;
19311
20145
  }
20146
+ /**
20147
+ * Add the Open Generative UI agent context entries (see
20148
+ * {@link buildOpenGenerativeUIContexts}) to a core.
20149
+ *
20150
+ * @returns A function that removes the entries this call added.
20151
+ *
20152
+ * @example
20153
+ * ```ts
20154
+ * const remove = ɵaddOpenGenerativeUIContexts(core, { designSkill, sandboxFunctions });
20155
+ * // when the feature turns off or the options change
20156
+ * remove();
20157
+ * ```
20158
+ */
20159
+ function addOpenGenerativeUIContexts(core, options) {
20160
+ const ids = buildOpenGenerativeUIContexts(options).map((entry) => core.addContext(entry));
20161
+ return () => {
20162
+ for (const id of ids) core.removeContext(id);
20163
+ };
20164
+ }
19312
20165
 
19313
20166
  //#endregion
19314
20167
  //#region src/open-generative-ui/placeholder.ts
@@ -19642,5 +20495,5 @@ function cn(...inputs) {
19642
20495
  }
19643
20496
 
19644
20497
  //#endregion
19645
- 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, A2UIActivityController as ɵA2UIActivityController, A2UI_DEFAULT_SURFACE_ID as ɵA2UI_DEFAULT_SURFACE_ID, A2UI_LIFECYCLE_TEXT as ɵA2UI_LIFECYCLE_TEXT, A2UI_OPERATIONS_KEY as ɵA2UI_OPERATIONS_KEY, A2UI_PAINT_FALLBACK_MS as ɵA2UI_PAINT_FALLBACK_MS, A2UI_RECOVERY_DEFAULTS as ɵA2UI_RECOVERY_DEFAULTS, A2UI_ROOT_COMPONENT_ID as ɵA2UI_ROOT_COMPONENT_ID, A2UI_SKELETON_ROWS as ɵA2UI_SKELETON_ROWS, A2UI_SURFACE_ACTIVITY_TYPE as ɵA2UI_SURFACE_ACTIVITY_TYPE, A2UI_SURFACE_CONTENT_SCHEMA as ɵA2UI_SURFACE_CONTENT_SCHEMA, ɵALL_AGENT_UPDATES, ɵAgentResolver, ɵAttachmentQueue, ɵAudioRecorder, ɵAudioRecorderError, ɵCOMPOSER_DEFAULT_MAX_ROWS, ɵCOPILOTKIT_FEATURES, ɵCOPILOT_CLOUD_PUBLIC_API_KEY_HEADER, ɵCOPILOT_CLOUD_RUNTIME_URL, ɵCOPY_FEEDBACK_RESET_MS, ɵChatConfigurationStore, ɵChatSubmitter, ɵComposerAutosize, ɵCopyFeedback, ɵDockedSidebar, ɵDockedSidebarRegistry, ɵFEEDBACK_COMMENT_CLOSE_DELAY_MS, ɵFeedbackCommentController, GENERATE_SANDBOXED_UI_ARGS_SCHEMA as ɵGENERATE_SANDBOXED_UI_ARGS_SCHEMA, ɵHITL_ABORTED_MESSAGE, ɵHOVER_MENU_CLOSE_DELAY_MS, ɵHoverMenuController, ɵHumanInTheLoopRegistry, ɵINLINE_FEATURE_WARNING_STYLE, ɵInspectorThreadOverride, ɵInterruptController, ɵInterruptExpiredError, ɵInterruptState, ɵKEYBOARD_OPEN_THRESHOLD_PX, ɵLICENSE_BANNER_OFFSET, ɵLICENSE_BANNER_STYLE, ɵLearningAutoStarter, ɵMAX_SOCKET_RETRIES, ɵMESSAGE_FEEDBACK_EVENT_NAME, ɵMESSAGE_FEEDBACK_MAX_COMMENT_LENGTH, ɵMOBILE_MAX_WIDTH_QUERY, ɵMessageViewModel, OPEN_GENERATIVE_UI_CONTENT_SCHEMA as ɵOPEN_GENERATIVE_UI_CONTENT_SCHEMA, OPEN_GENERATIVE_UI_DESIGN_CONTEXT_DESCRIPTION as ɵOPEN_GENERATIVE_UI_DESIGN_CONTEXT_DESCRIPTION, OPEN_GENERATIVE_UI_SANDBOX_FUNCTIONS_CONTEXT_DESCRIPTION as ɵOPEN_GENERATIVE_UI_SANDBOX_FUNCTIONS_CONTEXT_DESCRIPTION, OpenGenerativeUIController as ɵOpenGenerativeUIController, PLACEHOLDER_CYCLE_MS as ɵPLACEHOLDER_CYCLE_MS, ɵPOPUP_ANIMATION_MS, PlaceholderCycler as ɵPlaceholderCycler, RENDER_A2UI_TOOL_NAME as ɵRENDER_A2UI_TOOL_NAME, ɵRUNTIME_PROBE_TIMEOUT_MS, ɵRendererRegistry, ɵRuntimeInfoStore, ɵSCROLL_BOTTOM_THRESHOLD_PX, ɵSTABLE_ARRAY_WARNINGS, ɵTHREAD_REQUEST_TIMEOUT_MS, TOOL_CALL_STATUS_ICONS as ɵTOOL_CALL_STATUS_ICONS, TOOL_CALL_STATUS_LABEL_KEYS as ɵTOOL_CALL_STATUS_LABEL_KEYS, ɵTRANSCRIPTION_ERROR_TIMEOUT_MS, ɵThreadSelection, ɵThreadSwitchCoordinator, ɵThreadsController, ɵagentUpdateHandlers, ɵappendTranscript, ɵbindDialogFocus, ɵbindPopupDismiss, ɵbindSuggestionsConfig, ɵbuildHumanInTheLoopTool, ɵbuildLearnFromUserActionPayload, buildOpenGenerativeUIContexts as ɵbuildOpenGenerativeUIContexts, ɵbuildToolCallRenderProps, ɵbuildUserMessage, ɵbuildUserMessageContent, ɵcanPreviewDocument, ɵclampSlashIndex, ɵclearAgentInterruptState, ɵclearAgentThreadCursors, cn as ɵcn, ɵcomponentToolDescription, ɵcomposerButtonState, ɵcopilotIconSvgAttributes, ɵcopilotIcons, countFailedToolCalls as ɵcountFailedToolCalls, ɵcreateChatSubmitter, ɵcreateComposerAutosize, ɵcreateDockedSidebar, ɵcreateLastUserMessageTracker, createMemoryStore as ɵcreateMemoryStore, ɵcreateMessageViewModel, ɵcreateObjectUrlFromSource, createOpenGenerativeUITool as ɵcreateOpenGenerativeUITool, ɵcreateThreadSelectors, createThreadStore as ɵcreateThreadStore, ɵcreateThreadsDrawerActions, ɵcreateWaveformRenderer, ɵdecodeTextSource, ɵdeduplicateMessages, ɵdescribeActivityRendererFailure, ɵdescribeUnrenderedToolCalls, diagnoseMissingSurface as ɵdiagnoseMissingSurface, diagnoseUnpaintedSurface as ɵdiagnoseUnpaintedSurface, diagnoseUnresolvedRoot as ɵdiagnoseUnresolvedRoot, ɵdimensionToCss, ɵdockedSidebarRegistryFor, ɵduplicateMessagesWarning, extractCompleteStyles as ɵextractCompleteStyles, ɵfilterCommands, ɵfindActivityRenderer, ɵfindChatInput, ɵfindToolMessage, ɵfitTextareaHeight, ɵflattenCommandItems, ɵflattenUserMessageContent, formatA2UIDebugPayload as ɵformatA2UIDebugPayload, formatA2UIRetryLabel as ɵformatA2UIRetryLabel, ɵformatCountLabel, ɵformatLabel, formatReasoningDuration as ɵformatReasoningDuration, ɵformatReasoningDurationLabel, formatToolNames as ɵformatToolNames, formatWorkDuration as ɵformatWorkDuration, getA2UIOperationSurfaceId as ɵgetA2UIOperationSurfaceId, getA2UIOperations as ɵgetA2UIOperations, getA2UIProgressPhase as ɵgetA2UIProgressPhase, ɵgetAgentCapabilities, ɵgetAgentInterruptState, ɵgetAgentResolver, getArgumentPreview as ɵgetArgumentPreview, ɵgetBranchNavState, ɵgetChatViewState, ɵgetCustomMessageRenderProps, ɵgetInlineFeatureWarningSpec, ɵgetLastUserMessageId, getLatestTurnKey as ɵgetLatestTurnKey, ɵgetLicenseBannerSpec, ɵgetMessageFeedback, ɵgetMessageFeedbackControls, ɵgetThreadsDrawerElementProps, ɵgetToolCallBadge, getToolCallGroupState as ɵgetToolCallGroupState, getToolCallLayouts as ɵgetToolCallLayouts, getToolCallPreview as ɵgetToolCallPreview, getToolCallRendererNames as ɵgetToolCallRendererNames, getToolCallRowStatus as ɵgetToolCallRowStatus, ɵgetToolCallStatus, getToolResults as ɵgetToolResults, getTurnWork as ɵgetTurnWork, ɵgetUserMessageMediaFilename, ɵgetUserMessageMediaParts, getWorkOpenState as ɵgetWorkOpenState, ɵgetWorkSummaryText, groupA2UIOperationsBySurface as ɵgroupA2UIOperationsBySurface, ɵhasAssistantMessageText, ɵhitlRenderProps, ɵinitialKeyboardState, ɵinspectorKiteFill, ɵinspectorKiteIcon, ɵinspectorShortcuts, ɵisCopilotKitFeature, ɵisHttpAgent, ɵisLearningFeedbackEnabled, ɵisMobileViewport, isOpenGenerativeUIActive as ɵisOpenGenerativeUIActive, isRetryableStatus as ɵisRetryableMemoryStatus, ɵisScrolledToBottom, isTurnWorkOpen as ɵisTurnWorkOpen, isTurnWorking as ɵisTurnWorking, ɵjoinPhoenixChannel$, loadWebsandbox as ɵloadWebsandbox, ɵmapMemoryMetadataEvent, ɵmatchActivityRenderer, ɵmeasureTextarea, ɵmemoryAdapterEvents, ɵmemoryDomainEvents, ɵmemoryReducer, ɵmemoryRestEvents, ɵmessagesFingerprint, ɵmorphViewTransition, ɵnextSlashIndex, ɵnormalizeAutoScroll, ɵnormalizeToolCallStatus, ɵobservePhoenixEvent$, ɵobservePhoenixJoinOutcome$, ɵobservePhoenixSocketHealth$, ɵobservePhoenixSocketSignals$, ɵparseSlashQuery, ɵparseToolCallArguments, ɵphoenixChannel$, ɵphoenixSocket$, ɵpinMessageToTop, pluralize as ɵpluralize, processPartialHtml as ɵprocessPartialHtml, ɵprojectThread, ɵpublicKeyHeaderDefaults, readA2UILifecycle as ɵreadA2UILifecycle, ɵreadKeyboardState, ɵrecordAnnotation, recordWorkTime as ɵrecordWorkTime, ɵreportProviderConfigDiagnostics, ɵreserveLicenseBannerOffset, ɵresetAgentThreadBaseline, ɵresetMessageFeedbackCache, resolveA2UIDebugExposure as ɵresolveA2UIDebugExposure, ɵresolveActivityRenderer, ɵresolveAgentId, ɵresolveAgentThreadId, ɵresolveChatNotice, ɵresolveComposerKey, ɵresolveCustomMessageRenderContext, ɵresolveCustomMessageRenderers, ɵresolveLicenseState, ɵresolveProviderConfig, ɵresolveSlashKey, ɵresolveThreadsLicense, ɵresolveToolCallAgentId, ɵresolveToolCallRenderer, ɵrmsAmplitude, runA2UIAction as ɵrunA2UIAction, ɵselectFetchMoreError, ɵselectHasNextPage, ɵselectIsFetchingNextPage, ɵselectIsMutating, ɵselectMemories, ɵselectMemoriesAvailable, ɵselectMemoriesError, ɵselectMemoriesIsLoading, ɵselectMemoriesIsMutating, ɵselectMemoriesRealtimeStatus, ɵselectThreads, ɵselectThreadsError, ɵselectThreadsIsLoading, ɵserializeContextValue, ɵsetMessageFeedback, shallowEqualRecord as ɵshallowEqualRecord, ɵshouldShowAssistantToolbar, ɵshouldShowMessageCursor, ɵsnapshotAgentState, ɵstopAgentWithFallback, stringifyToolCallAttr as ɵstringifyToolCallAttr, stringifyToolCallPayload as ɵstringifyToolCallPayload, ɵsubscribeToAgentSuggestions, ɵsubscribeToAgentUpdates, ɵsubscribeToLearningFeedbackEnabled, ɵsubscribeToMessageFeedback, surfaceHasRenderableContent as ɵsurfaceHasRenderableContent, ɵthreadAdapterEvents, toA2UIClientEvent as ɵtoA2UIClientEvent, ɵtoDrawerThread, ɵtoLearningConfig, toolCallAppearance as ɵtoolCallAppearance, ɵtoolRendererShapeChanged, ɵtranscribeAudio, ɵtranscriptionErrorMessageKey, ɵtranscriptionErrorNotice, ɵvalidateAgentBinding, ɵwaitForActiveRun, ɵwatchKeyboardState, ɵwatchMobileViewport, ɵwithHeaderDefaults };
20498
+ 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, A2UIActivityController as ɵA2UIActivityController, A2UI_DEFAULT_SURFACE_ID as ɵA2UI_DEFAULT_SURFACE_ID, A2UI_LIFECYCLE_TEXT as ɵA2UI_LIFECYCLE_TEXT, A2UI_OPERATIONS_KEY as ɵA2UI_OPERATIONS_KEY, A2UI_PAINT_FALLBACK_MS as ɵA2UI_PAINT_FALLBACK_MS, A2UI_RECOVERY_DEFAULTS as ɵA2UI_RECOVERY_DEFAULTS, A2UI_ROOT_COMPONENT_ID as ɵA2UI_ROOT_COMPONENT_ID, A2UI_SKELETON_ROWS as ɵA2UI_SKELETON_ROWS, A2UI_SURFACE_ACTIVITY_TYPE as ɵA2UI_SURFACE_ACTIVITY_TYPE, A2UI_SURFACE_CONTENT_SCHEMA as ɵA2UI_SURFACE_CONTENT_SCHEMA, ɵALL_AGENT_UPDATES, ɵAgentResolver, ɵAttachmentQueue, ɵAudioRecorder, ɵAudioRecorderError, ɵCOMPOSER_DEFAULT_MAX_ROWS, ɵCOPILOTKIT_FEATURES, ɵCOPILOT_CLOUD_PUBLIC_API_KEY_HEADER, ɵCOPILOT_CLOUD_RUNTIME_URL, ɵCOPY_FEEDBACK_RESET_MS, ɵChatConfigurationStore, ɵChatConnection, ɵChatSubmitter, ɵComposerAutosize, ɵComposerController, ɵCopyFeedback, ɵDockedSidebar, ɵDockedSidebarRegistry, ɵExitPresence, ɵFEEDBACK_COMMENT_CLOSE_DELAY_MS, ɵFeedbackCommentController, ɵFreshThreadId, GENERATE_SANDBOXED_UI_ARGS_SCHEMA as ɵGENERATE_SANDBOXED_UI_ARGS_SCHEMA, ɵHITL_ABORTED_MESSAGE, ɵHOVER_MENU_CLOSE_DELAY_MS, ɵHoverMenuController, ɵHumanInTheLoopRegistry, ɵINLINE_FEATURE_WARNING_STYLE, ɵInspectorThreadOverride, ɵInterruptController, ɵInterruptExpiredError, ɵInterruptState, ɵKEYBOARD_OPEN_THRESHOLD_PX, ɵLICENSE_BANNER_OFFSET, ɵLICENSE_BANNER_STYLE, ɵLearningAutoStarter, ɵMAX_SOCKET_RETRIES, ɵMESSAGE_FEEDBACK_EVENT_NAME, ɵMESSAGE_FEEDBACK_MAX_COMMENT_LENGTH, ɵMOBILE_MAX_WIDTH_QUERY, ɵMessageViewModel, OPEN_GENERATIVE_UI_CONTENT_SCHEMA as ɵOPEN_GENERATIVE_UI_CONTENT_SCHEMA, OPEN_GENERATIVE_UI_DESIGN_CONTEXT_DESCRIPTION as ɵOPEN_GENERATIVE_UI_DESIGN_CONTEXT_DESCRIPTION, OPEN_GENERATIVE_UI_SANDBOX_FUNCTIONS_CONTEXT_DESCRIPTION as ɵOPEN_GENERATIVE_UI_SANDBOX_FUNCTIONS_CONTEXT_DESCRIPTION, OpenGenerativeUIController as ɵOpenGenerativeUIController, PLACEHOLDER_CYCLE_MS as ɵPLACEHOLDER_CYCLE_MS, ɵPOPUP_ANIMATION_MS, ɵPOPUP_DEFAULT_HEIGHT, ɵPOPUP_DEFAULT_WIDTH, PlaceholderCycler as ɵPlaceholderCycler, RENDER_A2UI_TOOL_NAME as ɵRENDER_A2UI_TOOL_NAME, ɵRESIZE_SETTLE_MS, ɵRUNTIME_PROBE_TIMEOUT_MS, ɵReasoningDisclosure, ɵRendererRegistry, ɵRuntimeInfoStore, ɵSCROLL_BOTTOM_THRESHOLD_PX, ɵSIDEBAR_DEFAULT_WIDTH, ɵSIDEBAR_TRANSITION_MS, ɵSTABLE_ARRAY_WARNINGS, ɵStickToBottom, ɵTAB_STOP_SELECTOR, ɵTHREAD_REQUEST_TIMEOUT_MS, TOOL_CALL_STATUS_ICONS as ɵTOOL_CALL_STATUS_ICONS, TOOL_CALL_STATUS_LABEL_KEYS as ɵTOOL_CALL_STATUS_LABEL_KEYS, ɵTRANSCRIPTION_ERROR_TIMEOUT_MS, ɵThreadSelection, ɵThreadSwitchCoordinator, ɵThreadsController, ɵadaptDefaultToolCallRenderProps, addOpenGenerativeUIContexts as ɵaddOpenGenerativeUIContexts, ɵagentUpdateHandlers, ɵappendTranscript, ɵassembleActivityRenderers, ɵassembleHumanInTheLoop, ɵassembleProviderRegistry, ɵassembleProviderToolRenderers, ɵassembleProviderTools, ɵbindDialogFocus, ɵbindPopupDismiss, ɵbindSuggestionsConfig, ɵbuildHumanInTheLoopTool, ɵbuildLearnFromUserActionPayload, buildOpenGenerativeUIContexts as ɵbuildOpenGenerativeUIContexts, ɵbuildToolCallRenderProps, ɵbuildUserMessage, ɵbuildUserMessageContent, ɵcanPreviewDocument, ɵclampSlashIndex, ɵclearAgentInterruptState, ɵclearAgentThreadCursors, cn as ɵcn, ɵcomponentToolDescription, ɵcomposerButtonState, ɵcopilotIconSvgAttributes, ɵcopilotIcons, countFailedToolCalls as ɵcountFailedToolCalls, ɵcreateChatSubmitter, ɵcreateComposerAutosize, ɵcreateDockedSidebar, ɵcreateExitPresence, ɵcreateLastUserMessageTracker, createMemoryStore as ɵcreateMemoryStore, ɵcreateMessageViewModel, ɵcreateObjectUrlFromSource, createOpenGenerativeUITool as ɵcreateOpenGenerativeUITool, ɵcreateStickToBottom, ɵcreateThreadSelectors, createThreadStore as ɵcreateThreadStore, ɵcreateThreadsDrawerActions, ɵcreateWaveformRenderer, ɵdecodeTextSource, ɵdeduplicateMessages, ɵdescribeActivityRendererFailure, ɵdescribeUnrenderedToolCalls, diagnoseMissingSurface as ɵdiagnoseMissingSurface, diagnoseUnpaintedSurface as ɵdiagnoseUnpaintedSurface, diagnoseUnresolvedRoot as ɵdiagnoseUnresolvedRoot, ɵdimensionToCss, ɵdockedSidebarRegistryFor, ɵduplicateMessagesWarning, extractCompleteStyles as ɵextractCompleteStyles, ɵfilterCommands, ɵfindActivityRenderer, ɵfindChatInput, ɵfindToolMessage, ɵfitTextareaHeight, ɵflattenCommandItems, ɵflattenToolsMenuForDisplay, ɵflattenUserMessageContent, formatA2UIDebugPayload as ɵformatA2UIDebugPayload, formatA2UIRetryLabel as ɵformatA2UIRetryLabel, ɵformatCountLabel, ɵformatLabel, formatReasoningDuration as ɵformatReasoningDuration, ɵformatReasoningDurationLabel, formatToolNames as ɵformatToolNames, formatWorkDuration as ɵformatWorkDuration, getA2UIOperationSurfaceId as ɵgetA2UIOperationSurfaceId, getA2UIOperations as ɵgetA2UIOperations, getA2UIProgressPhase as ɵgetA2UIProgressPhase, ɵgetAgentCapabilities, ɵgetAgentInterruptState, ɵgetAgentResolver, getArgumentPreview as ɵgetArgumentPreview, ɵgetBranchNavState, ɵgetChatViewState, ɵgetCustomMessageRenderProps, ɵgetInlineFeatureWarningSpec, ɵgetLastUserMessageId, getLatestTurnKey as ɵgetLatestTurnKey, ɵgetLicenseBannerSpec, ɵgetMessageFeedback, ɵgetMessageFeedbackControls, ɵgetMessageRunStateSnapshot, ɵgetReasoningHeaderLabel, ɵgetThreadsDrawerElementProps, ɵgetToolCallBadge, getToolCallGroupState as ɵgetToolCallGroupState, getToolCallLayouts as ɵgetToolCallLayouts, getToolCallPreview as ɵgetToolCallPreview, getToolCallRendererNames as ɵgetToolCallRendererNames, getToolCallRowStatus as ɵgetToolCallRowStatus, ɵgetToolCallStatus, getToolResults as ɵgetToolResults, getTurnWork as ɵgetTurnWork, ɵgetUserMessageMediaFilename, ɵgetUserMessageMediaParts, getWorkOpenState as ɵgetWorkOpenState, ɵgetWorkSummaryText, groupA2UIOperationsBySurface as ɵgroupA2UIOperationsBySurface, ɵhasAssistantMessageText, ɵhitlRenderProps, ɵimplementsConnect, ɵinitialKeyboardState, ɵinspectorKiteFill, ɵinspectorKiteIcon, ɵinspectorShortcuts, isContentPart as ɵisContentPart, ɵisContentScrolledToBottom, ɵisCopilotKitFeature, ɵisFocusVisible, ɵisHttpAgent, ɵisLearningFeedbackEnabled, ɵisMobileViewport, isOpenGenerativeUIActive as ɵisOpenGenerativeUIActive, ɵisOwnFeedbackThumb, isRetryableStatus as ɵisRetryableMemoryStatus, ɵisScrolledToBottom, isTurnWorkOpen as ɵisTurnWorkOpen, isTurnWorking as ɵisTurnWorking, ɵjoinPhoenixChannel$, loadWebsandbox as ɵloadWebsandbox, ɵmapMemoryMetadataEvent, ɵmatchActivityRenderer, ɵmeasureTextarea, ɵmemoryAdapterEvents, ɵmemoryDomainEvents, ɵmemoryReducer, ɵmemoryRestEvents, ɵmessagesFingerprint, ɵmorphViewTransition, ɵnextSlashIndex, ɵnextTabStop, ɵnormalizeAutoScroll, ɵnormalizeToolCallStatus, ɵnormalizeToolsMenu, ɵobservePhoenixEvent$, ɵobservePhoenixJoinOutcome$, ɵobservePhoenixSocketHealth$, ɵobservePhoenixSocketSignals$, ɵparseSlashQuery, ɵparseToolCallArguments, ɵphoenixChannel$, ɵphoenixSocket$, ɵpinMessageToTop, pluralize as ɵpluralize, processPartialHtml as ɵprocessPartialHtml, ɵprojectThread, ɵpublicKeyHeaderDefaults, readA2UILifecycle as ɵreadA2UILifecycle, ɵreadKeyboardState, ɵrecordAnnotation, recordWorkTime as ɵrecordWorkTime, ɵregisterFrontendTools, ɵreportProviderConfigDiagnostics, ɵreserveLicenseBannerOffset, ɵresetAgentThreadBaseline, ɵresetMessageFeedbackCache, ɵresolveA2UIActivation, resolveA2UIDebugExposure as ɵresolveA2UIDebugExposure, ɵresolveActivityRenderer, ɵresolveAgentId, ɵresolveAgentThreadId, ɵresolveChatNotice, ɵresolveComposerKey, ɵresolveCustomMessageRenderContext, ɵresolveCustomMessageRenderers, ɵresolveLicenseState, ɵresolveProviderConfig, ɵresolveSlashKey, ɵresolveThreadsLicense, ɵresolveToolCallAgentId, ɵresolveToolCallRenderer, ɵrmsAmplitude, runA2UIAction as ɵrunA2UIAction, ɵselectFetchMoreError, ɵselectHasNextPage, ɵselectIsFetchingNextPage, ɵselectIsMutating, ɵselectMemories, ɵselectMemoriesAvailable, ɵselectMemoriesError, ɵselectMemoriesIsLoading, ɵselectMemoriesIsMutating, ɵselectMemoriesRealtimeStatus, ɵselectThreads, ɵselectThreadsError, ɵselectThreadsIsLoading, ɵserializeContextValue, ɵsetMessageFeedback, shallowEqualRecord as ɵshallowEqualRecord, ɵshouldShowAssistantToolbar, ɵshouldShowMessageCursor, ɵshowsComposerDisclaimer, ɵsnapshotAgentState, ɵstableArrayPropWarning, ɵstopAgentWithFallback, stringifyToolCallAttr as ɵstringifyToolCallAttr, stringifyToolCallPayload as ɵstringifyToolCallPayload, ɵsubscribeToAgentErrors, ɵsubscribeToAgentSuggestions, ɵsubscribeToAgentUpdates, ɵsubscribeToLearningFeedbackEnabled, ɵsubscribeToMessageFeedback, surfaceHasRenderableContent as ɵsurfaceHasRenderableContent, ɵsyncRecorderToMode, ɵthreadAdapterEvents, toA2UIClientEvent as ɵtoA2UIClientEvent, ɵtoDefaultToolCallStatus, ɵtoDrawerThread, ɵtoLearningConfig, toolCallAppearance as ɵtoolCallAppearance, ɵtoolRendererShapeChanged, ɵtranscribeAudio, ɵtranscriptionErrorMessageKey, ɵtranscriptionErrorNotice, ɵvalidateAgentBinding, ɵwaitForActiveRun, ɵwatchElementHeight, ɵwatchElementWidth, ɵwatchKeyboardState, ɵwatchMobileViewport, ɵwithHeaderDefaults };
19646
20499
  //# sourceMappingURL=index.mjs.map