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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Throttler } from "@tanstack/pacer";
2
2
  import { AGUIConnectNotImplementedError, AbstractAgent, CompatibilityBoundary, EventType, HttpAgent, buildResumeArray, isInterruptExpired, randomUUID, runHttpRequest, structuredClone_, transformChunks, transformHttpEventStream } from "@ag-ui/client";
3
- import { A2UI_VERSION, GENERATIVE_UI_ROOT_ID, RUNTIME_MODE_INTELLIGENCE, RUNTIME_MODE_SSE, THREAD_ALREADY_RUNNING_ERROR_CODE, TranscriptionErrorCode, createLicenseContextValue, logger, parseInspectorMetadataV1, partialJSONParse, phoenixExponentialBackoff, randomUUID as randomUUID$1, resolveDebugConfig, schemaToJsonSchema, stripIntelligenceRoutingFields } from "@copilotkit/shared";
3
+ import { A2UI_VERSION, GENERATIVE_UI_ROOT_ID, RUNTIME_MODE_INTELLIGENCE, RUNTIME_MODE_SSE, THREAD_ALREADY_RUNNING_ERROR_CODE, TranscriptionErrorCode, copyToClipboard, createLicenseContextValue, logger, parseInspectorMetadataV1, partialJSONParse, phoenixExponentialBackoff, randomUUID as randomUUID$1, resolveDebugConfig, schemaToJsonSchema, stripIntelligenceRoutingFields } from "@copilotkit/shared";
4
4
  import { BehaviorSubject, EMPTY, NEVER, Notification, Observable, Subject, Subscription, asapScheduler, combineLatest, concat, defer, dematerialize, firstValueFrom, from, lastValueFrom, merge, observeOn, of, switchMap, throwError } from "rxjs";
5
5
  import { catchError, concatMap, concatWith, delay, distinctUntilChanged, endWith, filter, finalize, ignoreElements, map, mergeMap, observeOn as observeOn$1, scan, share, shareReplay, startWith, switchMap as switchMap$1, take, takeUntil, tap, timeout, withLatestFrom } from "rxjs/operators";
6
6
  import { Socket } from "phoenix";
@@ -12260,6 +12260,152 @@ function ɵresolveThreadsLicense(context) {
12260
12260
  licensePending: status === null
12261
12261
  };
12262
12262
  }
12263
+ const PRICING_URL = "https://copilotkit.ai/pricing";
12264
+ const DASHBOARD_URL = "https://dashboard.operations.copilotkit.ai";
12265
+ /**
12266
+ * What one license banner shows: its severity, text, and link. React, Vue,
12267
+ * and Angular render it with {@link ɵLICENSE_BANNER_STYLE}.
12268
+ *
12269
+ * @param type - The banner type, for example from
12270
+ * {@link ɵresolveLicenseState}'s `bannerType`.
12271
+ * @param labels - The chat labels in effect, so apps can translate the text.
12272
+ * @param details - The feature name, expiry date, or days left.
12273
+ *
12274
+ * @example
12275
+ * ```ts
12276
+ * const spec = ɵgetLicenseBannerSpec("expiring", labels, { graceRemaining: 3 });
12277
+ * // { severity: "warning", message: "… expires in 3 days …", actionLabel: "Renew", … }
12278
+ * ```
12279
+ */
12280
+ function ɵgetLicenseBannerSpec(type, labels, { featureName, expiryDate, graceRemaining } = {}) {
12281
+ switch (type) {
12282
+ case "no_license": return bannerSpec("info", labels.licensePoweredByText, labels.licenseGetLicenseLabel, PRICING_URL);
12283
+ case "feature_unlicensed": return bannerSpec("warning", ɵformatLabel(labels.licenseFeatureUnlicensedText, { feature: featureName ?? "" }), labels.licenseGetLicenseLabel, PRICING_URL);
12284
+ case "expiring": return bannerSpec("warning", expiringMessage(labels, graceRemaining), labels.licenseRenewLabel, DASHBOARD_URL);
12285
+ case "expired": return bannerSpec("critical", expiryDate ? ɵformatLabel(labels.licenseExpiredOnDateText, { date: expiryDate }) : labels.licenseExpiredText, labels.licenseRenewNowLabel, PRICING_URL);
12286
+ case "invalid": return bannerSpec("critical", labels.licenseInvalidText, labels.licenseGetLicenseLabel, PRICING_URL);
12287
+ }
12288
+ }
12289
+ const bannerSpec = (severity, message, actionLabel, actionUrl) => ({
12290
+ severity,
12291
+ message,
12292
+ actionLabel,
12293
+ actionUrl
12294
+ });
12295
+ /**
12296
+ * The "expires soon" text. Without a day count it says "soon", never "in
12297
+ * undefined days".
12298
+ */
12299
+ function expiringMessage(labels, graceRemaining) {
12300
+ if (graceRemaining === void 0) return labels.licenseExpiringText;
12301
+ return ɵformatLabel(graceRemaining === 1 ? labels.licenseExpiringInDaysOne : labels.licenseExpiringInDaysOther, { days: graceRemaining });
12302
+ }
12303
+ const FONT_FAMILY = "-apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif";
12304
+ /**
12305
+ * Inline styles of the fixed license banner, in camelCase, for React `style`
12306
+ * and Vue `:style`. `base` is the layout; `severity` holds the colours.
12307
+ */
12308
+ const ɵLICENSE_BANNER_STYLE = {
12309
+ base: {
12310
+ position: "fixed",
12311
+ bottom: "8px",
12312
+ left: "50%",
12313
+ transform: "translateX(-50%)",
12314
+ zIndex: 99999,
12315
+ display: "inline-flex",
12316
+ alignItems: "center",
12317
+ gap: "12px",
12318
+ whiteSpace: "nowrap",
12319
+ padding: "8px 16px",
12320
+ fontSize: "13px",
12321
+ fontFamily: FONT_FAMILY,
12322
+ borderRadius: "6px",
12323
+ boxShadow: "0 2px 8px rgba(0, 0, 0, 0.15)"
12324
+ },
12325
+ severity: {
12326
+ info: {
12327
+ backgroundColor: "#eff6ff",
12328
+ border: "1px solid #93c5fd",
12329
+ color: "#1e40af"
12330
+ },
12331
+ warning: {
12332
+ backgroundColor: "#fffbeb",
12333
+ border: "1px solid #fbbf24",
12334
+ color: "#92400e"
12335
+ },
12336
+ critical: {
12337
+ backgroundColor: "#fef2f2",
12338
+ border: "1px solid #fca5a5",
12339
+ color: "#991b1b"
12340
+ }
12341
+ },
12342
+ actions: {
12343
+ display: "flex",
12344
+ gap: "8px",
12345
+ alignItems: "center"
12346
+ },
12347
+ link: {
12348
+ fontWeight: 600,
12349
+ textDecoration: "underline",
12350
+ color: "inherit"
12351
+ },
12352
+ dismiss: {
12353
+ background: "none",
12354
+ border: "none",
12355
+ cursor: "pointer",
12356
+ color: "inherit",
12357
+ fontSize: "16px"
12358
+ }
12359
+ };
12360
+ /**
12361
+ * The bottom space the fixed banner takes: banner height (~36px) + bottom
12362
+ * offset (8px) + gap above the chat input (~8px). The chat input reads it
12363
+ * through `padding-bottom: var(--copilotkit-license-banner-offset)`.
12364
+ */
12365
+ const ɵLICENSE_BANNER_OFFSET = {
12366
+ cssVar: "--copilotkit-license-banner-offset",
12367
+ px: 52
12368
+ };
12369
+ /**
12370
+ * Publishes {@link ɵLICENSE_BANNER_OFFSET} on the root element while a
12371
+ * banner shows. Does nothing without a document (SSR).
12372
+ *
12373
+ * @returns A function that removes the offset again.
12374
+ */
12375
+ function ɵreserveLicenseBannerOffset() {
12376
+ if (typeof document === "undefined") return () => {};
12377
+ const root = document.documentElement;
12378
+ root.style.setProperty(ɵLICENSE_BANNER_OFFSET.cssVar, `${ɵLICENSE_BANNER_OFFSET.px}px`);
12379
+ return () => root.style.removeProperty(ɵLICENSE_BANNER_OFFSET.cssVar);
12380
+ }
12381
+ /**
12382
+ * What the inline warning shows when a chat component needs a license it
12383
+ * does not have: the `licenseFeatureUnlicensedText` label and a pricing
12384
+ * link. Render it with {@link ɵINLINE_FEATURE_WARNING_STYLE}.
12385
+ */
12386
+ function ɵgetInlineFeatureWarningSpec(featureName, labels) {
12387
+ return {
12388
+ message: ɵformatLabel(labels.licenseFeatureUnlicensedText, { feature: featureName }),
12389
+ actionLabel: "Get one at copilotkit.ai/pricing",
12390
+ actionUrl: PRICING_URL
12391
+ };
12392
+ }
12393
+ /** Inline styles of the inline feature warning, in camelCase. */
12394
+ const ɵINLINE_FEATURE_WARNING_STYLE = {
12395
+ container: {
12396
+ padding: "8px 12px",
12397
+ backgroundColor: "#fffbeb",
12398
+ border: "1px solid #fbbf24",
12399
+ borderRadius: "6px",
12400
+ fontSize: "13px",
12401
+ color: "#92400e",
12402
+ fontFamily: FONT_FAMILY
12403
+ },
12404
+ link: {
12405
+ color: "#b45309",
12406
+ textDecoration: "underline"
12407
+ }
12408
+ };
12263
12409
 
12264
12410
  //#endregion
12265
12411
  //#region src/chat/icons.ts
@@ -12488,6 +12634,880 @@ const ɵcopilotIconSvgAttributes = {
12488
12634
  "stroke-linejoin": "round"
12489
12635
  };
12490
12636
 
12637
+ //#endregion
12638
+ //#region src/chat/message-feedback.ts
12639
+ /** Trajectory event name for a rating of one assistant message. */
12640
+ const ɵMESSAGE_FEEDBACK_EVENT_NAME = "message.feedback";
12641
+ /** Longest comment kept, in characters; the rest is cut so the event stays small. */
12642
+ const ɵMESSAGE_FEEDBACK_MAX_COMMENT_LENGTH = 1e3;
12643
+ /** Longest excerpt of the rated response sent with the rating, in characters. */
12644
+ const RESPONSE_EXCERPT_LENGTH = 500;
12645
+ /**
12646
+ * How long the pointer may be away from the rating and its comment before the
12647
+ * comment closes: enough to cross the gap between them, short enough that
12648
+ * passing over a rating does not leave it open.
12649
+ */
12650
+ const ɵFEEDBACK_COMMENT_CLOSE_DELAY_MS = 150;
12651
+ const ratings = /* @__PURE__ */ new Map();
12652
+ const listeners = /* @__PURE__ */ new Map();
12653
+ const threadKey = (agentId, threadId) => JSON.stringify([agentId, threadId]);
12654
+ const messageKey = (agentId, threadId, messageId) => JSON.stringify([
12655
+ agentId,
12656
+ threadId,
12657
+ messageId
12658
+ ]);
12659
+ /** Cuts `text` to `max` characters without splitting a surrogate pair. */
12660
+ const clip = (text, max) => {
12661
+ const characters = Array.from(text);
12662
+ return characters.length > max ? characters.slice(0, max).join("") : text;
12663
+ };
12664
+ /** The comment as kept and sent: trimmed and capped, or none. */
12665
+ const normalizeComment = (comment) => {
12666
+ if (comment === void 0) return void 0;
12667
+ const text = clip(comment.trim(), ɵMESSAGE_FEEDBACK_MAX_COMMENT_LENGTH);
12668
+ return text === "" ? void 0 : text;
12669
+ };
12670
+ /** The rating this page gave one message, if any. */
12671
+ function ɵgetMessageFeedback(agentId, threadId, messageId) {
12672
+ return ratings.get(messageKey(agentId, threadId, messageId));
12673
+ }
12674
+ /** Calls `listener` whenever a rating in this Thread changes. */
12675
+ function ɵsubscribeToMessageFeedback(agentId, threadId, listener) {
12676
+ const key = threadKey(agentId, threadId);
12677
+ let set = listeners.get(key);
12678
+ if (set === void 0) {
12679
+ set = /* @__PURE__ */ new Set();
12680
+ listeners.set(key, set);
12681
+ }
12682
+ const subscribed = set;
12683
+ subscribed.add(listener);
12684
+ return () => {
12685
+ subscribed.delete(listener);
12686
+ if (subscribed.size === 0) listeners.delete(key);
12687
+ };
12688
+ }
12689
+ /**
12690
+ * Sets (or, with `null`, clears) this page's rating of one message and sends
12691
+ * it to the active Trajectory. Every change is a new event; the newest event
12692
+ * for a `feedbackId` is the current one. Like any Trajectory event, a change
12693
+ * made while no Trajectory captures, for example during a reconnect, is not
12694
+ * sent; the page still shows it.
12695
+ */
12696
+ function ɵsetMessageFeedback(params) {
12697
+ const { copilotkit, agentId, threadId, message } = params;
12698
+ const comment = normalizeComment(params.feedback?.comment);
12699
+ const feedback = params.feedback && {
12700
+ rating: params.feedback.rating,
12701
+ ...comment ? { comment } : {}
12702
+ };
12703
+ const key = messageKey(agentId, threadId, message.id);
12704
+ if (feedback) ratings.set(key, feedback);
12705
+ else ratings.delete(key);
12706
+ const threadListeners = listeners.get(threadKey(agentId, threadId)) ?? [];
12707
+ for (const listener of threadListeners) listener();
12708
+ const runId = copilotkit.getRunIdForMessage(agentId, threadId, message.id);
12709
+ copilotkit.emitTrajectoryEvent(ɵMESSAGE_FEEDBACK_EVENT_NAME, {
12710
+ feedbackId: `${threadId}:${message.id}`,
12711
+ threadId,
12712
+ messageId: message.id,
12713
+ agentId,
12714
+ ...runId ? { runId } : {},
12715
+ rating: feedback?.rating ?? null,
12716
+ ...feedback?.comment ? { comment: feedback.comment } : {},
12717
+ ...copilotkit.ɵlearningCapturesAgentText ? { response: clip(message.content ?? "", RESPONSE_EXCERPT_LENGTH) } : {}
12718
+ });
12719
+ }
12720
+ /** @internal Forgets every rating, so each test starts empty. */
12721
+ function ɵresetMessageFeedbackCache() {
12722
+ ratings.clear();
12723
+ }
12724
+ const capturedCores = /* @__PURE__ */ new WeakSet();
12725
+ const rememberCapture = (copilotkit) => {
12726
+ if (capturedCores.has(copilotkit)) return;
12727
+ capturedCores.add(copilotkit);
12728
+ const unsubscribe = copilotkit.ɵsubscribeToLearningConfigured(() => {
12729
+ if (copilotkit.ɵlearningConfigured) return;
12730
+ capturedCores.delete(copilotkit);
12731
+ unsubscribe();
12732
+ });
12733
+ };
12734
+ /**
12735
+ * Whether the thumbs record feedback for Learning. True once a Trajectory of
12736
+ * this Core has started and as long as Learning stays configured, also while
12737
+ * capture reconnects or is stopped, so the buttons do not flicker. Ratings
12738
+ * given meanwhile still show but, like any Trajectory event, are not sent. A
12739
+ * capture that never starts (for example without a license) leaves it false.
12740
+ *
12741
+ * Re-read it when {@link ɵsubscribeToLearningFeedbackEnabled} notifies.
12742
+ */
12743
+ function ɵisLearningFeedbackEnabled(copilotkit) {
12744
+ const capturing = copilotkit.trajectoryId !== null;
12745
+ if (capturing) rememberCapture(copilotkit);
12746
+ return copilotkit.ɵlearningConfigured && (capturing || capturedCores.has(copilotkit));
12747
+ }
12748
+ /**
12749
+ * Calls `listener` when {@link ɵisLearningFeedbackEnabled} may have changed:
12750
+ * when Learning is configured or removed, and when the Trajectory changes.
12751
+ * Returns the unsubscribe function.
12752
+ */
12753
+ function ɵsubscribeToLearningFeedbackEnabled(copilotkit, listener) {
12754
+ const unsubscribeConfigured = copilotkit.ɵsubscribeToLearningConfigured(listener);
12755
+ const subscription = copilotkit.subscribe({ onTrajectoryChanged: listener });
12756
+ return () => {
12757
+ unsubscribeConfigured();
12758
+ subscription.unsubscribe();
12759
+ };
12760
+ }
12761
+ /**
12762
+ * The feedback this page gave `message` in `scope`, and how to change it.
12763
+ * Read it again when {@link ɵsubscribeToMessageFeedback} notifies for the
12764
+ * scope's Thread.
12765
+ */
12766
+ function ɵgetMessageFeedbackControls(scope, message) {
12767
+ const feedback = ɵgetMessageFeedback(scope.agentId, scope.threadId, message.id);
12768
+ const save = (next) => ɵsetMessageFeedback({
12769
+ ...scope,
12770
+ message,
12771
+ feedback: next
12772
+ });
12773
+ return {
12774
+ feedback,
12775
+ rate: (rating) => {
12776
+ if (feedback?.rating !== rating) save({ rating });
12777
+ },
12778
+ clear: () => {
12779
+ if (feedback) save(null);
12780
+ },
12781
+ comment: (comment) => {
12782
+ if (feedback) save({
12783
+ rating: feedback.rating,
12784
+ comment
12785
+ });
12786
+ }
12787
+ };
12788
+ }
12789
+ /**
12790
+ * Drives the comment popover of a rated message.
12791
+ *
12792
+ * It opens when a rating is given and whenever the pointer or keyboard focus
12793
+ * reaches the chosen thumb, with the saved comment in the field. It closes by
12794
+ * itself shortly after the pointer leaves the thumb and the popover, unless
12795
+ * focus is in the field: then it stays until focus moves away, Enter, or
12796
+ * Escape. Closing saves a changed comment; Escape, a click on a thumb, and
12797
+ * removing the rating discard it.
12798
+ *
12799
+ * Frameworks render from `getSnapshot()` and re-render when `subscribe()`
12800
+ * notifies. Call `dispose()` on unmount: it keeps an unsaved edit, for a
12801
+ * message that scrolls out of a virtual list. The controller stays usable
12802
+ * after `dispose()`, so a remount (React Strict Mode) can keep it.
12803
+ *
12804
+ * @example
12805
+ * ```ts
12806
+ * const comment = new ɵFeedbackCommentController({ getControls: () => controls });
12807
+ * comment.subscribe(() => render(comment.getSnapshot()));
12808
+ * comment.show({ comment: "", focus: false });
12809
+ * // On unmount:
12810
+ * comment.dispose();
12811
+ * ```
12812
+ */
12813
+ var ɵFeedbackCommentController = class {
12814
+ #getControls;
12815
+ #closeDelayMs;
12816
+ #listeners = /* @__PURE__ */ new Set();
12817
+ #state = {
12818
+ open: false,
12819
+ draft: "",
12820
+ focusRequest: 0
12821
+ };
12822
+ #timer;
12823
+ #editing = false;
12824
+ #focusWaiting = false;
12825
+ #pointerOver = false;
12826
+ #returning = false;
12827
+ constructor(options) {
12828
+ this.#getControls = options.getControls;
12829
+ this.#closeDelayMs = options.closeDelayMs ?? ɵFEEDBACK_COMMENT_CLOSE_DELAY_MS;
12830
+ }
12831
+ /** The current state. The same object until something changes. */
12832
+ getSnapshot = () => this.#state;
12833
+ /** Calls `listener` when the state changes. Returns the unsubscribe function. */
12834
+ subscribe = (listener) => {
12835
+ this.#listeners.add(listener);
12836
+ return () => {
12837
+ this.#listeners.delete(listener);
12838
+ };
12839
+ };
12840
+ /** Sets the comment being edited. */
12841
+ setDraft = (draft) => {
12842
+ this.#update({ draft });
12843
+ };
12844
+ /** Whether a focus request waits; reading it answers the request. */
12845
+ takeFocusRequest = () => {
12846
+ const waiting = this.#focusWaiting;
12847
+ this.#focusWaiting = false;
12848
+ return waiting;
12849
+ };
12850
+ /** Opens with `comment` in the field. */
12851
+ show = ({ comment, focus }) => {
12852
+ this.#cancelClose();
12853
+ if (focus) this.#focusWaiting = true;
12854
+ this.#update({
12855
+ open: true,
12856
+ draft: comment,
12857
+ focusRequest: this.#state.focusRequest + (focus ? 1 : 0)
12858
+ });
12859
+ };
12860
+ /** The pointer or focus reached the rating or the popover. */
12861
+ enter = (via = "focus") => {
12862
+ this.#cancelClose();
12863
+ if (via === "pointer") this.#pointerOver = true;
12864
+ if (this.#returning) return;
12865
+ if (!this.#state.open && this.#getControls()?.feedback) this.show({
12866
+ comment: this.#savedComment(),
12867
+ focus: false
12868
+ });
12869
+ };
12870
+ /**
12871
+ * It left them: close soon, unless the user is editing the comment or, when
12872
+ * focus left, the pointer is still on the rating or the popover.
12873
+ */
12874
+ leave = (via = "focus") => {
12875
+ if (via === "pointer") this.#pointerOver = false;
12876
+ else if (this.#pointerOver) return;
12877
+ this.#cancelClose();
12878
+ this.#timer = setTimeout(() => {
12879
+ this.#timer = void 0;
12880
+ if (!this.#editing) this.close();
12881
+ }, this.#closeDelayMs);
12882
+ };
12883
+ /** Tracks whether focus is in the comment form. */
12884
+ setEditing = (editing) => {
12885
+ this.#editing = editing;
12886
+ };
12887
+ /** Closes, saving a changed comment unless `save` is false. */
12888
+ close = ({ save = true } = {}) => {
12889
+ this.#cancelClose();
12890
+ this.#focusWaiting = false;
12891
+ this.#pointerOver = false;
12892
+ if (!this.#state.open) return;
12893
+ if (save) this.#saveDraft();
12894
+ this.#editing = false;
12895
+ this.#update({ open: false });
12896
+ };
12897
+ /** Moves focus back to the thumb without opening the comment again. */
12898
+ returnFocus = (target) => {
12899
+ this.#returning = true;
12900
+ try {
12901
+ target?.focus();
12902
+ } finally {
12903
+ this.#returning = false;
12904
+ }
12905
+ };
12906
+ /** Stops the close timer and saves a changed comment that is still open. */
12907
+ dispose = () => {
12908
+ this.#cancelClose();
12909
+ if (this.#state.open) this.#saveDraft();
12910
+ };
12911
+ #savedComment() {
12912
+ return this.#getControls()?.feedback?.comment ?? "";
12913
+ }
12914
+ #saveDraft() {
12915
+ const controls = this.#getControls();
12916
+ const draft = this.#state.draft;
12917
+ if (controls?.feedback && draft.trim() !== this.#savedComment()) controls.comment(draft);
12918
+ }
12919
+ #cancelClose() {
12920
+ if (this.#timer === void 0) return;
12921
+ clearTimeout(this.#timer);
12922
+ this.#timer = void 0;
12923
+ }
12924
+ #update(patch) {
12925
+ const next = {
12926
+ ...this.#state,
12927
+ ...patch
12928
+ };
12929
+ if (next.open === this.#state.open && next.draft === this.#state.draft && next.focusRequest === this.#state.focusRequest) return;
12930
+ this.#state = next;
12931
+ for (const listener of this.#listeners) listener();
12932
+ }
12933
+ };
12934
+
12935
+ //#endregion
12936
+ //#region src/chat/viewport.ts
12937
+ const AUTO_SCROLL_MODES = [
12938
+ "pin-to-bottom",
12939
+ "pin-to-send",
12940
+ "none"
12941
+ ];
12942
+ const isAutoScrollMode = (value) => AUTO_SCROLL_MODES.includes(value);
12943
+ /**
12944
+ * Turns the `autoScroll` prop into a mode. `true` and a missing value mean
12945
+ * `"pin-to-bottom"`, `false` means `"none"`, and an unknown string falls back
12946
+ * to `"pin-to-bottom"`.
12947
+ */
12948
+ function ɵnormalizeAutoScroll(value) {
12949
+ if (value === false) return "none";
12950
+ if (value === void 0 || value === true) return "pin-to-bottom";
12951
+ return isAutoScrollMode(value) ? value : "pin-to-bottom";
12952
+ }
12953
+ /**
12954
+ * Media query for the mobile range, where the threads drawer and the chat
12955
+ * modal are mutually exclusive.
12956
+ */
12957
+ const ɵMOBILE_MAX_WIDTH_QUERY = "(max-width: 767px)";
12958
+ /** `window.matchMedia` for the mobile query, or `null` without a DOM. */
12959
+ const mobileMediaQuery = () => {
12960
+ return typeof window !== "undefined" && typeof window.matchMedia === "function" ? window.matchMedia(ɵMOBILE_MAX_WIDTH_QUERY) : null;
12961
+ };
12962
+ /**
12963
+ * Whether the viewport is in the mobile range (`<768px`). `false` during SSR
12964
+ * and where `window.matchMedia` is missing (some test runners and webviews).
12965
+ */
12966
+ function ɵisMobileViewport() {
12967
+ return mobileMediaQuery()?.matches ?? false;
12968
+ }
12969
+ /**
12970
+ * Calls `listener` with {@link ɵisMobileViewport} now and each time the
12971
+ * viewport enters or leaves the mobile range. Does nothing without
12972
+ * `window.matchMedia`. Returns the unsubscribe function.
12973
+ */
12974
+ function ɵwatchMobileViewport(listener) {
12975
+ const query = mobileMediaQuery();
12976
+ if (query === null) return () => {};
12977
+ const update = () => listener(query.matches);
12978
+ update();
12979
+ query.addEventListener("change", update);
12980
+ return () => query.removeEventListener("change", update);
12981
+ }
12982
+ /**
12983
+ * The on-screen keyboard is treated as open once it covers more than this
12984
+ * many pixels of the layout viewport.
12985
+ */
12986
+ const ɵKEYBOARD_OPEN_THRESHOLD_PX = 150;
12987
+ /**
12988
+ * Reads the keyboard state with the Visual Viewport API: the keyboard height
12989
+ * is `innerHeight - visualViewport.height`, clamped to 0. Without the API (or
12990
+ * during SSR) it reports a closed keyboard and the full window height.
12991
+ */
12992
+ function ɵreadKeyboardState() {
12993
+ if (typeof window === "undefined") return closedKeyboard(0);
12994
+ const visualViewport = window.visualViewport;
12995
+ if (!visualViewport) return closedKeyboard(window.innerHeight);
12996
+ const layoutHeight = window.innerHeight;
12997
+ const keyboardHeight = Math.max(0, layoutHeight - visualViewport.height);
12998
+ return {
12999
+ isKeyboardOpen: keyboardHeight > ɵKEYBOARD_OPEN_THRESHOLD_PX,
13000
+ keyboardHeight,
13001
+ availableHeight: visualViewport.height,
13002
+ viewportHeight: layoutHeight
13003
+ };
13004
+ }
13005
+ const closedKeyboard = (height) => ({
13006
+ isKeyboardOpen: false,
13007
+ keyboardHeight: 0,
13008
+ availableHeight: height,
13009
+ viewportHeight: height
13010
+ });
13011
+ /**
13012
+ * The state for the first render, before {@link ɵwatchKeyboardState} reads
13013
+ * the visual viewport: a closed keyboard over the full window height (0
13014
+ * during SSR).
13015
+ */
13016
+ function ɵinitialKeyboardState() {
13017
+ return closedKeyboard(typeof window === "undefined" ? 0 : window.innerHeight);
13018
+ }
13019
+ /**
13020
+ * Calls `listener` with {@link ɵreadKeyboardState} now and on each visual
13021
+ * viewport resize or scroll. Does nothing during SSR or without the Visual
13022
+ * Viewport API. Returns the unsubscribe function.
13023
+ */
13024
+ function ɵwatchKeyboardState(listener) {
13025
+ if (typeof window === "undefined") return () => {};
13026
+ const visualViewport = window.visualViewport;
13027
+ if (!visualViewport) return () => {};
13028
+ const update = () => listener(ɵreadKeyboardState());
13029
+ update();
13030
+ visualViewport.addEventListener("resize", update);
13031
+ visualViewport.addEventListener("scroll", update);
13032
+ return () => {
13033
+ visualViewport.removeEventListener("resize", update);
13034
+ visualViewport.removeEventListener("scroll", update);
13035
+ };
13036
+ }
13037
+ /** Escapes `id` for a CSS attribute selector, also without `CSS.escape`. */
13038
+ const escapeSelectorValue = (id) => typeof CSS !== "undefined" && typeof CSS.escape === "function" ? CSS.escape(id) : id.replace(/[!"#$%&'()*+,./:;<=>?@[\\\]^`{|}~]/g, "\\$&");
13039
+ /**
13040
+ * Offset of `el` from the top of `stopAt`'s content, including `stopAt`'s
13041
+ * scroll. Uses `getBoundingClientRect`, so it works for any CSS position.
13042
+ */
13043
+ const offsetTopWithin = (el, stopAt) => el.getBoundingClientRect().top - stopAt.getBoundingClientRect().top + stopAt.scrollTop;
13044
+ /**
13045
+ * Pins a sent message to the top of the chat: sizes the spacer so the
13046
+ * message bubble can scroll to `topOffset` from the viewport top, scrolls
13047
+ * there on the next frame, and then shrinks the spacer as the reply below
13048
+ * grows, so the bubble stays put.
13049
+ *
13050
+ * The message element's top padding is scrolled off-screen: the bubble, not
13051
+ * its padded box, is pinned. Does nothing when no element in `contentEl` has
13052
+ * `data-message-id` equal to `messageId`. Skips the scroll without
13053
+ * `requestAnimationFrame` and the spacer updates without `ResizeObserver`.
13054
+ *
13055
+ * @returns A function that cancels the scroll and stops the spacer updates.
13056
+ * It returns `false` when it cancelled a scroll that had not run yet, so the
13057
+ * caller can pin the same send again. React's StrictMode tears an effect
13058
+ * down before the next frame, so the first run never scrolls.
13059
+ *
13060
+ * @example
13061
+ * ```ts
13062
+ * const unpin = ɵpinMessageToTop({ scrollEl, contentEl, spacerEl, messageId });
13063
+ * // On the next send or on unmount:
13064
+ * unpin();
13065
+ * ```
13066
+ */
13067
+ function ɵpinMessageToTop({ scrollEl, contentEl, spacerEl, messageId, topOffset = 16 }) {
13068
+ const targetEl = contentEl.querySelector(`[data-message-id="${escapeSelectorValue(messageId)}"]`);
13069
+ if (!targetEl) return () => true;
13070
+ const viewportHeight = scrollEl.clientHeight;
13071
+ const userMessageHeight = targetEl.getBoundingClientRect().height;
13072
+ const paddingTop = parseFloat(getComputedStyle(targetEl).paddingTop) || 0;
13073
+ const bubbleHeight = Math.max(0, userMessageHeight - paddingTop);
13074
+ const spacerHeight = Math.max(0, viewportHeight - bubbleHeight - topOffset);
13075
+ spacerEl.style.height = `${spacerHeight}px`;
13076
+ let scrolled = false;
13077
+ const frame = typeof requestAnimationFrame === "function" ? requestAnimationFrame(() => {
13078
+ scrolled = true;
13079
+ const targetTop = offsetTopWithin(targetEl, scrollEl) + paddingTop - topOffset;
13080
+ scrollEl.scrollTo({
13081
+ top: Math.max(0, targetTop),
13082
+ behavior: "smooth"
13083
+ });
13084
+ }) : null;
13085
+ const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(() => {
13086
+ const consumedBelow = contentEl.getBoundingClientRect().height - offsetTopWithin(targetEl, contentEl) - userMessageHeight;
13087
+ const remaining = Math.max(0, spacerHeight - consumedBelow);
13088
+ spacerEl.style.height = `${remaining}px`;
13089
+ });
13090
+ observer?.observe(contentEl);
13091
+ return () => {
13092
+ if (frame !== null && typeof cancelAnimationFrame === "function") cancelAnimationFrame(frame);
13093
+ observer?.disconnect();
13094
+ return frame === null || scrolled;
13095
+ };
13096
+ }
13097
+
13098
+ //#endregion
13099
+ //#region src/chat/message-display.ts
13100
+ /**
13101
+ * How long the model reasoned, as label text: "a few seconds", "4 seconds",
13102
+ * "2 minutes", or "1m 5s".
13103
+ *
13104
+ * @param seconds - The elapsed time in seconds. It may have a fraction.
13105
+ * @param labels - The chat labels that hold the duration texts.
13106
+ */
13107
+ function ɵformatReasoningDurationLabel(seconds, labels) {
13108
+ const duration = formatReasoningDuration(seconds);
13109
+ switch (duration.unit) {
13110
+ case "fewSeconds": return labels.reasoningMessageDurationFewSeconds;
13111
+ case "seconds": return ɵformatLabel(labels.reasoningMessageDurationSeconds, { count: duration.seconds });
13112
+ case "minutes": return ɵformatCountLabel(duration.minutes, {
13113
+ one: labels.reasoningMessageDurationMinutesOne,
13114
+ other: labels.reasoningMessageDurationMinutesOther
13115
+ });
13116
+ case "minutesSeconds": return ɵformatLabel(labels.reasoningMessageDurationMinutesSeconds, {
13117
+ minutes: duration.minutes,
13118
+ seconds: duration.seconds
13119
+ });
13120
+ }
13121
+ }
13122
+ /**
13123
+ * The text of the work summary line at the top of a reply in the `"turn"`
13124
+ * tool-call display.
13125
+ *
13126
+ * - While working: `label` is "Working" and `detail` the live timer ("4s"),
13127
+ * or `null` when the elapsed time is not known.
13128
+ * - When done with a known time: `label` is "Worked for 9s" (at least 1s)
13129
+ * and `detail` the tool count ("7 tools").
13130
+ * - When done without a time: `label` is "Used 7 tools" and `detail` `null`.
13131
+ * - `failed` is "2 failed" when tool calls failed, otherwise `null`. It is
13132
+ * always `null` while working.
13133
+ */
13134
+ function ɵgetWorkSummaryText({ isWorking, calls, elapsedMs, workingSince, now, labels }) {
13135
+ if (isWorking) {
13136
+ const isTimed = elapsedMs !== void 0 && workingSince !== void 0;
13137
+ return {
13138
+ label: labels.workSummaryWorkingLabel,
13139
+ detail: isTimed ? formatWorkDuration(elapsedMs + Math.max(0, now - workingSince)) : null,
13140
+ failed: null
13141
+ };
13142
+ }
13143
+ const failedCount = countFailedToolCalls(calls);
13144
+ const failed = failedCount > 0 ? ɵformatLabel(labels.toolCallFailedCountLabel, { count: failedCount }) : null;
13145
+ if (elapsedMs === void 0) return {
13146
+ label: ɵformatCountLabel(calls.length, {
13147
+ one: labels.toolCallUsedToolsOne,
13148
+ other: labels.toolCallUsedToolsOther
13149
+ }),
13150
+ detail: null,
13151
+ failed
13152
+ };
13153
+ const duration = formatWorkDuration(Math.max(1e3, elapsedMs));
13154
+ return {
13155
+ label: ɵformatLabel(labels.workSummaryWorkedForLabel, { duration }),
13156
+ detail: ɵformatCountLabel(calls.length, {
13157
+ one: labels.toolCallToolCountOne,
13158
+ other: labels.toolCallToolCountOther
13159
+ }),
13160
+ failed
13161
+ };
13162
+ }
13163
+ /**
13164
+ * The text of a user message: the string content, or its text parts joined
13165
+ * by newlines. Parts that are not text, and malformed parts from untyped
13166
+ * data, add nothing.
13167
+ */
13168
+ function ɵflattenUserMessageContent(content) {
13169
+ if (!content) return "";
13170
+ if (typeof content === "string") return content;
13171
+ return content.map((part) => part?.type === "text" && typeof part.text === "string" ? part.text : "").filter((text) => text.length > 0).join("\n");
13172
+ }
13173
+ const isMediaPart = (part) => part?.type === "image" || part?.type === "audio" || part?.type === "video" || part?.type === "document";
13174
+ /** The image, audio, video, and document parts of a user message. */
13175
+ function ɵgetUserMessageMediaParts(content) {
13176
+ if (!content || typeof content === "string") return [];
13177
+ return content.filter(isMediaPart);
13178
+ }
13179
+ /** The file name stored in an attachment's `metadata.filename`, if any. */
13180
+ function ɵgetUserMessageMediaFilename(part) {
13181
+ const meta = part.metadata;
13182
+ return meta != null && typeof meta === "object" && "filename" in meta && typeof meta.filename === "string" ? meta.filename : void 0;
13183
+ }
13184
+ /**
13185
+ * Whether a user message shows its branch navigation and which arrows work.
13186
+ * It shows only with more than one branch and a switch handler: without the
13187
+ * handler the arrows would do nothing.
13188
+ */
13189
+ function ɵgetBranchNavState({ branchIndex, numberOfBranches, canSwitch }) {
13190
+ const show = canSwitch && numberOfBranches > 1;
13191
+ return {
13192
+ show,
13193
+ canGoPrev: show && branchIndex > 0,
13194
+ canGoNext: show && branchIndex < numberOfBranches - 1
13195
+ };
13196
+ }
13197
+ /** Whether an assistant message has text beyond whitespace. */
13198
+ function ɵhasAssistantMessageText(content) {
13199
+ return !!content && content.trim().length > 0;
13200
+ }
13201
+ /**
13202
+ * Whether an assistant message shows its toolbar: when toolbars are on, the
13203
+ * message has text or the Inspector shortcut shows, and the message is not
13204
+ * the one still streaming (the latest while the agent runs).
13205
+ */
13206
+ function ɵshouldShowAssistantToolbar({ toolbarVisible, hasContent, showInspectorShortcut, isRunning, isLatest }) {
13207
+ return toolbarVisible && (hasContent || showInspectorShortcut) && !(isRunning && isLatest);
13208
+ }
13209
+ /** How long a copy button shows its "copied" check mark, in ms. */
13210
+ const ɵCOPY_FEEDBACK_RESET_MS = 2e3;
13211
+ /**
13212
+ * The "copied" state of a copy button. After a copy it is `true` for
13213
+ * {@link ɵCOPY_FEEDBACK_RESET_MS}; another copy in that time restarts the
13214
+ * wait, so rapid clicks do not flicker.
13215
+ *
13216
+ * Frameworks render from `getSnapshot()` and re-render when `subscribe()`
13217
+ * notifies. Call `dispose()` on unmount. The controller stays usable after
13218
+ * `dispose()`, so a remount (React Strict Mode) can keep it.
13219
+ *
13220
+ * @example
13221
+ * ```ts
13222
+ * const feedback = new ɵCopyFeedback();
13223
+ * feedback.subscribe(() => render(feedback.getSnapshot()));
13224
+ * await feedback.copy(text);
13225
+ * ```
13226
+ */
13227
+ var ɵCopyFeedback = class {
13228
+ #listeners = /* @__PURE__ */ new Set();
13229
+ #resetMs;
13230
+ #copied = false;
13231
+ #timer;
13232
+ constructor({ resetMs = ɵCOPY_FEEDBACK_RESET_MS } = {}) {
13233
+ this.#resetMs = resetMs;
13234
+ }
13235
+ /** Whether the check mark shows. */
13236
+ getSnapshot = () => this.#copied;
13237
+ /** Calls `listener` when the state changes. Returns the unsubscribe function. */
13238
+ subscribe = (listener) => {
13239
+ this.#listeners.add(listener);
13240
+ return () => {
13241
+ this.#listeners.delete(listener);
13242
+ };
13243
+ };
13244
+ /** Shows the check mark, or keeps it for the full time again. */
13245
+ markCopied = () => {
13246
+ this.#clearTimer();
13247
+ this.#set(true);
13248
+ this.#timer = setTimeout(() => {
13249
+ this.#timer = void 0;
13250
+ this.#set(false);
13251
+ }, this.#resetMs);
13252
+ };
13253
+ /**
13254
+ * Copies `text` to the clipboard and shows the check mark on success.
13255
+ * Empty text copies nothing.
13256
+ *
13257
+ * @returns Whether the text was copied.
13258
+ */
13259
+ copy = async (text) => {
13260
+ if (!text) return false;
13261
+ const copied = await copyToClipboard(text);
13262
+ if (copied) this.markCopied();
13263
+ return copied;
13264
+ };
13265
+ /** Stops the reset timer. */
13266
+ dispose = () => {
13267
+ this.#clearTimer();
13268
+ };
13269
+ #clearTimer() {
13270
+ if (this.#timer === void 0) return;
13271
+ clearTimeout(this.#timer);
13272
+ this.#timer = void 0;
13273
+ }
13274
+ #set(copied) {
13275
+ if (copied === this.#copied) return;
13276
+ this.#copied = copied;
13277
+ for (const listener of this.#listeners) listener();
13278
+ }
13279
+ };
13280
+
13281
+ //#endregion
13282
+ //#region src/chat/inspector-button.ts
13283
+ let shortcutsHidden = false;
13284
+ const shortcutListeners = /* @__PURE__ */ new Set();
13285
+ const notifyShortcutListeners = () => {
13286
+ for (const listener of shortcutListeners) listener();
13287
+ };
13288
+ /**
13289
+ * Whether the user hid the Inspector shortcuts in the message toolbars
13290
+ * ("Hide this icon"). It lasts until the page reloads and applies to every
13291
+ * chat on the page.
13292
+ *
13293
+ * @example
13294
+ * ```ts
13295
+ * ɵinspectorShortcuts.subscribe(() => render(ɵinspectorShortcuts.hidden));
13296
+ * ɵinspectorShortcuts.hide();
13297
+ * ```
13298
+ */
13299
+ const ɵinspectorShortcuts = {
13300
+ get hidden() {
13301
+ return shortcutsHidden;
13302
+ },
13303
+ hide() {
13304
+ if (shortcutsHidden) return;
13305
+ shortcutsHidden = true;
13306
+ notifyShortcutListeners();
13307
+ },
13308
+ subscribe(listener) {
13309
+ shortcutListeners.add(listener);
13310
+ return () => {
13311
+ shortcutListeners.delete(listener);
13312
+ };
13313
+ },
13314
+ reset() {
13315
+ if (!shortcutsHidden) return;
13316
+ shortcutsHidden = false;
13317
+ notifyShortcutListeners();
13318
+ }
13319
+ };
13320
+ const kiteStroke = (d, stroke, strokeWidth) => ({
13321
+ d,
13322
+ stroke,
13323
+ strokeWidth,
13324
+ strokeLinecap: "round"
13325
+ });
13326
+ /**
13327
+ * The Inspector kite artwork as data, as in
13328
+ * `web-inspector/src/assets/inspector-logo-kite.svg`. Render an `<svg>` with
13329
+ * `viewBox` and `fill="none"`, one `<path>` per entry of `paths`, and a
13330
+ * `<linearGradient gradientUnits="userSpaceOnUse">` per entry of `gradients`
13331
+ * in `<defs>`. Give each gradient the id `${prefix}-${gradient.id}` with a
13332
+ * prefix unique to the icon, and fill paths with
13333
+ * {@link ɵinspectorKiteFill}.
13334
+ */
13335
+ const ɵinspectorKiteIcon = {
13336
+ viewBox: "4.57 3.36 17.8 17.8",
13337
+ paths: [
13338
+ {
13339
+ d: "M6.36084 10.9855C8.34277 8.393 9.98843 5.82939 10.6204 3.75914C10.6382 3.70281 10.7043 3.67888 10.7534 3.7114C12.9536 5.16894 16.9635 6.12833 20.5086 6.15085C20.5703 6.15124 20.6124 6.2114 20.5895 6.26829C19.4109 9.25938 17.9705 14.6189 17.9148 20.7392C17.9148 20.8301 17.7873 20.8627 17.7419 20.7837C15.7236 17.2522 9.26021 12.2898 6.39414 11.1186C6.34112 11.0968 6.32556 11.0313 6.36084 10.9855Z",
13340
+ fillGradient: "paint0_linear"
13341
+ },
13342
+ {
13343
+ d: "M13.0475 9.39974C9.95016 10.3806 7.11935 10.9259 6.44331 11.0498C6.40027 11.0577 6.39115 11.1172 6.43152 11.134C9.3203 12.3347 15.7516 17.2826 17.7511 20.7998C17.7551 20.8075 17.7647 20.8103 17.7728 20.8068C17.7809 20.803 17.7853 20.793 17.7819 20.7844L13.0475 9.39974Z",
13344
+ fillGradient: "paint1_linear"
13345
+ },
13346
+ {
13347
+ d: "M10.762 3.705C13.4137 5.15161 16.4787 5.80132 20.545 6.14367C20.5703 6.14585 20.5787 6.18008 20.5557 6.19197C20.0359 6.45923 17.0574 7.97512 14.8455 8.78701C14.2524 9.00453 13.6564 9.20632 13.0692 9.39249C13.0562 9.39656 13.0419 9.39015 13.0369 9.37774L10.7005 3.75979C10.6849 3.72196 10.7257 3.68538 10.762 3.705Z",
13348
+ fillGradient: "paint2_linear"
13349
+ },
13350
+ kiteStroke("M10.7145 3.79041L17.8305 20.7659", "#513C9F", "0.17284"),
13351
+ kiteStroke("M6.44531 11.0476C6.44531 11.0476 10.375 10.3422 14.0686 9.06804C17.7623 7.7939 20.5122 6.23373 20.5122 6.23373", "#513C9F", "0.17284"),
13352
+ kiteStroke("M11.6914 5.93518L9.05534 14.7068M9.05534 14.7068H15.3203M9.05534 14.7068L0.15625 26.3646", "#ABABAB", "0.302474"),
13353
+ {
13354
+ d: "M6.02539 23.9646L4.85806 24.1287C5.46272 25.7287 6.70381 26.4276 8.18528 26.4276C11.8147 26.4276 10.707 22.3227 12.8103 22.3227C14.3358 22.3227 13.7155 25.6498 16.9992 25.6498C19.0029 25.6498 19.2028 23.631 18.8607 22.7625C18.8589 22.7572 18.8568 22.7524 18.8538 22.7476L18.3166 21.9253C18.2817 21.8706 18.1968 21.8912 18.1907 21.9562L18.0908 22.9529C18.0838 23.0222 18.0857 23.0913 18.0936 23.1605C18.1764 23.8491 18.2291 25.5202 16.9992 25.5202C15.7015 25.5202 15.3895 22.2362 12.8103 22.2362C9.78393 22.2362 10.1726 26.298 8.31487 26.298C7.08938 26.298 6.15447 24.9153 6.02539 23.9646Z",
13355
+ fillGradient: "paint3_linear"
13356
+ }
13357
+ ],
13358
+ gradients: [
13359
+ {
13360
+ id: "paint0_linear",
13361
+ x1: "15.5372",
13362
+ y1: "5.0278",
13363
+ x2: "12.0802",
13364
+ y2: "14.534",
13365
+ stops: [{ color: "#6430AB" }, {
13366
+ offset: "1",
13367
+ color: "#AA89D8"
13368
+ }]
13369
+ },
13370
+ {
13371
+ id: "paint1_linear",
13372
+ x1: "12.8583",
13373
+ y1: "10.3858",
13374
+ x2: "8.40764",
13375
+ y2: "18.9846",
13376
+ stops: [{ color: "#005DBB" }, {
13377
+ offset: "1",
13378
+ color: "#3D92E8"
13379
+ }]
13380
+ },
13381
+ {
13382
+ id: "paint2_linear",
13383
+ x1: "14.8452",
13384
+ y1: "5.02774",
13385
+ x2: "13.5047",
13386
+ y2: "9.21911",
13387
+ stops: [{ color: "#1B70C4" }, {
13388
+ offset: "1",
13389
+ color: "#54A4F2"
13390
+ }]
13391
+ },
13392
+ {
13393
+ id: "paint3_linear",
13394
+ x1: "4.85806",
13395
+ y1: "24.2455",
13396
+ x2: "18.9963",
13397
+ y2: "24.2455",
13398
+ stops: [
13399
+ { color: "#4497EA" },
13400
+ {
13401
+ offset: "0.254755",
13402
+ color: "#1463B2"
13403
+ },
13404
+ {
13405
+ offset: "0.498725",
13406
+ color: "#0A437D"
13407
+ },
13408
+ {
13409
+ offset: "0.666667",
13410
+ color: "#2476C8"
13411
+ },
13412
+ {
13413
+ offset: "0.972542",
13414
+ color: "#0C549A"
13415
+ }
13416
+ ]
13417
+ }
13418
+ ]
13419
+ };
13420
+ /**
13421
+ * The `fill` of a kite path: its gradient under the icon's id `prefix`, or
13422
+ * `undefined` for a stroke-only path.
13423
+ */
13424
+ function ɵinspectorKiteFill(prefix, path) {
13425
+ return path.fillGradient === void 0 ? void 0 : `url(#${prefix}-${path.fillGradient})`;
13426
+ }
13427
+ /** How long a hover-opened menu stays after the pointer leaves, in ms. */
13428
+ const ɵHOVER_MENU_CLOSE_DELAY_MS = 180;
13429
+ /**
13430
+ * The open state of a menu that opens when the pointer reaches its trigger,
13431
+ * like the Inspector shortcut's menu.
13432
+ *
13433
+ * - A mouse or pen over the trigger opens it; touch does not.
13434
+ * - Leaving the trigger or the menu closes it after `closeDelayMs`, unless
13435
+ * the pointer comes back first or the keyboard has used the menu since.
13436
+ * - Opening reads whether the trigger is inside a `.dark` element, so a menu
13437
+ * in a portal can match the theme.
13438
+ *
13439
+ * Frameworks render from `getSnapshot()` and re-render when `subscribe()`
13440
+ * notifies. Call `dispose()` on unmount; the controller stays usable.
13441
+ */
13442
+ var ɵHoverMenuController = class {
13443
+ #closeDelayMs;
13444
+ #listeners = /* @__PURE__ */ new Set();
13445
+ #state = {
13446
+ open: false,
13447
+ dark: false
13448
+ };
13449
+ #timer;
13450
+ #openedByHover = false;
13451
+ constructor({ closeDelayMs = ɵHOVER_MENU_CLOSE_DELAY_MS } = {}) {
13452
+ this.#closeDelayMs = closeDelayMs;
13453
+ }
13454
+ /** The current state. The same object until something changes. */
13455
+ getSnapshot = () => this.#state;
13456
+ /** Calls `listener` when the state changes. Returns the unsubscribe function. */
13457
+ subscribe = (listener) => {
13458
+ this.#listeners.add(listener);
13459
+ return () => {
13460
+ this.#listeners.delete(listener);
13461
+ };
13462
+ };
13463
+ /** Whether the pointer opened the menu and the keyboard has not used it. */
13464
+ get openedByHover() {
13465
+ return this.#openedByHover;
13466
+ }
13467
+ /**
13468
+ * Opens or closes the menu and stops a pending close. `trigger` is read on
13469
+ * open for the dark theme.
13470
+ */
13471
+ setOpen = (open, trigger) => {
13472
+ this.cancelClose();
13473
+ const dark = open ? !!trigger?.closest(".dark") : this.#state.dark;
13474
+ if (open === this.#state.open && dark === this.#state.dark) return;
13475
+ this.#state = {
13476
+ open,
13477
+ dark
13478
+ };
13479
+ for (const listener of this.#listeners) listener();
13480
+ };
13481
+ /** The pointer reached the trigger: opens, except for touch or disabled. */
13482
+ pointerEnter = ({ pointerType, disabled = false, trigger }) => {
13483
+ if (disabled || pointerType === "touch") return;
13484
+ this.#openedByHover = true;
13485
+ this.setOpen(true, trigger);
13486
+ };
13487
+ /** The keyboard used the trigger or the menu: keep it open on leave. */
13488
+ keyboardUsed = () => {
13489
+ this.#openedByHover = false;
13490
+ };
13491
+ /** The pointer left the trigger or the menu: close soon if hover opened it. */
13492
+ scheduleClose = () => {
13493
+ this.cancelClose();
13494
+ this.#timer = setTimeout(() => {
13495
+ this.#timer = void 0;
13496
+ if (this.#openedByHover) this.setOpen(false);
13497
+ }, this.#closeDelayMs);
13498
+ };
13499
+ /** The pointer came back: keep the menu open. */
13500
+ cancelClose = () => {
13501
+ if (this.#timer === void 0) return;
13502
+ clearTimeout(this.#timer);
13503
+ this.#timer = void 0;
13504
+ };
13505
+ /** Stops a pending close. */
13506
+ dispose = () => {
13507
+ this.cancelClose();
13508
+ };
13509
+ };
13510
+
12491
13511
  //#endregion
12492
13512
  //#region src/open-generative-ui/content.ts
12493
13513
  /**
@@ -12915,5 +13935,27 @@ var OpenGenerativeUIController = class {
12915
13935
  };
12916
13936
 
12917
13937
  //#endregion
12918
- export { A2UI_FENCE_LANGUAGE, AgentRegistry, AgentThreadLockedError, ContextStore, CopilotChatDefaultLabels, CopilotKitCore, CopilotKitCoreErrorCode, CopilotKitCoreRuntimeConnectionStatus, CopilotKitHeaderResolutionError, DEFAULT_OPEN_GENERATIVE_UI_DESIGN_SKILL, GENERATE_SANDBOXED_UI_TOOL_NAME, INSPECTOR_THREAD_BRIDGE_PLUGIN_ID, INTERRUPT_EVENT_NAME, IntelligenceAgent, MEMORY_ERROR_REGISTRY, MemoryError, OPEN_GENERATIVE_UI_ACTIVITY_TYPE, ProxiedCopilotRuntimeAgent, RunHandler, StateManager, SuggestionEngine, ToolCallStatus, TranscriptionError, TranscriptionErrorCode, WebMCPRegistry, classifySurfaceCards, completePartialMarkdown, createActionGroup, createEffect, createInspectorThreadRequestId, createReducer, createSelector, createStore, emitInspectorActiveThread, emitInspectorStopViewing, emitInspectorViewThread, emitInspectorViewThreadResult, empty, ensureObjectArgs, extractCompleteArrayItems, extractFenceOperations, extractStringField, flattenInformationalCards, getMarkdownOperationSurfaceId, getWebMCPModelContext, isAbortError, isInspectorThreadBridgeEnabled, isRunCompletionAware, ofType, on, onInspectorActiveThread, onInspectorStopViewing, onInspectorViewThread, onInspectorViewThreadResult, parseToolArguments, prepareSurfaceOperations, props, segmentSurfaceProse, select, splitA2UIMarkdown, ɵCOPILOTKIT_FEATURES, ɵInterruptState, ɵMAX_SOCKET_RETRIES, OpenGenerativeUIController as ɵOpenGenerativeUIController, ɵRUNTIME_PROBE_TIMEOUT_MS, ɵTHREAD_REQUEST_TIMEOUT_MS, ɵclearAgentInterruptState, ɵcomposerButtonState, ɵcopilotIconSvgAttributes, ɵcopilotIcons, countFailedToolCalls as ɵcountFailedToolCalls, createMemoryStore as ɵcreateMemoryStore, ɵcreateThreadSelectors, createThreadStore as ɵcreateThreadStore, ɵdeduplicateMessages, extractCompleteStyles as ɵextractCompleteStyles, ɵformatCountLabel, ɵformatLabel, formatReasoningDuration as ɵformatReasoningDuration, formatToolNames as ɵformatToolNames, formatWorkDuration as ɵformatWorkDuration, ɵgetAgentInterruptState, getArgumentPreview as ɵgetArgumentPreview, getLatestTurnKey as ɵgetLatestTurnKey, getToolCallLayouts as ɵgetToolCallLayouts, getToolCallPreview as ɵgetToolCallPreview, getToolCallRendererNames as ɵgetToolCallRendererNames, getToolCallRowStatus as ɵgetToolCallRowStatus, getToolResults as ɵgetToolResults, getTurnWork as ɵgetTurnWork, getWorkOpenState as ɵgetWorkOpenState, ɵisCopilotKitFeature, ɵisHttpAgent, isRetryableStatus as ɵisRetryableMemoryStatus, isTurnWorkOpen as ɵisTurnWorkOpen, isTurnWorking as ɵisTurnWorking, ɵjoinPhoenixChannel$, loadWebsandbox as ɵloadWebsandbox, ɵmapMemoryMetadataEvent, ɵmemoryAdapterEvents, ɵmemoryDomainEvents, ɵmemoryReducer, ɵmemoryRestEvents, ɵmessagesFingerprint, ɵobservePhoenixEvent$, ɵobservePhoenixJoinOutcome$, ɵobservePhoenixSocketHealth$, ɵobservePhoenixSocketSignals$, ɵphoenixChannel$, ɵphoenixSocket$, pluralize as ɵpluralize, processPartialHtml as ɵprocessPartialHtml, recordWorkTime as ɵrecordWorkTime, ɵresolveActivityRenderer, ɵresolveComposerKey, ɵresolveCustomMessageRenderers, ɵresolveLicenseState, ɵresolveThreadsLicense, ɵresolveToolCallRenderer, ɵselectFetchMoreError, ɵselectHasNextPage, ɵselectIsFetchingNextPage, ɵselectIsMutating, ɵselectMemories, ɵselectMemoriesAvailable, ɵselectMemoriesError, ɵselectMemoriesIsLoading, ɵselectMemoriesIsMutating, ɵselectMemoriesRealtimeStatus, ɵselectThreads, ɵselectThreadsError, ɵselectThreadsIsLoading, stringifyToolCallPayload as ɵstringifyToolCallPayload, ɵthreadAdapterEvents, ɵtranscribeAudio, ɵtranscriptionErrorMessageKey, ɵwithHeaderDefaults };
13938
+ //#region src/utils/class-names.ts
13939
+ /**
13940
+ * Joins class names, skipping falsy values. Takes the same inputs as `clsx`.
13941
+ * Classes are not merged: every rule CopilotKit ships sits in `:where()`, so a
13942
+ * class the app adds wins without removing ours.
13943
+ */
13944
+ function cn(...inputs) {
13945
+ const out = [];
13946
+ for (const input of inputs) {
13947
+ if (!input) continue;
13948
+ if (typeof input === "string" || typeof input === "number" || typeof input === "bigint") out.push(String(input));
13949
+ else if (Array.isArray(input)) {
13950
+ const nested = cn(...input);
13951
+ if (nested) out.push(nested);
13952
+ } else if (typeof input === "object") {
13953
+ for (const key in input) if (input[key]) out.push(key);
13954
+ }
13955
+ }
13956
+ return out.join(" ");
13957
+ }
13958
+
13959
+ //#endregion
13960
+ export { A2UI_FENCE_LANGUAGE, AgentRegistry, AgentThreadLockedError, ContextStore, CopilotChatDefaultLabels, CopilotKitCore, CopilotKitCoreErrorCode, CopilotKitCoreRuntimeConnectionStatus, CopilotKitHeaderResolutionError, DEFAULT_OPEN_GENERATIVE_UI_DESIGN_SKILL, GENERATE_SANDBOXED_UI_TOOL_NAME, INSPECTOR_THREAD_BRIDGE_PLUGIN_ID, INTERRUPT_EVENT_NAME, IntelligenceAgent, MEMORY_ERROR_REGISTRY, MemoryError, OPEN_GENERATIVE_UI_ACTIVITY_TYPE, ProxiedCopilotRuntimeAgent, RunHandler, StateManager, SuggestionEngine, ToolCallStatus, TranscriptionError, TranscriptionErrorCode, WebMCPRegistry, classifySurfaceCards, completePartialMarkdown, createActionGroup, createEffect, createInspectorThreadRequestId, createReducer, createSelector, createStore, emitInspectorActiveThread, emitInspectorStopViewing, emitInspectorViewThread, emitInspectorViewThreadResult, empty, ensureObjectArgs, extractCompleteArrayItems, extractFenceOperations, extractStringField, flattenInformationalCards, getMarkdownOperationSurfaceId, getWebMCPModelContext, isAbortError, isInspectorThreadBridgeEnabled, isRunCompletionAware, ofType, on, onInspectorActiveThread, onInspectorStopViewing, onInspectorViewThread, onInspectorViewThreadResult, parseToolArguments, prepareSurfaceOperations, props, segmentSurfaceProse, select, splitA2UIMarkdown, ɵCOPILOTKIT_FEATURES, ɵCOPY_FEEDBACK_RESET_MS, ɵCopyFeedback, ɵFEEDBACK_COMMENT_CLOSE_DELAY_MS, ɵFeedbackCommentController, ɵHOVER_MENU_CLOSE_DELAY_MS, ɵHoverMenuController, ɵINLINE_FEATURE_WARNING_STYLE, ɵInterruptState, ɵKEYBOARD_OPEN_THRESHOLD_PX, ɵLICENSE_BANNER_OFFSET, ɵLICENSE_BANNER_STYLE, ɵMAX_SOCKET_RETRIES, ɵMESSAGE_FEEDBACK_EVENT_NAME, ɵMESSAGE_FEEDBACK_MAX_COMMENT_LENGTH, ɵMOBILE_MAX_WIDTH_QUERY, OpenGenerativeUIController as ɵOpenGenerativeUIController, ɵRUNTIME_PROBE_TIMEOUT_MS, ɵTHREAD_REQUEST_TIMEOUT_MS, ɵclearAgentInterruptState, cn as ɵcn, ɵcomposerButtonState, ɵcopilotIconSvgAttributes, ɵcopilotIcons, countFailedToolCalls as ɵcountFailedToolCalls, createMemoryStore as ɵcreateMemoryStore, ɵcreateThreadSelectors, createThreadStore as ɵcreateThreadStore, ɵdeduplicateMessages, extractCompleteStyles as ɵextractCompleteStyles, ɵflattenUserMessageContent, ɵformatCountLabel, ɵformatLabel, formatReasoningDuration as ɵformatReasoningDuration, ɵformatReasoningDurationLabel, formatToolNames as ɵformatToolNames, formatWorkDuration as ɵformatWorkDuration, ɵgetAgentInterruptState, getArgumentPreview as ɵgetArgumentPreview, ɵgetBranchNavState, ɵgetInlineFeatureWarningSpec, getLatestTurnKey as ɵgetLatestTurnKey, ɵgetLicenseBannerSpec, ɵgetMessageFeedback, ɵgetMessageFeedbackControls, getToolCallLayouts as ɵgetToolCallLayouts, getToolCallPreview as ɵgetToolCallPreview, getToolCallRendererNames as ɵgetToolCallRendererNames, getToolCallRowStatus as ɵgetToolCallRowStatus, getToolResults as ɵgetToolResults, getTurnWork as ɵgetTurnWork, ɵgetUserMessageMediaFilename, ɵgetUserMessageMediaParts, getWorkOpenState as ɵgetWorkOpenState, ɵgetWorkSummaryText, ɵhasAssistantMessageText, ɵinitialKeyboardState, ɵinspectorKiteFill, ɵinspectorKiteIcon, ɵinspectorShortcuts, ɵisCopilotKitFeature, ɵisHttpAgent, ɵisLearningFeedbackEnabled, ɵisMobileViewport, isRetryableStatus as ɵisRetryableMemoryStatus, isTurnWorkOpen as ɵisTurnWorkOpen, isTurnWorking as ɵisTurnWorking, ɵjoinPhoenixChannel$, loadWebsandbox as ɵloadWebsandbox, ɵmapMemoryMetadataEvent, ɵmemoryAdapterEvents, ɵmemoryDomainEvents, ɵmemoryReducer, ɵmemoryRestEvents, ɵmessagesFingerprint, ɵnormalizeAutoScroll, ɵobservePhoenixEvent$, ɵobservePhoenixJoinOutcome$, ɵobservePhoenixSocketHealth$, ɵobservePhoenixSocketSignals$, ɵphoenixChannel$, ɵphoenixSocket$, ɵpinMessageToTop, pluralize as ɵpluralize, processPartialHtml as ɵprocessPartialHtml, ɵreadKeyboardState, recordWorkTime as ɵrecordWorkTime, ɵreserveLicenseBannerOffset, ɵresetMessageFeedbackCache, ɵresolveActivityRenderer, ɵresolveComposerKey, ɵresolveCustomMessageRenderers, ɵresolveLicenseState, ɵresolveThreadsLicense, ɵresolveToolCallRenderer, ɵselectFetchMoreError, ɵselectHasNextPage, ɵselectIsFetchingNextPage, ɵselectIsMutating, ɵselectMemories, ɵselectMemoriesAvailable, ɵselectMemoriesError, ɵselectMemoriesIsLoading, ɵselectMemoriesIsMutating, ɵselectMemoriesRealtimeStatus, ɵselectThreads, ɵselectThreadsError, ɵselectThreadsIsLoading, ɵsetMessageFeedback, shallowEqualRecord as ɵshallowEqualRecord, ɵshouldShowAssistantToolbar, stringifyToolCallPayload as ɵstringifyToolCallPayload, ɵsubscribeToLearningFeedbackEnabled, ɵsubscribeToMessageFeedback, ɵthreadAdapterEvents, ɵtranscribeAudio, ɵtranscriptionErrorMessageKey, ɵwatchKeyboardState, ɵwatchMobileViewport, ɵwithHeaderDefaults };
12919
13961
  //# sourceMappingURL=index.mjs.map