@mgamadeus/ddd-agents 0.16.1 → 0.17.1

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.
Files changed (95) hide show
  1. package/README.md +113 -10
  2. package/boundary.json +15 -1
  3. package/dist/admin-chat-widgets.js +158 -0
  4. package/dist/admin-chat-widgets.js.map +1 -0
  5. package/dist/admin.js +92 -65
  6. package/dist/admin.js.map +1 -1
  7. package/dist/chat.js +19 -19
  8. package/dist/chat.js.map +1 -1
  9. package/dist/chunks/AgentScheduleOrderDraftPanel-DM6pz_hc.js +304 -0
  10. package/dist/chunks/AgentScheduleOrderDraftPanel-DM6pz_hc.js.map +1 -0
  11. package/dist/chunks/{ConversationMarkdown-DNQcVuz-.js → ConversationMarkdown-dj0EF6bu.js} +5 -5
  12. package/dist/chunks/{ConversationMarkdown-DNQcVuz-.js.map → ConversationMarkdown-dj0EF6bu.js.map} +1 -1
  13. package/dist/chunks/{ConversationMessageInputComposerWidgets-BlpIule7.js → ConversationMessageInputComposerWidgets-ClgCwnVW.js} +6 -6
  14. package/dist/chunks/{ConversationMessageInputComposerWidgets-BlpIule7.js.map → ConversationMessageInputComposerWidgets-ClgCwnVW.js.map} +1 -1
  15. package/dist/chunks/{VoiceBarsIcon-eODB_UTI.js → VoiceBarsIcon-B6VTVtdB.js} +4 -4
  16. package/dist/chunks/{VoiceBarsIcon-eODB_UTI.js.map → VoiceBarsIcon-B6VTVtdB.js.map} +1 -1
  17. package/dist/chunks/{WebSearchResultsConversationWidget-l9Aek_lG.js → WebSearchResultsConversationWidget-BVMwJfhL.js} +73 -64
  18. package/dist/chunks/WebSearchResultsConversationWidget-BVMwJfhL.js.map +1 -0
  19. package/dist/chunks/{agents-http-trace-mappers-rsbGAf2_.js → agents-http-trace-mappers-CuGZOFu-.js} +53 -14
  20. package/dist/chunks/agents-http-trace-mappers-CuGZOFu-.js.map +1 -0
  21. package/dist/chunks/{browser-request-interception-D678IemW.js → browser-request-interception-BnOQWLaJ.js} +2 -2
  22. package/dist/chunks/{browser-request-interception-D678IemW.js.map → browser-request-interception-BnOQWLaJ.js.map} +1 -1
  23. package/dist/chunks/{canvas-label-context-C1Pc_Ldo.js → canvas-label-context-5yvbmK-V.js} +3 -3
  24. package/dist/chunks/{canvas-label-context-C1Pc_Ldo.js.map → canvas-label-context-5yvbmK-V.js.map} +1 -1
  25. package/dist/chunks/{canvas-reducers-BYArW_Ji.js → canvas-reducers-133Kl1QH.js} +2 -2
  26. package/dist/chunks/{canvas-reducers-BYArW_Ji.js.map → canvas-reducers-133Kl1QH.js.map} +1 -1
  27. package/dist/chunks/{canvasBodies-BpLPp-S8.js → canvasBodies-B2M6aWao.js} +4 -4
  28. package/dist/chunks/{canvasBodies-BpLPp-S8.js.map → canvasBodies-B2M6aWao.js.map} +1 -1
  29. package/dist/chunks/{canvasStorage-DSspwRMg.js → canvasStorage-B69JHOLd.js} +2 -2
  30. package/dist/chunks/{canvasStorage-DSspwRMg.js.map → canvasStorage-B69JHOLd.js.map} +1 -1
  31. package/dist/chunks/{content-from-unified-diff-DWyBHRSy.js → content-from-unified-diff-BKdgop63.js} +39 -5
  32. package/dist/chunks/content-from-unified-diff-BKdgop63.js.map +1 -0
  33. package/dist/chunks/{contract-DtFmOk91.js → contract-CQ6PO_e8.js} +2 -2
  34. package/dist/chunks/{contract-DtFmOk91.js.map → contract-CQ6PO_e8.js.map} +1 -1
  35. package/dist/chunks/{conversation-Cbrqtx-_.js → conversation-VosmRbsr.js} +4 -2
  36. package/dist/chunks/{conversation-Cbrqtx-_.js.map → conversation-VosmRbsr.js.map} +1 -1
  37. package/dist/chunks/conversation-trace-fVeh6Lg6.js.map +1 -1
  38. package/dist/chunks/{widget-name-resolver-DXIE9JUr.js → conversationWidgetRegistry-webrYtkI.js} +810 -530
  39. package/dist/chunks/conversationWidgetRegistry-webrYtkI.js.map +1 -0
  40. package/dist/chunks/{index-DZovGMpG.js → index-DAEGct6X.js} +61 -61
  41. package/dist/chunks/index-DAEGct6X.js.map +1 -0
  42. package/dist/chunks/{link-navigation-a_sRfmsj.js → link-navigation-DQWyeNkx.js} +2 -2
  43. package/dist/chunks/{link-navigation-a_sRfmsj.js.map → link-navigation-DQWyeNkx.js.map} +1 -1
  44. package/dist/chunks/{withPollingChangeSubscription-Cz3Diolr.js → withPollingChangeSubscription-Ct8kjmlL.js} +19 -2
  45. package/dist/chunks/withPollingChangeSubscription-Ct8kjmlL.js.map +1 -0
  46. package/dist/client-testing.js +39 -5
  47. package/dist/client-testing.js.map +1 -1
  48. package/dist/client.js +43 -14
  49. package/dist/client.js.map +1 -1
  50. package/dist/contract.js +4 -3
  51. package/dist/files/i18n-keys.json +619 -15
  52. package/dist/files/widgets/DriveFilesConversationWidget/DriveFilesConversationWidget.md +4 -2
  53. package/dist/files/widgets/OwnerStepConfirmationConversationWidget/OwnerStepConfirmationConversationWidget.md +54 -0
  54. package/dist/files/widgets/OwnerStepConfirmationConversationWidget/owner-step-confirmation.preview-fixtures.json +16 -0
  55. package/dist/image-render.js +8 -8
  56. package/dist/index.js +16 -16
  57. package/dist/kit.js +2 -2
  58. package/dist/preview.js +124 -117
  59. package/dist/preview.js.map +1 -1
  60. package/dist/provider.js +2 -2
  61. package/dist/renderer.js +53 -52
  62. package/dist/styles.css +46 -0
  63. package/dist/types/admin/connections/connection-parts.d.ts +2 -1
  64. package/dist/types/admin/schedules/AgentScheduleOrderDraftPanel.d.ts +45 -0
  65. package/dist/types/admin/schedules/AgentSchedulesPanel.d.ts +11 -3
  66. package/dist/types/admin/schedules/agent-schedules-api.d.ts +38 -2
  67. package/dist/types/admin/schedules/agent-schedules-format.d.ts +22 -1
  68. package/dist/types/admin/schedules/agent-schedules-types.d.ts +91 -1
  69. package/dist/types/admin-chat-widgets/ScheduleOrderApprovalConversationWidget.d.ts +37 -0
  70. package/dist/types/admin-chat-widgets/registerScheduleOrderApprovalWidget.d.ts +11 -0
  71. package/dist/types/chat/trace/TurnMetaLine.d.ts +5 -3
  72. package/dist/types/chat/trace/trace-counts.d.ts +2 -0
  73. package/dist/types/chat/trace/trace-types.d.ts +4 -0
  74. package/dist/types/client/AgentsConversationClient.d.ts +17 -1
  75. package/dist/types/client/http/agents-http-mappers.d.ts +4 -2
  76. package/dist/types/client/http/agents-http-trace-wire.d.ts +2 -0
  77. package/dist/types/client/http/agents-http-wire.d.ts +24 -0
  78. package/dist/types/client/testing/createInMemoryAgentsConversationClient.d.ts +13 -1
  79. package/dist/types/contract/conversation-trace.d.ts +4 -0
  80. package/dist/types/contract/conversation.d.ts +43 -0
  81. package/dist/types/entries/admin-chat-widgets.d.ts +2 -0
  82. package/dist/types/entries/admin.d.ts +4 -2
  83. package/dist/types/entries/renderer.d.ts +1 -1
  84. package/dist/types/renderer/widget-tree/composed-node-schema.d.ts +20 -3
  85. package/dist/types/widgets/DriveFilesConversationWidget/shared/drive-files.d.ts +3 -1
  86. package/dist/voice.js +2 -2
  87. package/dist/widgets.js +4 -4
  88. package/package.json +7 -1
  89. package/public-api.json +39 -0
  90. package/dist/chunks/WebSearchResultsConversationWidget-l9Aek_lG.js.map +0 -1
  91. package/dist/chunks/agents-http-trace-mappers-rsbGAf2_.js.map +0 -1
  92. package/dist/chunks/content-from-unified-diff-DWyBHRSy.js.map +0 -1
  93. package/dist/chunks/index-DZovGMpG.js.map +0 -1
  94. package/dist/chunks/widget-name-resolver-DXIE9JUr.js.map +0 -1
  95. package/dist/chunks/withPollingChangeSubscription-Cz3Diolr.js.map +0 -1
@@ -4,6 +4,66 @@ import { useSyncExternalStore, useMemo, useRef, useEffect, useState, useCallback
4
4
  import { A as AgentsConversationClientProvider } from "./AgentsConversationClientContext-B_UJSLXU.js";
5
5
  import ReactMarkdown from "react-markdown";
6
6
  import remarkGfm from "remark-gfm";
7
+ let appEnvironment = {};
8
+ const environmentListeners = /* @__PURE__ */ new Set();
9
+ const setAgentsEnvironment = (environment) => {
10
+ appEnvironment = environment;
11
+ for (const notifyListener of environmentListeners) notifyListener();
12
+ };
13
+ const getAgentsEnvironment = () => appEnvironment;
14
+ const subscribeToAgentsEnvironment = (listener) => {
15
+ environmentListeners.add(listener);
16
+ return () => {
17
+ environmentListeners.delete(listener);
18
+ };
19
+ };
20
+ const substitutePlaceholders = (key, replacements) => replacements ? key.replace(
21
+ /%([A-Za-z0-9_]+)%/g,
22
+ (placeholder, name) => Object.hasOwn(replacements, name) ? String(replacements[name]) : placeholder
23
+ ) : key;
24
+ const DEFAULT_AGENTS_TEXTS = { translate: substitutePlaceholders };
25
+ const translateText = (key, replacements, context) => (appEnvironment.texts ?? DEFAULT_AGENTS_TEXTS).translate(key, replacements, context);
26
+ const escapePlainTextForText = (text) => appEnvironment.escapePlainTextForText ? appEnvironment.escapePlainTextForText(text) : text;
27
+ const openImageGallery = (images, startIndex) => {
28
+ if (appEnvironment.openImageGallery) {
29
+ appEnvironment.openImageGallery(images, startIndex);
30
+ return;
31
+ }
32
+ const startImage = images[startIndex];
33
+ if (!startImage) return;
34
+ if (appEnvironment.onNavigate?.(startImage.url, null) === true) return;
35
+ window.open(startImage.url, "_blank", "noopener,noreferrer");
36
+ };
37
+ const canStartConversationInPersonalSpace = () => appEnvironment.startConversationInPersonalSpace !== void 0;
38
+ const startConversationInPersonalSpace = (ownerText) => {
39
+ if (!appEnvironment.startConversationInPersonalSpace) return false;
40
+ appEnvironment.startConversationInPersonalSpace(ownerText);
41
+ return true;
42
+ };
43
+ const canOpenConnectionPermissions = () => appEnvironment.openConnectionPermissions !== void 0;
44
+ const openConnectionPermissions = (target) => {
45
+ if (!appEnvironment.openConnectionPermissions) return false;
46
+ appEnvironment.openConnectionPermissions(target);
47
+ return true;
48
+ };
49
+ const DEFAULT_WIDGET_SELF_HYDRATION_KEY_FIELD_NAME = "agentSpaceId";
50
+ const getWidgetSelfHydrationKeyFieldName = () => appEnvironment.widgetSelfHydrationKeyFieldName ?? DEFAULT_WIDGET_SELF_HYDRATION_KEY_FIELD_NAME;
51
+ const appendAnotherAgentSpaceToOwnerText = (ownerText, anotherAgentSpaceKey) => appEnvironment.appendAnotherAgentSpaceToOwnerText ? appEnvironment.appendAnotherAgentSpaceToOwnerText(ownerText, anotherAgentSpaceKey) : ownerText;
52
+ const buildUnnamedAgentSpaceLabel = (agentSpaceKey) => appEnvironment.buildUnnamedAgentSpaceLabel ? appEnvironment.buildUnnamedAgentSpaceLabel(agentSpaceKey) : `#${agentSpaceKey}`;
53
+ const buildWidgetOfAnotherAgentSpaceExplanation = (agentSpaceLabel) => appEnvironment.buildWidgetOfAnotherAgentSpaceExplanation ? appEnvironment.buildWidgetOfAnotherAgentSpaceExplanation(agentSpaceLabel) : translateText("This widget shows data for %label%, not for what you currently have selected.", {
54
+ label: agentSpaceLabel
55
+ });
56
+ const getSandboxLegacyAliases = () => appEnvironment.sandboxLegacyAliases ?? {};
57
+ const DEFAULT_WIDGET_IMAGE_CAPTURE_READ_PATH_PREFIX = "/api/";
58
+ const getWidgetImageCaptureReadPathPrefix = () => appEnvironment.widgetImageCaptureReadPathPrefix ?? DEFAULT_WIDGET_IMAGE_CAPTURE_READ_PATH_PREFIX;
59
+ const getGoogleMapWidgetNames = () => appEnvironment.googleMapWidgetNames ?? [];
60
+ const getFurtherWidgetClickSignalSources = () => appEnvironment.furtherWidgetClickSignalSources ?? [];
61
+ const getFurtherCanvasBehaviours = () => appEnvironment.furtherCanvasBehaviours ?? {};
62
+ const getAgentDisplayName = () => appEnvironment.agentDisplayName ?? translateText("the assistant");
63
+ const reportRunningTurn = () => appEnvironment.reportRunningTurn?.();
64
+ const reportWidgetCrash = (widgetName, error, errorInfo) => {
65
+ appEnvironment.reportWidgetCrash?.(widgetName, error, errorInfo);
66
+ };
7
67
  const SLICE_NAME = "widgetHydrationSlice";
8
68
  const emptyMemory = () => {
9
69
  return {
@@ -880,66 +940,6 @@ const DEFAULT_AGENTS_COMPONENTS = {
880
940
  WidgetFeatureGate: DefaultWidgetFeatureGate,
881
941
  ConversationSearchResultsList: DefaultConversationSearchResultsList
882
942
  };
883
- let appEnvironment = {};
884
- const environmentListeners = /* @__PURE__ */ new Set();
885
- const setAgentsEnvironment = (environment) => {
886
- appEnvironment = environment;
887
- for (const notifyListener of environmentListeners) notifyListener();
888
- };
889
- const getAgentsEnvironment = () => appEnvironment;
890
- const subscribeToAgentsEnvironment = (listener) => {
891
- environmentListeners.add(listener);
892
- return () => {
893
- environmentListeners.delete(listener);
894
- };
895
- };
896
- const substitutePlaceholders = (key, replacements) => replacements ? key.replace(
897
- /%([A-Za-z0-9_]+)%/g,
898
- (placeholder, name) => Object.hasOwn(replacements, name) ? String(replacements[name]) : placeholder
899
- ) : key;
900
- const DEFAULT_AGENTS_TEXTS = { translate: substitutePlaceholders };
901
- const translateText = (key, replacements, context) => (appEnvironment.texts ?? DEFAULT_AGENTS_TEXTS).translate(key, replacements, context);
902
- const escapePlainTextForText = (text) => appEnvironment.escapePlainTextForText ? appEnvironment.escapePlainTextForText(text) : text;
903
- const openImageGallery = (images, startIndex) => {
904
- if (appEnvironment.openImageGallery) {
905
- appEnvironment.openImageGallery(images, startIndex);
906
- return;
907
- }
908
- const startImage = images[startIndex];
909
- if (!startImage) return;
910
- if (appEnvironment.onNavigate?.(startImage.url, null) === true) return;
911
- window.open(startImage.url, "_blank", "noopener,noreferrer");
912
- };
913
- const canStartConversationInPersonalSpace = () => appEnvironment.startConversationInPersonalSpace !== void 0;
914
- const startConversationInPersonalSpace = (ownerText) => {
915
- if (!appEnvironment.startConversationInPersonalSpace) return false;
916
- appEnvironment.startConversationInPersonalSpace(ownerText);
917
- return true;
918
- };
919
- const canOpenConnectionPermissions = () => appEnvironment.openConnectionPermissions !== void 0;
920
- const openConnectionPermissions = (target) => {
921
- if (!appEnvironment.openConnectionPermissions) return false;
922
- appEnvironment.openConnectionPermissions(target);
923
- return true;
924
- };
925
- const DEFAULT_WIDGET_SELF_HYDRATION_KEY_FIELD_NAME = "agentSpaceId";
926
- const getWidgetSelfHydrationKeyFieldName = () => appEnvironment.widgetSelfHydrationKeyFieldName ?? DEFAULT_WIDGET_SELF_HYDRATION_KEY_FIELD_NAME;
927
- const appendAnotherAgentSpaceToOwnerText = (ownerText, anotherAgentSpaceKey) => appEnvironment.appendAnotherAgentSpaceToOwnerText ? appEnvironment.appendAnotherAgentSpaceToOwnerText(ownerText, anotherAgentSpaceKey) : ownerText;
928
- const buildUnnamedAgentSpaceLabel = (agentSpaceKey) => appEnvironment.buildUnnamedAgentSpaceLabel ? appEnvironment.buildUnnamedAgentSpaceLabel(agentSpaceKey) : `#${agentSpaceKey}`;
929
- const buildWidgetOfAnotherAgentSpaceExplanation = (agentSpaceLabel) => appEnvironment.buildWidgetOfAnotherAgentSpaceExplanation ? appEnvironment.buildWidgetOfAnotherAgentSpaceExplanation(agentSpaceLabel) : translateText("This widget shows data for %label%, not for what you currently have selected.", {
930
- label: agentSpaceLabel
931
- });
932
- const getSandboxLegacyAliases = () => appEnvironment.sandboxLegacyAliases ?? {};
933
- const DEFAULT_WIDGET_IMAGE_CAPTURE_READ_PATH_PREFIX = "/api/";
934
- const getWidgetImageCaptureReadPathPrefix = () => appEnvironment.widgetImageCaptureReadPathPrefix ?? DEFAULT_WIDGET_IMAGE_CAPTURE_READ_PATH_PREFIX;
935
- const getGoogleMapWidgetNames = () => appEnvironment.googleMapWidgetNames ?? [];
936
- const getFurtherWidgetClickSignalSources = () => appEnvironment.furtherWidgetClickSignalSources ?? [];
937
- const getFurtherCanvasBehaviours = () => appEnvironment.furtherCanvasBehaviours ?? {};
938
- const getAgentDisplayName = () => appEnvironment.agentDisplayName ?? translateText("the assistant");
939
- const reportRunningTurn = () => appEnvironment.reportRunningTurn?.();
940
- const reportWidgetCrash = (widgetName, error, errorInfo) => {
941
- appEnvironment.reportWidgetCrash?.(widgetName, error, errorInfo);
942
- };
943
943
  const AgentsEnvironmentContext = createContext(null);
944
944
  const NO_SUBTREE_ENVIRONMENT = {};
945
945
  const AgentsProvider = (props) => {
@@ -1202,4 +1202,4 @@ export {
1202
1202
  buildUnnamedAgentSpaceLabel as y,
1203
1203
  buildWidgetOfAnotherAgentSpaceExplanation as z
1204
1204
  };
1205
- //# sourceMappingURL=index-DZovGMpG.js.map
1205
+ //# sourceMappingURL=index-DAEGct6X.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index-DAEGct6X.js","sources":["../../src/provider/environment.ts","../../src/renderer/widget-hydration/widget-hydration.reducer.ts","../../src/renderer/widget-hydration/widget-hydration-state-store.ts","../../src/provider/components/markdown-image-source.ts","../../src/provider/class-names.ts","../../src/provider/components/default-components.tsx","../../src/provider/AgentsProvider.tsx","../../src/provider/components/index.tsx"],"sourcesContent":["import type { ComponentType, ErrorInfo, ReactNode } from \"react\";\nimport type { AgentsComponents } from \"./components/types\";\nimport type { ConversationWidgetStatePartition } from \"../renderer/conversation-widget-state-partition\";\nimport type { ChatAssistantCategory } from \"../chat/chat-assistant-identity\";\nimport type { AgentChatActivityTiming } from \"../chat/controller/chat-activity-timing\";\nimport type { ComposedNodeSchemaApplicationPart } from \"../renderer/widget-tree/composed-node-schema\";\nimport type { CanvasBehaviour } from \"../renderer/canvas/canvas-behaviours\";\nimport type { OpenEntityActionTarget } from \"../renderer/canvas/entity-detail-instance\";\n\n/** Translates interface copy. The key is the English source text. */\nexport interface AgentsTexts {\n translate: (key: string, replacements?: Record<string, string | number>, context?: string) => string;\n}\n\n/** The permission of an agent connection a step needs (`AgentsEnvironment.openConnectionPermissions`). */\nexport interface AgentsConnectionPermissionTarget {\n /** The connection's id. */\n connectionId: number;\n /** The capability: MAIL, CALENDAR, CONTACTS, FILES or CHAT. */\n capability: string;\n /** The level the step needs (a level constant of the backend, e.g. SEND_WITH_APPROVAL). */\n level: string;\n}\n\n/** One image of a gallery the app opens over the page. */\nexport interface AgentsGalleryImage {\n /** Identifies the image within the gallery. */\n id: string;\n url: string;\n name?: string;\n}\n\n/**\n * An action the package dispatches into the state store. The index signature is the shape of redux 5's\n * `UnknownAction`, so a host store that registers the package's reducers keeps the action type react-redux 9 expects.\n */\nexport interface AgentsStateAction {\n type: string;\n payload?: unknown;\n [extraProps: string]: unknown;\n}\n\n/**\n * A state store as React hooks: the package keeps its widget hydration state in it, and an app's older chat state\n * partitions are read through it (`defaultChatStatePartition`). Without an app store the package uses its own.\n */\nexport interface AgentsStateStore {\n useSelector: <Selected>(selector: (state: any) => Selected) => Selected;\n useDispatch: () => (action: AgentsStateAction) => unknown;\n}\n\n/** The owner's language and the active agent space's date and time settings. Every field may be missing. */\nexport interface AgentsOwnerSettings {\n /** The owner's language (`de`). */\n languageCode?: string | null;\n /** The owner's locale (`de-DE`). */\n locale?: string | null;\n /** The date locale of the active agent space (`de-DE`). */\n dateLocale?: string | null;\n /** The time zone of the active agent space. */\n timeZone?: string | null;\n /** The active agent space writes times with AM/PM. */\n usesAmPm?: boolean | null;\n}\n\n/** What the error card of a reached budget offers (the error card's upgrade data). */\nexport interface AgentsBudgetLimit {\n /** An upgrade lifts the limit: the card offers it. */\n canUpgrade: boolean;\n /** Opens the app's upgrade flow. */\n openUpgrade: () => void;\n /** The app presents the budget as a fair-use allowance (the card uses that wording). */\n showsFairUseWording: boolean;\n}\n\n/** The badge of a named assistant's icon (its intro card, its openings). */\nexport interface AgentsAssistantIconBadgeProps {\n /** The icon's name in the app's icon set (`ChatAssistantIdentity.iconClass`). */\n iconName: string;\n color: string;\n backgroundColor: string;\n /** Larger on the intro card than on an opening. */\n isLarge?: boolean;\n}\n\n/** The background of a chat with a named assistant's category (or with none, the overview of every category). */\nexport interface AgentsAssistantBackgroundProps {\n category?: ChatAssistantCategory;\n /** The category's alias; undefined for a chat without a category. */\n categoryAlias?: string;\n}\n\n/** The state of the app's map script loader. */\nexport interface AgentsMapsLoaderState {\n isLoaded: boolean;\n loadError: Error | undefined;\n languageCode: string | undefined;\n}\n\n/**\n * Further names of the sandbox and readiness signals that an app declares beside the package's own (`AGENTS_VISUALIZATION`,\n * `--agents-*`, `__AGENTS_WIDGET_IMAGE_V1__`, `__AGENTS_WIDGET_PREVIEW_V1__`): the names its stored visualization scripts,\n * its skill texts or its headless capture already use. Every list is optional; the package's names always exist.\n */\n/**\n * How the agent chat lays out its canvas, for a host that frames the canvas itself (its own card, tabs, close control).\n * Every member is optional and defaults to the package's own chrome, so a host without the setting sees no change.\n */\nexport interface AgentsCanvasLayout {\n /** The canvas pane's own \"Close canvas\" button. Default true; a host whose frame closes the canvas sets false. */\n showsCloseButton?: boolean;\n /** The round canvas toggle on the divider (where the chat enables it). Default true. */\n showsDividerToggle?: boolean;\n /** The \"Re-open canvas\" control over the chat of a narrow viewport. Default true. */\n showsNarrowReopenControl?: boolean;\n /**\n * The narrowest the chat column gets beside an open canvas, in px: the default split and every pull of the edge stop\n * there. Default `CHAT_COLUMN_MIN_WIDTH_PX`.\n */\n chatColumnMinWidthPx?: number;\n /** The inset of the side-split canvas from its pane edge, in px, while the chat boxes the canvas. Default `CANVAS_BOXED_INSET_PX`. */\n boxedInsetPx?: number;\n /**\n * The canvas pane's own surface: `card` (default) paints the rounded surface of a boxed canvas and pads the pane;\n * `none` leaves both to the host's frame (its `SplitView` replacement draws the card).\n */\n paneSurface?: \"card\" | \"none\";\n}\n\nexport type AgentsSandboxLegacyAliases = {\n /** Further names of the sandbox global, e.g. the name stored scripts of the app read. */\n visualizationGlobalNames?: string[];\n /** Further prefixes of the frame's theme variables, e.g. `--app-` (each variable is set under every prefix). */\n themeVariablePrefixes?: string[];\n /** Further names of the image-capture readiness signal on `window`. */\n imageReadinessGlobalNames?: string[];\n /** Further names of the preview readiness signal on `window`. */\n previewReadinessGlobalNames?: string[];\n};\n\n/**\n * Everything an app supplies to the package. Every member is optional: the package has a default for each.\n * An app sets it once at start (`setAgentsEnvironment`) or per subtree (`AgentsProvider`); the functions are read\n * from the app-wide environment only.\n */\nexport interface AgentsEnvironment {\n /**\n * The state store hooks (see `AgentsStateStore`). Default: the package's own widget hydration store (one per page,\n * `createAgentsWidgetHydrationStateStore`). An app supplies its own to keep the hydration state in its store\n * (host application: its Redux store, which mounts `WidgetHydrationReducer` under `AIExtensionsWidgetHydration`).\n */\n stateStore?: AgentsStateStore;\n /**\n * The partition of the app's own chat state a widget provider reads when its host passes neither a chat store nor a\n * partition (host application: the AI-Extensions chat's slice). Default: none — such a provider keeps a store of its own.\n */\n defaultChatStatePartition?: ConversationWidgetStatePartition;\n /** A React hook returning the owner's settings. Default: none known (the browser's language stands in). */\n useOwnerSettings?: () => AgentsOwnerSettings;\n /**\n * A React hook returning the key of the agent space the owner works in. The key of an agent space is what the\n * client knows it by: the id of the space, unless the app's backend hands out another key\n * (`AgentSpace::getWidgetSelfHydrationKey()`). Default: no agent space.\n */\n useActiveAgentSpaceKey?: () => number | undefined;\n /** Reads the display name of an agent space (the header of a widget of another agent space). Default: no name. */\n readAgentSpaceName?: (agentSpaceKey: number, signal: AbortSignal) => Promise<string | undefined>;\n /**\n * The field of a widget block that carries the key of the block's agent space, as the app's backend writes it\n * (`WidgetBlockFieldNames::WIDGET_SELF_HYDRATION_KEY`). An app whose stored conversations use another field name\n * declares it here and in its backend class. Default: `agentSpaceId`.\n */\n widgetSelfHydrationKeyFieldName?: string;\n /**\n * The owner's text for a click on a widget of another agent space than the active one: returns the text with the\n * suffix the app's backend reads that agent space from\n * (`WidgetBlockFieldNames::OWNER_TEXT_SUFFIX_PATTERN_OF_ANOTHER_SPACE`). Default: the text unchanged.\n */\n appendAnotherAgentSpaceToOwnerText?: (ownerText: string, anotherAgentSpaceKey: number) => string;\n /** The label of an agent space whose name is not known. Default: `#<key>`. */\n buildUnnamedAgentSpaceLabel?: (agentSpaceKey: number) => string;\n /**\n * The sentence that tells the owner that a widget shows another agent space than the active one; `agentSpaceLabel`\n * is its name or the label above. Default: a sentence that names no kind of agent space.\n */\n buildWidgetOfAnotherAgentSpaceExplanation?: (agentSpaceLabel: string) => string;\n /** The name the owner knows the agent by, for the interface texts that name it. Default: `the assistant`. */\n agentDisplayName?: string;\n /**\n * The timing of every chat's activity reads and working indicator, for the fields a chat's own `activityTiming`\n * leaves out (`AgentChatActivityTiming`). Default: the package's values (one activity read per 3 s, a line at least\n * 2.2 s beside the face). A host with a realtime push that writes `activityUpdatedAt` lowers the read window.\n */\n chatActivityTiming?: AgentChatActivityTiming;\n /** A React hook returning what the error card of a reached budget offers. Default: no upgrade, the plain wording. */\n useBudgetLimit?: () => AgentsBudgetLimit;\n /** A React hook returning the map script loader's state. Default: no maps. */\n useMapsLoader?: () => AgentsMapsLoaderState;\n /**\n * The action that tells the app whether an agent chat surface is open (dispatched into the state store when the\n * first surface mounts and the last unmounts). Default: nothing is dispatched.\n */\n buildChatSurfaceOpenChangedAction?: (isOpen: boolean) => AgentsStateAction;\n /**\n * Hosts an image in model text may load from, besides the page's own origin and inline raster data: `cdn.example.com`\n * or `*.example.com` (https only). Model text is foreign; an image of any other host renders as a link, so a page the\n * agent read cannot make the browser send data to its host. Default: none.\n */\n markdownImageHosts?: readonly string[];\n components?: Partial<AgentsComponents>;\n /** How the chat lays out its canvas (see `AgentsCanvasLayout`). Default: the package's own chrome. */\n canvasLayout?: AgentsCanvasLayout;\n texts?: AgentsTexts;\n /**\n * Prepares a plain text (a model's words, the owner's own message, a business name) for the app's `Text`, `Button`,\n * `StatusBadge` and `Tooltip` replacements, which may read a string as markup. Default: the text unchanged.\n */\n escapePlainTextForText?: (text: string) => string;\n /**\n * Decides where a link of the package goes — every anchor (Markdown links, sources, kit links) and every link the\n * package opens by code (a video's watch page, an `openUrl` action, a gallery image without a lightbox). `event` is\n * the click, null when there is none. Return true when the host navigated itself (an in-app route; the package then\n * does nothing), false to let the package open the link in a new tab. Default: every link opens in a new tab.\n */\n onNavigate?: (href: string, event: MouseEvent | null) => boolean;\n /**\n * Opens the entity of an `openEntity` action (a composed view's row, a map point) on a host route instead of the\n * `entityDetail` canvas. Return true when the host opened it, false to open the canvas. Default: the canvas.\n */\n onOpenEntity?: (target: OpenEntityActionTarget) => boolean;\n /** Opens the images in the app's lightbox, starting at `startIndex`. Default: the start image in a new tab. */\n openImageGallery?: (images: AgentsGalleryImage[], startIndex: number) => void;\n /**\n * Starts a NEW conversation in the owner's personal agent space whose first message is `ownerText`, and shows it (the\n * `ContinueInPersonalSpace` widget's button: a request that only a connection of the owner alone may answer, asked in\n * a conversation others read). Nothing goes back into the conversation the button sits in. Default: none — the\n * widget then renders nothing.\n */\n startConversationInPersonalSpace?: (ownerText: string) => void;\n /**\n * Opens the app's settings of an agent connection with the permission a step needs preselected (the\n * `ExtendConnectionPermission` widget's button). The level takes effect only once the owner raised it there.\n * Default: none — the widget then renders nothing.\n */\n openConnectionPermissions?: (target: AgentsConnectionPermissionTarget) => void;\n /** Reports a widget that crashed while rendering. Default: nothing (the crash is logged to the console). */\n reportWidgetCrash?: (widgetName: string, error: Error, errorInfo: ErrorInfo) => void;\n /**\n * The footer under an assistant message (host application: the admin's forensics panel, which gates itself). Receives the\n * message as the message view got it. Default: none.\n */\n MessageFooter?: ComponentType<{ message?: unknown }>;\n /**\n * The colour theme class of a named assistant's category (the assistant identity and theme). Default:\n * none — the generic chat colours.\n */\n readAssistantThemeClassName?: (categoryAlias: string) => string;\n /** The badge of a named assistant's icon. Default: none. */\n AssistantIconBadge?: ComponentType<AgentsAssistantIconBadgeProps>;\n /** The chat's own background when the host paints none (host application: the category illustrations). Default: none. */\n AssistantBackground?: ComponentType<AgentsAssistantBackgroundProps>;\n /**\n * Wraps the body of an open canvas (host application: page components inside a canvas must not mirror their filters into\n * the page URL). Default: no wrapper.\n */\n CanvasBodyContainer?: ComponentType<{ children: ReactNode }>;\n /**\n * Tells the app that a turn of the agent runs in an open chat (the host application keeps the tab \"ambient active\" then);\n * returns the release the chat calls when the turn ends. Default: nothing.\n */\n reportRunningTurn?: () => () => void;\n /**\n * Further names of the CustomVisualization sandbox (its global, its theme variable prefixes) and of the image and\n * preview readiness signals, beside the package's own names (see `AgentsSandboxLegacyAliases`). An app whose stored\n * scripts or capture read older names declares them here. Default: none — only the package's names exist.\n */\n sandboxLegacyAliases?: AgentsSandboxLegacyAliases;\n /**\n * The app's part of the ComposedView node schema: the node types, widgets (which embed, at which size), data sources\n * and entity types its own classes declare, as its backend generates them beside the package's\n * `composed-node-schema.json`. The tree readers and the kit read the package's schema with this part added\n * (`getComposedNodeSchema`). Default: none — only the package's own types exist.\n */\n composedNodeSchemaApplicationPart?: ComposedNodeSchemaApplicationPart;\n /**\n * The path prefix of the app's API reads a live widget image capture lets through (same origin, GET only, sent with\n * the capture's bearer; every other request of the capture fails it). Default: `/api/`.\n */\n widgetImageCaptureReadPathPrefix?: string;\n /**\n * The app's widgets that draw a Google map: a widget image capture of one of them, or of a `ComposedView` that embeds\n * one, may load the Maps SDK (the narrow transport exception of the capture; the twin of the backend's list that opens\n * the capture page's CSP). A `ComposedView` holding a `Map` node always may. Default: none.\n */\n googleMapWidgetNames?: string[];\n /**\n * Further `signalSource`s a widget click of the app posts (`injectSignal`), beside the package's own\n * (`FRONTEND_WIDGET_CLICK`, `OWNER_ACTION_CONFIRM`): the message list reads every one of them as the owner's answer to\n * a widget, so an answered widget never comes back interactive after a reload. Default: none.\n */\n furtherWidgetClickSignalSources?: string[];\n /**\n * The canvases of the app's widgets (canvas id → behaviour), beside the package's own (`packageCanvasBehaviours`):\n * every canvas an app widget lists in `opensCanvases`. The app registers each one's body with `registerCanvasBodies`\n * and, when gated, its requirement with `registerCanvasFeatureFlags`. A package canvas id here is ignored. Default:\n * none.\n */\n furtherCanvasBehaviours?: Readonly<Record<string, CanvasBehaviour>>;\n}\n\nlet appEnvironment: AgentsEnvironment = {};\nconst environmentListeners = new Set<() => void>();\n\n/** Sets the app-wide environment. Call it once before the first render; a later call re-renders the readers. */\nexport const setAgentsEnvironment = (environment: AgentsEnvironment): void => {\n appEnvironment = environment;\n for (const notifyListener of environmentListeners) notifyListener();\n};\n\nexport const getAgentsEnvironment = (): AgentsEnvironment => appEnvironment;\n\nexport const subscribeToAgentsEnvironment = (listener: () => void): (() => void) => {\n environmentListeners.add(listener);\n return () => {\n environmentListeners.delete(listener);\n };\n};\n\nconst substitutePlaceholders = (key: string, replacements?: Record<string, string | number>): string =>\n replacements\n ? key.replace(/%([A-Za-z0-9_]+)%/g, (placeholder, name: string) =>\n Object.hasOwn(replacements, name) ? String(replacements[name]) : placeholder,\n )\n : key;\n\n/** The package default: the English key with its placeholders substituted. */\nexport const DEFAULT_AGENTS_TEXTS: AgentsTexts = { translate: substitutePlaceholders };\n\n/** Translates an interface text through the app-wide environment, for a string a component hands on (a label). */\nexport const translateText = (key: string, replacements?: Record<string, string | number>, context?: string): string =>\n (appEnvironment.texts ?? DEFAULT_AGENTS_TEXTS).translate(key, replacements, context);\n\n/** A plain text as the app's text components take it (`AgentsEnvironment.escapePlainTextForText`). */\nexport const escapePlainTextForText = (text: string): string =>\n appEnvironment.escapePlainTextForText ? appEnvironment.escapePlainTextForText(text) : text;\n\n/** Opens an image gallery over the page (`AgentsEnvironment.openImageGallery`). */\nexport const openImageGallery = (images: AgentsGalleryImage[], startIndex: number): void => {\n if (appEnvironment.openImageGallery) {\n appEnvironment.openImageGallery(images, startIndex);\n return;\n }\n const startImage = images[startIndex];\n if (!startImage) return;\n if (appEnvironment.onNavigate?.(startImage.url, null) === true) return;\n window.open(startImage.url, \"_blank\", \"noopener,noreferrer\");\n};\n\n/** Whether the app can start a conversation in the owner's personal space (`AgentsEnvironment.startConversationInPersonalSpace`). */\nexport const canStartConversationInPersonalSpace = (): boolean => appEnvironment.startConversationInPersonalSpace !== undefined;\n\n/** Starts a conversation in the owner's personal space with `ownerText` as its first message; false when the app cannot. */\nexport const startConversationInPersonalSpace = (ownerText: string): boolean => {\n if (!appEnvironment.startConversationInPersonalSpace) return false;\n appEnvironment.startConversationInPersonalSpace(ownerText);\n return true;\n};\n\n/** Whether the app can open the permissions of a connection (`AgentsEnvironment.openConnectionPermissions`). */\nexport const canOpenConnectionPermissions = (): boolean => appEnvironment.openConnectionPermissions !== undefined;\n\n/** Opens the permissions of a connection in the app; false when the app cannot. */\nexport const openConnectionPermissions = (target: AgentsConnectionPermissionTarget): boolean => {\n if (!appEnvironment.openConnectionPermissions) return false;\n appEnvironment.openConnectionPermissions(target);\n return true;\n};\n\n/** The block field of the package's backend default (`WidgetBlockFieldNames::WIDGET_SELF_HYDRATION_KEY`). */\nexport const DEFAULT_WIDGET_SELF_HYDRATION_KEY_FIELD_NAME = \"agentSpaceId\";\n\n/** The field of a widget block that carries the key of its agent space (`AgentsEnvironment.widgetSelfHydrationKeyFieldName`). */\nexport const getWidgetSelfHydrationKeyFieldName = (): string =>\n appEnvironment.widgetSelfHydrationKeyFieldName ?? DEFAULT_WIDGET_SELF_HYDRATION_KEY_FIELD_NAME;\n\n/** The owner's text for a click on a widget of another agent space (`AgentsEnvironment.appendAnotherAgentSpaceToOwnerText`). */\nexport const appendAnotherAgentSpaceToOwnerText = (ownerText: string, anotherAgentSpaceKey: number): string =>\n appEnvironment.appendAnotherAgentSpaceToOwnerText\n ? appEnvironment.appendAnotherAgentSpaceToOwnerText(ownerText, anotherAgentSpaceKey)\n : ownerText;\n\n/** The label of an agent space without a known name (`AgentsEnvironment.buildUnnamedAgentSpaceLabel`). */\nexport const buildUnnamedAgentSpaceLabel = (agentSpaceKey: number): string =>\n appEnvironment.buildUnnamedAgentSpaceLabel ? appEnvironment.buildUnnamedAgentSpaceLabel(agentSpaceKey) : `#${agentSpaceKey}`;\n\n/** The sentence under a widget of another agent space (`AgentsEnvironment.buildWidgetOfAnotherAgentSpaceExplanation`). */\nexport const buildWidgetOfAnotherAgentSpaceExplanation = (agentSpaceLabel: string): string =>\n appEnvironment.buildWidgetOfAnotherAgentSpaceExplanation\n ? appEnvironment.buildWidgetOfAnotherAgentSpaceExplanation(agentSpaceLabel)\n : translateText(\"This widget shows data for %label%, not for what you currently have selected.\", {\n label: agentSpaceLabel,\n });\n\n/** The further sandbox and readiness names the app declares (`AgentsEnvironment.sandboxLegacyAliases`). */\nexport const getSandboxLegacyAliases = (): AgentsSandboxLegacyAliases => appEnvironment.sandboxLegacyAliases ?? {};\n\n/** The package default of `AgentsEnvironment.widgetImageCaptureReadPathPrefix`. */\nexport const DEFAULT_WIDGET_IMAGE_CAPTURE_READ_PATH_PREFIX = \"/api/\";\n\n/** The path prefix of the API reads a live widget image capture lets through (`AgentsEnvironment.widgetImageCaptureReadPathPrefix`). */\nexport const getWidgetImageCaptureReadPathPrefix = (): string =>\n appEnvironment.widgetImageCaptureReadPathPrefix ?? DEFAULT_WIDGET_IMAGE_CAPTURE_READ_PATH_PREFIX;\n\n/** The app's widgets that draw a Google map (`AgentsEnvironment.googleMapWidgetNames`). */\nexport const getGoogleMapWidgetNames = (): readonly string[] => appEnvironment.googleMapWidgetNames ?? [];\n\n/** The app's further widget click signal sources (`AgentsEnvironment.furtherWidgetClickSignalSources`). */\nexport const getFurtherWidgetClickSignalSources = (): readonly string[] =>\n appEnvironment.furtherWidgetClickSignalSources ?? [];\n\n/** The canvases of the app's widgets (`AgentsEnvironment.furtherCanvasBehaviours`). */\nexport const getFurtherCanvasBehaviours = (): Readonly<Record<string, CanvasBehaviour>> =>\n appEnvironment.furtherCanvasBehaviours ?? {};\n\n/** The name the owner knows the agent by (`AgentsEnvironment.agentDisplayName`). */\nexport const getAgentDisplayName = (): string => appEnvironment.agentDisplayName ?? translateText(\"the assistant\");\n\n/** Reports a running turn of an open chat (`AgentsEnvironment.reportRunningTurn`); returns the release. */\nexport const reportRunningTurn = (): (() => void) | undefined => appEnvironment.reportRunningTurn?.();\n\n/** Reports a crashed widget (`AgentsEnvironment.reportWidgetCrash`). */\nexport const reportWidgetCrash = (widgetName: string, error: Error, errorInfo: ErrorInfo): void => {\n appEnvironment.reportWidgetCrash?.(widgetName, error, errorInfo);\n};\n","import type { AgentsStateAction } from \"../../provider/environment\";\nimport { WidgetHydrationSliceState, WidgetMemory } from \"./widget-hydration.types\";\n\n/**\n * The widget hydration state: one memory per hydration key. A plain reducer under the key\n * `AIExtensionsWidgetHydration` of a state store: the app's own (`AgentsEnvironment.stateStore`, the host application mounts it in\n * its Redux store) or, without one, the package's default store (`widget-hydration-state-store.ts`).\n */\n\nconst SLICE_NAME = \"widgetHydrationSlice\";\n\nconst emptyMemory = (): WidgetMemory => {\n return {\n data: null,\n status: \"idle\",\n error: null,\n loadingInstanceId: null,\n inFlight: false,\n requestId: 0,\n lastLoadedAt: null,\n };\n};\n\nconst initialState: WidgetHydrationSliceState = {\n widgets: {},\n};\n\nconst readMemory = (state: WidgetHydrationSliceState, key: string): WidgetMemory => state.widgets[key] ?? emptyMemory();\n\nconst withMemory = (state: WidgetHydrationSliceState, key: string, memory: WidgetMemory): WidgetHydrationSliceState => ({\n ...state,\n widgets: { ...state.widgets, [key]: memory },\n});\n\n/** Does a result still belong to the request the memory tracks? (0 = the memory was reset since.) */\nconst isCurrentRequest = (memory: WidgetMemory, requestId: number): boolean =>\n memory.requestId === 0 || memory.requestId === requestId;\n\ninterface MemoryEnsuredPayload {\n key: string;\n}\ninterface InstanceAttachedPayload {\n key: string;\n instanceId: string;\n}\ninterface HydrationStartedPayload {\n key: string;\n instanceId: string;\n requestId: number;\n}\ninterface HydrationSucceededPayload {\n key: string;\n requestId: number;\n data: unknown;\n}\ninterface HydrationFailedPayload {\n key: string;\n requestId: number;\n error: string;\n}\ninterface WidgetResetPayload {\n key: string;\n}\n\nconst actionType = (name: string): string => `${SLICE_NAME}/${name}`;\n\n/** The action creators (the action types are the ones the former Redux Toolkit slice used). */\nexport const WidgetHydrationSlice = {\n memoryEnsured: (payload: MemoryEnsuredPayload): AgentsStateAction => ({ type: actionType(\"memoryEnsured\"), payload }),\n instanceAttached: (payload: InstanceAttachedPayload): AgentsStateAction => ({\n type: actionType(\"instanceAttached\"),\n payload,\n }),\n hydrationStarted: (payload: HydrationStartedPayload): AgentsStateAction => ({\n type: actionType(\"hydrationStarted\"),\n payload,\n }),\n hydrationSucceeded: (payload: HydrationSucceededPayload): AgentsStateAction => ({\n type: actionType(\"hydrationSucceeded\"),\n payload,\n }),\n hydrationFailed: (payload: HydrationFailedPayload): AgentsStateAction => ({\n type: actionType(\"hydrationFailed\"),\n payload,\n }),\n widgetReset: (payload: WidgetResetPayload): AgentsStateAction => ({ type: actionType(\"widgetReset\"), payload }),\n allWidgetsReset: (): AgentsStateAction => ({ type: actionType(\"allWidgetsReset\") }),\n};\n\nexport const WidgetHydrationReducer = (\n state: WidgetHydrationSliceState = initialState,\n action: AgentsStateAction,\n): WidgetHydrationSliceState => {\n switch (action.type) {\n case actionType(\"memoryEnsured\"): {\n const { key } = action.payload as MemoryEnsuredPayload;\n return state.widgets[key] ? state : withMemory(state, key, emptyMemory());\n }\n case actionType(\"instanceAttached\"): {\n const { key, instanceId } = action.payload as InstanceAttachedPayload;\n return withMemory(state, key, { ...readMemory(state, key), loadingInstanceId: instanceId });\n }\n case actionType(\"hydrationStarted\"): {\n const { key, instanceId, requestId } = action.payload as HydrationStartedPayload;\n return withMemory(state, key, {\n ...readMemory(state, key),\n status: \"loading\",\n error: null,\n inFlight: true,\n loadingInstanceId: instanceId,\n requestId,\n });\n }\n case actionType(\"hydrationSucceeded\"): {\n const { key, requestId, data } = action.payload as HydrationSucceededPayload;\n const memory = readMemory(state, key);\n if (!isCurrentRequest(memory, requestId)) return state.widgets[key] ? state : withMemory(state, key, memory);\n return withMemory(state, key, {\n ...memory,\n status: \"success\",\n error: null,\n inFlight: false,\n data,\n loadingInstanceId: null,\n requestId,\n lastLoadedAt: Date.now(),\n });\n }\n case actionType(\"hydrationFailed\"): {\n const { key, requestId, error } = action.payload as HydrationFailedPayload;\n const memory = readMemory(state, key);\n if (!isCurrentRequest(memory, requestId)) return state.widgets[key] ? state : withMemory(state, key, memory);\n return withMemory(state, key, {\n ...memory,\n status: \"error\",\n error,\n inFlight: false,\n loadingInstanceId: null,\n requestId,\n });\n }\n case actionType(\"widgetReset\"): {\n const { key } = action.payload as WidgetResetPayload;\n if (!(key in state.widgets)) return state;\n const { [key]: removedMemory, ...remainingWidgets } = state.widgets;\n return { ...state, widgets: remainingWidgets };\n }\n case actionType(\"allWidgetsReset\"):\n return { ...state, widgets: {} };\n default:\n return state;\n }\n};\n","import { useSyncExternalStore } from \"react\";\nimport type { AgentsStateAction, AgentsStateStore } from \"../../provider/environment\";\nimport { WidgetHydrationReducer } from \"./widget-hydration.reducer\";\nimport type { WidgetHydrationSliceState } from \"./widget-hydration.types\";\n\n/** The state of the package's default store: the widget hydration state under the key package code reads. */\nexport interface AgentsWidgetHydrationState {\n AIExtensionsWidgetHydration: WidgetHydrationSliceState;\n}\n\n/**\n * The package's own state store (widget hydration is one store per app): the widget hydration reducer\n * behind `useSyncExternalStore`, no Redux. Package code reads and dispatches through it whenever the app supplies no\n * `AgentsEnvironment.stateStore` (the host application supplies its Redux store, which mounts the same reducer). Actions the\n * reducer does not know (the app's \"a chat surface is open\" action) change nothing.\n */\nexport class AgentsWidgetHydrationStateContainer implements AgentsStateStore {\n protected state: AgentsWidgetHydrationState = {\n AIExtensionsWidgetHydration: WidgetHydrationReducer(undefined, { type: \"agents/widgetHydrationStoreCreated\" }),\n };\n protected readonly listeners = new Set<() => void>();\n\n getState = (): AgentsWidgetHydrationState => this.state;\n\n subscribe = (listener: () => void): (() => void) => {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n };\n\n dispatch = (action: AgentsStateAction): AgentsStateAction => {\n const nextHydrationState = WidgetHydrationReducer(this.state.AIExtensionsWidgetHydration, action);\n if (nextHydrationState === this.state.AIExtensionsWidgetHydration) return action;\n this.state = { AIExtensionsWidgetHydration: nextHydrationState };\n for (const notifyListener of [...this.listeners]) notifyListener();\n return action;\n };\n\n /** `AgentsStateStore.useSelector`: one value of the state, re-rendering when it changes. */\n useSelector = <Selected,>(selector: (state: AgentsWidgetHydrationState) => Selected): Selected => {\n const readSelectedValue = () => selector(this.state);\n return useSyncExternalStore(this.subscribe, readSelectedValue, readSelectedValue);\n };\n\n /** `AgentsStateStore.useDispatch`. */\n useDispatch = (): ((action: AgentsStateAction) => AgentsStateAction) => this.dispatch;\n}\n\n/** A new widget hydration store (a test, a second app on one page). */\nexport const createAgentsWidgetHydrationStateStore = (): AgentsStateStore =>\n new AgentsWidgetHydrationStateContainer();\n\nlet defaultStateStore: AgentsStateStore | null = null;\n\n/** The one default store of the page, created on first use. */\nexport const getDefaultAgentsStateStore = (): AgentsStateStore => {\n defaultStateStore ??= createAgentsWidgetHydrationStateStore();\n return defaultStateStore;\n};\n","/**\n * Whether a Markdown image in model text may load its source. Model text is foreign: an image of any host would let a\n * page or a document the agent read make the browser send what the model knows to that host (the data rides in the\n * URL). Allowed: the page's own origin (a relative URL included), `blob:` URLs, inline `data:image/…` raster images and\n * the hosts the app lists in `AgentsEnvironment.markdownImageHosts` (`cdn.example.com`, or `*.example.com` for every\n * subdomain). Everything else renders as a link the owner may open.\n */\nexport const isAllowedMarkdownImageSource = (\n source: string,\n pageOrigin: string | undefined,\n allowedHosts: readonly string[] | undefined,\n): boolean => {\n const trimmedSource = source.trim();\n if (trimmedSource === \"\") {\n return false;\n }\n if (/^data:image\\/(png|jpe?g|gif|webp);/i.test(trimmedSource)) {\n return true;\n }\n let sourceUrl: URL;\n try {\n sourceUrl = new URL(trimmedSource, pageOrigin ?? \"http://invalid.invalid\");\n } catch {\n return false;\n }\n if (sourceUrl.protocol === \"blob:\") {\n return true;\n }\n if (sourceUrl.protocol !== \"https:\" && sourceUrl.protocol !== \"http:\") {\n return false;\n }\n if (pageOrigin !== undefined && sourceUrl.origin === pageOrigin) {\n return true;\n }\n if (sourceUrl.protocol !== \"https:\") {\n return false;\n }\n const sourceHost = sourceUrl.hostname.toLowerCase();\n return (allowedHosts ?? []).some((allowedHost) => {\n const normalizedHost = allowedHost.trim().toLowerCase();\n if (normalizedHost.startsWith(\"*.\")) {\n const parentHost = normalizedHost.slice(2);\n return sourceHost.endsWith(`.${parentHost}`);\n }\n return normalizedHost !== \"\" && sourceHost === normalizedHost;\n });\n};\n","type ClassNameValue = string | undefined | null | false | Readonly<Record<string, boolean | undefined | null>>;\n\n/** The class names one argument contributes: a set string, or every key of an object whose value is truthy. */\nconst readClassNamesOfValue = (value: ClassNameValue): string[] => {\n if (typeof value === \"string\") return value.length > 0 ? [value] : [];\n if (!value) return [];\n return Object.keys(value).filter((className) => className.length > 0 && Boolean(value[className]));\n};\n\n/**\n * Joins the class names that are set, skipping empty and falsy values; an object adds each key whose value is truthy\n * (`classNames(styles.card, { [styles.selected]: isSelected })`), in argument order, as the `classnames` package does.\n */\nexport const classNames = (...args: ClassNameValue[]): string => args.flatMap(readClassNamesOfValue).join(\" \");\n","import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport ReactMarkdown, { type Components } from \"react-markdown\";\nimport remarkGfm from \"remark-gfm\";\nimport type { PluggableList } from \"unified\";\nimport type {\n AgentsButtonProps,\n AgentsCheckboxProps,\n AgentsComponents,\n AgentsConversationSearchResultsListProps,\n AgentsHeroRowProps,\n AgentsHeroValueProps,\n AgentsMarkdownProps,\n AgentsSegmentBarProps,\n AgentsSkeletonTextProps,\n AgentsStatusBadgeStatus,\n AgentsStatusChipProps,\n AgentsStatusChipTone,\n AgentsWidgetFeatureGateProps,\n AgentsWidgetTextProps,\n AgentsDateInputProps,\n AgentsGlowFrameProps,\n AgentsIconProps,\n AgentsInteractiveSurfaceProps,\n AgentsLoadingSpinnerProps,\n AgentsMapMarkerProps,\n AgentsMapProps,\n AgentsModalLayerProps,\n AgentsProgressBarProps,\n AgentsRadioGroupProps,\n AgentsRangeSliderProps,\n AgentsSelectProps,\n AgentsSkeletonProps,\n AgentsSplitViewProps,\n AgentsStatusBadgeProps,\n AgentsTabsProps,\n AgentsTextAreaProps,\n AgentsTextInputProps,\n AgentsTextProps,\n AgentsTextReplacements,\n AgentsTooltipProps,\n AgentsTrendDeltaProps,\n} from \"./types\";\nimport { useAgentsEnvironment, useAgentsTexts } from \"../AgentsProvider\";\nimport { isAllowedMarkdownImageSource } from \"./markdown-image-source\";\nimport { classNames } from \"../class-names\";\n\nconst TEXT_ELEMENT_BY_ROLE = {\n title: \"h4\",\n intro: \"p\",\n body: \"span\",\n help: \"span\",\n caption: \"span\",\n} as const;\n\n/** `--token` stands for `var(--token)`; any other value is a CSS colour. */\nconst readCssColor = (color: string | undefined): string | undefined =>\n color?.startsWith(\"--\") ? `var(${color})` : color;\n\nconst readPlainReplacements = (replacements?: AgentsTextReplacements): Record<string, string | number> => {\n const plainReplacements: Record<string, string | number> = {};\n for (const [name, value] of Object.entries(replacements ?? {})) {\n if (typeof value === \"string\" || typeof value === \"number\") plainReplacements[name] = value;\n }\n return plainReplacements;\n};\n\nconst useTranslatedText = (\n text: string | undefined,\n translate = true,\n replacements?: AgentsTextReplacements,\n context?: string,\n): string | undefined => {\n const texts = useAgentsTexts();\n if (text === undefined) return undefined;\n return translate ? texts.translate(text, readPlainReplacements(replacements), context) : text;\n};\n\n/** The package's own text: an element per role, styled by `agents-text--*` classes of the package stylesheet. */\nconst DefaultText = (props: AgentsTextProps) => {\n const {\n children,\n role = \"body\",\n weight,\n color,\n translate = true,\n replacements,\n context,\n ellipsis,\n display,\n textAlign,\n textWrap,\n allowNewLines,\n headingLevel,\n ariaHidden,\n className,\n testId,\n } = props;\n const texts = useAgentsTexts();\n const Element = TEXT_ELEMENT_BY_ROLE[role];\n const content =\n typeof children === \"string\" && translate\n ? texts.translate(children, readPlainReplacements(replacements), context)\n : children;\n return (\n <Element\n data-testid={testId}\n role={headingLevel ? \"heading\" : undefined}\n aria-level={headingLevel}\n aria-hidden={ariaHidden || undefined}\n className={classNames(\n \"agents-text\",\n `agents-text--${role}`,\n weight && `agents-text--weight-${weight}`,\n ellipsis && \"agents-text--ellipsis\",\n allowNewLines && \"agents-text--new-lines\",\n className,\n )}\n style={{\n color: readCssColor(color),\n display,\n textAlign,\n whiteSpace: textWrap === \"nowrap\" || ellipsis ? \"nowrap\" : allowNewLines ? \"pre-line\" : undefined,\n }}\n >\n {content}\n </Element>\n );\n};\n\nconst DefaultIcon = (props: AgentsIconProps) => {\n const { name, hostIconName, size, pixelSize, color, className, style } = props;\n const iconName = name ?? hostIconName;\n return (\n <span\n aria-hidden\n data-icon={iconName}\n className={classNames(\"agents-icon\", size && `agents-icon--${size}`, className)}\n style={{ color: readCssColor(color), ...(pixelSize ? { width: pixelSize, height: pixelSize } : null), ...style }}\n />\n );\n};\n\nconst DefaultButton = (props: AgentsButtonProps) => {\n const {\n children,\n variant = \"primary\",\n size = \"medium\",\n onClick,\n disabled,\n isLoading,\n rounded,\n pressed,\n onDark,\n blurred,\n inverted,\n icon,\n iconPosition = \"left\",\n htmlType = \"button\",\n fullWidth,\n wrapsLabel,\n translate,\n replacements,\n className,\n testId,\n ariaLabel,\n } = props;\n const label = useTranslatedText(children, translate, replacements);\n return (\n <button\n type={htmlType}\n aria-label={ariaLabel}\n aria-pressed={pressed}\n aria-busy={isLoading || undefined}\n disabled={disabled || isLoading}\n data-testid={testId}\n onClick={onClick}\n className={classNames(\n \"agents-button\",\n `agents-button--${variant}`,\n `agents-button--${size}`,\n rounded && \"agents-button--rounded\",\n pressed && \"agents-button--pressed\",\n onDark && \"agents-button--on-dark\",\n blurred && \"agents-button--blurred\",\n inverted && \"agents-button--inverted\",\n fullWidth && \"agents-button--full-width\",\n wrapsLabel && \"agents-button--wraps-label\",\n className,\n )}\n >\n {icon && iconPosition === \"left\" ? <DefaultIcon name={icon} size=\"small\" /> : null}\n {label}\n {icon && iconPosition === \"right\" ? <DefaultIcon name={icon} size=\"small\" /> : null}\n </button>\n );\n};\n\nconst DefaultInteractiveSurface = (props: AgentsInteractiveSurfaceProps) => {\n const { children, hoverable, className, style, testId } = props;\n return (\n <div\n data-testid={testId}\n className={classNames(\"agents-interactive-surface\", hoverable && \"agents-interactive-surface--hoverable\", className)}\n style={style}\n >\n {children}\n </div>\n );\n};\n\nconst DefaultSkeleton = (props: AgentsSkeletonProps) => {\n const { width, height, borderRadius = 4, className, style } = props;\n return (\n <div\n aria-hidden\n className={classNames(\"agents-skeleton\", className)}\n style={{ width, height, borderRadius, ...style }}\n />\n );\n};\n\nconst DefaultLoadingSpinner = (_props: AgentsLoadingSpinnerProps) => (\n <span role=\"progressbar\" aria-busy className=\"agents-loading-spinner\" />\n);\n\nconst DefaultTooltip = (props: AgentsTooltipProps) => {\n const { children, text, replacements, placement = \"top\", dark } = props;\n const [isShown, setIsShown] = useState(false);\n const shownText = useTranslatedText(text, true, replacements);\n return (\n <span\n className=\"agents-tooltip\"\n style={{ position: \"relative\", display: \"inline-flex\" }}\n onMouseEnter={() => setIsShown(true)}\n onMouseLeave={() => setIsShown(false)}\n onFocus={() => setIsShown(true)}\n onBlur={() => setIsShown(false)}\n >\n {children}\n {shownText && isShown ? (\n <span\n role=\"tooltip\"\n className={classNames(\"agents-tooltip__panel\", `agents-tooltip__panel--${placement}`, dark && \"agents-tooltip__panel--dark\")}\n style={{ position: \"absolute\", bottom: \"100%\", left: \"50%\", transform: \"translateX(-50%)\" }}\n >\n {shownText}\n </span>\n ) : null}\n </span>\n );\n};\n\nconst DefaultGlowFrame = (props: AgentsGlowFrameProps) => {\n const { children, className, color, borderRadius, borderWidth } = props;\n return (\n <div\n className={classNames(\"agents-glow-frame\", className)}\n style={{ borderRadius, borderWidth, borderStyle: borderWidth ? \"solid\" : undefined, borderColor: color }}\n >\n {children}\n </div>\n );\n};\n\nconst DefaultProgressBar = (props: AgentsProgressBarProps) => {\n const { value, height, color, indeterminate } = props;\n return (\n <progress\n className=\"agents-progress-bar\"\n max={100}\n value={indeterminate ? undefined : value}\n style={{ height, accentColor: color, width: \"100%\" }}\n />\n );\n};\n\n/** The width of an element, followed with a `ResizeObserver`; null until it is laid out. */\nconst useElementWidth = (): [number | null, (element: HTMLElement | null) => void] => {\n const [width, setWidth] = useState<number | null>(null);\n const resizeObserverRef = useRef<ResizeObserver | null>(null);\n const observeElement = useCallback((element: HTMLElement | null) => {\n resizeObserverRef.current?.disconnect();\n resizeObserverRef.current = null;\n if (element === null) return;\n const initialWidth = element.getBoundingClientRect().width;\n setWidth(initialWidth > 0 ? initialWidth : null);\n if (typeof ResizeObserver === \"undefined\") return;\n resizeObserverRef.current = new ResizeObserver((entries) => {\n const entry = entries[entries.length - 1];\n if (entry && entry.contentRect.width > 0) setWidth(entry.contentRect.width);\n });\n resizeObserverRef.current.observe(element);\n }, []);\n return [width, observeElement];\n};\n\n/**\n * Two panes side by side. Below `coversBelowWidth` — measured on the split view's own box, so a narrow chat column in a\n * wide window counts as narrow — the open side pane covers the main pane instead of narrowing it.\n *\n * While the side pane covers the main pane: it takes the full width of the split, sits in its own stacking context\n * above the main pane's layers with an opaque background, the covered main pane is inert (no Tab, hidden from\n * assistive technology), the focus moves into the side pane and back to where it was in the main pane when the side\n * pane stops covering it, and the toggle floats over the side pane's top end. Below `coversBelowWidth` with the side\n * pane closed there is no divider: the toggle floats over the main pane's top end as the re-open control, unless the\n * main pane shows its own (`sideToggle.mainPaneShowsReopen`). Side by side the toggle is the strip on the divider. The\n * toggle carries a translated name (`Close canvas` / `Re-open canvas`) and an icon.\n */\nconst DefaultSplitView = (props: AgentsSplitViewProps) => {\n const { isSideOpen, coversBelowWidth, main, side, sideToggle } = props;\n const [splitViewWidth, observeSplitView] = useElementWidth();\n const coversMain = coversBelowWidth !== undefined && splitViewWidth !== null && splitViewWidth < coversBelowWidth;\n const isMainCovered = isSideOpen && coversMain;\n // Narrow and closed: no divider to carry the toggle, so it floats over the chat — the only way back to the canvas\n // unless the chat shows its own re-open control.\n const floatsReopenOverMain = coversMain && !isSideOpen && !sideToggle?.mainPaneShowsReopen;\n // Covering with its own close control in the side pane: a floating toggle would sit on top of that control.\n const floatsCloseOverSide = isMainCovered && !sideToggle?.sidePaneShowsClose;\n const togglesFloat = floatsCloseOverSide || floatsReopenOverMain;\n const toggleLabel = useTranslatedText(isSideOpen ? \"Close canvas\" : \"Re-open canvas\");\n const sidePaneRef = useRef<HTMLDivElement>(null);\n const lastFocusedInMainRef = useRef<HTMLElement | null>(null);\n\n // The covered main pane is inert, so a focus inside it would fall to the page: it moves into the side pane, and back\n // to the element last focused in the main pane (the control that opened the side pane) once the main pane is free.\n useEffect(() => {\n if (typeof document === \"undefined\") return;\n if (isMainCovered) {\n const sidePane = sidePaneRef.current;\n if (sidePane && !sidePane.contains(document.activeElement)) sidePane.focus({ preventScroll: true });\n return;\n }\n const lastFocusedInMain = lastFocusedInMainRef.current;\n const focusIsLost = document.activeElement === null || document.activeElement === document.body;\n if (focusIsLost && lastFocusedInMain?.isConnected) lastFocusedInMain.focus({ preventScroll: true });\n }, [isMainCovered]);\n\n const toggleButton = sideToggle ? (\n <button\n type=\"button\"\n className={classNames(\"agents-split-view__toggle\", togglesFloat && \"agents-split-view__toggle--floating\")}\n onClick={sideToggle.onToggle}\n aria-expanded={isSideOpen}\n aria-label={toggleLabel}\n title={toggleLabel}\n style={togglesFloat ? { position: \"absolute\", top: 8, insetInlineEnd: 8, zIndex: 21 } : undefined}\n >\n <DefaultIcon name={isSideOpen ? \"closeCanvas\" : \"maximize\"} size=\"small\" />\n </button>\n ) : null;\n\n return (\n <div\n ref={observeSplitView}\n className={classNames(\"agents-split-view\", coversMain && \"agents-split-view--covering\")}\n style={{\n display: \"flex\",\n width: \"100%\",\n height: \"100%\",\n position: \"relative\",\n overflow: isMainCovered ? \"hidden\" : undefined,\n }}\n >\n <div\n className=\"agents-split-view__main\"\n style={{\n width: isSideOpen && !coversMain ? (main.narrowedWidth ?? main.width) : isMainCovered ? \"100%\" : main.width,\n background: main.background,\n isolation: isMainCovered ? \"isolate\" : undefined,\n }}\n inert={isMainCovered}\n aria-hidden={isMainCovered ? true : undefined}\n onFocusCapture={(event) => {\n lastFocusedInMainRef.current = event.target as HTMLElement;\n }}\n >\n {main.content}\n </div>\n {!coversMain ? toggleButton : null}\n {isSideOpen ? (\n <div\n ref={sidePaneRef}\n className=\"agents-split-view__side\"\n tabIndex={isMainCovered ? -1 : undefined}\n style={\n isMainCovered\n ? {\n position: \"absolute\",\n inset: 0,\n width: \"100%\",\n maxWidth: \"100%\",\n boxSizing: \"border-box\",\n borderLeft: \"none\",\n overflowX: \"hidden\",\n outline: \"none\",\n isolation: \"isolate\",\n zIndex: 20,\n background: side.background ?? \"var(--agents-bg-surface)\",\n }\n : { width: side.narrowedWidth ?? side.width, background: side.background }\n }\n >\n {side.content}\n </div>\n ) : null}\n {togglesFloat ? toggleButton : null}\n </div>\n );\n};\n\nconst DefaultTrendDelta = (props: AgentsTrendDeltaProps) => {\n const { current, previous = 0, higherIsBetter = true, format } = props;\n const change = current - previous;\n const magnitude = Math.abs(change);\n const isGood = change === 0 ? undefined : (change > 0) === higherIsBetter;\n return (\n <span\n className={classNames(\n \"agents-trend-delta\",\n isGood === true && \"agents-trend-delta--good\",\n isGood === false && \"agents-trend-delta--bad\",\n )}\n >\n {change > 0 ? \"▲ \" : change < 0 ? \"▼ \" : \"\"}\n {format ? format(magnitude) : String(magnitude)}\n </span>\n );\n};\n\nconst DefaultCheckbox = (props: AgentsCheckboxProps) => {\n const { checked, disabled, label, translate, onChange, testId } = props;\n const translatedLabel = useTranslatedText(typeof label === \"string\" ? label : undefined, translate);\n return (\n <label className=\"agents-checkbox\" data-testid={testId}>\n <input type=\"checkbox\" checked={checked ?? false} disabled={disabled} onChange={onChange} />\n {typeof label === \"string\" ? translatedLabel : label}\n </label>\n );\n};\n\nconst DefaultTextInput = (props: AgentsTextInputProps) => {\n const { id, value, type = \"text\", label, placeholder, maxLength, onChange, testId } = props;\n const translatedLabel = useTranslatedText(label);\n return (\n <label className=\"agents-text-input\">\n {translatedLabel ? <span className=\"agents-text-input__label\">{translatedLabel}</span> : null}\n <input\n id={id}\n type={type}\n value={value ?? \"\"}\n placeholder={placeholder}\n maxLength={maxLength}\n data-testid={testId}\n onChange={(event) => onChange?.(event.target.value)}\n />\n </label>\n );\n};\n\nconst DefaultTextArea = (props: AgentsTextAreaProps) => {\n const { id, value, label, placeholder, maxLength, rows, minRows, showsCounter, autoFocus, onChange, testId } = props;\n const translatedLabel = useTranslatedText(label);\n return (\n <label className=\"agents-text-area\">\n {translatedLabel ? <span className=\"agents-text-area__label\">{translatedLabel}</span> : null}\n <textarea\n id={id}\n value={value ?? \"\"}\n placeholder={placeholder}\n maxLength={maxLength}\n rows={rows ?? minRows}\n autoFocus={autoFocus}\n data-testid={testId}\n onChange={(event) => onChange?.(event.target.value)}\n />\n {showsCounter && maxLength ? (\n <span className=\"agents-text-area__counter\">{`${(value ?? \"\").length} / ${maxLength}`}</span>\n ) : null}\n </label>\n );\n};\n\nconst DefaultRangeSlider = (props: AgentsRangeSliderProps) => {\n const { value, min, max, step, onMove, onRelease } = props;\n return (\n <input\n type=\"range\"\n className=\"agents-range-slider\"\n value={value}\n min={min}\n max={max}\n step={step}\n onChange={(event) => onMove?.(Number(event.target.value))}\n onPointerUp={(event) => onRelease?.(Number(event.currentTarget.value))}\n onKeyUp={(event) => onRelease?.(Number(event.currentTarget.value))}\n />\n );\n};\n\nconst toIsoDay = (timestamp: number | undefined): string | undefined => {\n if (timestamp === undefined) return undefined;\n const day = new Date(timestamp);\n const month = String(day.getMonth() + 1).padStart(2, \"0\");\n const dayOfMonth = String(day.getDate()).padStart(2, \"0\");\n return `${day.getFullYear()}-${month}-${dayOfMonth}`;\n};\n\nconst DefaultDateInput = (props: AgentsDateInputProps) => {\n const { value, minDate, maxDate, onChange } = props;\n return (\n <input\n type=\"date\"\n className=\"agents-date-input\"\n value={toIsoDay(value) ?? \"\"}\n min={toIsoDay(minDate)}\n max={toIsoDay(maxDate)}\n onChange={(event) => {\n const [year, month, day] = event.target.value.split(\"-\").map(Number);\n onChange?.(event.target.value ? new Date(year, month - 1, day).getTime() : null);\n }}\n />\n );\n};\n\nconst DefaultRadioGroup = (props: AgentsRadioGroupProps) => {\n const { name, value, options, direction = \"column\", onChange } = props;\n return (\n <div className=\"agents-radio-group\" style={{ display: \"flex\", flexDirection: direction }}>\n {options.map((option) => (\n <label key={option.value} className=\"agents-radio-group__option\">\n <input\n type=\"radio\"\n name={name}\n value={option.value}\n checked={option.value === value}\n disabled={option.disabled}\n onChange={() => onChange(option.value)}\n />\n {option.label}\n </label>\n ))}\n </div>\n );\n};\n\nconst DefaultSelect = (props: AgentsSelectProps) => {\n const { id, value, options, placeholder, onChange, testId } = props;\n return (\n <select\n id={id}\n className=\"agents-select\"\n value={value}\n data-testid={testId}\n onChange={(event) => onChange(event.target.value)}\n >\n {placeholder !== undefined ? (\n <option value=\"\" disabled>\n {placeholder}\n </option>\n ) : null}\n {options.map((option) => (\n <option key={option.value} value={option.value} disabled={option.disabled} title={option.description}>\n {option.label}\n </option>\n ))}\n </select>\n );\n};\n\nconst DefaultTabs = (props: AgentsTabsProps) => {\n const { options, value, onChange, ariaLabel } = props;\n return (\n <div role=\"tablist\" aria-label={ariaLabel} className=\"agents-tabs\">\n {options\n .filter((option) => !option.disabled)\n .map((option) => (\n <button\n key={option.value}\n type=\"button\"\n role=\"tab\"\n aria-selected={option.value === value}\n data-testid={option.testId}\n className={classNames(\"agents-tabs__tab\", option.value === value && \"agents-tabs__tab--selected\")}\n onClick={() => onChange(option.value)}\n >\n {option.label}\n </button>\n ))}\n </div>\n );\n};\n\nconst DefaultStatusBadge = (props: AgentsStatusBadgeProps) => {\n const { status, text, translate, size, className } = props;\n const shownText = useTranslatedText(text, translate);\n return (\n <span\n className={classNames(\n \"agents-status-badge\",\n `agents-status-badge--${status}`,\n size && `agents-status-badge--${size}`,\n className,\n )}\n >\n {shownText}\n </span>\n );\n};\n\n/** No map without the app's map: a placeholder that says so. */\nconst DefaultMap = (props: AgentsMapProps) => {\n const { className, testId } = props;\n const noMapText = useTranslatedText(\"No map available.\");\n return (\n <div className={classNames(\"agents-map-placeholder\", className)} data-testid={testId} data-map=\"none\">\n {noMapText}\n </div>\n );\n};\n\nconst DefaultMapMarker = (_props: AgentsMapMarkerProps) => null;\n\nconst DefaultModalLayer = (props: AgentsModalLayerProps) => {\n const { children } = props;\n return <>{children}</>;\n};\n\nconst DefaultHeroRow = (props: AgentsHeroRowProps) => {\n const { children, className } = props;\n return (\n <div data-hero-row=\"\" className={classNames(\"agents-hero-row\", className)}>\n {children}\n </div>\n );\n};\n\nconst DefaultHeroValue = (props: AgentsHeroValueProps) => {\n const { children, color } = props;\n return (\n <span data-hero=\"\" data-hero-value=\"\" className=\"agents-hero-value\" style={{ color: readCssColor(color) }}>\n {children}\n </span>\n );\n};\n\nconst DefaultWidgetText = (props: AgentsWidgetTextProps) => {\n const {\n children,\n variant = \"inherit\",\n tone,\n color,\n weight,\n uppercase,\n tabular,\n strikethrough,\n inline = variant === \"inherit\",\n translate = typeof children === \"string\",\n context,\n replacements,\n className,\n testId,\n } = props;\n const texts = useAgentsTexts();\n const plainReplacements: Record<string, string | number> = {};\n for (const [name, value] of Object.entries(replacements ?? {})) {\n if (value !== null && value !== undefined) plainReplacements[name] = value;\n }\n const content =\n typeof children === \"string\" && translate ? texts.translate(children, plainReplacements, context) : children;\n const Element = inline ? \"span\" : \"div\";\n return (\n <Element\n data-testid={testId}\n className={classNames(\n \"agents-widget-text\",\n `agents-widget-text--${variant}`,\n tone && !color && `agents-widget-text--${tone}`,\n weight && `agents-widget-text--weight-${weight}`,\n uppercase && \"agents-widget-text--uppercase\",\n tabular && \"agents-widget-text--tabular\",\n strikethrough && \"agents-widget-text--strikethrough\",\n className,\n )}\n style={color ? { color: readCssColor(color) } : undefined}\n >\n {content}\n </Element>\n );\n};\n\nconst DefaultSkeletonText = (props: AgentsSkeletonTextProps) => {\n const { width = \"4.5em\", height = \"1em\", className } = props;\n return (\n <span\n aria-hidden\n className={classNames(\"agents-skeleton\", className)}\n style={{ display: \"inline-block\", width, height, borderRadius: 999 }}\n />\n );\n};\n\nconst STATUS_BADGE_STATUS_BY_CHIP_TONE: Record<AgentsStatusChipTone, AgentsStatusBadgeStatus> = {\n success: \"success\",\n warning: \"warning\",\n danger: \"danger\",\n neutral: \"neutral\",\n info: \"info\",\n error: \"danger\",\n};\n\nconst DefaultStatusChip = (props: AgentsStatusChipProps) => {\n const { tone = \"neutral\", children, compact = false, translate = true } = props;\n return (\n <DefaultStatusBadge\n status={STATUS_BADGE_STATUS_BY_CHIP_TONE[tone]}\n text={children}\n translate={translate}\n size=\"small\"\n hideIcon={compact || tone !== \"error\"}\n />\n );\n};\n\nconst DefaultSegmentBar = (props: AgentsSegmentBarProps) => {\n const { segments, height = 6, className, loading = false, testId } = props;\n const total = segments.reduce((sum, segment) => sum + Math.max(0, segment.value), 0);\n return (\n <div\n className={classNames(\"agents-segment-bar\", className)}\n style={{ display: \"flex\", height, borderRadius: height, overflow: \"hidden\" }}\n data-segment-bar=\"\"\n data-testid={testId}\n >\n {total > 0 || loading\n ? segments.map((segment, segmentIndex) => (\n <div\n key={segmentIndex}\n style={{\n width: loading\n ? `${100 / segments.length}%`\n : `${(Math.max(0, segment.value) / total) * 100}%`,\n background: segment.color,\n opacity: segment.muted || loading ? 0.5 : undefined,\n }}\n />\n ))\n : null}\n </div>\n );\n};\n\nconst NO_MARKDOWN_PLUGINS: PluggableList = [];\n\n/**\n * An image of model text loads only from an allowed source (`isAllowedMarkdownImageSource`: the page's origin, inline\n * raster data, `AgentsEnvironment.markdownImageHosts`); any other becomes a link the owner may open. Drops an image\n * without a source: streamed Markdown emits a partial `![alt](` that would fetch the page itself.\n */\nconst MarkdownImage: Components[\"img\"] = (imageProps) => {\n const { src, node, ...otherProps } = imageProps;\n const { markdownImageHosts } = useAgentsEnvironment();\n if (!src) {\n return null;\n }\n const pageOrigin = typeof window !== \"undefined\" ? window.location.origin : undefined;\n if (isAllowedMarkdownImageSource(src, pageOrigin, markdownImageHosts)) {\n return <img src={src} {...otherProps} />;\n }\n return (\n <a href={src} target=\"_blank\" rel=\"noopener noreferrer nofollow\" referrerPolicy=\"no-referrer\">\n {otherProps.alt || src}\n </a>\n );\n};\n\nconst DefaultMarkdown = (props: AgentsMarkdownProps) => {\n const { markdown, color, remarkPlugins = NO_MARKDOWN_PLUGINS, rehypePlugins = NO_MARKDOWN_PLUGINS, components } = props;\n const markdownComponents = useMemo(() => ({ img: MarkdownImage, ...components }) as Components, [components]);\n const markdownRemarkPlugins = useMemo(() => [remarkGfm, ...remarkPlugins], [remarkPlugins]);\n return (\n <div style={{ color }} className=\"agents-markdown\" data-markdown-blocks-root>\n <ReactMarkdown\n remarkPlugins={markdownRemarkPlugins}\n rehypePlugins={rehypePlugins}\n components={markdownComponents}\n >\n {markdown}\n </ReactMarkdown>\n </div>\n );\n};\n\n/** Without an app gate every widget is available. */\nconst DefaultWidgetFeatureGate = (props: AgentsWidgetFeatureGateProps) => {\n const { children } = props;\n return <>{children}</>;\n};\n\nconst DefaultConversationSearchResultsList = (props: AgentsConversationSearchResultsListProps) => {\n const { groups, onOpenConversation } = props;\n return (\n <ul className=\"agents-conversation-search-results\">\n {groups.map((group, groupIndex) => (\n <li key={group.conversationId ?? groupIndex} className=\"agents-conversation-search-results__group\">\n <DefaultText role=\"body\" weight=\"bold\" translate={false}>\n {group.title ?? \"\"}\n </DefaultText>\n {group.hits.map((hit, hitIndex) => (\n <button\n key={hit.messageId ?? hitIndex}\n type=\"button\"\n className=\"agents-conversation-search-results__hit\"\n onClick={() => {\n if (group.conversationId !== undefined) onOpenConversation(group.conversationId, hit.messageId);\n }}\n >\n <DefaultText role=\"help\" translate={false}>\n {hit.excerpt ?? \"\"}\n </DefaultText>\n </button>\n ))}\n </li>\n ))}\n </ul>\n );\n};\n\n/** The package default of every replaceable component. */\nexport const DEFAULT_AGENTS_COMPONENTS: AgentsComponents = {\n Text: DefaultText,\n Button: DefaultButton,\n Icon: DefaultIcon,\n InteractiveSurface: DefaultInteractiveSurface,\n Skeleton: DefaultSkeleton,\n LoadingSpinner: DefaultLoadingSpinner,\n Tooltip: DefaultTooltip,\n GlowFrame: DefaultGlowFrame,\n ProgressBar: DefaultProgressBar,\n SplitView: DefaultSplitView,\n TrendDelta: DefaultTrendDelta,\n Checkbox: DefaultCheckbox,\n TextInput: DefaultTextInput,\n TextArea: DefaultTextArea,\n RangeSlider: DefaultRangeSlider,\n DateInput: DefaultDateInput,\n RadioGroup: DefaultRadioGroup,\n Select: DefaultSelect,\n Tabs: DefaultTabs,\n StatusBadge: DefaultStatusBadge,\n Map: DefaultMap,\n MapMarker: DefaultMapMarker,\n ModalLayer: DefaultModalLayer,\n HeroRow: DefaultHeroRow,\n HeroValue: DefaultHeroValue,\n WidgetText: DefaultWidgetText,\n SkeletonText: DefaultSkeletonText,\n StatusChip: DefaultStatusChip,\n SegmentBar: DefaultSegmentBar,\n Markdown: DefaultMarkdown,\n WidgetFeatureGate: DefaultWidgetFeatureGate,\n ConversationSearchResultsList: DefaultConversationSearchResultsList,\n};\n","import { createContext, type ReactNode, useContext, useMemo, useSyncExternalStore } from \"react\";\nimport type { AgentsConversationClient } from \"../client/AgentsConversationClient\";\nimport { AgentsConversationClientProvider } from \"../client/AgentsConversationClientContext\";\nimport { getDefaultAgentsStateStore } from \"../renderer/widget-hydration/widget-hydration-state-store\";\nimport { DEFAULT_AGENTS_COMPONENTS } from \"./components/default-components\";\nimport type { AgentsComponents } from \"./components/types\";\nimport {\n type AgentsBudgetLimit,\n type AgentsEnvironment,\n type AgentsMapsLoaderState,\n type AgentsOwnerSettings,\n type AgentsStateAction,\n type AgentsTexts,\n DEFAULT_AGENTS_TEXTS,\n getAgentsEnvironment,\n subscribeToAgentsEnvironment,\n} from \"./environment\";\n\nconst AgentsEnvironmentContext = createContext<AgentsEnvironment | null>(null);\n\nexport interface AgentsProviderProps {\n /** The subtree's environment; members it leaves out fall back to the app-wide one, then to the defaults. */\n environment?: AgentsEnvironment;\n /** The conversation client the chat below reads and sends through (the one required input of a chat). */\n client?: AgentsConversationClient;\n children: ReactNode;\n}\n\nconst NO_SUBTREE_ENVIRONMENT: AgentsEnvironment = {};\n\n/**\n * Supplies an environment and the conversation client to one subtree. `<AgentsProvider client={client}><AgentChat />\n * </AgentsProvider>` is a whole chat with the package defaults.\n */\nexport const AgentsProvider = (props: AgentsProviderProps) => {\n const { environment = NO_SUBTREE_ENVIRONMENT, client, children } = props;\n const environmentTree = <AgentsEnvironmentContext.Provider value={environment}>{children}</AgentsEnvironmentContext.Provider>;\n return client ? (\n <AgentsConversationClientProvider client={client}>{environmentTree}</AgentsConversationClientProvider>\n ) : (\n environmentTree\n );\n};\n\nconst useAppEnvironment = (): AgentsEnvironment =>\n useSyncExternalStore(subscribeToAgentsEnvironment, getAgentsEnvironment, getAgentsEnvironment);\n\n/** The components package code renders: the subtree's replacements over the app's over the package defaults. */\nexport const useAgentsComponents = (): AgentsComponents => {\n const subtreeEnvironment = useContext(AgentsEnvironmentContext);\n const appEnvironment = useAppEnvironment();\n return useMemo(\n () => ({ ...DEFAULT_AGENTS_COMPONENTS, ...appEnvironment.components, ...subtreeEnvironment?.components }),\n [appEnvironment, subtreeEnvironment],\n );\n};\n\nexport const useAgentsTexts = (): AgentsTexts => {\n const subtreeEnvironment = useContext(AgentsEnvironmentContext);\n const appEnvironment = useAppEnvironment();\n return subtreeEnvironment?.texts ?? appEnvironment.texts ?? DEFAULT_AGENTS_TEXTS;\n};\n\n/** The environment of this subtree: its own members over the app-wide ones. */\nexport const useAgentsEnvironment = (): AgentsEnvironment => {\n const subtreeEnvironment = useContext(AgentsEnvironmentContext);\n const appEnvironment = useAppEnvironment();\n return useMemo(\n () => (subtreeEnvironment ? { ...appEnvironment, ...subtreeEnvironment } : appEnvironment),\n [appEnvironment, subtreeEnvironment],\n );\n};\n\n/** The app's state store, else the package's own widget hydration store. */\nconst readStateStore = (environment: AgentsEnvironment) => environment.stateStore ?? getDefaultAgentsStateStore();\n\n/** Reads from the state store (`AgentsEnvironment.stateStore`, else the package's default store). */\nexport const useAgentsStateSelector = <Selected,>(selector: (state: any) => Selected): Selected =>\n readStateStore(useAgentsEnvironment()).useSelector(selector);\n\n/** The dispatch of the state store (`AgentsEnvironment.stateStore`, else the package's default store). */\nexport const useAgentsStateDispatch = (): ((action: AgentsStateAction) => unknown) =>\n readStateStore(useAgentsEnvironment()).useDispatch();\n\nconst NO_OWNER_SETTINGS: AgentsOwnerSettings = {};\nconst useNoOwnerSettings = (): AgentsOwnerSettings => NO_OWNER_SETTINGS;\n\n/** The owner's language and the active agent space's date and time settings (`AgentsEnvironment.useOwnerSettings`). */\nexport const useAgentsOwnerSettings = (): AgentsOwnerSettings => {\n const useOwnerSettings = useAgentsEnvironment().useOwnerSettings ?? useNoOwnerSettings;\n return useOwnerSettings();\n};\n\nconst useNoActiveAgentSpaceKey = (): number | undefined => undefined;\n\n/** The key of the agent space the owner works in (`AgentsEnvironment.useActiveAgentSpaceKey`). */\nexport const useAgentsActiveAgentSpaceKey = (): number | undefined => {\n const useActiveAgentSpaceKey = useAgentsEnvironment().useActiveAgentSpaceKey ?? useNoActiveAgentSpaceKey;\n return useActiveAgentSpaceKey();\n};\n\nconst NO_MAPS: AgentsMapsLoaderState = {\n isLoaded: false,\n loadError: new Error(\"The agents environment has no maps loader.\"),\n languageCode: undefined,\n};\nconst useNoMapsLoader = (): AgentsMapsLoaderState => NO_MAPS;\n\n/** The map script loader's state (`AgentsEnvironment.useMapsLoader`). */\nexport const useAgentsMapsLoader = (): AgentsMapsLoaderState => {\n const useMapsLoader = useAgentsEnvironment().useMapsLoader ?? useNoMapsLoader;\n return useMapsLoader();\n};\n\nconst NO_BUDGET_UPGRADE: AgentsBudgetLimit = { canUpgrade: false, openUpgrade: () => undefined, showsFairUseWording: false };\nconst useNoBudgetLimit = (): AgentsBudgetLimit => NO_BUDGET_UPGRADE;\n\n/** What the error card of a reached budget offers (`AgentsEnvironment.useBudgetLimit`). */\nexport const useAgentsBudgetLimit = (): AgentsBudgetLimit => {\n const useBudgetLimit = useAgentsEnvironment().useBudgetLimit ?? useNoBudgetLimit;\n return useBudgetLimit();\n};\n","import { useAgentsComponents } from \"../AgentsProvider\";\nimport type {\n AgentsButtonProps,\n AgentsCheckboxProps,\n AgentsDateInputProps,\n AgentsGlowFrameProps,\n AgentsIconProps,\n AgentsInteractiveSurfaceProps,\n AgentsLoadingSpinnerProps,\n AgentsMapMarkerProps,\n AgentsMapProps,\n AgentsModalLayerProps,\n AgentsProgressBarProps,\n AgentsRadioGroupProps,\n AgentsRangeSliderProps,\n AgentsSelectProps,\n AgentsSkeletonProps,\n AgentsSplitViewProps,\n AgentsStatusBadgeProps,\n AgentsTabsProps,\n AgentsTextAreaProps,\n AgentsTextInputProps,\n AgentsTextProps,\n AgentsTooltipProps,\n AgentsTrendDeltaProps,\n AgentsHeroRowProps,\n AgentsHeroValueProps,\n AgentsWidgetTextProps,\n AgentsSkeletonTextProps,\n AgentsStatusChipProps,\n AgentsSegmentBarProps,\n AgentsMarkdownProps,\n AgentsWidgetFeatureGateProps,\n AgentsConversationSearchResultsListProps,\n} from \"./types\";\n\n/**\n * The components package code imports. Each renders the app's replacement when the environment has one, else the\n * package default — package code never imports an app's component library.\n */\nexport const Text = (props: AgentsTextProps) => {\n const { Text: TextComponent } = useAgentsComponents();\n return <TextComponent {...props} />;\n};\n\nexport const Button = (props: AgentsButtonProps) => {\n const { Button: ButtonComponent } = useAgentsComponents();\n return <ButtonComponent {...props} />;\n};\n\nexport const Icon = (props: AgentsIconProps) => {\n const { Icon: IconComponent } = useAgentsComponents();\n return <IconComponent {...props} />;\n};\n\nexport const InteractiveSurface = (props: AgentsInteractiveSurfaceProps) => {\n const { InteractiveSurface: InteractiveSurfaceComponent } = useAgentsComponents();\n return <InteractiveSurfaceComponent {...props} />;\n};\n\nexport const Skeleton = (props: AgentsSkeletonProps) => {\n const { Skeleton: SkeletonComponent } = useAgentsComponents();\n return <SkeletonComponent {...props} />;\n};\n\nexport const LoadingSpinner = (props: AgentsLoadingSpinnerProps) => {\n const { LoadingSpinner: LoadingSpinnerComponent } = useAgentsComponents();\n return <LoadingSpinnerComponent {...props} />;\n};\n\nexport const Tooltip = (props: AgentsTooltipProps) => {\n const { Tooltip: TooltipComponent } = useAgentsComponents();\n return <TooltipComponent {...props} />;\n};\n\nexport const GlowFrame = (props: AgentsGlowFrameProps) => {\n const { GlowFrame: GlowFrameComponent } = useAgentsComponents();\n return <GlowFrameComponent {...props} />;\n};\n\nexport const ProgressBar = (props: AgentsProgressBarProps) => {\n const { ProgressBar: ProgressBarComponent } = useAgentsComponents();\n return <ProgressBarComponent {...props} />;\n};\n\nexport const SplitView = (props: AgentsSplitViewProps) => {\n const { SplitView: SplitViewComponent } = useAgentsComponents();\n return <SplitViewComponent {...props} />;\n};\n\nexport const TrendDelta = (props: AgentsTrendDeltaProps) => {\n const { TrendDelta: TrendDeltaComponent } = useAgentsComponents();\n return <TrendDeltaComponent {...props} />;\n};\n\nexport const Checkbox = (props: AgentsCheckboxProps) => {\n const { Checkbox: CheckboxComponent } = useAgentsComponents();\n return <CheckboxComponent {...props} />;\n};\n\nexport const TextInput = (props: AgentsTextInputProps) => {\n const { TextInput: TextInputComponent } = useAgentsComponents();\n return <TextInputComponent {...props} />;\n};\n\nexport const TextArea = (props: AgentsTextAreaProps) => {\n const { TextArea: TextAreaComponent } = useAgentsComponents();\n return <TextAreaComponent {...props} />;\n};\n\nexport const RangeSlider = (props: AgentsRangeSliderProps) => {\n const { RangeSlider: RangeSliderComponent } = useAgentsComponents();\n return <RangeSliderComponent {...props} />;\n};\n\nexport const DateInput = (props: AgentsDateInputProps) => {\n const { DateInput: DateInputComponent } = useAgentsComponents();\n return <DateInputComponent {...props} />;\n};\n\nexport const RadioGroup = (props: AgentsRadioGroupProps) => {\n const { RadioGroup: RadioGroupComponent } = useAgentsComponents();\n return <RadioGroupComponent {...props} />;\n};\n\nexport const Select = (props: AgentsSelectProps) => {\n const { Select: SelectComponent } = useAgentsComponents();\n return <SelectComponent {...props} />;\n};\n\nexport const Tabs = (props: AgentsTabsProps) => {\n const { Tabs: TabsComponent } = useAgentsComponents();\n return <TabsComponent {...props} />;\n};\n\nexport const StatusBadge = (props: AgentsStatusBadgeProps) => {\n const { StatusBadge: StatusBadgeComponent } = useAgentsComponents();\n return <StatusBadgeComponent {...props} />;\n};\n\nexport const Map = (props: AgentsMapProps) => {\n const { Map: MapComponent } = useAgentsComponents();\n return <MapComponent {...props} />;\n};\n\nexport const MapMarker = (props: AgentsMapMarkerProps) => {\n const { MapMarker: MapMarkerComponent } = useAgentsComponents();\n return <MapMarkerComponent {...props} />;\n};\n\nexport const ModalLayer = (props: AgentsModalLayerProps) => {\n const { ModalLayer: ModalLayerComponent } = useAgentsComponents();\n return <ModalLayerComponent {...props} />;\n};\n\nexport const HeroRow = (props: AgentsHeroRowProps) => {\n const { HeroRow: HeroRowComponent } = useAgentsComponents();\n return <HeroRowComponent {...props} />;\n};\n\nexport const HeroValue = (props: AgentsHeroValueProps) => {\n const { HeroValue: HeroValueComponent } = useAgentsComponents();\n return <HeroValueComponent {...props} />;\n};\n\nexport const WidgetText = (props: AgentsWidgetTextProps) => {\n const { WidgetText: WidgetTextComponent } = useAgentsComponents();\n return <WidgetTextComponent {...props} />;\n};\n\nexport const SkeletonText = (props: AgentsSkeletonTextProps) => {\n const { SkeletonText: SkeletonTextComponent } = useAgentsComponents();\n return <SkeletonTextComponent {...props} />;\n};\n\nexport const StatusChip = (props: AgentsStatusChipProps) => {\n const { StatusChip: StatusChipComponent } = useAgentsComponents();\n return <StatusChipComponent {...props} />;\n};\n\nexport const SegmentBar = (props: AgentsSegmentBarProps) => {\n const { SegmentBar: SegmentBarComponent } = useAgentsComponents();\n return <SegmentBarComponent {...props} />;\n};\n\nexport const Markdown = (props: AgentsMarkdownProps) => {\n const { Markdown: MarkdownComponent } = useAgentsComponents();\n return <MarkdownComponent {...props} />;\n};\n\nexport const WidgetFeatureGate = (props: AgentsWidgetFeatureGateProps) => {\n const { WidgetFeatureGate: WidgetFeatureGateComponent } = useAgentsComponents();\n return <WidgetFeatureGateComponent {...props} />;\n};\n\nexport const ConversationSearchResultsList = (props: AgentsConversationSearchResultsListProps) => {\n const { ConversationSearchResultsList: ConversationSearchResultsListComponent } = useAgentsComponents();\n return <ConversationSearchResultsListComponent {...props} />;\n};\n\nexport type * from \"./types\";\nexport { AGENTS_ICON_NAMES, isAgentsIconName } from \"./icon-names\";\n"],"names":["appEnvironment"],"mappings":";;;;;;AAsTA,IAAI,iBAAoC,CAAA;AACxC,M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iC;AAC1D,QAAM,EAAE,YAAY,oBAAA,IAAwB,oBAAA;AAC5C,SAAO,oBAAC,qBAAA,EAAqB,GAAG,MAAA,CAAO;AACzC;AAEO,MAAM,aAAa,CAAC,UAAiC;AAC1D,QAAM,EAAE,YAAY,oBAAA,IAAwB,oBAAA;AAC5C,SAAO,oBAAC,qBAAA,EAAqB,GAAG,MAAA,CAAO;AACzC;AAEO,MAAM,WAAW,CAAC,UAA+B;AACtD,QAAM,EAAE,UAAU,kBAAA,IAAsB,oBAAA;AACxC,SAAO,oBAAC,mBAAA,EAAmB,GAAG,MAAA,CAAO;AACvC;AAEO,MAAM,oBAAoB,CAAC,UAAwC;AACxE,QAAM,EAAE,mBAAmB,2BAAA,IAA+B,oBAAA;AAC1D,SAAO,oBAAC,4BAAA,EAA4B,GAAG,MAAA,CAAO;AAChD;AAEO,MAAM,gCAAgC,CAAC,UAAoD;AAChG,QAAM,EAAE,+BAA+B,uCAAA,IAA2C,oBAAA;AAClF,SAAO,oBAAC,wCAAA,EAAwC,GAAG,MAAA,CAAO;AAC5D;"}
@@ -1,7 +1,7 @@
1
1
  "use client";
2
2
  import { jsx } from "react/jsx-runtime";
3
3
  import { useMemo } from "react";
4
- import { a4 as useAgentsEnvironment } from "./index-DZovGMpG.js";
4
+ import { a4 as useAgentsEnvironment } from "./index-DAEGct6X.js";
5
5
  const openInNewTab = (href) => {
6
6
  window.open(href, "_blank", "noopener,noreferrer");
7
7
  };
@@ -46,4 +46,4 @@ export {
46
46
  AgentsLink as A,
47
47
  useAgentsLinkNavigation as u
48
48
  };
49
- //# sourceMappingURL=link-navigation-a_sRfmsj.js.map
49
+ //# sourceMappingURL=link-navigation-DQWyeNkx.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"link-navigation-a_sRfmsj.js","sources":["../../src/provider/link-navigation.tsx"],"sourcesContent":["import { type AnchorHTMLAttributes, type MouseEvent as ReactMouseEvent, useMemo } from \"react\";\nimport { useAgentsEnvironment } from \"./AgentsProvider\";\nimport type { AgentsEnvironment } from \"./environment\";\n\n/** Opens a link the package's default way: a new tab, without opener or referrer. */\nconst openInNewTab = (href: string): void => {\n window.open(href, \"_blank\", \"noopener,noreferrer\");\n};\n\n/**\n * Opens a link through the environment's `onNavigate` (the host decides: an in-app route, a new tab, nothing), else in\n * a new tab. `event` is the click that asked for it, when there is one.\n */\nexport const openLinkThroughEnvironment = (\n environment: Pick<AgentsEnvironment, \"onNavigate\">,\n href: string,\n event: MouseEvent | null,\n): void => {\n if (environment.onNavigate?.(href, event) === true) return;\n openInNewTab(href);\n};\n\nconst readNativeEvent = (event: ReactMouseEvent | MouseEvent | undefined): MouseEvent | null =>\n event === undefined ? null : \"nativeEvent\" in event ? event.nativeEvent : event;\n\n/** How package code opens a link: through the host's `onNavigate`, else in a new tab. */\nexport interface AgentsLinkNavigation {\n /** Opens `href` (a link opened by code, e.g. a button: the package's `window.open` places). */\n openLink: (href: string, event?: ReactMouseEvent | MouseEvent) => void;\n /**\n * The click handler of an anchor that opens in a new tab: hands the click to the host's `onNavigate` and keeps the\n * browser from following the anchor when the host took it.\n */\n handleLinkClick: (event: ReactMouseEvent<HTMLAnchorElement>, href?: string) => void;\n}\n\n/** The link navigation of this subtree (`AgentsEnvironment.onNavigate`). */\nexport const useAgentsLinkNavigation = (): AgentsLinkNavigation => {\n const { onNavigate } = useAgentsEnvironment();\n return useMemo(\n () => ({\n openLink: (href, event) => openLinkThroughEnvironment({ onNavigate }, href, readNativeEvent(event)),\n handleLinkClick: (event, href) => {\n const target = href ?? event.currentTarget.getAttribute(\"href\") ?? \"\";\n if (!target || !onNavigate) return;\n if (onNavigate(target, event.nativeEvent) === true) event.preventDefault();\n },\n }),\n [onNavigate],\n );\n};\n\nexport type AgentsLinkProps = AnchorHTMLAttributes<HTMLAnchorElement> & {\n /** The hast node react-markdown passes to a custom component; never put on the DOM element. */\n node?: unknown;\n};\n\n/**\n * The anchor every package link renders: a new tab without opener or referrer, unless the host's `onNavigate` takes\n * the click (an in-app route). A host's own widget uses it for the same behaviour.\n */\nexport const AgentsLink = (props: AgentsLinkProps) => {\n const { node, href, onClick, children, ...anchorProps } = props;\n const { handleLinkClick } = useAgentsLinkNavigation();\n return (\n <a\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n {...anchorProps}\n href={href}\n onClick={(event) => {\n onClick?.(event);\n if (!event.defaultPrevented && href) handleLinkClick(event, href);\n }}\n >\n {children}\n </a>\n );\n};\n"],"names":[],"mappings":";;;;AAKA,MAAM,eAAe,CAAC,SAAuB;AAC3C,SAAO,KAAK,MAAM,UAAU,qBAAqB;AACnD;AAMO,MAAM,6BAA6B,CACxC,aACA,MACA,UACS;AACT,MAAI,YAAY,aAAa,MAAM,KAAK,MAAM,KAAM;AACpD,eAAa,IAAI;AACnB;AAEA,MAAM,kBAAkB,CAAC,UACvB,UAAU,SAAY,OAAO,iBAAiB,QAAQ,MAAM,cAAc;AAcrE,MAAM,0BAA0B,MAA4B;AACjE,QAAM,EAAE,WAAA,IAAe,qBAAA;AACvB,SAAO;AAAA,IACL,OAAO;AAAA,MACL,UAAU,CAAC,MAAM,UAAU,2BAA2B,EAAE,WAAA,GAAc,MAAM,gBAAgB,KAAK,CAAC;AAAA,MAClG,iBAAiB,CAAC,OAAO,SAAS;AAChC,cAAM,SAAS,QAAQ,MAAM,cAAc,aAAa,MAAM,KAAK;AACnE,YAAI,CAAC,UAAU,CAAC,WAAY;AAC5B,YAAI,WAAW,QAAQ,MAAM,WAAW,MAAM,YAAY,eAAA;AAAA,MAC5D;AAAA,IAAA;AAAA,IAEF,CAAC,UAAU;AAAA,EAAA;AAEf;AAWO,MAAM,aAAa,CAAC,UAA2B;AACpD,QAAM,EAAE,MAAM,MAAM,SAAS,UAAU,GAAG,gBAAgB;AAC1D,QAAM,EAAE,gBAAA,IAAoB,wBAAA;AAC5B,SACE;AAAA,IAAC;AAAA,IAAA;AAAA,MACC,QAAO;AAAA,MACP,KAAI;AAAA,MACH,GAAG;AAAA,MACJ;AAAA,MACA,SAAS,CAAC,UAAU;AAClB,kBAAU,KAAK;AACf,YAAI,CAAC,MAAM,oBAAoB,KAAM,iBAAgB,OAAO,IAAI;AAAA,MAClE;AAAA,MAEC;AAAA,IAAA;AAAA,EAAA;AAGP;"}
1
+ {"version":3,"file":"link-navigation-DQWyeNkx.js","sources":["../../src/provider/link-navigation.tsx"],"sourcesContent":["import { type AnchorHTMLAttributes, type MouseEvent as ReactMouseEvent, useMemo } from \"react\";\nimport { useAgentsEnvironment } from \"./AgentsProvider\";\nimport type { AgentsEnvironment } from \"./environment\";\n\n/** Opens a link the package's default way: a new tab, without opener or referrer. */\nconst openInNewTab = (href: string): void => {\n window.open(href, \"_blank\", \"noopener,noreferrer\");\n};\n\n/**\n * Opens a link through the environment's `onNavigate` (the host decides: an in-app route, a new tab, nothing), else in\n * a new tab. `event` is the click that asked for it, when there is one.\n */\nexport const openLinkThroughEnvironment = (\n environment: Pick<AgentsEnvironment, \"onNavigate\">,\n href: string,\n event: MouseEvent | null,\n): void => {\n if (environment.onNavigate?.(href, event) === true) return;\n openInNewTab(href);\n};\n\nconst readNativeEvent = (event: ReactMouseEvent | MouseEvent | undefined): MouseEvent | null =>\n event === undefined ? null : \"nativeEvent\" in event ? event.nativeEvent : event;\n\n/** How package code opens a link: through the host's `onNavigate`, else in a new tab. */\nexport interface AgentsLinkNavigation {\n /** Opens `href` (a link opened by code, e.g. a button: the package's `window.open` places). */\n openLink: (href: string, event?: ReactMouseEvent | MouseEvent) => void;\n /**\n * The click handler of an anchor that opens in a new tab: hands the click to the host's `onNavigate` and keeps the\n * browser from following the anchor when the host took it.\n */\n handleLinkClick: (event: ReactMouseEvent<HTMLAnchorElement>, href?: string) => void;\n}\n\n/** The link navigation of this subtree (`AgentsEnvironment.onNavigate`). */\nexport const useAgentsLinkNavigation = (): AgentsLinkNavigation => {\n const { onNavigate } = useAgentsEnvironment();\n return useMemo(\n () => ({\n openLink: (href, event) => openLinkThroughEnvironment({ onNavigate }, href, readNativeEvent(event)),\n handleLinkClick: (event, href) => {\n const target = href ?? event.currentTarget.getAttribute(\"href\") ?? \"\";\n if (!target || !onNavigate) return;\n if (onNavigate(target, event.nativeEvent) === true) event.preventDefault();\n },\n }),\n [onNavigate],\n );\n};\n\nexport type AgentsLinkProps = AnchorHTMLAttributes<HTMLAnchorElement> & {\n /** The hast node react-markdown passes to a custom component; never put on the DOM element. */\n node?: unknown;\n};\n\n/**\n * The anchor every package link renders: a new tab without opener or referrer, unless the host's `onNavigate` takes\n * the click (an in-app route). A host's own widget uses it for the same behaviour.\n */\nexport const AgentsLink = (props: AgentsLinkProps) => {\n const { node, href, onClick, children, ...anchorProps } = props;\n const { handleLinkClick } = useAgentsLinkNavigation();\n return (\n <a\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n {...anchorProps}\n href={href}\n onClick={(event) => {\n onClick?.(event);\n if (!event.defaultPrevented && href) handleLinkClick(event, href);\n }}\n >\n {children}\n </a>\n );\n};\n"],"names":[],"mappings":";;;;AAKA,MAAM,eAAe,CAAC,SAAuB;AAC3C,SAAO,KAAK,MAAM,UAAU,qBAAqB;AACnD;AAMO,MAAM,6BAA6B,CACxC,aACA,MACA,UACS;AACT,MAAI,YAAY,aAAa,MAAM,KAAK,MAAM,KAAM;AACpD,eAAa,IAAI;AACnB;AAEA,MAAM,kBAAkB,CAAC,UACvB,UAAU,SAAY,OAAO,iBAAiB,QAAQ,MAAM,cAAc;AAcrE,MAAM,0BAA0B,MAA4B;AACjE,QAAM,EAAE,WAAA,IAAe,qBAAA;AACvB,SAAO;AAAA,IACL,OAAO;AAAA,MACL,UAAU,CAAC,MAAM,UAAU,2BAA2B,EAAE,WAAA,GAAc,MAAM,gBAAgB,KAAK,CAAC;AAAA,MAClG,iBAAiB,CAAC,OAAO,SAAS;AAChC,cAAM,SAAS,QAAQ,MAAM,cAAc,aAAa,MAAM,KAAK;AACnE,YAAI,CAAC,UAAU,CAAC,WAAY;AAC5B,YAAI,WAAW,QAAQ,MAAM,WAAW,MAAM,YAAY,eAAA;AAAA,MAC5D;AAAA,IAAA;AAAA,IAEF,CAAC,UAAU;AAAA,EAAA;AAEf;AAWO,MAAM,aAAa,CAAC,UAA2B;AACpD,QAAM,EAAE,MAAM,MAAM,SAAS,UAAU,GAAG,gBAAgB;AAC1D,QAAM,EAAE,gBAAA,IAAoB,wBAAA;AAC5B,SACE;AAAA,IAAC;AAAA,IAAA;AAAA,MACC,QAAO;AAAA,MACP,KAAI;AAAA,MACH,GAAG;AAAA,MACJ;AAAA,MACA,SAAS,CAAC,UAAU;AAClB,kBAAU,KAAK;AACf,YAAI,CAAC,MAAM,oBAAoB,KAAM,iBAAgB,OAAO,IAAI;AAAA,MAClE;AAAA,MAEC;AAAA,IAAA;AAAA,EAAA;AAGP;"}
@@ -1,5 +1,5 @@
1
1
  "use client";
2
- import { r as readConversationRunStatusOfRunState, d as CONVERSATION_RUN_STATES_THAT_END_THE_CONVERSATION, i as isAgentsClientError } from "./conversation-Cbrqtx-_.js";
2
+ import { r as readConversationRunStatusOfRunState, e as CONVERSATION_RUN_STATES_THAT_END_THE_CONVERSATION, i as isAgentsClientError } from "./conversation-VosmRbsr.js";
3
3
  const POLLING_RUNNING_INTERVAL_MS = 2e3;
4
4
  const POLLING_IDLE_INTERVAL_MS = 2e4;
5
5
  const POLLING_MAX_BACKOFF_MS = 6e4;
@@ -239,6 +239,23 @@ class PollingAgentsConversationClient {
239
239
  this.getTurnTraces = binding.getTurnTraces?.bind(binding);
240
240
  this.getMessageContextComposition = binding.getMessageContextComposition?.bind(binding);
241
241
  this.getFileChangeDiff = binding.getFileChangeDiff?.bind(binding);
242
+ this.getStepConfirmation = binding.getStepConfirmation?.bind(binding);
243
+ const executeStepConfirmation = binding.executeStepConfirmation?.bind(binding);
244
+ if (executeStepConfirmation) {
245
+ this.executeStepConfirmation = async (conversationId, stepConfirmationId, contentHash) => {
246
+ const stepConfirmation = await executeStepConfirmation(conversationId, stepConfirmationId, contentHash);
247
+ this.polling.notifyLocalActivity(conversationId);
248
+ return stepConfirmation;
249
+ };
250
+ }
251
+ const discardStepConfirmation = binding.discardStepConfirmation?.bind(binding);
252
+ if (discardStepConfirmation) {
253
+ this.discardStepConfirmation = async (conversationId, stepConfirmationId) => {
254
+ const stepConfirmation = await discardStepConfirmation(conversationId, stepConfirmationId);
255
+ this.polling.notifyLocalActivity(conversationId);
256
+ return stepConfirmation;
257
+ };
258
+ }
242
259
  const stopTurn = binding.stopTurn?.bind(binding);
243
260
  if (stopTurn) {
244
261
  this.stopTurn = async (conversationId) => {
@@ -276,4 +293,4 @@ export {
276
293
  readPolledRunStatus as r,
277
294
  withPollingChangeSubscription as w
278
295
  };
279
- //# sourceMappingURL=withPollingChangeSubscription-Cz3Diolr.js.map
296
+ //# sourceMappingURL=withPollingChangeSubscription-Ct8kjmlL.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"withPollingChangeSubscription-Ct8kjmlL.js","sources":["../../src/client/polling/createPollingConversationChangeSubscription.ts","../../src/client/polling/withPollingChangeSubscription.ts"],"sourcesContent":["import {\n type ConversationChangeSignal,\n type ConversationRunStateRead,\n type ConversationRunStatus,\n type ConversationSubscriptionEndReason,\n CONVERSATION_RUN_STATES_THAT_END_THE_CONVERSATION,\n isAgentsClientError,\n readConversationRunStatusOfRunState,\n} from \"../../contract/conversation\";\n\n/** Read interval while a turn runs (or right after a local send). */\nexport const POLLING_RUNNING_INTERVAL_MS = 2_000;\n/** Read interval while the conversation is idle or failed. */\nexport const POLLING_IDLE_INTERVAL_MS = 20_000;\n/** Ceiling of the exponential backoff after failed reads. */\nexport const POLLING_MAX_BACKOFF_MS = 60_000;\n/**\n * How long after a local send the poller keeps the running interval although the conversation still reads idle: the\n * server may store the owner's message before it marks the turn as running.\n */\nexport const POLLING_LOCAL_ACTIVITY_WINDOW_MS = 10_000;\n\n/**\n * Reads a conversation's run state — the port's `getConversationRunState`, or its `getConversationMetadata` (every\n * conversation carries the fields the poller reads).\n */\nexport type ConversationMetadataReader = (conversationId: number) => Promise<ConversationRunStateRead>;\n\n/** The timer functions the poller uses; a spec hands in fake ones. */\nexport interface PollingTimers {\n setTimeout: (callback: () => void, delayMs: number) => unknown;\n clearTimeout: (timerHandle: unknown) => void;\n now: () => number;\n}\n\n/** Whether the page is hidden, and a way to hear when that changes; a spec hands in its own. */\nexport interface PollingDocumentVisibility {\n isHidden: () => boolean;\n /** Calls `listener` on every visibility change; returns the function that stops it. */\n listen: (listener: () => void) => () => void;\n}\n\nexport interface PollingConversationChangeSubscriptionOptions {\n /** Default `POLLING_RUNNING_INTERVAL_MS` (2 s). */\n runningIntervalMs?: number;\n /** Default `POLLING_IDLE_INTERVAL_MS` (20 s). */\n idleIntervalMs?: number;\n /** Default `POLLING_MAX_BACKOFF_MS` (60 s). */\n maxBackoffMs?: number;\n /** Default `POLLING_LOCAL_ACTIVITY_WINDOW_MS` (10 s). */\n localActivityWindowMs?: number;\n /** Default: the global `setTimeout` / `clearTimeout` and `Date.now`. */\n timers?: PollingTimers;\n /** Default: the browser `document`; `null` = the page counts as always visible (no `document`, a worker). */\n documentVisibility?: PollingDocumentVisibility | null;\n}\n\n/**\n * The polling default of the live updates: the port's `subscribeToConversationChanges` plus\n * `notifyLocalActivity`, which `withPollingChangeSubscription` calls after every send the server accepted.\n */\nexport interface PollingConversationChangeSubscription {\n subscribeToConversationChanges: (\n conversationId: number,\n onSignal: (signal: ConversationChangeSignal) => void,\n onEnded: (reason: ConversationSubscriptionEndReason) => void,\n ) => () => void;\n /** Reads the conversation's metadata now and keeps the running interval for the local-activity window. */\n notifyLocalActivity: (conversationId: number) => void;\n}\n\ninterface ResolvedPollingOptions {\n runningIntervalMs: number;\n idleIntervalMs: number;\n maxBackoffMs: number;\n localActivityWindowMs: number;\n timers: PollingTimers;\n documentVisibility: PollingDocumentVisibility | null;\n}\n\n/** The global timer functions, looked up on each call (so a spec's fake timers installed later still apply). */\nclass GlobalPollingTimers implements PollingTimers {\n setTimeout = (callback: () => void, delayMs: number): unknown => globalThis.setTimeout(callback, delayMs);\n\n clearTimeout = (timerHandle: unknown): void => globalThis.clearTimeout(timerHandle as ReturnType<typeof setTimeout>);\n\n now = (): number => Date.now();\n}\n\n/** The browser document's `visibilityState` and `visibilitychange` event. */\nclass BrowserDocumentVisibility implements PollingDocumentVisibility {\n constructor(protected readonly browserDocument: Document) {}\n\n isHidden = (): boolean => this.browserDocument.visibilityState === \"hidden\";\n\n listen = (listener: () => void): (() => void) => {\n this.browserDocument.addEventListener(\"visibilitychange\", listener);\n return this.browserDocument.removeEventListener.bind(this.browserDocument, \"visibilitychange\", listener);\n };\n}\n\n/**\n * The three-value run status a polled read reports: the stored run state, and \"running\" for an idle conversation the\n * server owes a turn (`agentTurnOwedAt`), as the chat's own derivation does.\n */\nexport const readPolledRunStatus = (\n conversation: Pick<ConversationRunStateRead, \"runState\" | \"agentTurnOwedAt\">,\n): ConversationRunStatus | null => {\n const runStatus = readConversationRunStatusOfRunState(conversation.runState);\n return runStatus === \"idle\" && conversation.agentTurnOwedAt ? \"running\" : runStatus;\n};\n\n/** The end of a subscription a failed read means: a vanished conversation or lost access; null for a passing failure. */\nconst readSubscriptionEndReasonOfReadFailure = (failure: unknown): ConversationSubscriptionEndReason | null => {\n if (!isAgentsClientError(failure)) return null;\n if (failure.kind === \"notFound\") return \"gone\";\n if (failure.kind === \"forbidden\") return \"forbidden\";\n return null;\n};\n\n/**\n * One subscription: reads the conversation's metadata on a timer and turns each read into the change signal.\n *\n * Numbering (the signal leaves it open; the metadata carries no server change counter): the poller keeps its own counter. It\n * starts at 0 with the first read and advances by one whenever a read differs from the previous one in the run status,\n * `lastMessageId` or `updated` — so every polled signal is an ordinary change signal (no `isStatusCheck`) and the\n * package rules apply unchanged: an advance reads the changed tail (throttled), a terminal status reads at once,\n * re-reads the metadata and converges on `lastMessageId`. A status check would carry only the run status as news and\n * would miss a new message under an unchanged status. Without `lastMessageId` in the metadata every poll of a running\n * turn counts as a change (the changed tail is read every poll). `summaryUpdatedAt` is a second local counter that\n * advances when `title` or `summary` changed. A read with no change emits nothing.\n */\nclass ConversationMetadataPoller {\n protected isStopped = false;\n protected isReading = false;\n protected readAgainAfterCurrentRead = false;\n protected timerHandle: unknown = null;\n protected consecutiveFailedReads = 0;\n protected changeCounter = 0;\n protected summaryRevision = 0;\n protected previousChangeFingerprint: string | null = null;\n protected previousSummaryFingerprint: string | null = null;\n protected runStatus: ConversationRunStatus | null = null;\n protected hasConversationEnded = false;\n protected runningIntervalUntil = 0;\n protected stopListeningToVisibility: (() => void) | null = null;\n\n constructor(\n readonly conversationId: number,\n protected readonly readMetadata: ConversationMetadataReader,\n protected readonly onSignal: (signal: ConversationChangeSignal) => void,\n protected readonly onEnded: (reason: ConversationSubscriptionEndReason) => void,\n protected readonly options: ResolvedPollingOptions,\n protected readonly activePollers: Set<ConversationMetadataPoller>,\n ) {}\n\n start = (): void => {\n this.activePollers.add(this);\n this.stopListeningToVisibility = this.options.documentVisibility?.listen(this.receiveVisibilityChange) ?? null;\n this.readNow();\n };\n\n /** The unsubscribe: no read, no timer and no signal after it; a read in flight is dropped. */\n stop = (): void => {\n this.isStopped = true;\n this.activePollers.delete(this);\n this.clearTimer();\n this.stopListeningToVisibility?.();\n this.stopListeningToVisibility = null;\n };\n\n receiveLocalActivity = (): void => {\n this.runningIntervalUntil = this.options.timers.now() + this.options.localActivityWindowMs;\n this.readNow();\n };\n\n /** Reads now; a read already in flight is followed by one more read instead (two reads never overlap). */\n protected readNow = (): void => {\n if (this.isStopped) return;\n if (this.isReading) {\n this.readAgainAfterCurrentRead = true;\n return;\n }\n this.clearTimer();\n this.isReading = true;\n void this.readMetadataOnce();\n };\n\n protected async readMetadataOnce(): Promise<void> {\n let conversation: ConversationRunStateRead;\n try {\n conversation = await this.readMetadata(this.conversationId);\n } catch (failure) {\n this.isReading = false;\n this.receiveReadFailure(failure);\n return;\n }\n this.isReading = false;\n if (this.isStopped) return;\n this.consecutiveFailedReads = 0;\n this.receiveConversation(conversation);\n this.continueAfterRead(this.readIntervalMs());\n }\n\n protected receiveConversation(conversation: ConversationRunStateRead): void {\n const runStatus = readPolledRunStatus(conversation);\n const reportsLastMessageId = conversation.lastMessageId !== undefined;\n const changeFingerprint = JSON.stringify([runStatus, conversation.lastMessageId ?? null, conversation.updated]);\n const summaryFingerprint = JSON.stringify([conversation.title, conversation.summary]);\n const isFirstRead = this.previousChangeFingerprint === null;\n const hasChanged =\n changeFingerprint !== this.previousChangeFingerprint || (!reportsLastMessageId && runStatus === \"running\");\n const hasSummaryChanged = !isFirstRead && summaryFingerprint !== this.previousSummaryFingerprint;\n if (!isFirstRead && hasChanged) this.changeCounter += 1;\n if (hasSummaryChanged) this.summaryRevision += 1;\n this.previousChangeFingerprint = changeFingerprint;\n this.previousSummaryFingerprint = summaryFingerprint;\n this.runStatus = runStatus;\n this.hasConversationEnded =\n conversation.runState !== null && CONVERSATION_RUN_STATES_THAT_END_THE_CONVERSATION.includes(conversation.runState);\n if (!isFirstRead && !hasChanged && !hasSummaryChanged) return;\n this.onSignal({\n changeCounter: this.changeCounter,\n lastMessageId: conversation.lastMessageId ?? null,\n runStatus,\n summaryUpdatedAt: this.summaryRevision,\n });\n }\n\n protected receiveReadFailure(failure: unknown): void {\n if (this.isStopped) return;\n const endReason = readSubscriptionEndReasonOfReadFailure(failure);\n if (endReason !== null) {\n this.stop();\n this.onEnded(endReason);\n return;\n }\n this.consecutiveFailedReads += 1;\n const backoffMs = this.readIntervalMs() * 2 ** this.consecutiveFailedReads;\n this.continueAfterRead(Math.min(backoffMs, this.options.maxBackoffMs));\n }\n\n protected continueAfterRead(nextReadDelayMs: number): void {\n if (this.readAgainAfterCurrentRead) {\n this.readAgainAfterCurrentRead = false;\n this.readNow();\n return;\n }\n // A completed or cancelled conversation changes no more: only a local send or the page's return reads it again.\n if (this.hasConversationEnded) return;\n this.scheduleRead(nextReadDelayMs);\n }\n\n protected readIntervalMs(): number {\n const isShortIntervalDue = this.runStatus === \"running\" || this.options.timers.now() < this.runningIntervalUntil;\n return isShortIntervalDue ? this.options.runningIntervalMs : this.options.idleIntervalMs;\n }\n\n /** Arms the next read — not while the page is hidden; its return reads at once. */\n protected scheduleRead(delayMs: number): void {\n this.clearTimer();\n if (this.isStopped || this.options.documentVisibility?.isHidden()) return;\n this.timerHandle = this.options.timers.setTimeout(this.readOnTimer, delayMs);\n }\n\n protected readOnTimer = (): void => {\n this.timerHandle = null;\n this.readNow();\n };\n\n protected receiveVisibilityChange = (): void => {\n if (this.isStopped) return;\n if (this.options.documentVisibility?.isHidden()) {\n this.clearTimer();\n return;\n }\n this.readNow();\n };\n\n protected clearTimer(): void {\n if (this.timerHandle === null) return;\n this.options.timers.clearTimeout(this.timerHandle);\n this.timerHandle = null;\n }\n}\n\n/** Every subscription of one polling default; `notifyLocalActivity` reaches the subscriptions of a conversation. */\nclass PollingConversationChangeSubscriptions implements PollingConversationChangeSubscription {\n protected readonly activePollers = new Set<ConversationMetadataPoller>();\n\n constructor(\n protected readonly readMetadata: ConversationMetadataReader,\n protected readonly options: ResolvedPollingOptions,\n ) {}\n\n subscribeToConversationChanges = (\n conversationId: number,\n onSignal: (signal: ConversationChangeSignal) => void,\n onEnded: (reason: ConversationSubscriptionEndReason) => void,\n ): (() => void) => {\n const poller = new ConversationMetadataPoller(\n conversationId,\n this.readMetadata,\n onSignal,\n onEnded,\n this.options,\n this.activePollers,\n );\n poller.start();\n return poller.stop;\n };\n\n notifyLocalActivity = (conversationId: number): void => {\n for (const poller of [...this.activePollers]) {\n if (poller.conversationId === conversationId) poller.receiveLocalActivity();\n }\n };\n}\n\nconst readDefaultDocumentVisibility = (): PollingDocumentVisibility | null =>\n typeof document === \"undefined\" ? null : new BrowserDocumentVisibility(document);\n\n/**\n * The polling default of `subscribeToConversationChanges` over a metadata read: every 2 s while a turn\n * runs, every 20 s while idle, at once after `notifyLocalActivity`; paused while the page is hidden and read once when\n * it shows again; exponential backoff on failed reads up to 60 s; a `notFound` / `forbidden` read ends the subscription\n * with `gone` / `forbidden`. One poller per subscription; see `ConversationMetadataPoller` for how a read becomes a\n * signal.\n */\nexport const createPollingConversationChangeSubscription = (\n readMetadata: ConversationMetadataReader,\n options: PollingConversationChangeSubscriptionOptions = {},\n): PollingConversationChangeSubscription =>\n new PollingConversationChangeSubscriptions(readMetadata, {\n runningIntervalMs: options.runningIntervalMs ?? POLLING_RUNNING_INTERVAL_MS,\n idleIntervalMs: options.idleIntervalMs ?? POLLING_IDLE_INTERVAL_MS,\n maxBackoffMs: options.maxBackoffMs ?? POLLING_MAX_BACKOFF_MS,\n localActivityWindowMs: options.localActivityWindowMs ?? POLLING_LOCAL_ACTIVITY_WINDOW_MS,\n timers: options.timers ?? new GlobalPollingTimers(),\n documentVisibility: options.documentVisibility === undefined ? readDefaultDocumentVisibility() : options.documentVisibility,\n });\n","import type { AgentsConversationClient } from \"../AgentsConversationClient\";\nimport type { AccountRealtimeRead } from \"../../ui/account-realtime\";\nimport type {\n AgentsConversation,\n ChangedConversationMessages,\n ChangedMessagesRequest,\n ConversationActivity,\n ConversationAttachmentReference,\n ConversationBackgroundJobStop,\n ConversationStepConfirmation,\n ConversationChangeSignal,\n ConversationListQueryOptions,\n ConversationMessageSearchHit,\n ConversationMessageSentPayload,\n ConversationMessagesPage,\n ConversationRunStateRead,\n ConversationSearchGroup,\n ConversationSearchOptions,\n ConversationSignal,\n ConversationSubscriptionEndReason,\n BoundConversationSubject,\n ConversationsOfSubject,\n ConversationSubject,\n PostedMessage,\n SelectableModel,\n PurposeStartRequest,\n StartedConversation,\n StartedPurposeConversation,\n} from \"../../contract/conversation\";\nimport type {\n ConversationContextComposition,\n ConversationFileChangeDiff,\n ConversationTurnStop,\n ConversationTurnTraces,\n ConversationTurnTracesOptions,\n} from \"../../contract/conversation-trace\";\nimport {\n createPollingConversationChangeSubscription,\n type PollingConversationChangeSubscription,\n type PollingConversationChangeSubscriptionOptions,\n} from \"./createPollingConversationChangeSubscription\";\n\n/** A conversation client whose `subscribeToConversationChanges` is present. */\nexport type AgentsConversationClientWithChangeSubscription = AgentsConversationClient &\n Required<Pick<AgentsConversationClient, \"subscribeToConversationChanges\">>;\n\n/**\n * A binding without push, with the polling default as its subscription. Every port function goes to the binding; the\n * three that make the server start a turn on an existing conversation (post, signal, retry) tell the poller once the\n * server accepted them, so the first read does not wait for the idle interval. A start needs no notice: the chat\n * subscribes to the new conversation afterwards, and a subscription reads at once.\n */\nclass PollingAgentsConversationClient implements AgentsConversationClientWithChangeSubscription {\n readonly getSelectableModels?: () => Promise<SelectableModel[]>;\n readonly composeSentMessageText?: (text: string, attachments: ConversationAttachmentReference[] | undefined) => string;\n readonly getMessageSentPayload?: (conversationId: number, messageId: number) => Promise<ConversationMessageSentPayload>;\n readonly getConversationRunState?: (conversationId: number) => Promise<ConversationRunStateRead>;\n readonly getAccountRealtimeMessages?: (clientId?: string) => Promise<AccountRealtimeRead>;\n readonly startPurpose?: (request: PurposeStartRequest) => Promise<StartedPurposeConversation>;\n readonly listConversationsOfSubject?: (subject: ConversationSubject, options?: ConversationListQueryOptions) => Promise<ConversationsOfSubject>;\n readonly getConversationSubject?: (conversationId: number) => Promise<BoundConversationSubject | null>;\n readonly listSubjectsOfConversations?: (agentSpaceKey: number, options?: ConversationListQueryOptions) => Promise<BoundConversationSubject[]>;\n readonly stopTurn?: (conversationId: number) => Promise<ConversationTurnStop>;\n readonly stopBackgroundJob?: (conversationId: number, backgroundJobId: number) => Promise<ConversationBackgroundJobStop>;\n readonly getStepConfirmation?: (conversationId: number, stepConfirmationId: number) => Promise<ConversationStepConfirmation>;\n readonly executeStepConfirmation?: (conversationId: number, stepConfirmationId: number, contentHash: string) => Promise<ConversationStepConfirmation>;\n readonly discardStepConfirmation?: (conversationId: number, stepConfirmationId: number) => Promise<ConversationStepConfirmation>;\n readonly getTurnTraces?: (conversationId: number, options?: ConversationTurnTracesOptions) => Promise<ConversationTurnTraces>;\n readonly getMessageContextComposition?: (conversationId: number, messageId: number) => Promise<ConversationContextComposition>;\n readonly getFileChangeDiff?: (fileChangeId: number) => Promise<ConversationFileChangeDiff>;\n\n constructor(\n protected readonly binding: AgentsConversationClient,\n protected readonly polling: PollingConversationChangeSubscription,\n ) {\n // The optional functions exist exactly when the binding has them (the chat reads their presence).\n this.getSelectableModels = binding.getSelectableModels?.bind(binding);\n this.composeSentMessageText = binding.composeSentMessageText?.bind(binding);\n this.getMessageSentPayload = binding.getMessageSentPayload?.bind(binding);\n this.getConversationRunState = binding.getConversationRunState?.bind(binding);\n this.getAccountRealtimeMessages = binding.getAccountRealtimeMessages?.bind(binding);\n this.startPurpose = binding.startPurpose?.bind(binding);\n this.listConversationsOfSubject = binding.listConversationsOfSubject?.bind(binding);\n this.getConversationSubject = binding.getConversationSubject?.bind(binding);\n this.listSubjectsOfConversations = binding.listSubjectsOfConversations?.bind(binding);\n this.getTurnTraces = binding.getTurnTraces?.bind(binding);\n this.getMessageContextComposition = binding.getMessageContextComposition?.bind(binding);\n this.getFileChangeDiff = binding.getFileChangeDiff?.bind(binding);\n this.getStepConfirmation = binding.getStepConfirmation?.bind(binding);\n // A step the owner ran or discarded signals the conversation: the poller reads at once instead of waiting.\n const executeStepConfirmation = binding.executeStepConfirmation?.bind(binding);\n if (executeStepConfirmation) {\n this.executeStepConfirmation = async (conversationId: number, stepConfirmationId: number, contentHash: string): Promise<ConversationStepConfirmation> => {\n const stepConfirmation = await executeStepConfirmation(conversationId, stepConfirmationId, contentHash);\n this.polling.notifyLocalActivity(conversationId);\n return stepConfirmation;\n };\n }\n const discardStepConfirmation = binding.discardStepConfirmation?.bind(binding);\n if (discardStepConfirmation) {\n this.discardStepConfirmation = async (conversationId: number, stepConfirmationId: number): Promise<ConversationStepConfirmation> => {\n const stepConfirmation = await discardStepConfirmation(conversationId, stepConfirmationId);\n this.polling.notifyLocalActivity(conversationId);\n return stepConfirmation;\n };\n }\n // A stop the server accepted ends the turn: the poller reads at once instead of waiting for its interval.\n const stopTurn = binding.stopTurn?.bind(binding);\n if (stopTurn) {\n this.stopTurn = async (conversationId: number): Promise<ConversationTurnStop> => {\n const turnStop = await stopTurn(conversationId);\n this.polling.notifyLocalActivity(conversationId);\n return turnStop;\n };\n }\n // A job stop the server accepted changes the conversation's work: the poller reads at once as well.\n const stopBackgroundJob = binding.stopBackgroundJob?.bind(binding);\n if (stopBackgroundJob) {\n this.stopBackgroundJob = async (conversationId: number, backgroundJobId: number): Promise<ConversationBackgroundJobStop> => {\n const backgroundJobStop = await stopBackgroundJob(conversationId, backgroundJobId);\n this.polling.notifyLocalActivity(conversationId);\n return backgroundJobStop;\n };\n }\n }\n\n getConversationMetadata = (conversationId: number): Promise<AgentsConversation> =>\n this.binding.getConversationMetadata(conversationId);\n\n getNewestMessagesPage = (conversationId: number, pageSize: number): Promise<ConversationMessagesPage> =>\n this.binding.getNewestMessagesPage(conversationId, pageSize);\n\n getOlderMessagesPage = (conversationId: number, beforeIndex: number, pageSize: number): Promise<ConversationMessagesPage> =>\n this.binding.getOlderMessagesPage(conversationId, beforeIndex, pageSize);\n\n getChangedMessages = (conversationId: number, request: ChangedMessagesRequest): Promise<ChangedConversationMessages> =>\n this.binding.getChangedMessages(conversationId, request);\n\n startConversation = (request: Parameters<AgentsConversationClient[\"startConversation\"]>[0]): Promise<StartedConversation> =>\n this.binding.startConversation(request);\n\n postMessage = async (\n conversationId: number,\n message: { text: string; model?: string; attachments?: ConversationAttachmentReference[] },\n ): Promise<PostedMessage> => {\n const postedMessage = await this.binding.postMessage(conversationId, message);\n this.polling.notifyLocalActivity(conversationId);\n return postedMessage;\n };\n\n injectSignal = async (conversationId: number, signal: ConversationSignal): Promise<void> => {\n await this.binding.injectSignal(conversationId, signal);\n this.polling.notifyLocalActivity(conversationId);\n };\n\n retryConversation = async (conversationId: number): Promise<void> => {\n await this.binding.retryConversation(conversationId);\n this.polling.notifyLocalActivity(conversationId);\n };\n\n renameConversation = (conversationId: number, title: string): Promise<AgentsConversation> =>\n this.binding.renameConversation(conversationId, title);\n\n deleteConversation = (conversationId: number): Promise<void> => this.binding.deleteConversation(conversationId);\n\n listConversations = (agentSpaceKey: number, options?: ConversationListQueryOptions): Promise<AgentsConversation[]> =>\n this.binding.listConversations(agentSpaceKey, options);\n\n searchConversations = (text: string, options?: ConversationSearchOptions): Promise<ConversationSearchGroup[]> =>\n this.binding.searchConversations(text, options);\n\n searchConversationMessages = (\n conversationId: number,\n text: string,\n options?: ConversationSearchOptions,\n ): Promise<ConversationMessageSearchHit[]> => this.binding.searchConversationMessages(conversationId, text, options);\n\n getConversationActivity = (conversationId: number, turnMessageId?: number | null): Promise<ConversationActivity> =>\n this.binding.getConversationActivity(conversationId, turnMessageId);\n\n subscribeToConversationChanges = (\n conversationId: number,\n onSignal: (signal: ConversationChangeSignal) => void,\n onEnded: (reason: ConversationSubscriptionEndReason) => void,\n ): (() => void) => this.polling.subscribeToConversationChanges(conversationId, onSignal, onEnded);\n}\n\n/**\n * The client with live updates: a client that brings its own `subscribeToConversationChanges` (a push\n * transport — the host application's Firebase binding) is returned as it is; any other gets the polling default over its\n * `getConversationRunState` when it has one, else over its `getConversationMetadata`\n * (`createPollingConversationChangeSubscription`, `options` tune the intervals). A post, a signal or a retry the server\n * accepted reads at once. The default `AgentChat` calls this by itself.\n */\nexport const withPollingChangeSubscription = (\n client: AgentsConversationClient,\n options?: PollingConversationChangeSubscriptionOptions,\n): AgentsConversationClientWithChangeSubscription => {\n if (client.subscribeToConversationChanges) return client as AgentsConversationClientWithChangeSubscription;\n return new PollingAgentsConversationClient(\n client,\n createPollingConversationChangeSubscription(\n client.getConversationRunState ? client.getConversationRunState.bind(client) : client.getConversationMetadata.bind(client),\n options,\n ),\n );\n};\n"],"names":[],"mappings":";;AAWO,MAAM,8BAA8B;AAEpC,MAAM,2BAA2B;AAEjC,MAAM,yBAAyB;AAK/B,MAAM,mCAAmC;AA6DhD,MAAM,oBAA6C;AAAA,EAAnD,cAAA;AACE,SAAA,aAAa,CAAC,UAAsB,YAA6B,WAAW,WAAW,UAAU,OAAO;AAExG,SAAA,eAAe,CAAC,gBAA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