@athenaintel/react 0.60.1 → 0.61.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +157 -5
- package/dist/agent-ui/AgentTarget.cjs +11 -0
- package/dist/agent-ui/AgentTarget.cjs.map +1 -0
- package/dist/agent-ui/AgentTarget.d.ts +17 -0
- package/dist/agent-ui/AgentTarget.js +11 -0
- package/dist/agent-ui/AgentTarget.js.map +1 -0
- package/dist/agent-ui/AgentUiLayer.cjs +387 -0
- package/dist/agent-ui/AgentUiLayer.cjs.map +1 -0
- package/dist/agent-ui/AgentUiLayer.d.ts +40 -0
- package/dist/agent-ui/AgentUiLayer.js +387 -0
- package/dist/agent-ui/AgentUiLayer.js.map +1 -0
- package/dist/agent-ui/contract.cjs +104 -0
- package/dist/agent-ui/contract.cjs.map +1 -0
- package/dist/agent-ui/contract.d.ts +113 -0
- package/dist/agent-ui/contract.js +104 -0
- package/dist/agent-ui/contract.js.map +1 -0
- package/dist/agent-ui/driver.cjs +335 -0
- package/dist/agent-ui/driver.cjs.map +1 -0
- package/dist/agent-ui/driver.d.ts +66 -0
- package/dist/agent-ui/driver.js +335 -0
- package/dist/agent-ui/driver.js.map +1 -0
- package/dist/agent-ui/index.cjs +33 -0
- package/dist/agent-ui/index.cjs.map +1 -0
- package/dist/agent-ui/index.d.ts +19 -0
- package/dist/agent-ui/index.js +33 -0
- package/dist/agent-ui/index.js.map +1 -0
- package/dist/agent-ui/pace.cjs +121 -0
- package/dist/agent-ui/pace.cjs.map +1 -0
- package/dist/agent-ui/pace.d.ts +66 -0
- package/dist/agent-ui/pace.js +121 -0
- package/dist/agent-ui/pace.js.map +1 -0
- package/dist/agent-ui/screen.cjs +471 -0
- package/dist/agent-ui/screen.cjs.map +1 -0
- package/dist/agent-ui/screen.d.ts +97 -0
- package/dist/agent-ui/screen.js +471 -0
- package/dist/agent-ui/screen.js.map +1 -0
- package/dist/agent-ui/secret-fields.cjs +50 -0
- package/dist/agent-ui/secret-fields.cjs.map +1 -0
- package/dist/agent-ui/secret-fields.d.ts +15 -0
- package/dist/agent-ui/secret-fields.js +50 -0
- package/dist/agent-ui/secret-fields.js.map +1 -0
- package/dist/agent-ui/stage.cjs +196 -0
- package/dist/agent-ui/stage.cjs.map +1 -0
- package/dist/agent-ui/stage.d.ts +110 -0
- package/dist/agent-ui/stage.js +196 -0
- package/dist/agent-ui/stage.js.map +1 -0
- package/dist/agent-ui/tools.cjs +448 -0
- package/dist/agent-ui/tools.cjs.map +1 -0
- package/dist/agent-ui/tools.d.ts +103 -0
- package/dist/agent-ui/tools.js +448 -0
- package/dist/agent-ui/tools.js.map +1 -0
- package/dist/agent-ui/use-agent-target.cjs +63 -0
- package/dist/agent-ui/use-agent-target.cjs.map +1 -0
- package/dist/agent-ui/use-agent-target.d.ts +27 -0
- package/dist/agent-ui/use-agent-target.js +63 -0
- package/dist/agent-ui/use-agent-target.js.map +1 -0
- package/dist/agent-ui/use-agent-ui.cjs +15 -0
- package/dist/agent-ui/use-agent-ui.cjs.map +1 -0
- package/dist/agent-ui/use-agent-ui.d.ts +24 -0
- package/dist/agent-ui/use-agent-ui.js +15 -0
- package/dist/agent-ui/use-agent-ui.js.map +1 -0
- package/dist/chat/AthenaChat.cjs +17 -4
- package/dist/chat/AthenaChat.cjs.map +1 -1
- package/dist/chat/AthenaChat.d.ts +13 -0
- package/dist/chat/AthenaChat.js +17 -4
- package/dist/chat/AthenaChat.js.map +1 -1
- package/dist/chat/StatewireClientToolBridge.cjs +17 -12
- package/dist/chat/StatewireClientToolBridge.cjs.map +1 -1
- package/dist/chat/StatewireClientToolBridge.d.ts +4 -2
- package/dist/chat/StatewireClientToolBridge.js +17 -12
- package/dist/chat/StatewireClientToolBridge.js.map +1 -1
- package/dist/chat/StatewireClientToolConsentCard.cjs +3 -2
- package/dist/chat/StatewireClientToolConsentCard.cjs.map +1 -1
- package/dist/chat/StatewireClientToolConsentCard.d.ts +2 -1
- package/dist/chat/StatewireClientToolConsentCard.js +3 -2
- package/dist/chat/StatewireClientToolConsentCard.js.map +1 -1
- package/dist/chat/chat-voice-controls.cjs +5 -2
- package/dist/chat/chat-voice-controls.cjs.map +1 -1
- package/dist/chat/chat-voice-controls.d.ts +6 -1
- package/dist/chat/chat-voice-controls.js +6 -3
- package/dist/chat/chat-voice-controls.js.map +1 -1
- package/dist/chat/client-tool-write-consent.cjs +16 -5
- package/dist/chat/client-tool-write-consent.cjs.map +1 -1
- package/dist/chat/client-tool-write-consent.d.ts +12 -4
- package/dist/chat/client-tool-write-consent.js +16 -5
- package/dist/chat/client-tool-write-consent.js.map +1 -1
- package/dist/chat-ui/messages/message-components.cjs +1 -1
- package/dist/chat-ui/messages/message-components.cjs.map +1 -1
- package/dist/chat-ui/messages/message-components.d.ts +2 -2
- package/dist/chat-ui/messages/message-components.js +1 -1
- package/dist/chat-ui/messages/message-components.js.map +1 -1
- package/dist/index.cjs +7 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +6 -0
- package/dist/index.js +7 -0
- package/dist/index.js.map +1 -1
- package/dist/provider/AthenaProvider.cjs +37 -8
- package/dist/provider/AthenaProvider.cjs.map +1 -1
- package/dist/provider/AthenaProvider.d.ts +18 -1
- package/dist/provider/AthenaProvider.js +33 -4
- package/dist/provider/AthenaProvider.js.map +1 -1
- package/dist/react/package.json.cjs +1 -1
- package/dist/react/package.json.js +1 -1
- package/dist/styles.css +1 -1
- package/package.json +6 -1
|
@@ -35,8 +35,11 @@ import { StatewireThreadConfigLaneSync } from "../runtime/StatewireThreadConfigL
|
|
|
35
35
|
import { AthenaStatewireServerLaneContext, STATEWIRE_SERVER_LANE_PENDING, nextServerLane } from "../runtime/statewire-server-lane-context.js";
|
|
36
36
|
import { installAthenaDiagnosticsGlobal, athenaDiagnostics, debugPropToDiagnosticsConfig } from "../diagnostics/athena-diagnostics.js";
|
|
37
37
|
import { AthenaSdkError } from "../diagnostics/errors.js";
|
|
38
|
-
import { backendDeclaredFrontendToolIds, clientToolWriteConsentSummaries, resolveClientToolSurface } from "../chat/statewire-client-tools.js";
|
|
38
|
+
import { backendDeclaredFrontendToolIds, requiresWriteConsent, clientToolWriteConsentSummaries, resolveClientToolSurface } from "../chat/statewire-client-tools.js";
|
|
39
39
|
import { useClientToolWriteConsentStore, ClientToolWriteConsentContext } from "../chat/client-tool-write-consent.js";
|
|
40
|
+
import { AgentUiLayer } from "../agent-ui/AgentUiLayer.js";
|
|
41
|
+
import { AGENT_UI_TOOL_NAMES, AGENT_UI_ACT_SUMMARY } from "../agent-ui/tools.js";
|
|
42
|
+
import { useAgentUi } from "../agent-ui/use-agent-ui.js";
|
|
40
43
|
import { TooltipProvider } from "../ui/tooltip.js";
|
|
41
44
|
import { DEFAULT_AUTO_OPEN_TOOLS } from "../tools/auto-open-tools.js";
|
|
42
45
|
import { AthenaContext } from "./AthenaContext.js";
|
|
@@ -59,6 +62,8 @@ import { DeepAgentConnectionContext } from "../agent-runtime/src/thread-status.j
|
|
|
59
62
|
import { DeepAgentChatOutboxContext, useDeepAgentChatOutbox } from "../agent-runtime/src/use-deep-agent-chat-outbox.js";
|
|
60
63
|
import { documentVisibleSignal, browserOnlineSignal, allChatOutboxSignals } from "../agent-runtime/src/chat-outbox-signals.js";
|
|
61
64
|
import { readServerConfig } from "../agent-runtime/src/use-deep-agent-config.js";
|
|
65
|
+
const EMPTY_AGENT_UI_OPTIONS = {};
|
|
66
|
+
const EMPTY_TOOLKIT = {};
|
|
62
67
|
const resolveTokenOverride = ({
|
|
63
68
|
config,
|
|
64
69
|
token
|
|
@@ -391,6 +396,7 @@ function AthenaStatewireStandalone({
|
|
|
391
396
|
citationLinks,
|
|
392
397
|
modes,
|
|
393
398
|
confirmClientToolWrites,
|
|
399
|
+
clientToolConsentAgentName,
|
|
394
400
|
...runtimeProps
|
|
395
401
|
}) {
|
|
396
402
|
const generatedIdRef = useRef(null);
|
|
@@ -477,6 +483,7 @@ function AthenaStatewireStandalone({
|
|
|
477
483
|
tools: clientTools,
|
|
478
484
|
threadId: published.threadId,
|
|
479
485
|
writeConsentSummaries,
|
|
486
|
+
writeConsentAgentName: clientToolConsentAgentName,
|
|
480
487
|
confirmWrites: confirmClientToolWrites
|
|
481
488
|
}
|
|
482
489
|
),
|
|
@@ -636,6 +643,7 @@ function AthenaProvider({
|
|
|
636
643
|
tools = [],
|
|
637
644
|
frontendTools = {},
|
|
638
645
|
confirmClientToolWrites,
|
|
646
|
+
agentUi: agentUiProp = false,
|
|
639
647
|
disableAutoOpen = false,
|
|
640
648
|
apiUrl,
|
|
641
649
|
backendUrl,
|
|
@@ -710,9 +718,26 @@ function AthenaProvider({
|
|
|
710
718
|
() => backendDeclaredFrontendToolIds(frontendTools),
|
|
711
719
|
[frontendTools]
|
|
712
720
|
);
|
|
721
|
+
const agentUiEnabled = agentUiProp === true || typeof agentUiProp === "object" && agentUiProp !== null;
|
|
722
|
+
const { classNames: agentUiClassNames, ...agentUiOptions } = typeof agentUiProp === "object" && agentUiProp !== null ? agentUiProp : EMPTY_AGENT_UI_OPTIONS;
|
|
723
|
+
const agentUiActConsent = agentUiOptions.actConsent ?? "host";
|
|
724
|
+
const agentUiHost = useAgentUi({ ...agentUiOptions, actConsent: agentUiActConsent });
|
|
725
|
+
const agentUiTools = useMemo(() => {
|
|
726
|
+
if (!agentUiEnabled) return EMPTY_TOOLKIT;
|
|
727
|
+
const act = agentUiHost.tools[AGENT_UI_TOOL_NAMES.actOn];
|
|
728
|
+
if (!act || agentUiActConsent !== "host") return agentUiHost.tools;
|
|
729
|
+
return {
|
|
730
|
+
...agentUiHost.tools,
|
|
731
|
+
[AGENT_UI_TOOL_NAMES.actOn]: requiresWriteConsent(act, { summary: AGENT_UI_ACT_SUMMARY })
|
|
732
|
+
};
|
|
733
|
+
}, [agentUiActConsent, agentUiEnabled, agentUiHost.tools]);
|
|
713
734
|
const effectiveFrontendTools = useMemo(
|
|
714
|
-
() =>
|
|
715
|
-
|
|
735
|
+
() => ({
|
|
736
|
+
...disableAutoOpen ? {} : DEFAULT_AUTO_OPEN_TOOLS,
|
|
737
|
+
...agentUiTools,
|
|
738
|
+
...frontendTools
|
|
739
|
+
}),
|
|
740
|
+
[agentUiTools, disableAutoOpen, frontendTools]
|
|
716
741
|
);
|
|
717
742
|
const themeStyleVars = useMemo(() => theme ? themeToStyleVars(theme) : void 0, [theme]);
|
|
718
743
|
const configuredEnvironment = (config == null ? void 0 : config.environment) ?? environment;
|
|
@@ -938,6 +963,7 @@ function AthenaProvider({
|
|
|
938
963
|
frontendToolIds: frontendToolNames,
|
|
939
964
|
frontendTools: effectiveFrontendTools,
|
|
940
965
|
confirmClientToolWrites,
|
|
966
|
+
clientToolConsentAgentName: agentUiEnabled ? agentUiOptions.agentName : void 0,
|
|
941
967
|
workbench,
|
|
942
968
|
knowledgeBase,
|
|
943
969
|
systemPrompt,
|
|
@@ -983,7 +1009,10 @@ function AthenaProvider({
|
|
|
983
1009
|
{
|
|
984
1010
|
className: themeStyleVars ? "athena-sdk athena-themed" : "athena-sdk",
|
|
985
1011
|
style: themeStyleVars,
|
|
986
|
-
children: /* @__PURE__ */ jsx(PostHogProvider, { config: posthogConfig, children: /* @__PURE__ */ jsx(ComposerHandoffContext.Provider, { value: composerHandoff, children: /* @__PURE__ */ jsx(StatewireSessionLaneContext.Provider, { value: sessionLane, children: /* @__PURE__ */
|
|
1012
|
+
children: /* @__PURE__ */ jsx(PostHogProvider, { config: posthogConfig, children: /* @__PURE__ */ jsx(ComposerHandoffContext.Provider, { value: composerHandoff, children: /* @__PURE__ */ jsx(StatewireSessionLaneContext.Provider, { value: sessionLane, children: /* @__PURE__ */ jsxs(AthenaThemeStyleContext.Provider, { value: themeStyleVars, children: [
|
|
1013
|
+
agentUiEnabled ? /* @__PURE__ */ jsx(AgentUiLayer, { agentUi: agentUiHost.agentUi, classNames: agentUiClassNames }) : null,
|
|
1014
|
+
/* @__PURE__ */ jsx(AthenaCredentialSourceContext.Provider, { value: credentials, children: /* @__PURE__ */ jsx(AthenaAgentSelectionContext.Provider, { value: agentSelection, children: /* @__PURE__ */ jsx(AthenaOfflineSnapshotsContext.Provider, { value: offlineSnapshots, children: /* @__PURE__ */ jsx(AthenaDataQueryClientProvider, { children: awaitingKeptSnapshots ? null : inner }) }) }) })
|
|
1015
|
+
] }) }) }) })
|
|
987
1016
|
}
|
|
988
1017
|
);
|
|
989
1018
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AthenaProvider.js","sources":["../../src/provider/AthenaProvider.tsx"],"sourcesContent":["import { AuiConfig, AuiProvider, useAui } from '@assistant-ui/react';\nimport {\n useCallback,\n useContext,\n useEffect,\n useLayoutEffect,\n useMemo,\n useReducer,\n useRef,\n useState,\n type ReactNode,\n} from 'react';\nimport type { AssistantClient, Toolkit } from '@assistant-ui/react';\nimport {\n allChatOutboxSignals,\n browserOnlineSignal,\n type ChatOutbox,\n type ChatOutboxAttachmentCheck,\n type ChatOutboxSignal,\n chatOutboxAttachmentPath,\n createChatOutboxAttachmentCheck,\n clearDeepAgentHistoryStores,\n createDeepAgentThreadSnapshotCache,\n createDeepAgentToolOutputStore,\n createDurableThreadSnapshotCache,\n createThreadSnapshotMirror,\n DeepAgentChatOutboxContext,\n DeepAgentConnectionContext,\n type DeepAgentThreadSnapshotCache,\n type DeepAgentToolOutputStore,\n documentVisibleSignal,\n readServerConfig,\n type ThreadSnapshotMirror,\n useDeepAgentChatOutbox,\n} from '@athenaintel/agent-runtime';\nimport { giveBackDeepAgentOutboxNamedAgents } from '@athenaintel/agent-runtime/named-agents';\nimport {\n type AthenaOfflineHistory,\n type AthenaOfflineSnapshots,\n AthenaOfflineSnapshotsContext,\n useKeptSnapshotsGate,\n} from '../offline/offline-history';\nimport {\n type AthenaChatOutbox,\n type AthenaChatSessionKeeping,\n type ChatOutboxOwnerStorage,\n chatOutboxStorageFor,\n resolveChatSessionKeeping,\n} from '../offline/chat-outbox';\nimport {\n assertHostMintedStatewireMount,\n deriveAthenaAppUrl,\n getAthenaEnvironmentUrls,\n resolveStatewireSyncUrl,\n type AthenaEnvironment,\n} from '../lib/athena-urls';\nimport { getAthenaApiBaseUrl } from '../collab/mint';\nimport { useParentBridge } from '../runtime/auth';\nimport { AthenaAuthContext } from '../auth/AthenaAuthContext';\nimport { AthenaCredentialSourceContext } from '../auth/AthenaCredentialSourceContext';\nimport { AthenaDataQueryClientProvider } from '../data/athena-data-client';\nimport {\n createAthenaCredentialSource,\n type AthenaCredentialInputs,\n} from '../auth/credential-source';\nimport { useRestartAfterAuthRefusal } from '../runtime/auth-refusal-restart';\nimport {\n useAthenaStatewireRuntime,\n useStatewireClientTools,\n} from '../runtime/useAthenaStatewireRuntime';\nimport { statewireSessionPrincipal } from '../runtime/statewire-session-key';\nimport {\n createStatewireSessionLaneGate,\n StatewireSessionLaneContext,\n type StatewireSessionLaneGate,\n} from '../runtime/statewire-session-lane';\nimport {\n athenaStatewireErrorNotice,\n type AthenaStatewireLifecycleState,\n initialStatewireLifecycle,\n isStatewireChannelLive,\n statewireLifecycleReducer,\n} from '../runtime/statewire-lifecycle';\nimport type { AthenaStatewireTokenGetter, StatewireAuthSource } from '../runtime/statewire-auth-headers';\nimport { sendWithCredentialRenewal } from '../runtime/credential-renewal';\nimport { effectiveStatewireStartChannel, resolveAgentProp } from '../runtime/statewire-run-config';\nimport {\n type ProviderThreadConfig,\n providerThreadConfig,\n} from '../runtime/statewire-thread-config-lane';\nimport { mintThreadId } from '../threads/mint-thread-id';\nimport { AthenaStatewireLifecycleContext } from './statewire-lifecycle-context';\nimport {\n ComposerHandoffContext,\n applyComposerWrite,\n clearComposerHandoff,\n createComposerHandoffStore,\n drainComposerHandoff,\n rememberRestoredAttachments,\n useComposerHandoffStore,\n useComposerReady,\n} from '../composer/composer-handoff';\nimport { giveBackHeldAttachedReferences } from '../composer/attached-references';\nimport { keepDraftForSignBackIn, takeDraftKeptForSignBackIn } from '../composer/sign-back-in-draft';\nimport {\n ATHENA_SIGN_BACK_IN_EVENT,\n bridgeOwnsCredential,\n restoreSignBackInHash,\n} from '../auth/sign-back-in';\nimport {\n createStatewireHistoryStore,\n StatewireHistoryContext,\n type StatewireHistoryStore,\n} from './statewire-history-context';\nimport { EarlierStepsButton } from '../chat/super-grouping/earlier-steps-button';\nimport { TurnStepsControlContext } from '../chat/super-grouping/use-turn-steps';\nimport { StatewireToolOutputsContext } from './statewire-window-context';\nimport { StatewireClientToolBridge } from '../chat/StatewireClientToolBridge';\nimport { StatewirePlanModeLaneSync } from '../runtime/StatewirePlanModeLaneSync';\nimport { StatewireThreadConfigLaneSync } from '../runtime/StatewireThreadConfigLaneSync';\nimport {\n type AthenaStatewireServerLane,\n AthenaStatewireServerLaneContext,\n nextServerLane,\n STATEWIRE_SERVER_LANE_PENDING,\n} from '../runtime/statewire-server-lane-context';\nimport {\n athenaDiagnostics,\n debugPropToDiagnosticsConfig,\n installAthenaDiagnosticsGlobal,\n type AthenaDiagnosticEvent,\n type AthenaDiagnosticLevel,\n type AthenaDiagnosticsConfig,\n} from '../diagnostics/athena-diagnostics';\nimport { AthenaSdkError } from '../diagnostics/errors';\nimport {\n backendDeclaredFrontendToolIds,\n clientToolWriteConsentSummaries,\n resolveClientToolSurface,\n} from '../chat/statewire-client-tools';\nimport {\n type ClientToolWriteConfirmer,\n ClientToolWriteConsentContext,\n useClientToolWriteConsentStore,\n} from '../chat/client-tool-write-consent';\nimport { TooltipProvider } from '../ui/tooltip';\nimport { DEFAULT_AUTO_OPEN_TOOLS } from '../tools/auto-open-tools';\nimport { AthenaContext, type AthenaConfig } from './AthenaContext';\nimport { type AthenaAgentSelection, AthenaAgentSelectionContext } from './agent-selection-context';\nimport { type AthenaChatModeSelection, AthenaChatModeSelectionContext } from './chat-mode-context';\nimport type { AthenaProviderConfig } from './config';\nimport {\n AthenaSessionPersistenceContext,\n type AthenaSessionPersistence,\n} from './session-persistence-context';\nimport type {\n AthenaCitationLinkOptions,\n AthenaLinkClickOptions,\n} from './citation-links';\nimport {\n AthenaStatewireThreadIdContext,\n AthenaThreadIdContext,\n useAthenaStatewireThreadId,\n} from '../threads/thread-id-context';\nimport {\n AthenaStatewireThreadListContext,\n AthenaStatewireThreadListProvider,\n StatewireThreadListSendSync,\n StatewireThreadTitlePoller,\n useAthenaStatewireThreadList,\n} from '../threads/statewire-thread-list';\nimport { type AssetOpener, useAssetPanelStore } from '../assets/asset-panel-store';\nimport { themeToStyleVars, type AthenaTheme } from '../theme';\nimport { AthenaThemeStyleContext } from './theme-style-context';\nimport { PostHogProvider, type PostHogConfig } from './PostHogProvider';\n\nexport interface AthenaProviderProps {\n children: ReactNode;\n\n /** Preferred structured config for auth and Athena endpoint settings. */\n config?: AthenaProviderConfig;\n\n /** @deprecated Prefer `config.apiKey`. API key for authentication in standalone mode. */\n apiKey?: string;\n\n /** @deprecated Prefer `config.token`. PropelAuth token. If provided, takes priority over apiKey. If omitted, the SDK\n * will automatically listen for a token from the parent window via PostMessage. */\n token?: string | null;\n\n /** Run the thread AS a published collab agent. The only accepted shape is\n * `collab_agent:<asset_id>`: the thread then uses that agent's prompt,\n * tools, and model default, and the caller must have view access to the\n * agent asset. Omit it (or pass a blank string) to run the Athena deep agent.\n *\n * Any other non-blank value throws at render — the statewire host cannot\n * honour named agents, and a selector that is silently dropped would let a\n * misconfigured deployment answer as the wrong agent. */\n agent?: string;\n\n /** Collab-agent channel id — a built-in channel (`email`, `sms`, …) or a\n * user-defined custom channel id from the agent's Channels tab. Selects\n * that channel's configuration overrides and stamps the session's origin.\n * Only meaningful together with a `collab_agent:<asset_id>` `agent`; sent\n * as `collab_channel_id`. An unknown or disabled channel rejects the run\n * with a structured, teaching error. */\n channel?: string;\n\n /** The agent's modes people can switch between in this chat, by id: `base`\n * (the agent as configured) or a mode's id from the agent's Modes tab.\n * `AthenaChat` shows a mode menu in its composer with the ones the agent's\n * published definition offers on `channel` (its start mode, the channel\n * itself, and the modes its author lists for it); `useAthenaChatMode`\n * drives a menu of your own. A pick applies to the open session's next\n * send. On a channel the author locks, people pick the mode before a\n * session's first message and it stays. Only meaningful with a collab\n * `agent`; omit it for no menu. */\n modes?: readonly string[];\n\n /** LLM model identifier. Defaults to the deep-agent default model\n * (`DEFAULT_STATEWIRE_MODEL`) — or, when a collab agent is selected, to\n * the model its author configured.\n *\n * Changing it while a thread is open applies to that thread's next turn:\n * on a thread whose server config already exists the SDK writes the new\n * model there (`undefined` clears it, so the agent's model applies). The\n * value a thread is opened with is not written; read the thread's own\n * model with `useAthenaThreadModel`. */\n model?: string;\n\n /** Backend toolkit IDs to enable (e.g. 'document_toolkit', 'web_search_browse_toolkit').\n *\n * Sent with the backend-bound `frontendTools` as `enabled_tools`. Like\n * `model`, a change while a thread is open applies to its next turn: on a\n * thread whose server config exists the SDK writes the new list there (an\n * empty list clears it, so a collab agent's own tools apply). The list a\n * thread is opened with is not written. */\n tools?: string[];\n\n /** Frontend tools that execute in the browser. The agent can invoke these.\n * Merged on top of the SDK's default auto-open tools; entries here take\n * precedence over defaults with the same name. Tools with a local\n * `execute` are declared to the backend as `client_tools` and run through\n * the statewire client-tool bridge. */\n frontendTools?: Toolkit;\n\n /** Your own consent UI for frontend tools marked `requiresWriteConsent`,\n * in place of the card `AthenaChat` draws. Called before such a tool's\n * first call in a conversation runs; resolve `true` to allow that\n * conversation's writes, `false` to decline the waiting calls. Its `signal`\n * aborts when the question no longer has a call to answer. */\n confirmClientToolWrites?: ClientToolWriteConfirmer;\n\n /** Disable the SDK's default auto-open behavior for created/touched assets. */\n disableAutoOpen?: boolean;\n\n /** @deprecated Prefer `config.apiUrl`. URL on the Iris host fronting the\n * deployment; its origin derives the statewire sync mount when\n * `statewireSyncUrl` is not set. */\n apiUrl?: string;\n\n /** @deprecated Prefer `config.backendUrl`. URL for the Athena backend API. */\n backendUrl?: string;\n\n /** @deprecated Prefer `config.appUrl`. URL for the Athena frontend app origin. */\n appUrl?: string;\n\n /** @deprecated Prefer `config.environment`. Athena environment preset used when URLs are not explicitly provided. */\n environment?: AthenaEnvironment;\n\n /** Resolve the latest auth token immediately before a request (for\n * expiring clients). Takes priority over `token` when it resolves.\n * Prefer `config.getToken` (see its `force` contract for refused\n * credentials). */\n getToken?: AthenaStatewireTokenGetter;\n\n /** Additional fields merged into runConfig.custom. Prefer\n * `config.extraRunConfig`. */\n extraRunConfig?: Record<string, unknown>;\n\n /** Statewire sync base URL override (the `…/v2/threads` mount). Defaults to\n * the mount a Marathon host mints, then the effective `apiUrl` host +\n * `/v2/threads`. Prefer `config.statewireSyncUrl`. */\n statewireSyncUrl?: string;\n\n /** Asset IDs to include in the workbench. A change while a thread is open\n * is written to its server config, as `model` is (empty clears it). */\n workbench?: string[];\n\n /** Knowledge base IDs for RAG context. A change while a thread is open is\n * written to its server config, as `model` is (empty clears it). */\n knowledgeBase?: string[];\n\n /** System prompt override. A change while a thread is open is written to\n * its server config, as `model` is (blank clears it, so a collab agent's\n * own prompt applies). */\n systemPrompt?: string;\n\n /** Plan mode: whether the agent keeps a to-do plan for multi-step work and\n * checks its steps off as it goes (the `write_todos` tool and its planning\n * prompt), which `AthenaChat` shows above the composer (`AthenaPlanStrip`).\n * `false` runs without one, `true` with one; omit it to leave each\n * thread's own setting (a thread plans unless its config says otherwise).\n *\n * Like `model`, changing it while a thread is open applies to that\n * thread's next turn: on a thread whose server config exists the SDK\n * writes it there (only the `write_todos` and `TodoListMiddleware`\n * entries of its exclusion lists change). The value a thread is opened\n * with is not written; read the thread's own with\n * `useAthenaThreadPlanMode`. A collab agent whose author turned its\n * built-in tools off never plans: a run can only narrow what an agent may\n * use. */\n planMode?: boolean;\n\n /** Client app identifier for session filtering.\n * Sessions created with this ID can be filtered in the thread list.\n * E.g. \"olympus\", \"athena-app\", or a computer asset ID like \"asset_<uuid>\". */\n appId?: string;\n\n /** Thread ID override. Auto-generated if not provided. */\n threadId?: string;\n\n /**\n * With `threadId` and no thread list: the host minted that id\n * (`mintThreadId`) for a chat that has not started, which attaches as a new\n * chat until this turns false. Turn it false once the backend lists the\n * thread (a host showing several chats keeps each one's id across a remount\n * this way). Default `false`: a given `threadId` names an existing thread.\n */\n threadIsNew?: boolean;\n\n /** Enable thread list management (sidebar thread switching). */\n enableThreadList?: boolean;\n\n /** Ask the thread list for live pull-request state on each session\n * (`include_pull_requests`), which `SessionList` renders as chips.\n * Defaults to `true` in thread-list mode; turn it off in a host that never\n * shows them to spare the server the lookup. */\n threadListIncludePullRequests?: boolean;\n\n /** Other client apps whose sessions the thread list shows beside this\n * provider's own (`appId`), e.g. a desktop app listing the sessions of the\n * desktop app it replaced. New sessions are still tagged `appId`. */\n threadListAdditionalAppIds?: readonly string[];\n\n /** Make this app the home of its collab `agent`: the thread list also shows\n * the conversations people have with the agent anywhere else (Slack, email,\n * SMS, …) that the viewer can already open, beside this provider's own\n * (`appId`), and a new one appears while the app is open. Needs\n * `enableThreadList` and a `collab_agent:<asset_id>` `agent`; without\n * either it does nothing. Athena widens the list only while the agent has a\n * home app set and the viewer can open the agent; an Athena that predates\n * the setting lists the app's sessions alone. New sessions are still tagged\n * `appId`. Default `false`. */\n threadListAgentHome?: boolean;\n\n /** Theme configuration. Pass a preset from `themes` or a custom `AthenaTheme` object.\n * Injects CSS variables on a wrapper element — no CSS files needed.\n *\n * @example\n * import { themes } from '@athenaintel/react';\n * <AthenaProvider theme={themes.dark}>\n *\n * @example\n * <AthenaProvider theme={{ primary: '#8b5cf6', radius: '1rem' }}>\n *\n * @example\n * <AthenaProvider theme={{ ...themes.dark, primary: '#22c55e' }}>\n */\n theme?: AthenaTheme;\n\n /** Customize how rendered chat links behave. */\n linkClicks?: AthenaLinkClickOptions;\n\n /** @deprecated Prefer `linkClicks`. Customize how Athena citation links rendered in chat messages behave. */\n citationLinks?: AthenaCitationLinkOptions;\n\n /** Opens assets the host's own way (a desktop app's tabs, a route of its own). While set, every\n * request to open an asset goes here before the SDK's asset panel: a tool card's Open, an\n * Athena citation or asset link in a message (which the SDK then intercepts as it does with an\n * asset panel mounted), and the auto-open after a tool created or touched an asset\n * (`origin: 'auto'`, with `autoOpen` saying which tool, and whether it made the asset, opened it\n * for the person or only touched it). Return `false` to let the panel open it as before. */\n onOpenAsset?: AssetOpener;\n\n /** PostHog analytics configuration. When omitted or keys are missing, PostHog is silently disabled.\n * Prefer `config.posthog` for structured configuration. */\n posthog?: PostHogConfig;\n\n /** SDK diagnostics.\n *\n * - `true` / a level: echo structured `[AthenaSDK]` events to the console\n * at that level (`true` = 'debug').\n * - An object: full diagnostics config (console level, PostHog timing\n * forwarding, buffer size).\n *\n * Independent of the prop, `localStorage.setItem('athena:debug','debug')`\n * (or `window.__ATHENA_SDK__.diagnostics.enableConsole()`) turns console\n * echo on at runtime without a rebuild. Errors log once even when off. */\n debug?: boolean | AthenaDiagnosticLevel | Partial<AthenaDiagnosticsConfig>;\n\n /** Receives every diagnostics event (timings, warnings, errors) — the hook\n * for shipping SDK telemetry to the host app's own pipeline. */\n onDiagnostic?: (event: AthenaDiagnosticEvent) => void;\n\n /** Receives every SDK error as a typed `AthenaSdkError` (stable `code`,\n * `hint`, structured server `detail`). Fires in addition to the UI's own\n * error handling, so integrations never fail silently. */\n onError?: (error: AthenaSdkError, event: AthenaDiagnosticEvent) => void;\n\n /** Opt-in: keep recent conversations and the session list on this device,\n * sealed with the host's key, readable while Athena can't be reached\n * (see {@link AthenaOfflineHistory}). Whether to keep anything is decided\n * at mount; without it nothing is stored. Passing none later (a policy\n * that now keeps nothing on devices) deletes what was kept. */\n offlineHistory?: AthenaOfflineHistory;\n\n /** Opt-in: messages typed while Athena can't be reached wait on this device, sealed with the\n * host's key, and are sent once Athena is back while the app is in front, after a countdown\n * (see {@link AthenaChatOutbox}). Without it a send goes to the transport as before. */\n chatOutbox?: AthenaChatOutbox;\n\n /** Opt-in: the chat loads a subagent's earlier steps, as the transcript drawer of\n * `AthenaChat`'s subagent lanes does (\"Load earlier steps\"). Turn it on when every `task` call\n * your chat shows renders in those lanes (`AthenaChat` with the registry's `task`,\n * `SubagentTaskToolUI`): the provider then declares the deep-agent lane-cut contract\n * (protocol 2), so Athena sends a finished subagent's card with only its newest steps, as it\n * sends a running one, and the drawer reads the rest. Off by default, so a chat that renders `task` with a UI of its own,\n * or reads every step off the card (`artifact.subgraph_state.messages`), keeps receiving\n * finished subagents whole. Read when a thread attaches. */\n subagentLaneHistory?: boolean;\n}\n\nconst resolveTokenOverride = ({\n config,\n token,\n}: {\n config?: AthenaProviderConfig;\n token?: string | null;\n}): string | null | undefined => {\n if (config?.token !== undefined) {\n return config.token;\n }\n return token;\n};\n\nconst useAthenaConfigValue = ({\n backendUrl,\n appUrl,\n apiKey,\n token,\n getToken,\n enabledToolkits,\n linkClicks,\n citationLinks,\n}: {\n backendUrl: string;\n appUrl: string;\n apiKey?: string;\n token?: string | null;\n getToken?: AthenaStatewireTokenGetter;\n enabledToolkits: string[];\n linkClicks?: AthenaLinkClickOptions;\n citationLinks?: AthenaCitationLinkOptions;\n}): AthenaConfig => {\n const linkClicksRef = useRef(linkClicks);\n linkClicksRef.current = linkClicks;\n const citationLinksRef = useRef(citationLinks);\n citationLinksRef.current = citationLinks;\n // Keep token in a ref so its value can update without invalidating the\n // config object identity. PropelAuth rotates tokens on window focus —\n // if token were a memo dep, every rotation would publish a new config\n // object to context and force every consumer (e.g. AssetIframe) to\n // re-render, causing asset panel flicker.\n const tokenRef = useRef(token);\n tokenRef.current = token;\n const getTokenRef = useRef(getToken);\n getTokenRef.current = getToken;\n\n return useMemo(\n () => ({\n backendUrl,\n appUrl,\n apiKey,\n enabledToolkits,\n get token() {\n return tokenRef.current;\n },\n get getToken() {\n return getTokenRef.current;\n },\n get linkClicks() {\n return linkClicksRef.current;\n },\n get citationLinks() {\n return citationLinksRef.current;\n },\n }),\n [backendUrl, appUrl, apiKey, enabledToolkits],\n );\n};\n\n/**\n * Delivers composer writes that were made before this mount was ready\n * (`useAppendToComposer` / `useSendMessage` queue them in the provider-level\n * store, which outlives the keyed per-thread mount). Lives under the\n * `AuiProvider` so it can read the thread's own loading state.\n */\nfunction ComposerHandoffDrain(): null {\n const aui = useAui();\n const store = useComposerHandoffStore();\n const threadId = useContext(AthenaStatewireThreadIdContext);\n const ready = useComposerReady();\n useEffect(() => {\n if (!ready || !store) return;\n // Writes bound to another thread are dropped here, not applied.\n drainComposerHandoff({ store, target: aui, threadId });\n }, [aui, ready, store, threadId]);\n return null;\n}\n\n/**\n * Keeps the composer's draft across the SDK's own trip through sign-in (a\n * session that ended while the page was open, `auth/sign-back-in.ts`): kept\n * when the page leaves, put back once this person's same conversation is ready\n * on the page that returns (`composer/sign-back-in-draft.ts`). Only for a\n * person a sign-in provider names; with none, nothing is kept.\n */\nfunction ComposerDraftCarry({ isNewChat }: { isNewChat: boolean }): null {\n const aui = useAui();\n const threadId = useContext(AthenaStatewireThreadIdContext);\n const principal = statewireSessionPrincipal(useContext(AthenaAuthContext));\n const ready = useComposerReady();\n useEffect(() => {\n if (!principal || !threadId) return;\n const keep = () => {\n keepDraftForSignBackIn({\n principal,\n threadId,\n isNewChat,\n text: aui.composer.getState().text ?? '',\n });\n };\n window.addEventListener(ATHENA_SIGN_BACK_IN_EVENT, keep);\n return () => window.removeEventListener(ATHENA_SIGN_BACK_IN_EVENT, keep);\n }, [aui, principal, threadId, isNewChat]);\n useEffect(() => {\n if (!ready || !principal || !threadId) return;\n const kept = takeDraftKeptForSignBackIn({ principal, threadId, isNewChat });\n if (kept === null) return;\n void applyComposerWrite({\n target: aui,\n store: null,\n write: { text: kept, replace: false, send: false, focus: false, threadId },\n });\n }, [aui, ready, principal, threadId, isNewChat]);\n return null;\n}\n\n// ─── Standalone Mode ──────────────────────────────────────────────────\n\nconst EMPTY_MODES: readonly string[] = [];\n\n/** How long one read of a waiting message's attachment may take (the outbox bounds the whole check too). */\nconst CHAT_OUTBOX_ATTACHMENT_READ_TIMEOUT_MS = 10_000;\n\n/** A provider whose chat outbox has not read its owner's write key yet: every session waits. */\nconst CHAT_SESSION_KEEPING_PENDING: AthenaChatSessionKeeping = { kind: 'pending' };\n\n/** `record` with `key` set to `value` (`null` drops it); the same object when nothing changes. */\nfunction withEntry(\n record: Readonly<Record<string, string>>,\n key: string,\n value: string | null,\n): Readonly<Record<string, string>> {\n if (value === null) {\n if (!(key in record)) return record;\n const { [key]: _dropped, ...rest } = record;\n return rest;\n }\n return record[key] === value ? record : { ...record, [key]: value };\n}\n\n/** Everything the per-thread runtime needs to attach and run a thread. */\ninterface AthenaStatewireRuntimeProps {\n syncUrl: string;\n apiKey?: string;\n token?: string | null;\n getToken?: AthenaStatewireTokenGetter;\n model?: string;\n agent?: string;\n channel?: string;\n /** The mode picked for this thread (`AthenaProviderProps.modes`). */\n mode?: string;\n tools: string[];\n frontendToolIds: string[];\n frontendTools: Toolkit;\n workbench?: string[];\n knowledgeBase?: string[];\n systemPrompt?: string;\n appId?: string;\n extraRunConfig?: Record<string, unknown>;\n /** `AthenaProviderProps.planMode`. */\n planMode?: boolean;\n /** The provider-owned snapshot cache (see `AthenaProvider`). */\n snapshotCache: DeepAgentThreadSnapshotCache;\n /** The provider-owned store of fetched-back cut tool outputs (see `AthenaProvider`). */\n toolOutputs: DeepAgentToolOutputStore;\n /** Where the open thread's windowed history stands (`StatewireHistoryContext`). */\n historyStore: StatewireHistoryStore;\n /** The provider's chat outbox host (`chatOutbox`), or `null` when the host keeps none. */\n chatOutbox?: AthenaStatewireChatOutboxHost | null;\n /** The provider-owned session lane gate the mounted runtime reports its lane to (see `AthenaProvider`). */\n sessionLane: StatewireSessionLaneGate;\n /** `AthenaProviderProps.subagentLaneHistory`. */\n subagentLaneHistory: boolean;\n}\n\n/** The chat outbox as the per-thread mount takes it: the owner's storage and the host's signals. */\ninterface AthenaStatewireChatOutboxHost {\n storage: ChatOutboxOwnerStorage;\n /** Where the thread's session lives (`pending` until the owner's write key is read). */\n keeping: AthenaChatSessionKeeping;\n reachability?: ChatOutboxSignal;\n foreground?: ChatOutboxSignal;\n /** Asks Athena, as the person, whether a waiting message's attachments can still be opened. */\n checkAttachments?: ChatOutboxAttachmentCheck;\n /** Opens another conversation holding waiting messages (the tray's Open), when the host can. */\n openThread?: (target: { threadId: string; newChat: boolean }) => void;\n}\n\ninterface AthenaStatewireStandaloneProps extends AthenaStatewireRuntimeProps {\n children: ReactNode;\n backendUrl: string;\n appUrl: string;\n /** `AthenaProviderProps.modes`. */\n modes?: readonly string[];\n threadId?: string;\n /** `AthenaProviderProps.threadIsNew`. */\n threadIsNew?: boolean;\n /**\n * Thread-list mode. The list owns the active id and alone knows whether the\n * backend has listed it yet: `isNewChat` overrides the \"new chat\"\n * derivation (the list mints ids for brand-new chats, which must still load\n * as new), and the scope publishes `AthenaThreadIdContext` — the backend id,\n * withheld while the chat is unpersisted. Absent outside thread-list mode,\n * where that context stays untouched.\n */\n threadList?: { isNewChat: boolean };\n linkClicks?: AthenaLinkClickOptions;\n citationLinks?: AthenaCitationLinkOptions;\n /** `AthenaProviderProps.confirmClientToolWrites`. */\n confirmClientToolWrites?: ClientToolWriteConfirmer;\n}\n\n/**\n * What one per-thread runtime mount hands to the stable scope around the\n * host's children: the assistant client attached to `threadId` and the\n * transport lifecycle observed on that attach. Published as ONE value so the\n * scope can never pair a thread's id with another thread's client.\n */\ninterface AthenaStatewireRuntimeSnapshot {\n /** Opaque lifetime of the host/principal/thread that produced this snapshot. */\n binding: object;\n sessionPersistence: AthenaSessionPersistence | null;\n threadId: string;\n isNewChat: boolean;\n client: AssistantClient;\n lifecycle: AthenaStatewireLifecycleState;\n /** The thread's server config lane as the host sent it on this attach. */\n serverLane: AthenaStatewireServerLane;\n /** The thread's chat outbox (`AthenaProviderProps.chatOutbox`), or `null`. */\n outbox: ChatOutbox | null;\n /**\n * The provider-owned thread-config values this thread's sends carry (the\n * model, system prompt, enabled tools, workbench and knowledge base, each\n * under its `extraRunConfig` override), published with the thread they apply\n * to: during a switch the scope still holds the outgoing thread for a render\n * while the host's props already describe the incoming one, and pairing them\n * would write the new values into the session being left.\n */\n threadConfig: ProviderThreadConfig;\n /**\n * The provider's `planMode` for this thread (`null`: it sets none), published\n * with the thread for the same reason as `threadConfig`.\n */\n planMode: boolean | null;\n}\n\n/**\n * {@link providerThreadConfig} for the props, as one object per VALUE: hosts\n * pass fresh array literals (and the provider defaults `tools` to a new `[]`)\n * on every render, and a new object per render would republish the thread's\n * snapshot, which re-renders this mount, without end.\n */\nfunction useProviderThreadConfig(\n inputs: Parameters<typeof providerThreadConfig>[0],\n): ProviderThreadConfig {\n const value = providerThreadConfig(inputs);\n const key = JSON.stringify(value);\n // `key` is the value-stable form of `value`.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n return useMemo(() => value, [key]);\n}\n\n/**\n * The per-thread half of the statewire lane: owns the runtime hook (statewire\n * client, pending-message lane, `useAui` client) and the lifecycle reducer\n * behind the connection/error banners, and renders nothing itself. Mounted\n * under `key={threadId}` so a switch — or a new chat — gets a fresh instance\n * of everything here, exactly as when the whole provider subtree was keyed,\n * without remounting the host's UI.\n *\n * An assistant client's readable state only advances when its tap fibers\n * commit (in effects), so an in-place `threadId` change on one mounted hook\n * would leave a commit in which the new id is published but `useAuiState`\n * still reads the previous thread's committed state; a fresh mount publishes\n * its own state on its first render. That is why the runtime is remounted per\n * thread rather than switched in place.\n *\n * The snapshot is published from a layout effect: React flushes the state\n * update a layout effect schedules synchronously, before the browser paints,\n * so the scope re-renders against this client in the same task as this\n * mount's commit — the previous client is never painted under the new id.\n */\nfunction AthenaStatewireRuntimeMount({\n binding,\n threadId,\n isNewChat,\n onPublish,\n syncUrl,\n apiKey,\n token,\n getToken,\n model,\n agent,\n channel,\n mode,\n tools,\n frontendToolIds,\n frontendTools,\n workbench,\n knowledgeBase,\n systemPrompt,\n appId,\n extraRunConfig,\n planMode,\n snapshotCache,\n toolOutputs,\n chatOutbox = null,\n sessionLane,\n subagentLaneHistory,\n}: AthenaStatewireRuntimeProps & {\n binding: object;\n threadId: string;\n isNewChat: boolean;\n onPublish: (snapshot: AthenaStatewireRuntimeSnapshot) => void;\n}): null {\n const activeBinding = useRef<object | null>(null);\n useLayoutEffect(() => {\n activeBinding.current = binding;\n return () => {\n activeBinding.current = null;\n };\n }, [binding]);\n const [persistence, setPersistence] = useState<{\n binding: object;\n value: AthenaSessionPersistence;\n } | null>(null);\n const sessionPersistence = persistence?.binding === binding ? persistence.value : null;\n const onSessionPersistedChange = useCallback(\n (event: AthenaSessionPersistence) => {\n if (activeBinding.current !== binding || event.threadId !== threadId) return;\n setPersistence((previous) => {\n if (activeBinding.current !== binding) return previous;\n if (\n previous?.binding === binding &&\n previous.value.sessionPersisted === event.sessionPersisted\n ) return previous;\n return {\n binding,\n value: { threadId: event.threadId, sessionPersisted: event.sessionPersisted },\n };\n });\n },\n [binding, threadId],\n );\n const [defaultForeground] = useState(documentVisibleSignal);\n const [lifecycle, dispatchLifecycle] = useReducer(\n statewireLifecycleReducer,\n initialStatewireLifecycle,\n );\n const [serverLane, setServerLane] = useState<AthenaStatewireServerLane>(\n STATEWIRE_SERVER_LANE_PENDING,\n );\n\n const client = useAthenaStatewireRuntime({\n onSessionPersistedChange,\n syncUrl,\n threadId,\n isNewChat,\n apiKey,\n token,\n getToken,\n model,\n agent,\n channel,\n mode,\n tools,\n frontendToolIds,\n frontendToolkit: frontendTools,\n workbench,\n knowledgeBase,\n systemPrompt,\n appId,\n extraRunConfig,\n planMode,\n snapshotCache,\n toolOutputs,\n subagentLaneHistory,\n // The runtime already records every transport error on the diagnostics\n // bus (with the channel-teardown split), so this layer only maps it to\n // the banner notice.\n onError: (error) => {\n const notice = athenaStatewireErrorNotice(error);\n if (notice) dispatchLifecycle({ type: 'error', error: notice });\n },\n onConnectionChange: (connection) => {\n dispatchLifecycle({ type: 'connection', connection });\n },\n onRawConnectionChange: (connection) => {\n dispatchLifecycle({ type: 'raw-connection', reconnect: connection.reconnect });\n },\n ...(chatOutbox && {\n chatSession: chatOutbox.keeping,\n foreground: chatOutbox.foreground ?? defaultForeground,\n }),\n // The lane as the host holds it: anything that decides from the lane waits\n // for this, never the placeholder or remembered snapshot rendered before.\n onServerState: (state) => {\n const config = readServerConfig(state);\n setServerLane((previous) => nextServerLane({ previous, config }));\n },\n });\n\n // The runtime's session lane, reported once its client has committed it\n // (this effect runs after the runtime's own): a send held while the sign-in\n // provider was still resolving who is signed in (`StatewireSessionLane`)\n // goes out over the signed-in user's lane, never into the parked one.\n const lanePending = statewireSessionPrincipal(useContext(AthenaAuthContext)) === null;\n useEffect(() => {\n sessionLane.setPending(lanePending);\n }, [sessionLane, lanePending]);\n\n // Athena's reachability for the outbox: the host's (the browser online when it names none) AND\n // this conversation's channel not failing to connect (an attach that keeps retrying means Athena\n // can't be reached from here, whatever the host's own model last heard).\n const connectionRef = useRef(lifecycle.connection);\n connectionRef.current = lifecycle.connection;\n const [connectionListeners] = useState(() => new Set<() => void>());\n useEffect(() => {\n for (const listener of connectionListeners) listener();\n }, [lifecycle.connection, connectionListeners]);\n const [channelReachability] = useState<ChatOutboxSignal>(() => ({\n get: () => connectionRef.current?.status !== 'retrying',\n subscribe: (listener) => {\n connectionListeners.add(listener);\n return () => {\n connectionListeners.delete(listener);\n };\n },\n }));\n const [browserOnline] = useState(browserOnlineSignal);\n const hostReachability = chatOutbox?.reachability;\n const reachability = useMemo(\n () => allChatOutboxSignals(hostReachability ?? browserOnline, channelReachability),\n [hostReachability, browserOnline, channelReachability],\n );\n const composerHandoff = useComposerHandoffStore();\n const outbox = useDeepAgentChatOutbox({\n client,\n threadId,\n isNewChat,\n ...(chatOutbox && {\n directory: chatOutbox.storage.directory,\n legacy: { reader: chatOutbox.storage.legacy },\n }),\n reachability,\n foreground: chatOutbox?.foreground ?? defaultForeground,\n // Cancel and Edit give the draft back, after anything typed since. Its attachments come back\n // as mentions in it, remembered so a message held again from it is asked about again, the\n // agents it named come back to the To line, and what an app attached to it comes back as chips.\n restore: (entry) => {\n const draft = entry.composerMarkdown ?? entry.text;\n const current = client.composer.getState().text ?? '';\n client.composer.setText(current.trim() ? `${current}\\n\\n${draft}` : draft);\n if (composerHandoff && entry.attachments) {\n rememberRestoredAttachments({\n store: composerHandoff,\n threadId,\n attachments: entry.attachments,\n });\n }\n giveBackDeepAgentOutboxNamedAgents(entry);\n giveBackHeldAttachedReferences(entry);\n },\n ...(chatOutbox?.openThread && { openThread: chatOutbox.openThread }),\n ...(chatOutbox?.checkAttachments && { checkAttachments: chatOutbox.checkAttachments }),\n enabled: chatOutbox !== null && chatOutbox.keeping.kind !== 'pending',\n });\n\n // A thread the host stopped for refusing its credential reconnects as soon\n // as a new token exists, instead of waiting for a retry click.\n useRestartAfterAuthRefusal({\n connection: lifecycle.connection,\n reconnect: lifecycle.reconnect,\n });\n\n const dismissError = useCallback(\n () => dispatchLifecycle({ type: 'error', error: null }),\n [],\n );\n const lifecycleValue = useMemo<AthenaStatewireLifecycleState>(\n () => ({\n connection: lifecycle.connection,\n error: lifecycle.error,\n reconnect: lifecycle.reconnect,\n dismissError,\n }),\n [lifecycle, dismissError],\n );\n\n const threadConfig = useProviderThreadConfig({\n model,\n systemPrompt,\n tools,\n frontendToolIds,\n workbench,\n knowledgeBase,\n extraRunConfig,\n });\n const snapshot = useMemo<AthenaStatewireRuntimeSnapshot>(\n () => ({\n binding,\n sessionPersistence,\n threadId,\n isNewChat,\n client,\n lifecycle: lifecycleValue,\n serverLane,\n threadConfig,\n planMode: planMode ?? null,\n outbox,\n }),\n [binding, sessionPersistence, threadId, isNewChat, client, lifecycleValue, serverLane, threadConfig, planMode, outbox],\n );\n useLayoutEffect(() => {\n onPublish(snapshot);\n }, [onPublish, snapshot]);\n\n return null;\n}\n\n/**\n * The stable half of the statewire lane: the scope around the host's\n * `children`. It mounts one `AthenaStatewireRuntimeMount` per thread beside\n * them and provides whatever that mount last published — client, thread ids,\n * lifecycle — so a thread switch swaps the client under the host's UI instead\n * of remounting it. Until the first mount has published, the children are\n * withheld: they need a client, and the first publication lands in the same\n * task as the mount's commit.\n *\n * A server render runs no effects, so it would withhold the children too.\n * That changes nothing today: `AthenaProvider` renders `null` until the parent\n * bridge reports ready, which only ever happens in an effect (`useParentBridge`\n * starts `ready: false`), so the SDK has never server-rendered the host UI —\n * it hydrates it. A future SSR-ready bridge would need the first publication\n * to happen in render as well.\n */\nfunction AthenaStatewireStandalone({\n children,\n backendUrl,\n appUrl,\n threadId: threadIdProp,\n threadIsNew = false,\n threadList,\n linkClicks,\n citationLinks,\n modes,\n confirmClientToolWrites,\n ...runtimeProps\n}: AthenaStatewireStandaloneProps) {\n // Statewire attaches to `${syncUrl}/${threadId}`, so a thread ID must exist\n // up front. An auto-generated ID is by definition a never-started local chat.\n const generatedIdRef = useRef<string | null>(null);\n if (generatedIdRef.current === null) {\n generatedIdRef.current = mintThreadId();\n }\n const threadId = threadIdProp ?? generatedIdRef.current;\n const isNewChat = threadList?.isNewChat ?? (!threadIdProp || threadIsNew);\n\n const [published, setPublished] = useState<AthenaStatewireRuntimeSnapshot | null>(null);\n const principal = statewireSessionPrincipal(useContext(AthenaAuthContext));\n // Match Core's attachment scope. Credential rotation and presentation URL\n // changes do not create a new Core attach or re-notify an unchanged verdict.\n const binding = useMemo(() => ({}), [threadId, runtimeProps.syncUrl, principal]);\n\n // The mode menu (`modes`), kept across thread switches per agent, channel\n // and thread: the mode this browser picked and has not yet seen the session\n // run in, and the channel each session runs on as last read. A send names\n // the pick, else the session's channel, so it never moves a session another\n // browser switched; a pick the host no longer lists is never sent.\n const agentSelection = useContext(AthenaAgentSelectionContext);\n const modeScope = `${agentSelection?.agentAssetId ?? ''}\\u0000${agentSelection?.channel ?? ''}`;\n const [modePicks, setModePicks] = useState<Readonly<Record<string, string>>>({});\n const [sessionChannels, setSessionChannels] = useState<Readonly<Record<string, string>>>({});\n const setModePick = useCallback(\n ({ threadId: pickedThread, modeId }: { threadId: string; modeId: string | null }) =>\n setModePicks((picks) => withEntry(picks, `${modeScope}\\u0000${pickedThread}`, modeId)),\n [modeScope],\n );\n const setSessionChannel = useCallback(\n ({ threadId: readThread, channel }: { threadId: string; channel: string | null }) =>\n setSessionChannels((channels) =>\n withEntry(channels, `${modeScope}\\u0000${readThread}`, channel),\n ),\n [modeScope],\n );\n const hostModes = modes ?? EMPTY_MODES;\n const modeKey = hostModes.join('\\u0000');\n const listedPick = (thread: string): string | null => {\n const pick = modePicks[`${modeScope}\\u0000${thread}`];\n return pick !== undefined && hostModes.includes(pick) ? pick : null;\n };\n const threadMode =\n hostModes.length > 0\n ? (listedPick(threadId) ?? sessionChannels[`${modeScope}\\u0000${threadId}`])\n : undefined;\n\n const clientTools = useStatewireClientTools(runtimeProps.frontendTools);\n // The write-consent question for this provider's chat, and each write tool's\n // own words for it. The store outlives thread switches (an answer covers its\n // conversation for as long as the provider is mounted) but never its person:\n // another account signing in, or another Athena, starts with no answers.\n const writeConsentStore = useClientToolWriteConsentStore(\n `${principal ?? 'signing-in'}\\u0000${runtimeProps.syncUrl}`,\n );\n const writeConsentSummaries = useMemo(\n () => clientToolWriteConsentSummaries(runtimeProps.frontendTools),\n [runtimeProps.frontendTools],\n );\n\n // The runtime binds `client_tools` only for a recognised `app_id`; with none\n // it drops every declaration without telling the client, and the model then\n // sees \"not a valid tool\". Say so here, once per configuration, as an error\n // so it reaches `onError` and the console even with diagnostics off.\n const clientToolNamesKey = clientTools.map((tool) => tool.definition.name).join(',');\n const clientToolAppId = runtimeProps.appId;\n useEffect(() => {\n if (clientTools.length === 0 || resolveClientToolSurface(clientToolAppId) !== null) return;\n athenaDiagnostics.emit('sdk.config.warning', {\n level: 'error',\n error: new AthenaSdkError({\n code: 'config_invalid',\n message: `frontendTools with an execute() need a recognised appId; ${clientTools.length} tool(s) will not be bound.`,\n hint:\n \"Pass appId={publicAppId} on <AthenaProvider> (a computer-asset app reads it from athena-public-config.json as computer_asset_<uuid>). Without it the deep-agent runtime drops every client tool.\",\n context: { appId: clientToolAppId ?? null, tools: clientToolNamesKey.split(',') },\n }),\n data: { appId: clientToolAppId ?? null, tools: clientToolNamesKey.split(',') },\n });\n // clientToolNamesKey is the value-stable form of the tool list.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [clientToolAppId, clientToolNamesKey]);\n\n const athenaConfig = useAthenaConfigValue({\n backendUrl,\n appUrl,\n apiKey: runtimeProps.apiKey,\n token: runtimeProps.token,\n getToken: runtimeProps.getToken,\n enabledToolkits: runtimeProps.tools,\n linkClicks,\n citationLinks,\n });\n\n const chatModeSelection = useMemo<AthenaChatModeSelection | null>(\n () =>\n published\n ? {\n hostModes,\n threadId: published.threadId,\n isNewChat: published.isNewChat,\n pick: listedPick(published.threadId),\n sessionChannel: sessionChannels[`${modeScope}\\u0000${published.threadId}`] ?? null,\n setPick: setModePick,\n setSessionChannel,\n }\n : null,\n // modeKey is the value-stable form of hostModes, which listedPick reads.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [modeKey, modeScope, modePicks, sessionChannels, published, setModePick, setSessionChannel],\n );\n\n const scope = published && (\n <AuiProvider value={published.client}>\n <AthenaContext.Provider value={athenaConfig}>\n <AthenaStatewireThreadIdContext.Provider value={published.threadId}>\n <AthenaStatewireLifecycleContext.Provider value={published.lifecycle}>\n <DeepAgentConnectionContext.Provider value={published.lifecycle.connection}>\n <AthenaStatewireServerLaneContext.Provider value={published.serverLane}>\n <StatewireToolOutputsContext.Provider value={runtimeProps.toolOutputs}>\n <TurnStepsControlContext.Provider value={EarlierStepsButton}>\n <StatewireHistoryContext.Provider value={runtimeProps.historyStore}>\n <TooltipProvider>\n <ClientToolWriteConsentContext.Provider value={writeConsentStore}>\n <StatewireClientToolBridge\n tools={clientTools}\n threadId={published.threadId}\n writeConsentSummaries={writeConsentSummaries}\n confirmWrites={confirmClientToolWrites}\n />\n {/* Keyed per thread: each attach starts with no pending lane write. */}\n <StatewireThreadConfigLaneSync\n key={published.threadId}\n threadId={published.threadId}\n config={published.threadConfig}\n lane={published.serverLane}\n channelLive={isStatewireChannelLive(published.lifecycle.connection)}\n />\n <StatewirePlanModeLaneSync\n key={`plan-mode:${published.threadId}`}\n threadId={published.threadId}\n planMode={published.planMode}\n lane={published.serverLane}\n channelLive={isStatewireChannelLive(published.lifecycle.connection)}\n />\n <ComposerHandoffDrain />\n <ComposerDraftCarry isNewChat={published.isNewChat} />\n <DeepAgentChatOutboxContext.Provider value={published.outbox}>\n <AthenaChatModeSelectionContext.Provider value={chatModeSelection}>\n <AthenaSessionPersistenceContext.Provider\n value={published.binding === binding ? published.sessionPersistence : null}\n >\n {children}\n </AthenaSessionPersistenceContext.Provider>\n </AthenaChatModeSelectionContext.Provider>\n </DeepAgentChatOutboxContext.Provider>\n </ClientToolWriteConsentContext.Provider>\n </TooltipProvider>\n </StatewireHistoryContext.Provider>\n </TurnStepsControlContext.Provider>\n </StatewireToolOutputsContext.Provider>\n </AthenaStatewireServerLaneContext.Provider>\n </DeepAgentConnectionContext.Provider>\n </AthenaStatewireLifecycleContext.Provider>\n </AthenaStatewireThreadIdContext.Provider>\n </AthenaContext.Provider>\n </AuiProvider>\n );\n\n return (\n <>\n <AthenaStatewireRuntimeMount\n key={threadId}\n binding={binding}\n threadId={threadId}\n isNewChat={isNewChat}\n onPublish={setPublished}\n mode={threadMode}\n {...runtimeProps}\n />\n {/* The backend id rides the same snapshot as the client, so\n history-gated UI (e.g. the loading overlay) never judges one thread\n by another's state; it is undefined for a never-started chat, which\n must not read as pending history. */}\n {threadList && published ? (\n <AthenaThreadIdContext.Provider\n value={published.isNewChat ? undefined : published.threadId}\n >\n {scope}\n </AthenaThreadIdContext.Provider>\n ) : (\n scope\n )}\n </>\n );\n}\n\n// ─── Thread List Mode ─────────────────────────────────────────────────\n\nfunction AthenaStatewireWithThreadList({\n children,\n backendUrl,\n syncUrl,\n appId,\n apiKey,\n token,\n getToken,\n initialThreadId,\n includePullRequests,\n additionalListAppIds,\n listHomeAgentId,\n offlineList,\n ...standaloneProps\n}: Omit<AthenaStatewireStandaloneProps, 'threadId' | 'threadList'> & {\n initialThreadId?: string;\n includePullRequests?: boolean;\n additionalListAppIds?: readonly string[];\n /** The collab agent whose home this app is (`threadListAgentHome`), as a bare asset id. */\n listHomeAgentId?: string;\n /** Where the session list is kept for reading offline (`offlineHistory` only). */\n offlineList?: { mirror: ThreadSnapshotMirror; ownerId: string };\n}) {\n return (\n <AthenaStatewireThreadListProvider\n backendUrl={backendUrl}\n syncUrl={syncUrl}\n apiKey={apiKey}\n token={token}\n getToken={getToken}\n appId={appId}\n additionalListAppIds={additionalListAppIds}\n homeAgentId={listHomeAgentId}\n initialThreadId={initialThreadId}\n includePullRequests={includePullRequests}\n offlineList={offlineList}\n // The list's hover prefetch warms the same cache the active-thread\n // mount seeds from, so a hovered-then-selected session paints at once.\n snapshotCache={standaloneProps.snapshotCache}\n >\n <AthenaStatewireActiveThreadHost\n backendUrl={backendUrl}\n syncUrl={syncUrl}\n appId={appId}\n apiKey={apiKey}\n token={token}\n getToken={getToken}\n {...standaloneProps}\n >\n {children}\n </AthenaStatewireActiveThreadHost>\n </AthenaStatewireThreadListProvider>\n );\n}\n\nfunction AthenaStatewireActiveThreadHost({\n children,\n chatOutbox,\n ...standaloneProps\n}: Omit<AthenaStatewireStandaloneProps, 'threadId' | 'threadList'>) {\n const list = useAthenaStatewireThreadList();\n const selectThread = list?.selectThread;\n // The provenance this chat's sends stamp, so a new chat's pending row is badged as the\n // server's row will be.\n const startChannel = effectiveStatewireStartChannel({\n agent: standaloneProps.agent,\n channel: standaloneProps.channel,\n mode: standaloneProps.mode,\n extraRunConfig: standaloneProps.extraRunConfig,\n });\n // The tray's Open, when the host gives none: the list switches to the conversation (one that\n // never started, as the new chat it still is).\n const outboxHost = useMemo(\n () =>\n chatOutbox && !chatOutbox.openThread && selectThread\n ? {\n ...chatOutbox,\n openThread: ({ threadId, newChat }: { threadId: string; newChat: boolean }) =>\n selectThread(threadId, { isNew: newChat }),\n }\n : chatOutbox,\n [chatOutbox, selectThread],\n );\n if (!list) return null;\n\n // Not keyed: the scope keeps the host's children mounted across a switch\n // and remounts only its per-thread runtime against the new\n // `…/v2/threads/{id}` URL (see `AthenaStatewireStandalone`).\n return (\n <AthenaStatewireStandalone\n threadId={list.activeThreadId}\n threadList={{ isNewChat: list.isNewChat }}\n chatOutbox={outboxHost}\n {...standaloneProps}\n >\n <StatewireThreadTitlePoller />\n <StatewireThreadListSendSync startChannel={startChannel}>\n <AssetPanelThreadSync />\n {children}\n </StatewireThreadListSendSync>\n </AthenaStatewireStandalone>\n );\n}\n\n/**\n * Syncs the active thread ID into the asset panel store so that open asset\n * tabs are scoped per-thread automatically.\n *\n * Scoped by the attached thread's minted id from creation onward — NOT by\n * `useAthenaThreadManager().activeThreadId`, which is deliberately `null`\n * while a new chat is unpersisted (so URL sync never names it). The minted id\n * is the id the thread persists under, so tabs opened in a brand-new chat\n * stay put when the backend first lists it instead of being left behind in a\n * `null` scope the store never restores. Read from the statewire scope (the\n * id published with its client) rather than the list's selection, which runs\n * one commit ahead of the client during a switch.\n */\nfunction AssetPanelThreadSync() {\n const threadId = useAthenaStatewireThreadId();\n const setCurrentThread = useAssetPanelStore((s) => s.setCurrentThread);\n\n useEffect(() => {\n setCurrentThread(threadId);\n }, [threadId, setCurrentThread]);\n\n return null;\n}\n\n// ─── Main Provider ────────────────────────────────────────────────────\n\nexport function AthenaProvider({\n children,\n config,\n apiKey,\n token: tokenProp,\n agent,\n channel,\n modes,\n model,\n tools = [],\n frontendTools = {},\n confirmClientToolWrites,\n disableAutoOpen = false,\n apiUrl,\n backendUrl,\n appUrl,\n environment,\n statewireSyncUrl,\n getToken,\n extraRunConfig,\n workbench,\n knowledgeBase,\n systemPrompt,\n planMode,\n appId,\n threadId: threadIdProp,\n threadIsNew,\n enableThreadList = false,\n threadListIncludePullRequests = true,\n threadListAdditionalAppIds,\n threadListAgentHome = false,\n theme,\n linkClicks,\n citationLinks,\n onOpenAsset,\n posthog: posthogProp,\n debug,\n onDiagnostic,\n onError,\n offlineHistory,\n chatOutbox,\n subagentLaneHistory = false,\n}: AthenaProviderProps) {\n // Fail loud before any effect, bridge wait, or network call: an `agent`\n // outside the collab_agent namespace can never apply, so a misconfigured\n // deployment must die at first render rather than answer as the wrong agent.\n const agentAssetId = resolveAgentProp({ agent });\n // The channel rides only with an agent, as the run config sends it.\n const trimmedChannel = channel?.trim() ?? '';\n const agentChannel = agentAssetId && trimmedChannel !== '' ? trimmedChannel : null;\n const agentSelection = useMemo<AthenaAgentSelection>(\n () => ({ agentAssetId, channel: agentChannel }),\n [agentAssetId, agentChannel],\n );\n\n // Diagnostics wiring first, so everything below is observable. Callbacks\n // ride refs: a per-render closure must not re-register the consumer. Each\n // provider registers its OWN consumer (additive, cleaned up on unmount), so\n // two mounted providers never clobber each other's onDiagnostic/onError —\n // only the console/PostHog/buffer settings are global (last writer wins).\n const onDiagnosticRef = useRef(onDiagnostic);\n onDiagnosticRef.current = onDiagnostic;\n const onErrorRef = useRef(onError);\n onErrorRef.current = onError;\n useEffect(() => {\n installAthenaDiagnosticsGlobal();\n return athenaDiagnostics.addConsumer({\n onEvent: (event) => onDiagnosticRef.current?.(event),\n onError: (error, event) => onErrorRef.current?.(error, event),\n });\n }, []);\n // A host that opens assets its own way takes every request the SDK makes to open one, on the\n // shared asset store. The callback rides a ref, so a new one each render does not re-register.\n const onOpenAssetRef = useRef(onOpenAsset);\n onOpenAssetRef.current = onOpenAsset;\n const opensAssets = onOpenAsset !== undefined;\n useEffect(() => {\n if (!opensAssets) return;\n // The host's answer as given: anything but `false` (a callback returning nothing included)\n // means it opened the asset.\n return useAssetPanelStore.getState().registerAssetOpener((request) => {\n const open = onOpenAssetRef.current;\n return open ? open(request) : false;\n });\n }, [opensAssets]);\n const debugKey = JSON.stringify(debugPropToDiagnosticsConfig(debug));\n useEffect(() => {\n athenaDiagnostics.configure(debugPropToDiagnosticsConfig(debug));\n // debugKey is the value-stable form of `debug` (consumers pass literals).\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [debugKey]);\n // Only declarations WITHOUT a local `execute` ride `enabled_tools`: they name\n // registry tools the backend binds itself. Executable tools are declared\n // through `client_tools` instead — listing them here too would switch on a\n // backend toolkit owning a tool of the same name, and the backend wins that\n // collision (the client tool is silently dropped).\n const frontendToolNames = useMemo(\n () => backendDeclaredFrontendToolIds(frontendTools),\n [frontendTools],\n );\n // Merge SDK auto-open defaults under the consumer's frontendTools. Consumer\n // entries win on name collision; auto-open tool names are NOT added to\n // frontendToolIds (they are already backend-advertised by their toolkits).\n const effectiveFrontendTools = useMemo<Toolkit>(\n () => (disableAutoOpen ? frontendTools : { ...DEFAULT_AUTO_OPEN_TOOLS, ...frontendTools }),\n [disableAutoOpen, frontendTools],\n );\n const themeStyleVars = useMemo(() => theme ? themeToStyleVars(theme) : undefined, [theme]);\n const configuredEnvironment = config?.environment ?? environment;\n const environmentUrls = useMemo(\n () => getAthenaEnvironmentUrls({ environment: configuredEnvironment }),\n [configuredEnvironment],\n );\n const configuredApiKey = config?.apiKey ?? apiKey;\n const configuredToken = resolveTokenOverride({ config, token: tokenProp });\n const configuredApiUrl = config?.apiUrl ?? apiUrl;\n const configuredBackendUrl = config?.backendUrl ?? backendUrl;\n const configuredAppUrl = config?.appUrl ?? appUrl;\n const configuredStatewireSyncUrl = config?.statewireSyncUrl ?? statewireSyncUrl;\n const configuredGetToken = config?.getToken ?? getToken;\n const configuredExtraRunConfig = config?.extraRunConfig ?? extraRunConfig;\n const configuredTrustedParentOrigins = config?.trustedParentOrigins;\n const posthogConfig: PostHogConfig | undefined = config?.posthog ?? posthogProp;\n\n // Statewire is the SDK's only chat transport; the gauge/event stay on the\n // diagnostics contract so dashboards keyed on them keep reading a value.\n useEffect(() => {\n athenaDiagnostics.gauge('sdk.transport', 'statewire');\n athenaDiagnostics.emit('sdk.transport', {\n level: 'debug',\n data: { transport: 'statewire', thread_list: enableThreadList },\n });\n }, [enableThreadList]);\n\n // If an AthenaAuthProvider is present above us, use its access token automatically.\n const authContext = useContext(AthenaAuthContext);\n const authProviderToken = authContext?.accessToken ?? null;\n\n const bridge = useParentBridge({\n trustedOrigins: configuredTrustedParentOrigins,\n // The Marathon bridge sends the page through sign-in itself only when its\n // token is the chat's credential: a sign-in provider above decides on its\n // own, and a host credential keeps working when the bridge's session ends.\n signBackInOnSessionEnd: bridgeOwnsCredential({\n signInProviderAbove: authContext !== null,\n token: configuredToken,\n getToken: configuredGetToken,\n apiKey: configuredApiKey,\n }),\n });\n // The page a trip through sign-in returned to gets its URL fragment back\n // (a hash-routed app's route), which Marathon's return drops.\n useEffect(() => {\n restoreSignBackInHash();\n }, []);\n\n // Per-provider snapshot cache: a switch back to a recently-visited thread\n // mounts with its last-known snapshot instead of a loading spinner. Owned\n // here, above the per-thread keyed mount, so it survives switches; cleared\n // when the acting identity changes so a snapshot captured under one account\n // never seeds a mount under another.\n //\n // With `offlineHistory` (opt-in, decided at mount) the cache is the durable\n // one: mirrored to this device under the host's key for the owner, readable\n // offline. The mirror only ever asks the host for the key of the owner it\n // is bound to; any other owner gets none.\n const offlineHistoryRef = useRef(offlineHistory);\n offlineHistoryRef.current = offlineHistory;\n const isOfflineNow = (): boolean =>\n offlineHistoryRef.current?.isOffline?.() ??\n (typeof navigator !== 'undefined' && navigator.onLine === false);\n const [offlineMirror] = useState(() =>\n offlineHistory\n ? createThreadSnapshotMirror({\n getKey: (ownerId) => {\n const host = offlineHistoryRef.current;\n return host && host.ownerId === ownerId ? host.getKey() : Promise.resolve(null);\n },\n })\n : null,\n );\n const [durableSnapshotCache] = useState(() =>\n offlineMirror\n ? createDurableThreadSnapshotCache({ mirror: offlineMirror, isOffline: isOfflineNow })\n : null,\n );\n const [snapshotCache] = useState<DeepAgentThreadSnapshotCache>(\n () => durableSnapshotCache ?? createDeepAgentThreadSnapshotCache(),\n );\n // The chat outbox (opt-in): the page's one storage per owner (`chatOutboxStorageFor`), asking\n // the host for that owner's key only. Its signals ride to each thread's mount.\n const chatOutboxRef = useRef(chatOutbox);\n chatOutboxRef.current = chatOutbox;\n const chatOutboxOwnerId = chatOutbox?.ownerId ?? null;\n const chatOutboxStorage = useMemo(() => {\n const host = chatOutboxRef.current;\n return host && host.ownerId === chatOutboxOwnerId ? chatOutboxStorageFor(host) : null;\n }, [chatOutboxOwnerId]);\n // The storage asks the latest host of its owner for the key.\n useEffect(() => {\n if (chatOutbox) chatOutboxStorageFor(chatOutbox);\n }, [chatOutbox]);\n // Sealed or in memory, read once per owner: every thread's session waits for it.\n const [chatSessionKeeping, setChatSessionKeeping] = useState<{\n storage: ChatOutboxOwnerStorage;\n keeping: AthenaChatSessionKeeping;\n } | null>(null);\n useEffect(() => {\n if (!chatOutboxStorage) return;\n let live = true;\n void resolveChatSessionKeeping(chatOutboxStorage).then((keeping) => {\n if (live) setChatSessionKeeping({ storage: chatOutboxStorage, keeping });\n });\n return () => {\n live = false;\n };\n }, [chatOutboxStorage]);\n const chatOutboxKeeping: AthenaChatSessionKeeping =\n chatSessionKeeping?.storage === chatOutboxStorage && chatSessionKeeping\n ? chatSessionKeeping.keeping\n : CHAT_SESSION_KEEPING_PENDING;\n const chatOutboxReachability = chatOutbox?.reachability;\n const chatOutboxForeground = chatOutbox?.foreground;\n const chatOutboxOpenThread = chatOutbox?.openThread;\n // A waiting message's attachments are asked about right before it goes: each read through\n // agora's permission-checked asset route as the person, with the credential and the backend this\n // provider holds at that moment (both assigned further down, every render).\n const outboxCheckAuthRef = useRef<StatewireAuthSource>({});\n const outboxCheckBackendRef = useRef('');\n const [checkChatOutboxAttachments] = useState<ChatOutboxAttachmentCheck>(() =>\n createChatOutboxAttachmentCheck({\n readAsset: (assetId) =>\n sendWithCredentialRenewal(outboxCheckAuthRef.current, (headers) =>\n fetch(`${outboxCheckBackendRef.current}${chatOutboxAttachmentPath(assetId)}`, {\n method: 'GET',\n headers,\n signal: AbortSignal.timeout(CHAT_OUTBOX_ATTACHMENT_READ_TIMEOUT_MS),\n }),\n ),\n }),\n );\n const chatOutboxHost = useMemo<AthenaStatewireChatOutboxHost | null>(\n () =>\n chatOutboxStorage === null\n ? null\n : {\n storage: chatOutboxStorage,\n keeping: chatOutboxKeeping,\n ...(chatOutboxReachability && { reachability: chatOutboxReachability }),\n ...(chatOutboxForeground && { foreground: chatOutboxForeground }),\n ...(chatOutboxOpenThread && { openThread: chatOutboxOpenThread }),\n checkAttachments: checkChatOutboxAttachments,\n },\n [\n chatOutboxStorage,\n chatOutboxKeeping,\n chatOutboxReachability,\n chatOutboxForeground,\n chatOutboxOpenThread,\n checkChatOutboxAttachments,\n ],\n );\n const offlineOwnerId = offlineHistory?.ownerId ?? null;\n // Binds the cache to the owner; a chat that mounts offline is held until what this device kept\n // for them is read, so its thread mounts on its seed.\n const awaitingKeptSnapshots = useKeptSnapshotsGate({\n cache: durableSnapshotCache,\n ownerId: offlineOwnerId,\n isOffline: isOfflineNow,\n });\n const offlineSnapshots = useMemo<AthenaOfflineSnapshots | null>(\n () =>\n durableSnapshotCache\n ? {\n offlineSeedAt: (threadId) => durableSnapshotCache.offlineSeedAt(threadId),\n subscribeOfflineSeeds: (listener) => durableSnapshotCache.subscribeOfflineSeeds(listener),\n }\n : null,\n [durableSnapshotCache],\n );\n const offlineList = useMemo(\n () => (offlineMirror && offlineOwnerId ? { mirror: offlineMirror, ownerId: offlineOwnerId } : undefined),\n [offlineMirror, offlineOwnerId],\n );\n // Composer writes that arrive before the per-thread mount is ready wait\n // here, above that mount, so a thread-list remount cannot drop them.\n const [composerHandoff] = useState(createComposerHandoffStore);\n // The windowed wire's fetched-back tool outputs, owned alongside the cache\n // for the same reasons: shared across the provider's thread switches (a\n // tool message id is unique across threads), dropped with the identity.\n const [toolOutputs] = useState(() => createDeepAgentToolOutputStore());\n // Where the open thread's history stands, reported by the chat's history\n // edge for other surfaces (the workbench's Shell pane).\n const [historyStore] = useState(createStatewireHistoryStore);\n const principal = authContext?.user?.userId ?? '';\n // Older history paged by command lives in the JS context's per-conversation\n // stores (`history/page`, shared by every reader of a conversation), so it\n // is dropped when the identity changes (it is what that identity may read),\n // not on a mount: another provider's open conversation keeps its pages.\n const pagedIdentity = useRef<{ principal: string; apiKey: string | undefined } | null>(null);\n useEffect(() => {\n snapshotCache.clear();\n toolOutputs.clear();\n const previous = pagedIdentity.current;\n if (previous !== null && (previous.principal !== principal || previous.apiKey !== configuredApiKey)) {\n clearDeepAgentHistoryStores();\n }\n pagedIdentity.current = { principal, apiKey: configuredApiKey };\n }, [snapshotCache, toolOutputs, principal, configuredApiKey]);\n // The principal the chat's command lane is scoped by: `null` while the\n // sign-in provider above is still resolving who is signed in. The lane is\n // pending until then (`useAthenaStatewireRuntime`), and sends wait for it on\n // the provider's gate, which the mounted runtime keeps current.\n const sessionPrincipal = statewireSessionPrincipal(authContext);\n const [sessionLane] = useState(() =>\n createStatewireSessionLaneGate({ pending: sessionPrincipal === null }),\n );\n // A draft or send queued under one identity must never land in another's\n // composer. One queued while the sign-in was still resolving was made by\n // whoever signs in and waits for their lane, so only a change from one known\n // identity to another drops what waits.\n const handoffIdentityRef = useRef<string | null>(null);\n useEffect(() => {\n if (sessionPrincipal === null) return;\n const identity = JSON.stringify([sessionPrincipal, configuredApiKey ?? null]);\n const previous = handoffIdentityRef.current;\n handoffIdentityRef.current = identity;\n if (previous !== null && previous !== identity) {\n clearComposerHandoff({ store: composerHandoff, reason: 'the signed-in identity changed' });\n }\n }, [composerHandoff, sessionPrincipal, configuredApiKey]);\n // Nothing drains after the provider is gone: settle what still waits so no\n // `useSendMessage` caller hangs.\n useEffect(\n () => () => clearComposerHandoff({ store: composerHandoff, reason: 'the chat provider unmounted' }),\n [composerHandoff],\n );\n\n const effectiveToken = configuredToken !== undefined\n ? configuredToken\n : authProviderToken ?? bridge.token;\n\n // One credential source for every network path below: it presents the\n // token chosen above and renews it the way its origin can. A host's own\n // `getToken` owns renewal; a host's static `token` never renews; a sign-in\n // provider's token renews through its getter (PropelAuth, SSO); a host\n // bridge token through the bridge (a Marathon re-mint, or the parent\n // window's next `athena-auth`).\n const authProviderGetToken = authContext?.getToken;\n const credentialInputsRef = useRef<AthenaCredentialInputs>({ token: null });\n credentialInputsRef.current = {\n hostGetToken: configuredGetToken,\n token: effectiveToken,\n renew:\n configuredToken !== undefined\n ? undefined\n : authProviderToken !== null\n ? authProviderGetToken\n ? async ({ force }) => (await authProviderGetToken({ force })) ?? null\n : undefined\n : bridge.token !== null\n ? bridge.renewToken\n : undefined,\n };\n const [credentials] = useState(() =>\n createAthenaCredentialSource(() => credentialInputsRef.current),\n );\n useEffect(() => {\n credentials.notifyTokenChanged();\n }, [credentials, effectiveToken]);\n // Only a provider that holds a token (or a host getter) hands one out, so\n // \"has credentials\" checks downstream keep meaning what they did.\n const credentialGetToken =\n configuredGetToken !== undefined || effectiveToken ? credentials.getToken : undefined;\n // Explicit config wins. A Marathon host mints the statewire mount, the bare\n // Agora base and the app origin outright (`/_athena/auth`, or a trusted\n // parent's `athena-config`); the environment preset is the last resort, and\n // the sync mount derives from the `apiUrl` host when no host minted one.\n const effectiveApiUrl = configuredApiUrl ?? environmentUrls.apiUrl;\n // Published as the bare Agora base: a historical `…/api/assistant-ui` value\n // is trimmed here once rather than by each REST helper.\n const effectiveBackendUrl = getAthenaApiBaseUrl(\n configuredBackendUrl ?? bridge.backendBaseUrl ?? environmentUrls.backendUrl,\n );\n // What the chat outbox's attachment check reads as (see `checkChatOutboxAttachments` above).\n outboxCheckBackendRef.current = effectiveBackendUrl;\n outboxCheckAuthRef.current = {\n apiKey: configuredApiKey,\n token: effectiveToken,\n getToken: credentialGetToken,\n };\n const hostStatewireSyncUrl = configuredStatewireSyncUrl ?? bridge.statewireSyncUrl ?? undefined;\n const effectiveAppUrl = configuredAppUrl\n ?? bridge.appUrl\n ?? deriveAthenaAppUrl({ apiUrl: effectiveApiUrl, backendUrl: effectiveBackendUrl })\n ?? environmentUrls.appUrl;\n\n // Wait for the parent bridge to deliver config/auth before rendering.\n // This prevents the thread list from fetching with wrong URLs or no token.\n // An iframe bridge falls back after a short timeout (2s) if no parent\n // answers; a Marathon mint is ready once its bounded retry cycle ends.\n if (!bridge.ready) {\n return null;\n }\n\n // Fail closed when the host's mint gave up and nothing else can\n // authenticate: the chat would otherwise attach with no credential (and to\n // the environment preset, since no host minted a mount). The bridge has\n // already reported the typed `auth_bridge_failed` / `auth_bridge_timeout`\n // error to `onError`; remounting the provider starts a new bounded mint.\n if (\n bridge.error &&\n !effectiveToken &&\n configuredGetToken === undefined &&\n !configuredApiKey\n ) {\n return null;\n }\n\n // Both throw on an unresolvable configuration instead of falling back to an\n // Athena default — a custom deployment's credentials must never be sent to\n // a host the consumer didn't configure. A host that answered the bridge\n // without minting the statewire mount is that case: its token would\n // otherwise ride the environment preset.\n assertHostMintedStatewireMount({\n hostAnswered: bridge.hostAnswered,\n hostStatewireSyncUrl: bridge.statewireSyncUrl,\n statewireSyncUrl: configuredStatewireSyncUrl,\n apiUrl: configuredApiUrl,\n });\n const effectiveStatewireSyncUrl = resolveStatewireSyncUrl({\n statewireSyncUrl: hostStatewireSyncUrl,\n apiUrl: effectiveApiUrl,\n });\n\n const statewireProps = {\n syncUrl: effectiveStatewireSyncUrl,\n backendUrl: effectiveBackendUrl,\n appUrl: effectiveAppUrl,\n apiKey: configuredApiKey,\n token: effectiveToken,\n getToken: credentialGetToken,\n model,\n agent,\n channel,\n modes,\n tools,\n frontendToolIds: frontendToolNames,\n frontendTools: effectiveFrontendTools,\n confirmClientToolWrites,\n workbench,\n knowledgeBase,\n systemPrompt,\n planMode,\n appId,\n extraRunConfig: configuredExtraRunConfig,\n snapshotCache,\n toolOutputs,\n historyStore,\n chatOutbox: chatOutboxHost,\n sessionLane,\n subagentLaneHistory,\n linkClicks,\n citationLinks,\n };\n\n // Each provider's assistant client is a root of its own (`extends={null}`): one mounted under\n // another provider's (a host showing several chats side by side) would otherwise extend that\n // client and define every tool a second time. The empty config is built per render (configs are\n // identity-insensitive), never at import, which a host's test stub of assistant-ui could not take.\n const inner: ReactNode = (\n <AuiProvider extends={null} config={AuiConfig({})}>\n {enableThreadList ? (\n <AthenaStatewireWithThreadList\n {...statewireProps}\n initialThreadId={threadIdProp}\n includePullRequests={threadListIncludePullRequests}\n additionalListAppIds={threadListAdditionalAppIds}\n listHomeAgentId={threadListAgentHome && agentAssetId ? agentAssetId : undefined}\n offlineList={offlineList}\n >\n {children}\n </AthenaStatewireWithThreadList>\n ) : (\n // A provider without a thread list is its own chat: one nested under a thread-list\n // provider (a host showing several chats side by side) must not read that list as its\n // own, or its banners and composer would follow the other chat's thread.\n <AthenaStatewireThreadListContext.Provider value={null}>\n <AthenaStatewireStandalone\n {...statewireProps}\n threadId={threadIdProp}\n threadIsNew={threadIsNew}\n >\n {children}\n </AthenaStatewireStandalone>\n </AthenaStatewireThreadListContext.Provider>\n )}\n </AuiProvider>\n );\n\n // The .athena-sdk wrapper (display: contents) anchors the SDK's design\n // tokens and scoped preflight from styles.css, so the stylesheet works\n // in hosts without their own Tailwind build. PostHog gracefully no-ops\n // when its config is missing.\n return (\n <div\n className={themeStyleVars ? \"athena-sdk athena-themed\" : \"athena-sdk\"}\n style={themeStyleVars as React.CSSProperties | undefined}\n >\n <PostHogProvider config={posthogConfig}>\n <ComposerHandoffContext.Provider value={composerHandoff}>\n <StatewireSessionLaneContext.Provider value={sessionLane}>\n <AthenaThemeStyleContext.Provider value={themeStyleVars}>\n <AthenaCredentialSourceContext.Provider value={credentials}>\n <AthenaAgentSelectionContext.Provider value={agentSelection}>\n <AthenaOfflineSnapshotsContext.Provider value={offlineSnapshots}>\n <AthenaDataQueryClientProvider>\n {awaitingKeptSnapshots ? null : inner}\n </AthenaDataQueryClientProvider>\n </AthenaOfflineSnapshotsContext.Provider>\n </AthenaAgentSelectionContext.Provider>\n </AthenaCredentialSourceContext.Provider>\n </AthenaThemeStyleContext.Provider>\n </StatewireSessionLaneContext.Provider>\n </ComposerHandoffContext.Provider>\n </PostHogProvider>\n </div>\n );\n}\n"],"names":["_a"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgbA,MAAM,uBAAuB,CAAC;AAAA,EAC5B;AAAA,EACA;AACF,MAGiC;AAC/B,OAAI,iCAAQ,WAAU,QAAW;AAC/B,WAAO,OAAO;AAAA,EAChB;AACA,SAAO;AACT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AA,MACC,WAAW,iBAAiB,6BAA6B;AAAA,MACzD,OAAO;AAAA,MAEP,UAAA,oBAAC,mBAAgB,QAAQ,eACvB,8BAAC,uBAAuB,UAAvB,EAAgC,OAAO,iBACtC,UAAA,oBAAC,4BAA4B,UAA5B,EAAqC,OAAO,aAC3C,UAAA,oBAAC,wBAAwB,UAAxB,EAAiC,OAAO,gBACvC,UAAA,oBAAC,8BAA8B,UAA9B,EAAuC,OAAO,aAC7C,UAAA,oBAAC,4BAA4B,UAA5B,EAAqC,OAAO,gBAC3C,UAAA,oBAAC,8BAA8B,UAA9B,EAAuC,OAAO,kBAC7C,UAAA,oBAAC,+BAAA,EACE,UAAA,wBAAwB,OAAO,MAAA,CAClC,EAAA,CACF,GACF,EAAA,CACF,EAAA,CACF,EAAA,CACF,EAAA,CACF,EAAA,CACF;AAAA,IAAA;AAAA,EAAA;AAGN;"}
|
|
1
|
+
{"version":3,"file":"AthenaProvider.js","sources":["../../src/provider/AthenaProvider.tsx"],"sourcesContent":["import { AuiConfig, AuiProvider, useAui } from '@assistant-ui/react';\nimport {\n useCallback,\n useContext,\n useEffect,\n useLayoutEffect,\n useMemo,\n useReducer,\n useRef,\n useState,\n type ReactNode,\n} from 'react';\nimport type { AssistantClient, Toolkit } from '@assistant-ui/react';\nimport {\n allChatOutboxSignals,\n browserOnlineSignal,\n type ChatOutbox,\n type ChatOutboxAttachmentCheck,\n type ChatOutboxSignal,\n chatOutboxAttachmentPath,\n createChatOutboxAttachmentCheck,\n clearDeepAgentHistoryStores,\n createDeepAgentThreadSnapshotCache,\n createDeepAgentToolOutputStore,\n createDurableThreadSnapshotCache,\n createThreadSnapshotMirror,\n DeepAgentChatOutboxContext,\n DeepAgentConnectionContext,\n type DeepAgentThreadSnapshotCache,\n type DeepAgentToolOutputStore,\n documentVisibleSignal,\n readServerConfig,\n type ThreadSnapshotMirror,\n useDeepAgentChatOutbox,\n} from '@athenaintel/agent-runtime';\nimport { giveBackDeepAgentOutboxNamedAgents } from '@athenaintel/agent-runtime/named-agents';\nimport {\n type AthenaOfflineHistory,\n type AthenaOfflineSnapshots,\n AthenaOfflineSnapshotsContext,\n useKeptSnapshotsGate,\n} from '../offline/offline-history';\nimport {\n type AthenaChatOutbox,\n type AthenaChatSessionKeeping,\n type ChatOutboxOwnerStorage,\n chatOutboxStorageFor,\n resolveChatSessionKeeping,\n} from '../offline/chat-outbox';\nimport {\n assertHostMintedStatewireMount,\n deriveAthenaAppUrl,\n getAthenaEnvironmentUrls,\n resolveStatewireSyncUrl,\n type AthenaEnvironment,\n} from '../lib/athena-urls';\nimport { getAthenaApiBaseUrl } from '../collab/mint';\nimport { useParentBridge } from '../runtime/auth';\nimport { AthenaAuthContext } from '../auth/AthenaAuthContext';\nimport { AthenaCredentialSourceContext } from '../auth/AthenaCredentialSourceContext';\nimport { AthenaDataQueryClientProvider } from '../data/athena-data-client';\nimport {\n createAthenaCredentialSource,\n type AthenaCredentialInputs,\n} from '../auth/credential-source';\nimport { useRestartAfterAuthRefusal } from '../runtime/auth-refusal-restart';\nimport {\n useAthenaStatewireRuntime,\n useStatewireClientTools,\n} from '../runtime/useAthenaStatewireRuntime';\nimport { statewireSessionPrincipal } from '../runtime/statewire-session-key';\nimport {\n createStatewireSessionLaneGate,\n StatewireSessionLaneContext,\n type StatewireSessionLaneGate,\n} from '../runtime/statewire-session-lane';\nimport {\n athenaStatewireErrorNotice,\n type AthenaStatewireLifecycleState,\n initialStatewireLifecycle,\n isStatewireChannelLive,\n statewireLifecycleReducer,\n} from '../runtime/statewire-lifecycle';\nimport type { AthenaStatewireTokenGetter, StatewireAuthSource } from '../runtime/statewire-auth-headers';\nimport { sendWithCredentialRenewal } from '../runtime/credential-renewal';\nimport { effectiveStatewireStartChannel, resolveAgentProp } from '../runtime/statewire-run-config';\nimport {\n type ProviderThreadConfig,\n providerThreadConfig,\n} from '../runtime/statewire-thread-config-lane';\nimport { mintThreadId } from '../threads/mint-thread-id';\nimport { AthenaStatewireLifecycleContext } from './statewire-lifecycle-context';\nimport {\n ComposerHandoffContext,\n applyComposerWrite,\n clearComposerHandoff,\n createComposerHandoffStore,\n drainComposerHandoff,\n rememberRestoredAttachments,\n useComposerHandoffStore,\n useComposerReady,\n} from '../composer/composer-handoff';\nimport { giveBackHeldAttachedReferences } from '../composer/attached-references';\nimport { keepDraftForSignBackIn, takeDraftKeptForSignBackIn } from '../composer/sign-back-in-draft';\nimport {\n ATHENA_SIGN_BACK_IN_EVENT,\n bridgeOwnsCredential,\n restoreSignBackInHash,\n} from '../auth/sign-back-in';\nimport {\n createStatewireHistoryStore,\n StatewireHistoryContext,\n type StatewireHistoryStore,\n} from './statewire-history-context';\nimport { EarlierStepsButton } from '../chat/super-grouping/earlier-steps-button';\nimport { TurnStepsControlContext } from '../chat/super-grouping/use-turn-steps';\nimport { StatewireToolOutputsContext } from './statewire-window-context';\nimport { StatewireClientToolBridge } from '../chat/StatewireClientToolBridge';\nimport { StatewirePlanModeLaneSync } from '../runtime/StatewirePlanModeLaneSync';\nimport { StatewireThreadConfigLaneSync } from '../runtime/StatewireThreadConfigLaneSync';\nimport {\n type AthenaStatewireServerLane,\n AthenaStatewireServerLaneContext,\n nextServerLane,\n STATEWIRE_SERVER_LANE_PENDING,\n} from '../runtime/statewire-server-lane-context';\nimport {\n athenaDiagnostics,\n debugPropToDiagnosticsConfig,\n installAthenaDiagnosticsGlobal,\n type AthenaDiagnosticEvent,\n type AthenaDiagnosticLevel,\n type AthenaDiagnosticsConfig,\n} from '../diagnostics/athena-diagnostics';\nimport { AthenaSdkError } from '../diagnostics/errors';\nimport {\n backendDeclaredFrontendToolIds,\n clientToolWriteConsentSummaries,\n requiresWriteConsent,\n resolveClientToolSurface,\n} from '../chat/statewire-client-tools';\nimport {\n type ClientToolWriteConfirmer,\n ClientToolWriteConsentContext,\n useClientToolWriteConsentStore,\n} from '../chat/client-tool-write-consent';\nimport { AgentUiLayer, type AgentUiLayerClassNames } from '../agent-ui/AgentUiLayer';\nimport {\n AGENT_UI_ACT_SUMMARY,\n AGENT_UI_TOOL_NAMES,\n type AgentUiOptions,\n} from '../agent-ui/tools';\nimport { useAgentUi } from '../agent-ui/use-agent-ui';\nimport { TooltipProvider } from '../ui/tooltip';\nimport { DEFAULT_AUTO_OPEN_TOOLS } from '../tools/auto-open-tools';\nimport { AthenaContext, type AthenaConfig } from './AthenaContext';\nimport { type AthenaAgentSelection, AthenaAgentSelectionContext } from './agent-selection-context';\nimport { type AthenaChatModeSelection, AthenaChatModeSelectionContext } from './chat-mode-context';\nimport type { AthenaProviderConfig } from './config';\nimport {\n AthenaSessionPersistenceContext,\n type AthenaSessionPersistence,\n} from './session-persistence-context';\nimport type {\n AthenaCitationLinkOptions,\n AthenaLinkClickOptions,\n} from './citation-links';\nimport {\n AthenaStatewireThreadIdContext,\n AthenaThreadIdContext,\n useAthenaStatewireThreadId,\n} from '../threads/thread-id-context';\nimport {\n AthenaStatewireThreadListContext,\n AthenaStatewireThreadListProvider,\n StatewireThreadListSendSync,\n StatewireThreadTitlePoller,\n useAthenaStatewireThreadList,\n} from '../threads/statewire-thread-list';\nimport { type AssetOpener, useAssetPanelStore } from '../assets/asset-panel-store';\nimport { themeToStyleVars, type AthenaTheme } from '../theme';\nimport { AthenaThemeStyleContext } from './theme-style-context';\nimport { PostHogProvider, type PostHogConfig } from './PostHogProvider';\n\n/** `AthenaProviderProps.agentUi` as options: the agent's own, and the overlay's look. */\nexport interface AthenaAgentUiOptions extends AgentUiOptions {\n /** Restyle the overlay's pieces (the mark, its note, the cursor, the walkthrough and question cards). */\n classNames?: AgentUiLayerClassNames;\n}\n\nconst EMPTY_AGENT_UI_OPTIONS: AthenaAgentUiOptions = {};\nconst EMPTY_TOOLKIT: Toolkit = {};\n\nexport interface AthenaProviderProps {\n children: ReactNode;\n\n /** Preferred structured config for auth and Athena endpoint settings. */\n config?: AthenaProviderConfig;\n\n /** @deprecated Prefer `config.apiKey`. API key for authentication in standalone mode. */\n apiKey?: string;\n\n /** @deprecated Prefer `config.token`. PropelAuth token. If provided, takes priority over apiKey. If omitted, the SDK\n * will automatically listen for a token from the parent window via PostMessage. */\n token?: string | null;\n\n /** Run the thread AS a published collab agent. The only accepted shape is\n * `collab_agent:<asset_id>`: the thread then uses that agent's prompt,\n * tools, and model default, and the caller must have view access to the\n * agent asset. Omit it (or pass a blank string) to run the Athena deep agent.\n *\n * Any other non-blank value throws at render — the statewire host cannot\n * honour named agents, and a selector that is silently dropped would let a\n * misconfigured deployment answer as the wrong agent. */\n agent?: string;\n\n /** Collab-agent channel id — a built-in channel (`email`, `sms`, …) or a\n * user-defined custom channel id from the agent's Channels tab. Selects\n * that channel's configuration overrides and stamps the session's origin.\n * Only meaningful together with a `collab_agent:<asset_id>` `agent`; sent\n * as `collab_channel_id`. An unknown or disabled channel rejects the run\n * with a structured, teaching error. */\n channel?: string;\n\n /** The agent's modes people can switch between in this chat, by id: `base`\n * (the agent as configured) or a mode's id from the agent's Modes tab.\n * `AthenaChat` shows a mode menu in its composer with the ones the agent's\n * published definition offers on `channel` (its start mode, the channel\n * itself, and the modes its author lists for it); `useAthenaChatMode`\n * drives a menu of your own. A pick applies to the open session's next\n * send. On a channel the author locks, people pick the mode before a\n * session's first message and it stays. Only meaningful with a collab\n * `agent`; omit it for no menu. */\n modes?: readonly string[];\n\n /** LLM model identifier. Defaults to the deep-agent default model\n * (`DEFAULT_STATEWIRE_MODEL`) — or, when a collab agent is selected, to\n * the model its author configured.\n *\n * Changing it while a thread is open applies to that thread's next turn:\n * on a thread whose server config already exists the SDK writes the new\n * model there (`undefined` clears it, so the agent's model applies). The\n * value a thread is opened with is not written; read the thread's own\n * model with `useAthenaThreadModel`. */\n model?: string;\n\n /** Backend toolkit IDs to enable (e.g. 'document_toolkit', 'web_search_browse_toolkit').\n *\n * Sent with the backend-bound `frontendTools` as `enabled_tools`. Like\n * `model`, a change while a thread is open applies to its next turn: on a\n * thread whose server config exists the SDK writes the new list there (an\n * empty list clears it, so a collab agent's own tools apply). The list a\n * thread is opened with is not written. */\n tools?: string[];\n\n /** Frontend tools that execute in the browser. The agent can invoke these.\n * Merged on top of the SDK's default auto-open tools; entries here take\n * precedence over defaults with the same name. Tools with a local\n * `execute` are declared to the backend as `client_tools` and run through\n * the statewire client-tool bridge. */\n frontendTools?: Toolkit;\n\n /** Your own consent UI for frontend tools marked `requiresWriteConsent`,\n * in place of the card `AthenaChat` draws. Called before such a tool's\n * first call in a conversation runs; resolve `true` to allow that\n * conversation's writes, `false` to decline the waiting calls. Its `signal`\n * aborts when the question no longer has a call to answer. */\n confirmClientToolWrites?: ClientToolWriteConfirmer;\n\n /** Let the agent see, point at and operate the elements this app marks as\n * agent targets (`agentTarget`, `useAgentTarget`, `<AgentTarget>`), on the\n * screen the person has open: it gains `read_screen`, `point_at`,\n * `show_steps` and `act_on` (and `go_to` with `routes`), and everything it\n * does is shown on the page. `true` takes the defaults; pass options to\n * name the agent, set the speed, turn acting off (`allowActing: false`, an\n * \"ask\" mode) or restyle the overlay. Before the agent first acts in a\n * conversation the person is asked (see `requiresWriteConsent`). An app\n * that marks no targets gives the agent nothing to see. */\n agentUi?: boolean | AthenaAgentUiOptions;\n\n /** Disable the SDK's default auto-open behavior for created/touched assets. */\n disableAutoOpen?: boolean;\n\n /** @deprecated Prefer `config.apiUrl`. URL on the Iris host fronting the\n * deployment; its origin derives the statewire sync mount when\n * `statewireSyncUrl` is not set. */\n apiUrl?: string;\n\n /** @deprecated Prefer `config.backendUrl`. URL for the Athena backend API. */\n backendUrl?: string;\n\n /** @deprecated Prefer `config.appUrl`. URL for the Athena frontend app origin. */\n appUrl?: string;\n\n /** @deprecated Prefer `config.environment`. Athena environment preset used when URLs are not explicitly provided. */\n environment?: AthenaEnvironment;\n\n /** Resolve the latest auth token immediately before a request (for\n * expiring clients). Takes priority over `token` when it resolves.\n * Prefer `config.getToken` (see its `force` contract for refused\n * credentials). */\n getToken?: AthenaStatewireTokenGetter;\n\n /** Additional fields merged into runConfig.custom. Prefer\n * `config.extraRunConfig`. */\n extraRunConfig?: Record<string, unknown>;\n\n /** Statewire sync base URL override (the `…/v2/threads` mount). Defaults to\n * the mount a Marathon host mints, then the effective `apiUrl` host +\n * `/v2/threads`. Prefer `config.statewireSyncUrl`. */\n statewireSyncUrl?: string;\n\n /** Asset IDs to include in the workbench. A change while a thread is open\n * is written to its server config, as `model` is (empty clears it). */\n workbench?: string[];\n\n /** Knowledge base IDs for RAG context. A change while a thread is open is\n * written to its server config, as `model` is (empty clears it). */\n knowledgeBase?: string[];\n\n /** System prompt override. A change while a thread is open is written to\n * its server config, as `model` is (blank clears it, so a collab agent's\n * own prompt applies). */\n systemPrompt?: string;\n\n /** Plan mode: whether the agent keeps a to-do plan for multi-step work and\n * checks its steps off as it goes (the `write_todos` tool and its planning\n * prompt), which `AthenaChat` shows above the composer (`AthenaPlanStrip`).\n * `false` runs without one, `true` with one; omit it to leave each\n * thread's own setting (a thread plans unless its config says otherwise).\n *\n * Like `model`, changing it while a thread is open applies to that\n * thread's next turn: on a thread whose server config exists the SDK\n * writes it there (only the `write_todos` and `TodoListMiddleware`\n * entries of its exclusion lists change). The value a thread is opened\n * with is not written; read the thread's own with\n * `useAthenaThreadPlanMode`. A collab agent whose author turned its\n * built-in tools off never plans: a run can only narrow what an agent may\n * use. */\n planMode?: boolean;\n\n /** Client app identifier for session filtering.\n * Sessions created with this ID can be filtered in the thread list.\n * E.g. \"olympus\", \"athena-app\", or a computer asset ID like \"asset_<uuid>\". */\n appId?: string;\n\n /** Thread ID override. Auto-generated if not provided. */\n threadId?: string;\n\n /**\n * With `threadId` and no thread list: the host minted that id\n * (`mintThreadId`) for a chat that has not started, which attaches as a new\n * chat until this turns false. Turn it false once the backend lists the\n * thread (a host showing several chats keeps each one's id across a remount\n * this way). Default `false`: a given `threadId` names an existing thread.\n */\n threadIsNew?: boolean;\n\n /** Enable thread list management (sidebar thread switching). */\n enableThreadList?: boolean;\n\n /** Ask the thread list for live pull-request state on each session\n * (`include_pull_requests`), which `SessionList` renders as chips.\n * Defaults to `true` in thread-list mode; turn it off in a host that never\n * shows them to spare the server the lookup. */\n threadListIncludePullRequests?: boolean;\n\n /** Other client apps whose sessions the thread list shows beside this\n * provider's own (`appId`), e.g. a desktop app listing the sessions of the\n * desktop app it replaced. New sessions are still tagged `appId`. */\n threadListAdditionalAppIds?: readonly string[];\n\n /** Make this app the home of its collab `agent`: the thread list also shows\n * the conversations people have with the agent anywhere else (Slack, email,\n * SMS, …) that the viewer can already open, beside this provider's own\n * (`appId`), and a new one appears while the app is open. Needs\n * `enableThreadList` and a `collab_agent:<asset_id>` `agent`; without\n * either it does nothing. Athena widens the list only while the agent has a\n * home app set and the viewer can open the agent; an Athena that predates\n * the setting lists the app's sessions alone. New sessions are still tagged\n * `appId`. Default `false`. */\n threadListAgentHome?: boolean;\n\n /** Theme configuration. Pass a preset from `themes` or a custom `AthenaTheme` object.\n * Injects CSS variables on a wrapper element — no CSS files needed.\n *\n * @example\n * import { themes } from '@athenaintel/react';\n * <AthenaProvider theme={themes.dark}>\n *\n * @example\n * <AthenaProvider theme={{ primary: '#8b5cf6', radius: '1rem' }}>\n *\n * @example\n * <AthenaProvider theme={{ ...themes.dark, primary: '#22c55e' }}>\n */\n theme?: AthenaTheme;\n\n /** Customize how rendered chat links behave. */\n linkClicks?: AthenaLinkClickOptions;\n\n /** @deprecated Prefer `linkClicks`. Customize how Athena citation links rendered in chat messages behave. */\n citationLinks?: AthenaCitationLinkOptions;\n\n /** Opens assets the host's own way (a desktop app's tabs, a route of its own). While set, every\n * request to open an asset goes here before the SDK's asset panel: a tool card's Open, an\n * Athena citation or asset link in a message (which the SDK then intercepts as it does with an\n * asset panel mounted), and the auto-open after a tool created or touched an asset\n * (`origin: 'auto'`, with `autoOpen` saying which tool, and whether it made the asset, opened it\n * for the person or only touched it). Return `false` to let the panel open it as before. */\n onOpenAsset?: AssetOpener;\n\n /** PostHog analytics configuration. When omitted or keys are missing, PostHog is silently disabled.\n * Prefer `config.posthog` for structured configuration. */\n posthog?: PostHogConfig;\n\n /** SDK diagnostics.\n *\n * - `true` / a level: echo structured `[AthenaSDK]` events to the console\n * at that level (`true` = 'debug').\n * - An object: full diagnostics config (console level, PostHog timing\n * forwarding, buffer size).\n *\n * Independent of the prop, `localStorage.setItem('athena:debug','debug')`\n * (or `window.__ATHENA_SDK__.diagnostics.enableConsole()`) turns console\n * echo on at runtime without a rebuild. Errors log once even when off. */\n debug?: boolean | AthenaDiagnosticLevel | Partial<AthenaDiagnosticsConfig>;\n\n /** Receives every diagnostics event (timings, warnings, errors) — the hook\n * for shipping SDK telemetry to the host app's own pipeline. */\n onDiagnostic?: (event: AthenaDiagnosticEvent) => void;\n\n /** Receives every SDK error as a typed `AthenaSdkError` (stable `code`,\n * `hint`, structured server `detail`). Fires in addition to the UI's own\n * error handling, so integrations never fail silently. */\n onError?: (error: AthenaSdkError, event: AthenaDiagnosticEvent) => void;\n\n /** Opt-in: keep recent conversations and the session list on this device,\n * sealed with the host's key, readable while Athena can't be reached\n * (see {@link AthenaOfflineHistory}). Whether to keep anything is decided\n * at mount; without it nothing is stored. Passing none later (a policy\n * that now keeps nothing on devices) deletes what was kept. */\n offlineHistory?: AthenaOfflineHistory;\n\n /** Opt-in: messages typed while Athena can't be reached wait on this device, sealed with the\n * host's key, and are sent once Athena is back while the app is in front, after a countdown\n * (see {@link AthenaChatOutbox}). Without it a send goes to the transport as before. */\n chatOutbox?: AthenaChatOutbox;\n\n /** Opt-in: the chat loads a subagent's earlier steps, as the transcript drawer of\n * `AthenaChat`'s subagent lanes does (\"Load earlier steps\"). Turn it on when every `task` call\n * your chat shows renders in those lanes (`AthenaChat` with the registry's `task`,\n * `SubagentTaskToolUI`): the provider then declares the deep-agent lane-cut contract\n * (protocol 2), so Athena sends a finished subagent's card with only its newest steps, as it\n * sends a running one, and the drawer reads the rest. Off by default, so a chat that renders `task` with a UI of its own,\n * or reads every step off the card (`artifact.subgraph_state.messages`), keeps receiving\n * finished subagents whole. Read when a thread attaches. */\n subagentLaneHistory?: boolean;\n}\n\nconst resolveTokenOverride = ({\n config,\n token,\n}: {\n config?: AthenaProviderConfig;\n token?: string | null;\n}): string | null | undefined => {\n if (config?.token !== undefined) {\n return config.token;\n }\n return token;\n};\n\nconst useAthenaConfigValue = ({\n backendUrl,\n appUrl,\n apiKey,\n token,\n getToken,\n enabledToolkits,\n linkClicks,\n citationLinks,\n}: {\n backendUrl: string;\n appUrl: string;\n apiKey?: string;\n token?: string | null;\n getToken?: AthenaStatewireTokenGetter;\n enabledToolkits: string[];\n linkClicks?: AthenaLinkClickOptions;\n citationLinks?: AthenaCitationLinkOptions;\n}): AthenaConfig => {\n const linkClicksRef = useRef(linkClicks);\n linkClicksRef.current = linkClicks;\n const citationLinksRef = useRef(citationLinks);\n citationLinksRef.current = citationLinks;\n // Keep token in a ref so its value can update without invalidating the\n // config object identity. PropelAuth rotates tokens on window focus —\n // if token were a memo dep, every rotation would publish a new config\n // object to context and force every consumer (e.g. AssetIframe) to\n // re-render, causing asset panel flicker.\n const tokenRef = useRef(token);\n tokenRef.current = token;\n const getTokenRef = useRef(getToken);\n getTokenRef.current = getToken;\n\n return useMemo(\n () => ({\n backendUrl,\n appUrl,\n apiKey,\n enabledToolkits,\n get token() {\n return tokenRef.current;\n },\n get getToken() {\n return getTokenRef.current;\n },\n get linkClicks() {\n return linkClicksRef.current;\n },\n get citationLinks() {\n return citationLinksRef.current;\n },\n }),\n [backendUrl, appUrl, apiKey, enabledToolkits],\n );\n};\n\n/**\n * Delivers composer writes that were made before this mount was ready\n * (`useAppendToComposer` / `useSendMessage` queue them in the provider-level\n * store, which outlives the keyed per-thread mount). Lives under the\n * `AuiProvider` so it can read the thread's own loading state.\n */\nfunction ComposerHandoffDrain(): null {\n const aui = useAui();\n const store = useComposerHandoffStore();\n const threadId = useContext(AthenaStatewireThreadIdContext);\n const ready = useComposerReady();\n useEffect(() => {\n if (!ready || !store) return;\n // Writes bound to another thread are dropped here, not applied.\n drainComposerHandoff({ store, target: aui, threadId });\n }, [aui, ready, store, threadId]);\n return null;\n}\n\n/**\n * Keeps the composer's draft across the SDK's own trip through sign-in (a\n * session that ended while the page was open, `auth/sign-back-in.ts`): kept\n * when the page leaves, put back once this person's same conversation is ready\n * on the page that returns (`composer/sign-back-in-draft.ts`). Only for a\n * person a sign-in provider names; with none, nothing is kept.\n */\nfunction ComposerDraftCarry({ isNewChat }: { isNewChat: boolean }): null {\n const aui = useAui();\n const threadId = useContext(AthenaStatewireThreadIdContext);\n const principal = statewireSessionPrincipal(useContext(AthenaAuthContext));\n const ready = useComposerReady();\n useEffect(() => {\n if (!principal || !threadId) return;\n const keep = () => {\n keepDraftForSignBackIn({\n principal,\n threadId,\n isNewChat,\n text: aui.composer.getState().text ?? '',\n });\n };\n window.addEventListener(ATHENA_SIGN_BACK_IN_EVENT, keep);\n return () => window.removeEventListener(ATHENA_SIGN_BACK_IN_EVENT, keep);\n }, [aui, principal, threadId, isNewChat]);\n useEffect(() => {\n if (!ready || !principal || !threadId) return;\n const kept = takeDraftKeptForSignBackIn({ principal, threadId, isNewChat });\n if (kept === null) return;\n void applyComposerWrite({\n target: aui,\n store: null,\n write: { text: kept, replace: false, send: false, focus: false, threadId },\n });\n }, [aui, ready, principal, threadId, isNewChat]);\n return null;\n}\n\n// ─── Standalone Mode ──────────────────────────────────────────────────\n\nconst EMPTY_MODES: readonly string[] = [];\n\n/** How long one read of a waiting message's attachment may take (the outbox bounds the whole check too). */\nconst CHAT_OUTBOX_ATTACHMENT_READ_TIMEOUT_MS = 10_000;\n\n/** A provider whose chat outbox has not read its owner's write key yet: every session waits. */\nconst CHAT_SESSION_KEEPING_PENDING: AthenaChatSessionKeeping = { kind: 'pending' };\n\n/** `record` with `key` set to `value` (`null` drops it); the same object when nothing changes. */\nfunction withEntry(\n record: Readonly<Record<string, string>>,\n key: string,\n value: string | null,\n): Readonly<Record<string, string>> {\n if (value === null) {\n if (!(key in record)) return record;\n const { [key]: _dropped, ...rest } = record;\n return rest;\n }\n return record[key] === value ? record : { ...record, [key]: value };\n}\n\n/** Everything the per-thread runtime needs to attach and run a thread. */\ninterface AthenaStatewireRuntimeProps {\n syncUrl: string;\n apiKey?: string;\n token?: string | null;\n getToken?: AthenaStatewireTokenGetter;\n model?: string;\n agent?: string;\n channel?: string;\n /** The mode picked for this thread (`AthenaProviderProps.modes`). */\n mode?: string;\n tools: string[];\n frontendToolIds: string[];\n frontendTools: Toolkit;\n workbench?: string[];\n knowledgeBase?: string[];\n systemPrompt?: string;\n appId?: string;\n extraRunConfig?: Record<string, unknown>;\n /** `AthenaProviderProps.planMode`. */\n planMode?: boolean;\n /** The provider-owned snapshot cache (see `AthenaProvider`). */\n snapshotCache: DeepAgentThreadSnapshotCache;\n /** The provider-owned store of fetched-back cut tool outputs (see `AthenaProvider`). */\n toolOutputs: DeepAgentToolOutputStore;\n /** Where the open thread's windowed history stands (`StatewireHistoryContext`). */\n historyStore: StatewireHistoryStore;\n /** The provider's chat outbox host (`chatOutbox`), or `null` when the host keeps none. */\n chatOutbox?: AthenaStatewireChatOutboxHost | null;\n /** The provider-owned session lane gate the mounted runtime reports its lane to (see `AthenaProvider`). */\n sessionLane: StatewireSessionLaneGate;\n /** `AthenaProviderProps.subagentLaneHistory`. */\n subagentLaneHistory: boolean;\n}\n\n/** The chat outbox as the per-thread mount takes it: the owner's storage and the host's signals. */\ninterface AthenaStatewireChatOutboxHost {\n storage: ChatOutboxOwnerStorage;\n /** Where the thread's session lives (`pending` until the owner's write key is read). */\n keeping: AthenaChatSessionKeeping;\n reachability?: ChatOutboxSignal;\n foreground?: ChatOutboxSignal;\n /** Asks Athena, as the person, whether a waiting message's attachments can still be opened. */\n checkAttachments?: ChatOutboxAttachmentCheck;\n /** Opens another conversation holding waiting messages (the tray's Open), when the host can. */\n openThread?: (target: { threadId: string; newChat: boolean }) => void;\n}\n\ninterface AthenaStatewireStandaloneProps extends AthenaStatewireRuntimeProps {\n children: ReactNode;\n backendUrl: string;\n appUrl: string;\n /** `AthenaProviderProps.modes`. */\n modes?: readonly string[];\n threadId?: string;\n /** `AthenaProviderProps.threadIsNew`. */\n threadIsNew?: boolean;\n /**\n * Thread-list mode. The list owns the active id and alone knows whether the\n * backend has listed it yet: `isNewChat` overrides the \"new chat\"\n * derivation (the list mints ids for brand-new chats, which must still load\n * as new), and the scope publishes `AthenaThreadIdContext` — the backend id,\n * withheld while the chat is unpersisted. Absent outside thread-list mode,\n * where that context stays untouched.\n */\n threadList?: { isNewChat: boolean };\n linkClicks?: AthenaLinkClickOptions;\n citationLinks?: AthenaCitationLinkOptions;\n /** `AthenaProviderProps.confirmClientToolWrites`. */\n confirmClientToolWrites?: ClientToolWriteConfirmer;\n /** The agent's name from `agentUi.agentName`: the write-consent question names who is asking. */\n clientToolConsentAgentName?: string;\n}\n\n/**\n * What one per-thread runtime mount hands to the stable scope around the\n * host's children: the assistant client attached to `threadId` and the\n * transport lifecycle observed on that attach. Published as ONE value so the\n * scope can never pair a thread's id with another thread's client.\n */\ninterface AthenaStatewireRuntimeSnapshot {\n /** Opaque lifetime of the host/principal/thread that produced this snapshot. */\n binding: object;\n sessionPersistence: AthenaSessionPersistence | null;\n threadId: string;\n isNewChat: boolean;\n client: AssistantClient;\n lifecycle: AthenaStatewireLifecycleState;\n /** The thread's server config lane as the host sent it on this attach. */\n serverLane: AthenaStatewireServerLane;\n /** The thread's chat outbox (`AthenaProviderProps.chatOutbox`), or `null`. */\n outbox: ChatOutbox | null;\n /**\n * The provider-owned thread-config values this thread's sends carry (the\n * model, system prompt, enabled tools, workbench and knowledge base, each\n * under its `extraRunConfig` override), published with the thread they apply\n * to: during a switch the scope still holds the outgoing thread for a render\n * while the host's props already describe the incoming one, and pairing them\n * would write the new values into the session being left.\n */\n threadConfig: ProviderThreadConfig;\n /**\n * The provider's `planMode` for this thread (`null`: it sets none), published\n * with the thread for the same reason as `threadConfig`.\n */\n planMode: boolean | null;\n}\n\n/**\n * {@link providerThreadConfig} for the props, as one object per VALUE: hosts\n * pass fresh array literals (and the provider defaults `tools` to a new `[]`)\n * on every render, and a new object per render would republish the thread's\n * snapshot, which re-renders this mount, without end.\n */\nfunction useProviderThreadConfig(\n inputs: Parameters<typeof providerThreadConfig>[0],\n): ProviderThreadConfig {\n const value = providerThreadConfig(inputs);\n const key = JSON.stringify(value);\n // `key` is the value-stable form of `value`.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n return useMemo(() => value, [key]);\n}\n\n/**\n * The per-thread half of the statewire lane: owns the runtime hook (statewire\n * client, pending-message lane, `useAui` client) and the lifecycle reducer\n * behind the connection/error banners, and renders nothing itself. Mounted\n * under `key={threadId}` so a switch — or a new chat — gets a fresh instance\n * of everything here, exactly as when the whole provider subtree was keyed,\n * without remounting the host's UI.\n *\n * An assistant client's readable state only advances when its tap fibers\n * commit (in effects), so an in-place `threadId` change on one mounted hook\n * would leave a commit in which the new id is published but `useAuiState`\n * still reads the previous thread's committed state; a fresh mount publishes\n * its own state on its first render. That is why the runtime is remounted per\n * thread rather than switched in place.\n *\n * The snapshot is published from a layout effect: React flushes the state\n * update a layout effect schedules synchronously, before the browser paints,\n * so the scope re-renders against this client in the same task as this\n * mount's commit — the previous client is never painted under the new id.\n */\nfunction AthenaStatewireRuntimeMount({\n binding,\n threadId,\n isNewChat,\n onPublish,\n syncUrl,\n apiKey,\n token,\n getToken,\n model,\n agent,\n channel,\n mode,\n tools,\n frontendToolIds,\n frontendTools,\n workbench,\n knowledgeBase,\n systemPrompt,\n appId,\n extraRunConfig,\n planMode,\n snapshotCache,\n toolOutputs,\n chatOutbox = null,\n sessionLane,\n subagentLaneHistory,\n}: AthenaStatewireRuntimeProps & {\n binding: object;\n threadId: string;\n isNewChat: boolean;\n onPublish: (snapshot: AthenaStatewireRuntimeSnapshot) => void;\n}): null {\n const activeBinding = useRef<object | null>(null);\n useLayoutEffect(() => {\n activeBinding.current = binding;\n return () => {\n activeBinding.current = null;\n };\n }, [binding]);\n const [persistence, setPersistence] = useState<{\n binding: object;\n value: AthenaSessionPersistence;\n } | null>(null);\n const sessionPersistence = persistence?.binding === binding ? persistence.value : null;\n const onSessionPersistedChange = useCallback(\n (event: AthenaSessionPersistence) => {\n if (activeBinding.current !== binding || event.threadId !== threadId) return;\n setPersistence((previous) => {\n if (activeBinding.current !== binding) return previous;\n if (\n previous?.binding === binding &&\n previous.value.sessionPersisted === event.sessionPersisted\n ) return previous;\n return {\n binding,\n value: { threadId: event.threadId, sessionPersisted: event.sessionPersisted },\n };\n });\n },\n [binding, threadId],\n );\n const [defaultForeground] = useState(documentVisibleSignal);\n const [lifecycle, dispatchLifecycle] = useReducer(\n statewireLifecycleReducer,\n initialStatewireLifecycle,\n );\n const [serverLane, setServerLane] = useState<AthenaStatewireServerLane>(\n STATEWIRE_SERVER_LANE_PENDING,\n );\n\n const client = useAthenaStatewireRuntime({\n onSessionPersistedChange,\n syncUrl,\n threadId,\n isNewChat,\n apiKey,\n token,\n getToken,\n model,\n agent,\n channel,\n mode,\n tools,\n frontendToolIds,\n frontendToolkit: frontendTools,\n workbench,\n knowledgeBase,\n systemPrompt,\n appId,\n extraRunConfig,\n planMode,\n snapshotCache,\n toolOutputs,\n subagentLaneHistory,\n // The runtime already records every transport error on the diagnostics\n // bus (with the channel-teardown split), so this layer only maps it to\n // the banner notice.\n onError: (error) => {\n const notice = athenaStatewireErrorNotice(error);\n if (notice) dispatchLifecycle({ type: 'error', error: notice });\n },\n onConnectionChange: (connection) => {\n dispatchLifecycle({ type: 'connection', connection });\n },\n onRawConnectionChange: (connection) => {\n dispatchLifecycle({ type: 'raw-connection', reconnect: connection.reconnect });\n },\n ...(chatOutbox && {\n chatSession: chatOutbox.keeping,\n foreground: chatOutbox.foreground ?? defaultForeground,\n }),\n // The lane as the host holds it: anything that decides from the lane waits\n // for this, never the placeholder or remembered snapshot rendered before.\n onServerState: (state) => {\n const config = readServerConfig(state);\n setServerLane((previous) => nextServerLane({ previous, config }));\n },\n });\n\n // The runtime's session lane, reported once its client has committed it\n // (this effect runs after the runtime's own): a send held while the sign-in\n // provider was still resolving who is signed in (`StatewireSessionLane`)\n // goes out over the signed-in user's lane, never into the parked one.\n const lanePending = statewireSessionPrincipal(useContext(AthenaAuthContext)) === null;\n useEffect(() => {\n sessionLane.setPending(lanePending);\n }, [sessionLane, lanePending]);\n\n // Athena's reachability for the outbox: the host's (the browser online when it names none) AND\n // this conversation's channel not failing to connect (an attach that keeps retrying means Athena\n // can't be reached from here, whatever the host's own model last heard).\n const connectionRef = useRef(lifecycle.connection);\n connectionRef.current = lifecycle.connection;\n const [connectionListeners] = useState(() => new Set<() => void>());\n useEffect(() => {\n for (const listener of connectionListeners) listener();\n }, [lifecycle.connection, connectionListeners]);\n const [channelReachability] = useState<ChatOutboxSignal>(() => ({\n get: () => connectionRef.current?.status !== 'retrying',\n subscribe: (listener) => {\n connectionListeners.add(listener);\n return () => {\n connectionListeners.delete(listener);\n };\n },\n }));\n const [browserOnline] = useState(browserOnlineSignal);\n const hostReachability = chatOutbox?.reachability;\n const reachability = useMemo(\n () => allChatOutboxSignals(hostReachability ?? browserOnline, channelReachability),\n [hostReachability, browserOnline, channelReachability],\n );\n const composerHandoff = useComposerHandoffStore();\n const outbox = useDeepAgentChatOutbox({\n client,\n threadId,\n isNewChat,\n ...(chatOutbox && {\n directory: chatOutbox.storage.directory,\n legacy: { reader: chatOutbox.storage.legacy },\n }),\n reachability,\n foreground: chatOutbox?.foreground ?? defaultForeground,\n // Cancel and Edit give the draft back, after anything typed since. Its attachments come back\n // as mentions in it, remembered so a message held again from it is asked about again, the\n // agents it named come back to the To line, and what an app attached to it comes back as chips.\n restore: (entry) => {\n const draft = entry.composerMarkdown ?? entry.text;\n const current = client.composer.getState().text ?? '';\n client.composer.setText(current.trim() ? `${current}\\n\\n${draft}` : draft);\n if (composerHandoff && entry.attachments) {\n rememberRestoredAttachments({\n store: composerHandoff,\n threadId,\n attachments: entry.attachments,\n });\n }\n giveBackDeepAgentOutboxNamedAgents(entry);\n giveBackHeldAttachedReferences(entry);\n },\n ...(chatOutbox?.openThread && { openThread: chatOutbox.openThread }),\n ...(chatOutbox?.checkAttachments && { checkAttachments: chatOutbox.checkAttachments }),\n enabled: chatOutbox !== null && chatOutbox.keeping.kind !== 'pending',\n });\n\n // A thread the host stopped for refusing its credential reconnects as soon\n // as a new token exists, instead of waiting for a retry click.\n useRestartAfterAuthRefusal({\n connection: lifecycle.connection,\n reconnect: lifecycle.reconnect,\n });\n\n const dismissError = useCallback(\n () => dispatchLifecycle({ type: 'error', error: null }),\n [],\n );\n const lifecycleValue = useMemo<AthenaStatewireLifecycleState>(\n () => ({\n connection: lifecycle.connection,\n error: lifecycle.error,\n reconnect: lifecycle.reconnect,\n dismissError,\n }),\n [lifecycle, dismissError],\n );\n\n const threadConfig = useProviderThreadConfig({\n model,\n systemPrompt,\n tools,\n frontendToolIds,\n workbench,\n knowledgeBase,\n extraRunConfig,\n });\n const snapshot = useMemo<AthenaStatewireRuntimeSnapshot>(\n () => ({\n binding,\n sessionPersistence,\n threadId,\n isNewChat,\n client,\n lifecycle: lifecycleValue,\n serverLane,\n threadConfig,\n planMode: planMode ?? null,\n outbox,\n }),\n [binding, sessionPersistence, threadId, isNewChat, client, lifecycleValue, serverLane, threadConfig, planMode, outbox],\n );\n useLayoutEffect(() => {\n onPublish(snapshot);\n }, [onPublish, snapshot]);\n\n return null;\n}\n\n/**\n * The stable half of the statewire lane: the scope around the host's\n * `children`. It mounts one `AthenaStatewireRuntimeMount` per thread beside\n * them and provides whatever that mount last published — client, thread ids,\n * lifecycle — so a thread switch swaps the client under the host's UI instead\n * of remounting it. Until the first mount has published, the children are\n * withheld: they need a client, and the first publication lands in the same\n * task as the mount's commit.\n *\n * A server render runs no effects, so it would withhold the children too.\n * That changes nothing today: `AthenaProvider` renders `null` until the parent\n * bridge reports ready, which only ever happens in an effect (`useParentBridge`\n * starts `ready: false`), so the SDK has never server-rendered the host UI —\n * it hydrates it. A future SSR-ready bridge would need the first publication\n * to happen in render as well.\n */\nfunction AthenaStatewireStandalone({\n children,\n backendUrl,\n appUrl,\n threadId: threadIdProp,\n threadIsNew = false,\n threadList,\n linkClicks,\n citationLinks,\n modes,\n confirmClientToolWrites,\n clientToolConsentAgentName,\n ...runtimeProps\n}: AthenaStatewireStandaloneProps) {\n // Statewire attaches to `${syncUrl}/${threadId}`, so a thread ID must exist\n // up front. An auto-generated ID is by definition a never-started local chat.\n const generatedIdRef = useRef<string | null>(null);\n if (generatedIdRef.current === null) {\n generatedIdRef.current = mintThreadId();\n }\n const threadId = threadIdProp ?? generatedIdRef.current;\n const isNewChat = threadList?.isNewChat ?? (!threadIdProp || threadIsNew);\n\n const [published, setPublished] = useState<AthenaStatewireRuntimeSnapshot | null>(null);\n const principal = statewireSessionPrincipal(useContext(AthenaAuthContext));\n // Match Core's attachment scope. Credential rotation and presentation URL\n // changes do not create a new Core attach or re-notify an unchanged verdict.\n const binding = useMemo(() => ({}), [threadId, runtimeProps.syncUrl, principal]);\n\n // The mode menu (`modes`), kept across thread switches per agent, channel\n // and thread: the mode this browser picked and has not yet seen the session\n // run in, and the channel each session runs on as last read. A send names\n // the pick, else the session's channel, so it never moves a session another\n // browser switched; a pick the host no longer lists is never sent.\n const agentSelection = useContext(AthenaAgentSelectionContext);\n const modeScope = `${agentSelection?.agentAssetId ?? ''}\\u0000${agentSelection?.channel ?? ''}`;\n const [modePicks, setModePicks] = useState<Readonly<Record<string, string>>>({});\n const [sessionChannels, setSessionChannels] = useState<Readonly<Record<string, string>>>({});\n const setModePick = useCallback(\n ({ threadId: pickedThread, modeId }: { threadId: string; modeId: string | null }) =>\n setModePicks((picks) => withEntry(picks, `${modeScope}\\u0000${pickedThread}`, modeId)),\n [modeScope],\n );\n const setSessionChannel = useCallback(\n ({ threadId: readThread, channel }: { threadId: string; channel: string | null }) =>\n setSessionChannels((channels) =>\n withEntry(channels, `${modeScope}\\u0000${readThread}`, channel),\n ),\n [modeScope],\n );\n const hostModes = modes ?? EMPTY_MODES;\n const modeKey = hostModes.join('\\u0000');\n const listedPick = (thread: string): string | null => {\n const pick = modePicks[`${modeScope}\\u0000${thread}`];\n return pick !== undefined && hostModes.includes(pick) ? pick : null;\n };\n const threadMode =\n hostModes.length > 0\n ? (listedPick(threadId) ?? sessionChannels[`${modeScope}\\u0000${threadId}`])\n : undefined;\n\n const clientTools = useStatewireClientTools(runtimeProps.frontendTools);\n // The write-consent question for this provider's chat, and each write tool's\n // own words for it. The store outlives thread switches (an answer covers its\n // conversation for as long as the provider is mounted) but never its person:\n // another account signing in, or another Athena, starts with no answers.\n const writeConsentStore = useClientToolWriteConsentStore(\n `${principal ?? 'signing-in'}\\u0000${runtimeProps.syncUrl}`,\n );\n const writeConsentSummaries = useMemo(\n () => clientToolWriteConsentSummaries(runtimeProps.frontendTools),\n [runtimeProps.frontendTools],\n );\n\n // The runtime binds `client_tools` only for a recognised `app_id`; with none\n // it drops every declaration without telling the client, and the model then\n // sees \"not a valid tool\". Say so here, once per configuration, as an error\n // so it reaches `onError` and the console even with diagnostics off.\n const clientToolNamesKey = clientTools.map((tool) => tool.definition.name).join(',');\n const clientToolAppId = runtimeProps.appId;\n useEffect(() => {\n if (clientTools.length === 0 || resolveClientToolSurface(clientToolAppId) !== null) return;\n athenaDiagnostics.emit('sdk.config.warning', {\n level: 'error',\n error: new AthenaSdkError({\n code: 'config_invalid',\n message: `frontendTools with an execute() need a recognised appId; ${clientTools.length} tool(s) will not be bound.`,\n hint:\n \"Pass appId={publicAppId} on <AthenaProvider> (a computer-asset app reads it from athena-public-config.json as computer_asset_<uuid>). Without it the deep-agent runtime drops every client tool.\",\n context: { appId: clientToolAppId ?? null, tools: clientToolNamesKey.split(',') },\n }),\n data: { appId: clientToolAppId ?? null, tools: clientToolNamesKey.split(',') },\n });\n // clientToolNamesKey is the value-stable form of the tool list.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [clientToolAppId, clientToolNamesKey]);\n\n const athenaConfig = useAthenaConfigValue({\n backendUrl,\n appUrl,\n apiKey: runtimeProps.apiKey,\n token: runtimeProps.token,\n getToken: runtimeProps.getToken,\n enabledToolkits: runtimeProps.tools,\n linkClicks,\n citationLinks,\n });\n\n const chatModeSelection = useMemo<AthenaChatModeSelection | null>(\n () =>\n published\n ? {\n hostModes,\n threadId: published.threadId,\n isNewChat: published.isNewChat,\n pick: listedPick(published.threadId),\n sessionChannel: sessionChannels[`${modeScope}\\u0000${published.threadId}`] ?? null,\n setPick: setModePick,\n setSessionChannel,\n }\n : null,\n // modeKey is the value-stable form of hostModes, which listedPick reads.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [modeKey, modeScope, modePicks, sessionChannels, published, setModePick, setSessionChannel],\n );\n\n const scope = published && (\n <AuiProvider value={published.client}>\n <AthenaContext.Provider value={athenaConfig}>\n <AthenaStatewireThreadIdContext.Provider value={published.threadId}>\n <AthenaStatewireLifecycleContext.Provider value={published.lifecycle}>\n <DeepAgentConnectionContext.Provider value={published.lifecycle.connection}>\n <AthenaStatewireServerLaneContext.Provider value={published.serverLane}>\n <StatewireToolOutputsContext.Provider value={runtimeProps.toolOutputs}>\n <TurnStepsControlContext.Provider value={EarlierStepsButton}>\n <StatewireHistoryContext.Provider value={runtimeProps.historyStore}>\n <TooltipProvider>\n <ClientToolWriteConsentContext.Provider value={writeConsentStore}>\n <StatewireClientToolBridge\n tools={clientTools}\n threadId={published.threadId}\n writeConsentSummaries={writeConsentSummaries}\n writeConsentAgentName={clientToolConsentAgentName}\n confirmWrites={confirmClientToolWrites}\n />\n {/* Keyed per thread: each attach starts with no pending lane write. */}\n <StatewireThreadConfigLaneSync\n key={published.threadId}\n threadId={published.threadId}\n config={published.threadConfig}\n lane={published.serverLane}\n channelLive={isStatewireChannelLive(published.lifecycle.connection)}\n />\n <StatewirePlanModeLaneSync\n key={`plan-mode:${published.threadId}`}\n threadId={published.threadId}\n planMode={published.planMode}\n lane={published.serverLane}\n channelLive={isStatewireChannelLive(published.lifecycle.connection)}\n />\n <ComposerHandoffDrain />\n <ComposerDraftCarry isNewChat={published.isNewChat} />\n <DeepAgentChatOutboxContext.Provider value={published.outbox}>\n <AthenaChatModeSelectionContext.Provider value={chatModeSelection}>\n <AthenaSessionPersistenceContext.Provider\n value={published.binding === binding ? published.sessionPersistence : null}\n >\n {children}\n </AthenaSessionPersistenceContext.Provider>\n </AthenaChatModeSelectionContext.Provider>\n </DeepAgentChatOutboxContext.Provider>\n </ClientToolWriteConsentContext.Provider>\n </TooltipProvider>\n </StatewireHistoryContext.Provider>\n </TurnStepsControlContext.Provider>\n </StatewireToolOutputsContext.Provider>\n </AthenaStatewireServerLaneContext.Provider>\n </DeepAgentConnectionContext.Provider>\n </AthenaStatewireLifecycleContext.Provider>\n </AthenaStatewireThreadIdContext.Provider>\n </AthenaContext.Provider>\n </AuiProvider>\n );\n\n return (\n <>\n <AthenaStatewireRuntimeMount\n key={threadId}\n binding={binding}\n threadId={threadId}\n isNewChat={isNewChat}\n onPublish={setPublished}\n mode={threadMode}\n {...runtimeProps}\n />\n {/* The backend id rides the same snapshot as the client, so\n history-gated UI (e.g. the loading overlay) never judges one thread\n by another's state; it is undefined for a never-started chat, which\n must not read as pending history. */}\n {threadList && published ? (\n <AthenaThreadIdContext.Provider\n value={published.isNewChat ? undefined : published.threadId}\n >\n {scope}\n </AthenaThreadIdContext.Provider>\n ) : (\n scope\n )}\n </>\n );\n}\n\n// ─── Thread List Mode ─────────────────────────────────────────────────\n\nfunction AthenaStatewireWithThreadList({\n children,\n backendUrl,\n syncUrl,\n appId,\n apiKey,\n token,\n getToken,\n initialThreadId,\n includePullRequests,\n additionalListAppIds,\n listHomeAgentId,\n offlineList,\n ...standaloneProps\n}: Omit<AthenaStatewireStandaloneProps, 'threadId' | 'threadList'> & {\n initialThreadId?: string;\n includePullRequests?: boolean;\n additionalListAppIds?: readonly string[];\n /** The collab agent whose home this app is (`threadListAgentHome`), as a bare asset id. */\n listHomeAgentId?: string;\n /** Where the session list is kept for reading offline (`offlineHistory` only). */\n offlineList?: { mirror: ThreadSnapshotMirror; ownerId: string };\n}) {\n return (\n <AthenaStatewireThreadListProvider\n backendUrl={backendUrl}\n syncUrl={syncUrl}\n apiKey={apiKey}\n token={token}\n getToken={getToken}\n appId={appId}\n additionalListAppIds={additionalListAppIds}\n homeAgentId={listHomeAgentId}\n initialThreadId={initialThreadId}\n includePullRequests={includePullRequests}\n offlineList={offlineList}\n // The list's hover prefetch warms the same cache the active-thread\n // mount seeds from, so a hovered-then-selected session paints at once.\n snapshotCache={standaloneProps.snapshotCache}\n >\n <AthenaStatewireActiveThreadHost\n backendUrl={backendUrl}\n syncUrl={syncUrl}\n appId={appId}\n apiKey={apiKey}\n token={token}\n getToken={getToken}\n {...standaloneProps}\n >\n {children}\n </AthenaStatewireActiveThreadHost>\n </AthenaStatewireThreadListProvider>\n );\n}\n\nfunction AthenaStatewireActiveThreadHost({\n children,\n chatOutbox,\n ...standaloneProps\n}: Omit<AthenaStatewireStandaloneProps, 'threadId' | 'threadList'>) {\n const list = useAthenaStatewireThreadList();\n const selectThread = list?.selectThread;\n // The provenance this chat's sends stamp, so a new chat's pending row is badged as the\n // server's row will be.\n const startChannel = effectiveStatewireStartChannel({\n agent: standaloneProps.agent,\n channel: standaloneProps.channel,\n mode: standaloneProps.mode,\n extraRunConfig: standaloneProps.extraRunConfig,\n });\n // The tray's Open, when the host gives none: the list switches to the conversation (one that\n // never started, as the new chat it still is).\n const outboxHost = useMemo(\n () =>\n chatOutbox && !chatOutbox.openThread && selectThread\n ? {\n ...chatOutbox,\n openThread: ({ threadId, newChat }: { threadId: string; newChat: boolean }) =>\n selectThread(threadId, { isNew: newChat }),\n }\n : chatOutbox,\n [chatOutbox, selectThread],\n );\n if (!list) return null;\n\n // Not keyed: the scope keeps the host's children mounted across a switch\n // and remounts only its per-thread runtime against the new\n // `…/v2/threads/{id}` URL (see `AthenaStatewireStandalone`).\n return (\n <AthenaStatewireStandalone\n threadId={list.activeThreadId}\n threadList={{ isNewChat: list.isNewChat }}\n chatOutbox={outboxHost}\n {...standaloneProps}\n >\n <StatewireThreadTitlePoller />\n <StatewireThreadListSendSync startChannel={startChannel}>\n <AssetPanelThreadSync />\n {children}\n </StatewireThreadListSendSync>\n </AthenaStatewireStandalone>\n );\n}\n\n/**\n * Syncs the active thread ID into the asset panel store so that open asset\n * tabs are scoped per-thread automatically.\n *\n * Scoped by the attached thread's minted id from creation onward — NOT by\n * `useAthenaThreadManager().activeThreadId`, which is deliberately `null`\n * while a new chat is unpersisted (so URL sync never names it). The minted id\n * is the id the thread persists under, so tabs opened in a brand-new chat\n * stay put when the backend first lists it instead of being left behind in a\n * `null` scope the store never restores. Read from the statewire scope (the\n * id published with its client) rather than the list's selection, which runs\n * one commit ahead of the client during a switch.\n */\nfunction AssetPanelThreadSync() {\n const threadId = useAthenaStatewireThreadId();\n const setCurrentThread = useAssetPanelStore((s) => s.setCurrentThread);\n\n useEffect(() => {\n setCurrentThread(threadId);\n }, [threadId, setCurrentThread]);\n\n return null;\n}\n\n// ─── Main Provider ────────────────────────────────────────────────────\n\nexport function AthenaProvider({\n children,\n config,\n apiKey,\n token: tokenProp,\n agent,\n channel,\n modes,\n model,\n tools = [],\n frontendTools = {},\n confirmClientToolWrites,\n agentUi: agentUiProp = false,\n disableAutoOpen = false,\n apiUrl,\n backendUrl,\n appUrl,\n environment,\n statewireSyncUrl,\n getToken,\n extraRunConfig,\n workbench,\n knowledgeBase,\n systemPrompt,\n planMode,\n appId,\n threadId: threadIdProp,\n threadIsNew,\n enableThreadList = false,\n threadListIncludePullRequests = true,\n threadListAdditionalAppIds,\n threadListAgentHome = false,\n theme,\n linkClicks,\n citationLinks,\n onOpenAsset,\n posthog: posthogProp,\n debug,\n onDiagnostic,\n onError,\n offlineHistory,\n chatOutbox,\n subagentLaneHistory = false,\n}: AthenaProviderProps) {\n // Fail loud before any effect, bridge wait, or network call: an `agent`\n // outside the collab_agent namespace can never apply, so a misconfigured\n // deployment must die at first render rather than answer as the wrong agent.\n const agentAssetId = resolveAgentProp({ agent });\n // The channel rides only with an agent, as the run config sends it.\n const trimmedChannel = channel?.trim() ?? '';\n const agentChannel = agentAssetId && trimmedChannel !== '' ? trimmedChannel : null;\n const agentSelection = useMemo<AthenaAgentSelection>(\n () => ({ agentAssetId, channel: agentChannel }),\n [agentAssetId, agentChannel],\n );\n\n // Diagnostics wiring first, so everything below is observable. Callbacks\n // ride refs: a per-render closure must not re-register the consumer. Each\n // provider registers its OWN consumer (additive, cleaned up on unmount), so\n // two mounted providers never clobber each other's onDiagnostic/onError —\n // only the console/PostHog/buffer settings are global (last writer wins).\n const onDiagnosticRef = useRef(onDiagnostic);\n onDiagnosticRef.current = onDiagnostic;\n const onErrorRef = useRef(onError);\n onErrorRef.current = onError;\n useEffect(() => {\n installAthenaDiagnosticsGlobal();\n return athenaDiagnostics.addConsumer({\n onEvent: (event) => onDiagnosticRef.current?.(event),\n onError: (error, event) => onErrorRef.current?.(error, event),\n });\n }, []);\n // A host that opens assets its own way takes every request the SDK makes to open one, on the\n // shared asset store. The callback rides a ref, so a new one each render does not re-register.\n const onOpenAssetRef = useRef(onOpenAsset);\n onOpenAssetRef.current = onOpenAsset;\n const opensAssets = onOpenAsset !== undefined;\n useEffect(() => {\n if (!opensAssets) return;\n // The host's answer as given: anything but `false` (a callback returning nothing included)\n // means it opened the asset.\n return useAssetPanelStore.getState().registerAssetOpener((request) => {\n const open = onOpenAssetRef.current;\n return open ? open(request) : false;\n });\n }, [opensAssets]);\n const debugKey = JSON.stringify(debugPropToDiagnosticsConfig(debug));\n useEffect(() => {\n athenaDiagnostics.configure(debugPropToDiagnosticsConfig(debug));\n // debugKey is the value-stable form of `debug` (consumers pass literals).\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [debugKey]);\n // Only declarations WITHOUT a local `execute` ride `enabled_tools`: they name\n // registry tools the backend binds itself. Executable tools are declared\n // through `client_tools` instead — listing them here too would switch on a\n // backend toolkit owning a tool of the same name, and the backend wins that\n // collision (the client tool is silently dropped).\n const frontendToolNames = useMemo(\n () => backendDeclaredFrontendToolIds(frontendTools),\n [frontendTools],\n );\n // Merge SDK auto-open defaults under the consumer's frontendTools. Consumer\n // entries win on name collision; auto-open tool names are NOT added to\n // frontendToolIds (they are already backend-advertised by their toolkits).\n // The agent's tools for the screen the person has open. The controller is\n // always there (hooks cannot be conditional); its tools are declared, and\n // its overlay mounted, only when the host asked for them.\n // Anything but `true` or options is off (a host passing `null` or `undefined` included).\n const agentUiEnabled = agentUiProp === true || (typeof agentUiProp === 'object' && agentUiProp !== null);\n const { classNames: agentUiClassNames, ...agentUiOptions } =\n typeof agentUiProp === 'object' && agentUiProp !== null ? agentUiProp : EMPTY_AGENT_UI_OPTIONS;\n const agentUiActConsent = agentUiOptions.actConsent ?? 'host';\n const agentUiHost = useAgentUi({ ...agentUiOptions, actConsent: agentUiActConsent });\n const agentUiTools = useMemo<Toolkit>(() => {\n if (!agentUiEnabled) return EMPTY_TOOLKIT;\n const act = agentUiHost.tools[AGENT_UI_TOOL_NAMES.actOn];\n // The one tool that changes something asks through the chat's consent\n // card, unless the host chose the overlay's own question.\n if (!act || agentUiActConsent !== 'host') return agentUiHost.tools;\n return {\n ...agentUiHost.tools,\n [AGENT_UI_TOOL_NAMES.actOn]: requiresWriteConsent(act, { summary: AGENT_UI_ACT_SUMMARY }),\n };\n }, [agentUiActConsent, agentUiEnabled, agentUiHost.tools]);\n // SDK defaults first, the host's own tools last: a host tool of the same\n // name always wins.\n const effectiveFrontendTools = useMemo<Toolkit>(\n () => ({\n ...(disableAutoOpen ? {} : DEFAULT_AUTO_OPEN_TOOLS),\n ...agentUiTools,\n ...frontendTools,\n }),\n [agentUiTools, disableAutoOpen, frontendTools],\n );\n const themeStyleVars = useMemo(() => theme ? themeToStyleVars(theme) : undefined, [theme]);\n const configuredEnvironment = config?.environment ?? environment;\n const environmentUrls = useMemo(\n () => getAthenaEnvironmentUrls({ environment: configuredEnvironment }),\n [configuredEnvironment],\n );\n const configuredApiKey = config?.apiKey ?? apiKey;\n const configuredToken = resolveTokenOverride({ config, token: tokenProp });\n const configuredApiUrl = config?.apiUrl ?? apiUrl;\n const configuredBackendUrl = config?.backendUrl ?? backendUrl;\n const configuredAppUrl = config?.appUrl ?? appUrl;\n const configuredStatewireSyncUrl = config?.statewireSyncUrl ?? statewireSyncUrl;\n const configuredGetToken = config?.getToken ?? getToken;\n const configuredExtraRunConfig = config?.extraRunConfig ?? extraRunConfig;\n const configuredTrustedParentOrigins = config?.trustedParentOrigins;\n const posthogConfig: PostHogConfig | undefined = config?.posthog ?? posthogProp;\n\n // Statewire is the SDK's only chat transport; the gauge/event stay on the\n // diagnostics contract so dashboards keyed on them keep reading a value.\n useEffect(() => {\n athenaDiagnostics.gauge('sdk.transport', 'statewire');\n athenaDiagnostics.emit('sdk.transport', {\n level: 'debug',\n data: { transport: 'statewire', thread_list: enableThreadList },\n });\n }, [enableThreadList]);\n\n // If an AthenaAuthProvider is present above us, use its access token automatically.\n const authContext = useContext(AthenaAuthContext);\n const authProviderToken = authContext?.accessToken ?? null;\n\n const bridge = useParentBridge({\n trustedOrigins: configuredTrustedParentOrigins,\n // The Marathon bridge sends the page through sign-in itself only when its\n // token is the chat's credential: a sign-in provider above decides on its\n // own, and a host credential keeps working when the bridge's session ends.\n signBackInOnSessionEnd: bridgeOwnsCredential({\n signInProviderAbove: authContext !== null,\n token: configuredToken,\n getToken: configuredGetToken,\n apiKey: configuredApiKey,\n }),\n });\n // The page a trip through sign-in returned to gets its URL fragment back\n // (a hash-routed app's route), which Marathon's return drops.\n useEffect(() => {\n restoreSignBackInHash();\n }, []);\n\n // Per-provider snapshot cache: a switch back to a recently-visited thread\n // mounts with its last-known snapshot instead of a loading spinner. Owned\n // here, above the per-thread keyed mount, so it survives switches; cleared\n // when the acting identity changes so a snapshot captured under one account\n // never seeds a mount under another.\n //\n // With `offlineHistory` (opt-in, decided at mount) the cache is the durable\n // one: mirrored to this device under the host's key for the owner, readable\n // offline. The mirror only ever asks the host for the key of the owner it\n // is bound to; any other owner gets none.\n const offlineHistoryRef = useRef(offlineHistory);\n offlineHistoryRef.current = offlineHistory;\n const isOfflineNow = (): boolean =>\n offlineHistoryRef.current?.isOffline?.() ??\n (typeof navigator !== 'undefined' && navigator.onLine === false);\n const [offlineMirror] = useState(() =>\n offlineHistory\n ? createThreadSnapshotMirror({\n getKey: (ownerId) => {\n const host = offlineHistoryRef.current;\n return host && host.ownerId === ownerId ? host.getKey() : Promise.resolve(null);\n },\n })\n : null,\n );\n const [durableSnapshotCache] = useState(() =>\n offlineMirror\n ? createDurableThreadSnapshotCache({ mirror: offlineMirror, isOffline: isOfflineNow })\n : null,\n );\n const [snapshotCache] = useState<DeepAgentThreadSnapshotCache>(\n () => durableSnapshotCache ?? createDeepAgentThreadSnapshotCache(),\n );\n // The chat outbox (opt-in): the page's one storage per owner (`chatOutboxStorageFor`), asking\n // the host for that owner's key only. Its signals ride to each thread's mount.\n const chatOutboxRef = useRef(chatOutbox);\n chatOutboxRef.current = chatOutbox;\n const chatOutboxOwnerId = chatOutbox?.ownerId ?? null;\n const chatOutboxStorage = useMemo(() => {\n const host = chatOutboxRef.current;\n return host && host.ownerId === chatOutboxOwnerId ? chatOutboxStorageFor(host) : null;\n }, [chatOutboxOwnerId]);\n // The storage asks the latest host of its owner for the key.\n useEffect(() => {\n if (chatOutbox) chatOutboxStorageFor(chatOutbox);\n }, [chatOutbox]);\n // Sealed or in memory, read once per owner: every thread's session waits for it.\n const [chatSessionKeeping, setChatSessionKeeping] = useState<{\n storage: ChatOutboxOwnerStorage;\n keeping: AthenaChatSessionKeeping;\n } | null>(null);\n useEffect(() => {\n if (!chatOutboxStorage) return;\n let live = true;\n void resolveChatSessionKeeping(chatOutboxStorage).then((keeping) => {\n if (live) setChatSessionKeeping({ storage: chatOutboxStorage, keeping });\n });\n return () => {\n live = false;\n };\n }, [chatOutboxStorage]);\n const chatOutboxKeeping: AthenaChatSessionKeeping =\n chatSessionKeeping?.storage === chatOutboxStorage && chatSessionKeeping\n ? chatSessionKeeping.keeping\n : CHAT_SESSION_KEEPING_PENDING;\n const chatOutboxReachability = chatOutbox?.reachability;\n const chatOutboxForeground = chatOutbox?.foreground;\n const chatOutboxOpenThread = chatOutbox?.openThread;\n // A waiting message's attachments are asked about right before it goes: each read through\n // agora's permission-checked asset route as the person, with the credential and the backend this\n // provider holds at that moment (both assigned further down, every render).\n const outboxCheckAuthRef = useRef<StatewireAuthSource>({});\n const outboxCheckBackendRef = useRef('');\n const [checkChatOutboxAttachments] = useState<ChatOutboxAttachmentCheck>(() =>\n createChatOutboxAttachmentCheck({\n readAsset: (assetId) =>\n sendWithCredentialRenewal(outboxCheckAuthRef.current, (headers) =>\n fetch(`${outboxCheckBackendRef.current}${chatOutboxAttachmentPath(assetId)}`, {\n method: 'GET',\n headers,\n signal: AbortSignal.timeout(CHAT_OUTBOX_ATTACHMENT_READ_TIMEOUT_MS),\n }),\n ),\n }),\n );\n const chatOutboxHost = useMemo<AthenaStatewireChatOutboxHost | null>(\n () =>\n chatOutboxStorage === null\n ? null\n : {\n storage: chatOutboxStorage,\n keeping: chatOutboxKeeping,\n ...(chatOutboxReachability && { reachability: chatOutboxReachability }),\n ...(chatOutboxForeground && { foreground: chatOutboxForeground }),\n ...(chatOutboxOpenThread && { openThread: chatOutboxOpenThread }),\n checkAttachments: checkChatOutboxAttachments,\n },\n [\n chatOutboxStorage,\n chatOutboxKeeping,\n chatOutboxReachability,\n chatOutboxForeground,\n chatOutboxOpenThread,\n checkChatOutboxAttachments,\n ],\n );\n const offlineOwnerId = offlineHistory?.ownerId ?? null;\n // Binds the cache to the owner; a chat that mounts offline is held until what this device kept\n // for them is read, so its thread mounts on its seed.\n const awaitingKeptSnapshots = useKeptSnapshotsGate({\n cache: durableSnapshotCache,\n ownerId: offlineOwnerId,\n isOffline: isOfflineNow,\n });\n const offlineSnapshots = useMemo<AthenaOfflineSnapshots | null>(\n () =>\n durableSnapshotCache\n ? {\n offlineSeedAt: (threadId) => durableSnapshotCache.offlineSeedAt(threadId),\n subscribeOfflineSeeds: (listener) => durableSnapshotCache.subscribeOfflineSeeds(listener),\n }\n : null,\n [durableSnapshotCache],\n );\n const offlineList = useMemo(\n () => (offlineMirror && offlineOwnerId ? { mirror: offlineMirror, ownerId: offlineOwnerId } : undefined),\n [offlineMirror, offlineOwnerId],\n );\n // Composer writes that arrive before the per-thread mount is ready wait\n // here, above that mount, so a thread-list remount cannot drop them.\n const [composerHandoff] = useState(createComposerHandoffStore);\n // The windowed wire's fetched-back tool outputs, owned alongside the cache\n // for the same reasons: shared across the provider's thread switches (a\n // tool message id is unique across threads), dropped with the identity.\n const [toolOutputs] = useState(() => createDeepAgentToolOutputStore());\n // Where the open thread's history stands, reported by the chat's history\n // edge for other surfaces (the workbench's Shell pane).\n const [historyStore] = useState(createStatewireHistoryStore);\n const principal = authContext?.user?.userId ?? '';\n // Older history paged by command lives in the JS context's per-conversation\n // stores (`history/page`, shared by every reader of a conversation), so it\n // is dropped when the identity changes (it is what that identity may read),\n // not on a mount: another provider's open conversation keeps its pages.\n const pagedIdentity = useRef<{ principal: string; apiKey: string | undefined } | null>(null);\n useEffect(() => {\n snapshotCache.clear();\n toolOutputs.clear();\n const previous = pagedIdentity.current;\n if (previous !== null && (previous.principal !== principal || previous.apiKey !== configuredApiKey)) {\n clearDeepAgentHistoryStores();\n }\n pagedIdentity.current = { principal, apiKey: configuredApiKey };\n }, [snapshotCache, toolOutputs, principal, configuredApiKey]);\n // The principal the chat's command lane is scoped by: `null` while the\n // sign-in provider above is still resolving who is signed in. The lane is\n // pending until then (`useAthenaStatewireRuntime`), and sends wait for it on\n // the provider's gate, which the mounted runtime keeps current.\n const sessionPrincipal = statewireSessionPrincipal(authContext);\n const [sessionLane] = useState(() =>\n createStatewireSessionLaneGate({ pending: sessionPrincipal === null }),\n );\n // A draft or send queued under one identity must never land in another's\n // composer. One queued while the sign-in was still resolving was made by\n // whoever signs in and waits for their lane, so only a change from one known\n // identity to another drops what waits.\n const handoffIdentityRef = useRef<string | null>(null);\n useEffect(() => {\n if (sessionPrincipal === null) return;\n const identity = JSON.stringify([sessionPrincipal, configuredApiKey ?? null]);\n const previous = handoffIdentityRef.current;\n handoffIdentityRef.current = identity;\n if (previous !== null && previous !== identity) {\n clearComposerHandoff({ store: composerHandoff, reason: 'the signed-in identity changed' });\n }\n }, [composerHandoff, sessionPrincipal, configuredApiKey]);\n // Nothing drains after the provider is gone: settle what still waits so no\n // `useSendMessage` caller hangs.\n useEffect(\n () => () => clearComposerHandoff({ store: composerHandoff, reason: 'the chat provider unmounted' }),\n [composerHandoff],\n );\n\n const effectiveToken = configuredToken !== undefined\n ? configuredToken\n : authProviderToken ?? bridge.token;\n\n // One credential source for every network path below: it presents the\n // token chosen above and renews it the way its origin can. A host's own\n // `getToken` owns renewal; a host's static `token` never renews; a sign-in\n // provider's token renews through its getter (PropelAuth, SSO); a host\n // bridge token through the bridge (a Marathon re-mint, or the parent\n // window's next `athena-auth`).\n const authProviderGetToken = authContext?.getToken;\n const credentialInputsRef = useRef<AthenaCredentialInputs>({ token: null });\n credentialInputsRef.current = {\n hostGetToken: configuredGetToken,\n token: effectiveToken,\n renew:\n configuredToken !== undefined\n ? undefined\n : authProviderToken !== null\n ? authProviderGetToken\n ? async ({ force }) => (await authProviderGetToken({ force })) ?? null\n : undefined\n : bridge.token !== null\n ? bridge.renewToken\n : undefined,\n };\n const [credentials] = useState(() =>\n createAthenaCredentialSource(() => credentialInputsRef.current),\n );\n useEffect(() => {\n credentials.notifyTokenChanged();\n }, [credentials, effectiveToken]);\n // Only a provider that holds a token (or a host getter) hands one out, so\n // \"has credentials\" checks downstream keep meaning what they did.\n const credentialGetToken =\n configuredGetToken !== undefined || effectiveToken ? credentials.getToken : undefined;\n // Explicit config wins. A Marathon host mints the statewire mount, the bare\n // Agora base and the app origin outright (`/_athena/auth`, or a trusted\n // parent's `athena-config`); the environment preset is the last resort, and\n // the sync mount derives from the `apiUrl` host when no host minted one.\n const effectiveApiUrl = configuredApiUrl ?? environmentUrls.apiUrl;\n // Published as the bare Agora base: a historical `…/api/assistant-ui` value\n // is trimmed here once rather than by each REST helper.\n const effectiveBackendUrl = getAthenaApiBaseUrl(\n configuredBackendUrl ?? bridge.backendBaseUrl ?? environmentUrls.backendUrl,\n );\n // What the chat outbox's attachment check reads as (see `checkChatOutboxAttachments` above).\n outboxCheckBackendRef.current = effectiveBackendUrl;\n outboxCheckAuthRef.current = {\n apiKey: configuredApiKey,\n token: effectiveToken,\n getToken: credentialGetToken,\n };\n const hostStatewireSyncUrl = configuredStatewireSyncUrl ?? bridge.statewireSyncUrl ?? undefined;\n const effectiveAppUrl = configuredAppUrl\n ?? bridge.appUrl\n ?? deriveAthenaAppUrl({ apiUrl: effectiveApiUrl, backendUrl: effectiveBackendUrl })\n ?? environmentUrls.appUrl;\n\n // Wait for the parent bridge to deliver config/auth before rendering.\n // This prevents the thread list from fetching with wrong URLs or no token.\n // An iframe bridge falls back after a short timeout (2s) if no parent\n // answers; a Marathon mint is ready once its bounded retry cycle ends.\n if (!bridge.ready) {\n return null;\n }\n\n // Fail closed when the host's mint gave up and nothing else can\n // authenticate: the chat would otherwise attach with no credential (and to\n // the environment preset, since no host minted a mount). The bridge has\n // already reported the typed `auth_bridge_failed` / `auth_bridge_timeout`\n // error to `onError`; remounting the provider starts a new bounded mint.\n if (\n bridge.error &&\n !effectiveToken &&\n configuredGetToken === undefined &&\n !configuredApiKey\n ) {\n return null;\n }\n\n // Both throw on an unresolvable configuration instead of falling back to an\n // Athena default — a custom deployment's credentials must never be sent to\n // a host the consumer didn't configure. A host that answered the bridge\n // without minting the statewire mount is that case: its token would\n // otherwise ride the environment preset.\n assertHostMintedStatewireMount({\n hostAnswered: bridge.hostAnswered,\n hostStatewireSyncUrl: bridge.statewireSyncUrl,\n statewireSyncUrl: configuredStatewireSyncUrl,\n apiUrl: configuredApiUrl,\n });\n const effectiveStatewireSyncUrl = resolveStatewireSyncUrl({\n statewireSyncUrl: hostStatewireSyncUrl,\n apiUrl: effectiveApiUrl,\n });\n\n const statewireProps = {\n syncUrl: effectiveStatewireSyncUrl,\n backendUrl: effectiveBackendUrl,\n appUrl: effectiveAppUrl,\n apiKey: configuredApiKey,\n token: effectiveToken,\n getToken: credentialGetToken,\n model,\n agent,\n channel,\n modes,\n tools,\n frontendToolIds: frontendToolNames,\n frontendTools: effectiveFrontendTools,\n confirmClientToolWrites,\n clientToolConsentAgentName: agentUiEnabled ? agentUiOptions.agentName : undefined,\n workbench,\n knowledgeBase,\n systemPrompt,\n planMode,\n appId,\n extraRunConfig: configuredExtraRunConfig,\n snapshotCache,\n toolOutputs,\n historyStore,\n chatOutbox: chatOutboxHost,\n sessionLane,\n subagentLaneHistory,\n linkClicks,\n citationLinks,\n };\n\n // Each provider's assistant client is a root of its own (`extends={null}`): one mounted under\n // another provider's (a host showing several chats side by side) would otherwise extend that\n // client and define every tool a second time. The empty config is built per render (configs are\n // identity-insensitive), never at import, which a host's test stub of assistant-ui could not take.\n const inner: ReactNode = (\n <AuiProvider extends={null} config={AuiConfig({})}>\n {enableThreadList ? (\n <AthenaStatewireWithThreadList\n {...statewireProps}\n initialThreadId={threadIdProp}\n includePullRequests={threadListIncludePullRequests}\n additionalListAppIds={threadListAdditionalAppIds}\n listHomeAgentId={threadListAgentHome && agentAssetId ? agentAssetId : undefined}\n offlineList={offlineList}\n >\n {children}\n </AthenaStatewireWithThreadList>\n ) : (\n // A provider without a thread list is its own chat: one nested under a thread-list\n // provider (a host showing several chats side by side) must not read that list as its\n // own, or its banners and composer would follow the other chat's thread.\n <AthenaStatewireThreadListContext.Provider value={null}>\n <AthenaStatewireStandalone\n {...statewireProps}\n threadId={threadIdProp}\n threadIsNew={threadIsNew}\n >\n {children}\n </AthenaStatewireStandalone>\n </AthenaStatewireThreadListContext.Provider>\n )}\n </AuiProvider>\n );\n\n // The .athena-sdk wrapper (display: contents) anchors the SDK's design\n // tokens and scoped preflight from styles.css, so the stylesheet works\n // in hosts without their own Tailwind build. PostHog gracefully no-ops\n // when its config is missing.\n return (\n <div\n className={themeStyleVars ? \"athena-sdk athena-themed\" : \"athena-sdk\"}\n style={themeStyleVars as React.CSSProperties | undefined}\n >\n <PostHogProvider config={posthogConfig}>\n <ComposerHandoffContext.Provider value={composerHandoff}>\n <StatewireSessionLaneContext.Provider value={sessionLane}>\n <AthenaThemeStyleContext.Provider value={themeStyleVars}>\n {agentUiEnabled ? (\n <AgentUiLayer agentUi={agentUiHost.agentUi} classNames={agentUiClassNames} />\n ) : null}\n <AthenaCredentialSourceContext.Provider value={credentials}>\n <AthenaAgentSelectionContext.Provider value={agentSelection}>\n <AthenaOfflineSnapshotsContext.Provider value={offlineSnapshots}>\n <AthenaDataQueryClientProvider>\n {awaitingKeptSnapshots ? null : inner}\n </AthenaDataQueryClientProvider>\n </AthenaOfflineSnapshotsContext.Provider>\n </AthenaAgentSelectionContext.Provider>\n </AthenaCredentialSourceContext.Provider>\n </AthenaThemeStyleContext.Provider>\n </StatewireSessionLaneContext.Provider>\n </ComposerHandoffContext.Provider>\n </PostHogProvider>\n </div>\n );\n}\n"],"names":["_a"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8LA,MAAM,yBAA+C,CAAA;AACrD,MAAM,gBAAyB,CAAA;AA6Q/B,MAAM,uBAAuB,CAAC;AAAA,EAC5B;AAAA,EACA;AACF,MAGiC;AAC/B,OAAI,iCAAQ,WAAU,QAAW;AAC/B,WAAO,OAAO;AAAA,EAChB;AACA,SAAO;AACT;AAEA,MAAM,uBAAuB,CAAC;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,MASoB;AAClB,QAAM,gBAAgB,OAAO,UAAU;AACvC,gBAAc,UAAU;AACxB,QAAM,mBAAmB,OAAO,aAAa;AAC7C,mBAAiB,UAAU;AAM3B,QAAM,WAAW,OAAO,KAAK;AAC7B,WAAS,UAAU;AACnB,QAAM,cAAc,OAAO,QAAQ;AACnC,cA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