@athenaintel/react 0.41.1 → 0.41.3
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 +12 -0
- package/dist/agent-runtime/src/durable-thread-snapshot-cache.cjs +158 -0
- package/dist/agent-runtime/src/durable-thread-snapshot-cache.cjs.map +1 -0
- package/dist/agent-runtime/src/durable-thread-snapshot-cache.js +158 -0
- package/dist/agent-runtime/src/durable-thread-snapshot-cache.js.map +1 -0
- package/dist/agent-runtime/src/protocol.cjs +15 -0
- package/dist/agent-runtime/src/protocol.cjs.map +1 -1
- package/dist/agent-runtime/src/protocol.js +16 -1
- package/dist/agent-runtime/src/protocol.js.map +1 -1
- package/dist/agent-runtime/src/thread-snapshot-cache.cjs +2 -1
- package/dist/agent-runtime/src/thread-snapshot-cache.cjs.map +1 -1
- package/dist/agent-runtime/src/thread-snapshot-cache.js +2 -1
- package/dist/agent-runtime/src/thread-snapshot-cache.js.map +1 -1
- package/dist/agent-runtime/src/thread-snapshot-mirror.cjs +400 -0
- package/dist/agent-runtime/src/thread-snapshot-mirror.cjs.map +1 -0
- package/dist/agent-runtime/src/thread-snapshot-mirror.js +400 -0
- package/dist/agent-runtime/src/thread-snapshot-mirror.js.map +1 -0
- package/dist/chat/AthenaChat.cjs +5 -1
- package/dist/chat/AthenaChat.cjs.map +1 -1
- package/dist/chat/AthenaChat.js +5 -1
- package/dist/chat/AthenaChat.js.map +1 -1
- package/dist/chat/super-grouping/activity-timeline.cjs +4 -3
- package/dist/chat/super-grouping/activity-timeline.cjs.map +1 -1
- package/dist/chat/super-grouping/activity-timeline.d.ts +7 -1
- package/dist/chat/super-grouping/activity-timeline.js +4 -3
- package/dist/chat/super-grouping/activity-timeline.js.map +1 -1
- package/dist/index.cjs +5 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -1
- package/dist/offline/offline-history.cjs +77 -0
- package/dist/offline/offline-history.cjs.map +1 -0
- package/dist/offline/offline-history.d.ts +60 -0
- package/dist/offline/offline-history.js +77 -0
- package/dist/offline/offline-history.js.map +1 -0
- package/dist/provider/AthenaProvider.cjs +46 -3
- package/dist/provider/AthenaProvider.cjs.map +1 -1
- package/dist/provider/AthenaProvider.d.ts +8 -1
- package/dist/provider/AthenaProvider.js +46 -3
- 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/runtime/useAthenaStatewireRuntime.cjs +4 -14
- package/dist/runtime/useAthenaStatewireRuntime.cjs.map +1 -1
- package/dist/runtime/useAthenaStatewireRuntime.d.ts +5 -4
- package/dist/runtime/useAthenaStatewireRuntime.js +4 -14
- package/dist/runtime/useAthenaStatewireRuntime.js.map +1 -1
- package/dist/threads/offline-session-list.cjs +75 -0
- package/dist/threads/offline-session-list.cjs.map +1 -0
- package/dist/threads/offline-session-list.d.ts +27 -0
- package/dist/threads/offline-session-list.js +75 -0
- package/dist/threads/offline-session-list.js.map +1 -0
- package/dist/threads/statewire-thread-list.cjs +63 -4
- package/dist/threads/statewire-thread-list.cjs.map +1 -1
- package/dist/threads/statewire-thread-list.d.ts +21 -2
- package/dist/threads/statewire-thread-list.js +64 -5
- package/dist/threads/statewire-thread-list.js.map +1 -1
- package/package.json +1 -1
|
@@ -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 createDeepAgentThreadSnapshotCache,\n createDeepAgentToolOutputStore,\n DeepAgentConnectionContext,\n type DeepAgentThreadSnapshotCache,\n type DeepAgentToolOutputStore,\n readServerConfig,\n} from '@athenaintel/agent-runtime';\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 {\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 {\n athenaStatewireErrorNotice,\n type AthenaStatewireLifecycleState,\n initialStatewireLifecycle,\n isStatewireChannelLive,\n statewireLifecycleReducer,\n} from '../runtime/statewire-lifecycle';\nimport type { AthenaStatewireTokenGetter } from '../runtime/statewire-auth-headers';\nimport { 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 clearComposerHandoff,\n createComposerHandoffStore,\n drainComposerHandoff,\n useComposerHandoffStore,\n useComposerReady,\n} from '../composer/composer-handoff';\nimport {\n createStatewireHistoryStore,\n StatewireHistoryContext,\n type StatewireHistoryStore,\n} from './statewire-history-context';\nimport { StatewireToolOutputsContext } from './statewire-window-context';\nimport { StatewireClientToolBridge } from '../chat/StatewireClientToolBridge';\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 resolveClientToolSurface,\n} from '../chat/statewire-client-tools';\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 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 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 /** 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 /** 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 /** 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'`). 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\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// ─── Standalone Mode ──────────────────────────────────────────────────\n\nconst EMPTY_MODES: readonly string[] = [];\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 /** 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}\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}\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 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 /**\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\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 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 snapshotCache,\n toolOutputs,\n}: AthenaStatewireRuntimeProps & {\n threadId: string;\n isNewChat: boolean;\n onPublish: (snapshot: AthenaStatewireRuntimeSnapshot) => void;\n}): null {\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 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 snapshotCache,\n toolOutputs,\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 // 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 // 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 threadId,\n isNewChat,\n client,\n lifecycle: lifecycleValue,\n serverLane,\n threadConfig,\n }),\n [threadId, isNewChat, client, lifecycleValue, serverLane, threadConfig],\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 ...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\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\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 <StatewireHistoryContext.Provider value={runtimeProps.historyStore}>\n <TooltipProvider>\n <StatewireClientToolBridge tools={clientTools} threadId={published.threadId} />\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 <ComposerHandoffDrain />\n <AthenaChatModeSelectionContext.Provider value={chatModeSelection}>\n {children}\n </AthenaChatModeSelectionContext.Provider>\n </TooltipProvider>\n </StatewireHistoryContext.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 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 ...standaloneProps\n}: Omit<AthenaStatewireStandaloneProps, 'threadId' | 'threadList'> & {\n initialThreadId?: string;\n includePullRequests?: boolean;\n additionalListAppIds?: readonly 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 initialThreadId={initialThreadId}\n includePullRequests={includePullRequests}\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 ...standaloneProps\n}: Omit<AthenaStatewireStandaloneProps, 'threadId' | 'threadList'>) {\n const list = useAthenaStatewireThreadList();\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 {...standaloneProps}\n >\n <StatewireThreadTitlePoller />\n <AssetPanelThreadSync />\n {children}\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 disableAutoOpen = false,\n apiUrl,\n backendUrl,\n appUrl,\n environment,\n statewireSyncUrl,\n getToken,\n extraRunConfig,\n workbench,\n knowledgeBase,\n systemPrompt,\n appId,\n threadId: threadIdProp,\n threadIsNew,\n enableThreadList = false,\n threadListIncludePullRequests = true,\n threadListAdditionalAppIds,\n theme,\n linkClicks,\n citationLinks,\n onOpenAsset,\n posthog: posthogProp,\n debug,\n onDiagnostic,\n onError,\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 const bridge = useParentBridge({\n trustedOrigins: configuredTrustedParentOrigins,\n });\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 // 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 const [snapshotCache] = useState(() => createDeepAgentThreadSnapshotCache());\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 useEffect(() => {\n snapshotCache.clear();\n toolOutputs.clear();\n // A draft or send queued under the previous identity must never land in\n // this one's composer.\n clearComposerHandoff({ store: composerHandoff, reason: 'the signed-in identity changed' });\n }, [snapshotCache, toolOutputs, composerHandoff, principal, 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 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 workbench,\n knowledgeBase,\n systemPrompt,\n appId,\n extraRunConfig: configuredExtraRunConfig,\n snapshotCache,\n toolOutputs,\n historyStore,\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 >\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 <AthenaThemeStyleContext.Provider value={themeStyleVars}>\n <AthenaCredentialSourceContext.Provider value={credentials}>\n <AthenaAgentSelectionContext.Provider value={agentSelection}>\n {inner}\n </AthenaAgentSelectionContext.Provider>\n </AthenaCredentialSourceContext.Provider>\n </AthenaThemeStyleContext.Provider>\n </ComposerHandoffContext.Provider>\n </PostHogProvider>\n </div>\n );\n}\n"],"names":["_a"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4TA,MAAM,uBAAuB,CAAC;AAAA,EAC5B;AAAA,EACA;AACF,MAGiC;AAC/B,OAAI,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,UAAvB,EAAgC,OAAO,iBACtC,UAAA,oBAAC,wBAAwB,UAAxB,EAAiC,OAAO,gBACvC,UAAA,oBAAC,8BAA8B,UAA9B,EAAuC,OAAO,aAC7C,8BAAC,4BAA4B,UAA5B,EAAqC,OAAO,gBAC1C,UAAA,MAAA,CACH,GACF,EAAA,CACF,GACF,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 createDeepAgentThreadSnapshotCache,\n createDeepAgentToolOutputStore,\n createDurableThreadSnapshotCache,\n createThreadSnapshotMirror,\n DeepAgentConnectionContext,\n type DeepAgentThreadSnapshotCache,\n type DeepAgentToolOutputStore,\n readServerConfig,\n type ThreadSnapshotMirror,\n} from '@athenaintel/agent-runtime';\nimport {\n type AthenaOfflineHistory,\n type AthenaOfflineSnapshots,\n AthenaOfflineSnapshotsContext,\n useKeptSnapshotsGate,\n} from '../offline/offline-history';\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 {\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 {\n athenaStatewireErrorNotice,\n type AthenaStatewireLifecycleState,\n initialStatewireLifecycle,\n isStatewireChannelLive,\n statewireLifecycleReducer,\n} from '../runtime/statewire-lifecycle';\nimport type { AthenaStatewireTokenGetter } from '../runtime/statewire-auth-headers';\nimport { 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 clearComposerHandoff,\n createComposerHandoffStore,\n drainComposerHandoff,\n useComposerHandoffStore,\n useComposerReady,\n} from '../composer/composer-handoff';\nimport {\n createStatewireHistoryStore,\n StatewireHistoryContext,\n type StatewireHistoryStore,\n} from './statewire-history-context';\nimport { StatewireToolOutputsContext } from './statewire-window-context';\nimport { StatewireClientToolBridge } from '../chat/StatewireClientToolBridge';\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 resolveClientToolSurface,\n} from '../chat/statewire-client-tools';\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 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 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 /** 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 /** 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 /** 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'`). 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\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// ─── Standalone Mode ──────────────────────────────────────────────────\n\nconst EMPTY_MODES: readonly string[] = [];\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 /** 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}\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}\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 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 /**\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\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 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 snapshotCache,\n toolOutputs,\n}: AthenaStatewireRuntimeProps & {\n threadId: string;\n isNewChat: boolean;\n onPublish: (snapshot: AthenaStatewireRuntimeSnapshot) => void;\n}): null {\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 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 snapshotCache,\n toolOutputs,\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 // 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 // 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 threadId,\n isNewChat,\n client,\n lifecycle: lifecycleValue,\n serverLane,\n threadConfig,\n }),\n [threadId, isNewChat, client, lifecycleValue, serverLane, threadConfig],\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 ...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\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\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 <StatewireHistoryContext.Provider value={runtimeProps.historyStore}>\n <TooltipProvider>\n <StatewireClientToolBridge tools={clientTools} threadId={published.threadId} />\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 <ComposerHandoffDrain />\n <AthenaChatModeSelectionContext.Provider value={chatModeSelection}>\n {children}\n </AthenaChatModeSelectionContext.Provider>\n </TooltipProvider>\n </StatewireHistoryContext.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 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 offlineList,\n ...standaloneProps\n}: Omit<AthenaStatewireStandaloneProps, 'threadId' | 'threadList'> & {\n initialThreadId?: string;\n includePullRequests?: boolean;\n additionalListAppIds?: readonly 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 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 ...standaloneProps\n}: Omit<AthenaStatewireStandaloneProps, 'threadId' | 'threadList'>) {\n const list = useAthenaStatewireThreadList();\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 {...standaloneProps}\n >\n <StatewireThreadTitlePoller />\n <AssetPanelThreadSync />\n {children}\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 disableAutoOpen = false,\n apiUrl,\n backendUrl,\n appUrl,\n environment,\n statewireSyncUrl,\n getToken,\n extraRunConfig,\n workbench,\n knowledgeBase,\n systemPrompt,\n appId,\n threadId: threadIdProp,\n threadIsNew,\n enableThreadList = false,\n threadListIncludePullRequests = true,\n threadListAdditionalAppIds,\n theme,\n linkClicks,\n citationLinks,\n onOpenAsset,\n posthog: posthogProp,\n debug,\n onDiagnostic,\n onError,\n offlineHistory,\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 const bridge = useParentBridge({\n trustedOrigins: configuredTrustedParentOrigins,\n });\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 // 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 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 useEffect(() => {\n snapshotCache.clear();\n toolOutputs.clear();\n // A draft or send queued under the previous identity must never land in\n // this one's composer.\n clearComposerHandoff({ store: composerHandoff, reason: 'the signed-in identity changed' });\n }, [snapshotCache, toolOutputs, composerHandoff, principal, 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 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 workbench,\n knowledgeBase,\n systemPrompt,\n appId,\n extraRunConfig: configuredExtraRunConfig,\n snapshotCache,\n toolOutputs,\n historyStore,\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 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 <AthenaThemeStyleContext.Provider value={themeStyleVars}>\n <AthenaCredentialSourceContext.Provider value={credentials}>\n <AthenaAgentSelectionContext.Provider value={agentSelection}>\n <AthenaOfflineSnapshotsContext.Provider value={offlineSnapshots}>\n {awaitingKeptSnapshots ? null : inner}\n </AthenaOfflineSnapshotsContext.Provider>\n </AthenaAgentSelectionContext.Provider>\n </AthenaCredentialSourceContext.Provider>\n </AthenaThemeStyleContext.Provider>\n </ComposerHandoffContext.Provider>\n </PostHogProvider>\n </div>\n );\n}\n"],"names":["_a"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4UA,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,gB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|
|
|
11
11
|
const runconfigContract = require("../agent-runtime/src/generated/runconfig-contract.cjs");
|
|
12
12
|
const useDeepAgentRuntime = require("../agent-runtime/src/use-deep-agent-runtime.cjs");
|
|
13
13
|
const errors = require("../agent-runtime/src/errors.cjs");
|
|
14
|
-
const
|
|
14
|
+
const protocol = require("../agent-runtime/src/protocol.cjs");
|
|
15
15
|
const composerMarkdown = require("../agent-runtime/src/composer-markdown.cjs");
|
|
16
16
|
const ATHENA_SDK_MESSAGE_WINDOW = {
|
|
17
17
|
size: runconfigContract.DEEP_AGENT_DEFAULT_MESSAGE_WINDOW
|
|
@@ -83,8 +83,6 @@ function useAthenaStatewireRuntime(config) {
|
|
|
83
83
|
clientTools: statewireClientTools.statewireClientToolWireEntries(clientTools)
|
|
84
84
|
});
|
|
85
85
|
const runConfigKey = JSON.stringify(runConfigValue);
|
|
86
|
-
const lastStateRef = react.useRef(null);
|
|
87
|
-
const helloLandedRef = react.useRef(false);
|
|
88
86
|
const auiTools = react.useMemo(() => react$1.Tools({ toolkit: frontendToolkit }), [frontendToolkit]);
|
|
89
87
|
const useSdkClient = (thread) => react$1.useAui({ thread, tools: auiTools });
|
|
90
88
|
return useDeepAgentRuntime.useDeepAgentRuntime({
|
|
@@ -123,14 +121,13 @@ function useAthenaStatewireRuntime(config) {
|
|
|
123
121
|
getMessageMetadata: composerMarkdown.withStagedComposerMarkdown({ threadId }),
|
|
124
122
|
useClient: useSdkClient,
|
|
125
123
|
onStateChange: (state) => {
|
|
124
|
+
if (!protocol.isDeepAgentHostState(state)) return;
|
|
126
125
|
const endSpan = attachSpanRef.current;
|
|
127
126
|
if (endSpan) {
|
|
128
127
|
attachSpanRef.current = null;
|
|
129
128
|
endSpan("statewire.snapshot", { data: { thread_id: threadId } });
|
|
130
129
|
}
|
|
131
|
-
|
|
132
|
-
lastStateRef.current = state;
|
|
133
|
-
if (helloLandedRef.current) onServerState == null ? void 0 : onServerState(state);
|
|
130
|
+
onServerState == null ? void 0 : onServerState(state);
|
|
134
131
|
},
|
|
135
132
|
onConnectionChange: (connection) => {
|
|
136
133
|
athenaDiagnostics.athenaDiagnostics.gauge("statewire.connection", (connection == null ? void 0 : connection.status) ?? null);
|
|
@@ -146,14 +143,7 @@ function useAthenaStatewireRuntime(config) {
|
|
|
146
143
|
}
|
|
147
144
|
onConnectionChange == null ? void 0 : onConnectionChange(connection);
|
|
148
145
|
},
|
|
149
|
-
onRawConnectionChange
|
|
150
|
-
if (connection.status === "connected" && !helloLandedRef.current) {
|
|
151
|
-
helloLandedRef.current = true;
|
|
152
|
-
const helloState = lastStateRef.current;
|
|
153
|
-
if (helloState) onServerState == null ? void 0 : onServerState(helloState);
|
|
154
|
-
}
|
|
155
|
-
onRawConnectionChange == null ? void 0 : onRawConnectionChange(connection);
|
|
156
|
-
},
|
|
146
|
+
onRawConnectionChange,
|
|
157
147
|
onRunningChange,
|
|
158
148
|
// Each model-context notification pulls the latest getter through the
|
|
159
149
|
// core's per-render ref; the value-stable key re-registers (and so
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAthenaStatewireRuntime.cjs","sources":["../../src/runtime/useAthenaStatewireRuntime.ts"],"sourcesContent":["import type { AssistantClient, Toolkit } from '@assistant-ui/react';\nimport { Tools, useAui } from '@assistant-ui/react';\nimport {\n DEEP_AGENT_DEFAULT_MESSAGE_WINDOW,\n type DeepAgentMessageWindowDeclaration,\n type DeepAgentStreamValues,\n type DeepAgentThreadElement,\n type DeepAgentThreadSnapshotCache,\n type DeepAgentToolOutputStore,\n isDeepAgentStateHydrated,\n isStatewireChannelTeardown,\n logUnhandledStatewireError,\n type RegisteredClientTool,\n useDeepAgentRuntime,\n type UseDeepAgentThreadOptions,\n withStagedComposerMarkdown,\n} from '@athenaintel/agent-runtime';\nimport { useContext, useMemo, useRef } from 'react';\nimport { AthenaAuthContext } from '../auth/AthenaAuthContext';\nimport {\n collectStatewireClientTools,\n statewireClientToolWireEntries,\n} from '../chat/statewire-client-tools';\nimport { athenaDiagnostics } from '../diagnostics/athena-diagnostics';\nimport {\n type AthenaStatewireTokenGetter,\n resolveStatewireAuthHeaders,\n} from './statewire-auth-headers';\nimport { statewireSessionKey } from './statewire-session-key';\n\ntype AthenaDiagnosticsSpanStarter = typeof athenaDiagnostics.span;\nimport {\n buildStatewireRunConfig,\n DEFAULT_STATEWIRE_MODEL,\n resolveAgentProp,\n} from './statewire-run-config';\n\nexport { DEFAULT_STATEWIRE_MODEL };\n\n/**\n * The head interest every SDK attach states (`athena/interest`): the host\n * mounts the transcript's tail as message documents instead of every message\n * — megabytes on long threads, over the 1 MiB frame limit of stock websocket\n * clients. Older pages load from the `StatewireHistoryEdge` row the chat UI\n * mounts above the messages, and cut tool outputs are fetched back for the\n * cards that show them.\n */\nexport const ATHENA_SDK_MESSAGE_WINDOW: DeepAgentMessageWindowDeclaration = {\n size: DEEP_AGENT_DEFAULT_MESSAGE_WINDOW,\n};\n\nexport interface AthenaStatewireRuntimeConfig {\n /** Base URL of the statewire sync host (the `…/v2/threads` mount). */\n syncUrl: string;\n /** Thread ID the statewire session attaches to. */\n threadId: string;\n /** True only for a never-started local chat. Existing (or pre-assigned)\n * threads load until their server snapshot arrives. */\n isNewChat?: boolean;\n /** API key for authentication. Used when no auth token is provided. */\n apiKey?: string;\n /** Auth token. Takes priority over apiKey. */\n token?: string | null;\n /** Resolve the latest token immediately before a request (for expiring\n * clients). Called with `{ force: true }` right after the host refused the\n * previous credential (the transport's `staleAuth`), so a caching getter\n * mints a fresh token instead of returning the refused one. */\n getToken?: AthenaStatewireTokenGetter;\n /**\n * Per-provider LRU of each thread's last wire state. A switch back to a\n * remembered thread mounts with that snapshot and projects ready on the\n * first frame instead of a loading treatment; the attach snapshot then\n * replaces it. Owned above the per-thread mount so it survives switches.\n */\n snapshotCache?: DeepAgentThreadSnapshotCache;\n /** The head interest stated on the attach (see {@link ATHENA_SDK_MESSAGE_WINDOW}, the default). */\n messageWindow?: DeepAgentMessageWindowDeclaration;\n /**\n * Full tool outputs fetched back for a windowed wire's cut tool messages;\n * the thread re-converts when one lands. `AthenaProvider` owns one per\n * provider and hands the same store to `StatewireHistoryEdge`.\n */\n toolOutputs?: DeepAgentToolOutputStore;\n /** LLM model identifier. Defaults to the deep-agent default model. */\n model?: string;\n /** Agent selector: only `collab_agent:<asset_id>` refs are accepted (the run\n * executes AS that published collab agent). Any other non-empty value\n * throws — see `resolveAgentProp`. */\n agent?: string;\n /** Collab-agent channel id selecting that channel's overrides. */\n channel?: string;\n /** The agent's mode picked for this thread (`AthenaProvider` `modes`). */\n mode?: string;\n /** Backend toolkit IDs to enable. */\n tools?: string[];\n /** Frontend tool IDs to include in enabled_tools. */\n frontendToolIds?: string[];\n /** Frontend tools registered on the assistant client. Tools with a local\n * `execute` are also declared as `client_tools` and executed through the\n * statewire client-tool bridge. */\n frontendToolkit?: Toolkit;\n /** Asset IDs to include in the workbench. */\n workbench?: string[];\n /** Knowledge base IDs for RAG context. */\n knowledgeBase?: string[];\n /** System prompt override. */\n systemPrompt?: string;\n /** Client app identifier for session filtering. Sent as app_id in runConfig.custom. */\n appId?: string;\n /** Additional fields merged into runConfig.custom. */\n extraRunConfig?: Record<string, unknown>;\n /** Called on statewire transport errors (send rejections, stream failures). */\n onError?: (error: Error) => void;\n /** Projected connection status changes (deduped; null on unmount). */\n onConnectionChange?: UseDeepAgentThreadOptions['onConnectionChange'];\n /** Raw connection observer — carries the transport's reconnect handle. */\n onRawConnectionChange?: UseDeepAgentThreadOptions['onRawConnectionChange'];\n /** Notified when a run starts/stops. */\n onRunningChange?: UseDeepAgentThreadOptions['onRunningChange'];\n /**\n * Observes the host's own state: called once the attach's hello has landed\n * (with the snapshot it carried) and then on every later frame — never with\n * the placeholder or remembered snapshot a thread renders before its hello.\n * Called per streamed token, so keep it cheap.\n */\n onServerState?: (state: DeepAgentStreamValues) => void;\n}\n\nconst EMPTY_TOOLKIT: Toolkit = {};\nconst EMPTY_TOOL_IDS: string[] = [];\n\n/** The client tools derived from the runtime's frontend toolkit — exposed so\n * the provider can mount the client-tool bridge with the same set. */\nexport function useStatewireClientTools(\n frontendToolkit: Toolkit | undefined,\n): RegisteredClientTool[] {\n return useMemo(\n () => collectStatewireClientTools(frontendToolkit ?? EMPTY_TOOLKIT),\n [frontendToolkit],\n );\n}\n\n/**\n * Statewire runtime for the Athena SDK — a thin shim over the shared\n * `@athenaintel/agent-runtime` `useDeepAgentRuntime`: it attaches to the\n * agora-hosted deep-agent thread at `${syncUrl}/${threadId}` and returns the\n * `AssistantClient` to mount via `AuiProvider` — the same integration shape as\n * the Olympus, Chrome extension, Office, and mobile statewire hosts.\n *\n * Auth: a token (resolved live through `getToken` when provided) rides\n * `Authorization: Bearer`, and an API key falls back to `X-API-KEY` — both\n * accepted by the statewire host.\n */\nexport function useAthenaStatewireRuntime(\n config: AthenaStatewireRuntimeConfig,\n): AssistantClient {\n const {\n syncUrl,\n threadId,\n isNewChat = false,\n apiKey,\n token,\n getToken,\n model,\n agent,\n channel,\n mode,\n tools = EMPTY_TOOL_IDS,\n frontendToolIds = EMPTY_TOOL_IDS,\n frontendToolkit = EMPTY_TOOLKIT,\n workbench,\n knowledgeBase,\n systemPrompt,\n appId,\n extraRunConfig,\n snapshotCache,\n messageWindow = ATHENA_SDK_MESSAGE_WINDOW,\n toolOutputs,\n onError,\n onConnectionChange,\n onRawConnectionChange,\n onRunningChange,\n onServerState,\n } = config;\n\n // Fail loud at mount, not at first send: the statewire host always runs the\n // Athena deep agent, so an `agent` outside the collab_agent namespace can\n // never apply. Throwing here (render time) is what makes a misconfigured\n // integration visible instead of quietly answering as the wrong agent.\n resolveAgentProp({ agent });\n\n const clientTools = useStatewireClientTools(frontendToolkit);\n\n // The persisted command lane is keyed by WHO is signed in as well as by host\n // and thread (see `statewireSessionKey`).\n const authContext = useContext(AthenaAuthContext);\n const principal = authContext?.user?.userId ?? '';\n\n // Attach → first server snapshot span, keyed per thread attach.\n const attachSpanRef = useRef<ReturnType<AthenaDiagnosticsSpanStarter> | null>(null);\n const attachThreadRef = useRef<string | null>(null);\n if (attachThreadRef.current !== threadId) {\n attachThreadRef.current = threadId;\n attachSpanRef.current = athenaDiagnostics.span(\n `statewire.attach:${threadId}`,\n 'statewire.attach.start',\n { thread_id: threadId, is_new_chat: isNewChat },\n );\n }\n\n // Built every render so its JSON signature can key the model-context\n // registration below: consumers commonly pass fresh array literals per\n // render, which must not thrash registration, while a changed value (a new\n // `model`, channel, tool list, system prompt, …) must re-sync the context\n // before the next send. The core pulls this value only on model-context\n // notifications, which a key change triggers.\n const runConfigValue = buildStatewireRunConfig({\n model,\n agent,\n channel,\n mode,\n tools,\n frontendToolIds,\n workbench,\n knowledgeBase,\n systemPrompt,\n appId,\n extraRunConfig,\n clientTools: statewireClientToolWireEntries(clientTools),\n });\n const runConfigKey = JSON.stringify(runConfigValue);\n\n // The host's state, told apart from what the thread renders before its\n // hello: statewire publishes the initial (placeholder or remembered) state\n // through `onStateChange` too, and reports `connected` in the same flush\n // right after publishing the state the hello carried. So the latest state\n // seen when the connection first turns `connected` is the hello's, and every\n // state after it is the host's. Refs are per attach: the runtime is mounted\n // per thread.\n const lastStateRef = useRef<DeepAgentStreamValues | null>(null);\n const helloLandedRef = useRef(false);\n\n const auiTools = useMemo(() => Tools({ toolkit: frontendToolkit }), [frontendToolkit]);\n // Web client for the shared runtime core (a `use*` name so the\n // rules-of-hooks lint sees the `useAui` call inside a custom hook; the core\n // invokes it unconditionally every render).\n const useSdkClient = (thread: DeepAgentThreadElement) => useAui({ thread, tools: auiTools });\n\n return useDeepAgentRuntime({\n surface: 'AthenaSDK',\n threadId,\n baseUrl: syncUrl,\n // Option closures are re-read per render by the core, so credential\n // rotation (new `token`/`getToken`/`apiKey` props) reaches the next\n // request without remounting the thread. The transport's `staleAuth`\n // (true right after a refused credential) is forwarded as `force`.\n headers: (ctx) => resolveStatewireAuthHeaders({ apiKey, token, getToken }, ctx),\n isNewChat,\n // Queued entries render in the SDK's queue panel, so only the steer lane\n // projects into the message tail.\n laneProjection: 'steer-only',\n // Durable session: a reload resumes the lane and resends whatever the\n // server has not marked durable. Scoped by host AND principal — a thread\n // id is only meaningful against the backend that minted it, and a stored\n // lane must never resend against another signed-in user. (Consumers\n // server-render this SDK; the core's availability probe keeps those\n // sessions process-local, as before the seam existed.)\n session: {\n kind: 'local-storage',\n key: (id) => statewireSessionKey({ syncUrl, principal, threadId: id }),\n },\n snapshotCache,\n // Head interest (see `ATHENA_SDK_MESSAGE_WINDOW`): the tail of the\n // transcript instead of every message; the chat UI's history edge pages\n // older ranges in and fetches cut tool outputs into `toolOutputs`.\n messageWindow,\n toolOutputs,\n capabilities: { edit: true, reload: true, continue: true },\n // The composer stages the draft each send came from right before it\n // sends; the message carries it as its composer markdown, so its bubble\n // shows the text exactly as typed (`UserMessageText`).\n getMessageMetadata: withStagedComposerMarkdown({ threadId }),\n useClient: useSdkClient,\n onStateChange: (state) => {\n // First snapshot for this attach ends the attach span (time-to-history).\n const endSpan = attachSpanRef.current;\n if (endSpan) {\n attachSpanRef.current = null;\n endSpan('statewire.snapshot', { data: { thread_id: threadId } });\n }\n // A replay boundary republishes the pre-stream default: not host state.\n if (!isDeepAgentStateHydrated(state)) return;\n lastStateRef.current = state;\n if (helloLandedRef.current) onServerState?.(state);\n },\n onConnectionChange: (connection) => {\n athenaDiagnostics.gauge('statewire.connection', connection?.status ?? null);\n if (connection?.status === 'stopped') {\n athenaDiagnostics.emit('statewire.connection', {\n level: 'warn',\n data: {\n status: connection.status,\n reason: connection.reason,\n message: connection.message,\n },\n });\n }\n onConnectionChange?.(connection);\n },\n onRawConnectionChange: (connection) => {\n if (connection.status === 'connected' && !helloLandedRef.current) {\n helloLandedRef.current = true;\n const helloState = lastStateRef.current;\n if (helloState) onServerState?.(helloState);\n }\n onRawConnectionChange?.(connection);\n },\n onRunningChange,\n // Each model-context notification pulls the latest getter through the\n // core's per-render ref; the value-stable key re-registers (and so\n // notifies) only when the built runConfig actually changed. On a thread\n // with a server config lane, agora keeps only the per-send keys of what\n // this carries; `StatewireThreadConfigLaneSync` writes a changed model,\n // system prompt, tool list, workbench or knowledge base to the lane itself.\n runConfig: {\n get: () => runConfigValue,\n key: runConfigKey,\n },\n onError: (error) => {\n if (!isStatewireChannelTeardown(error)) {\n athenaDiagnostics.error(\n 'statewire.error',\n error,\n {\n code: 'statewire_rejected',\n message: 'The statewire host rejected a command',\n hint: 'Inspect error.detail — agora rejections carry a structured {code, message}.',\n },\n { thread_id: threadId },\n );\n }\n if (onError) {\n onError(error);\n return;\n }\n logUnhandledStatewireError('AthenaSDK', error);\n },\n });\n}\n"],"names":["DEEP_AGENT_DEFAULT_MESSAGE_WINDOW","useMemo","collectStatewireClientTools","resolveAgentProp","useContext","AthenaAuthContext","useRef","athenaDiagnostics","buildStatewireRunConfig","statewireClientToolWireEntries","Tools","useAui","useDeepAgentRuntime","resolveStatewireAuthHeaders","statewireSessionKey","withStagedComposerMarkdown","isDeepAgentStateHydrated","isStatewireChannelTeardown","logUnhandledStatewireError"],"mappings":";;;;;;;;;;;;;;;AA+CO,MAAM,4BAA+D;AAAA,EAC1E,MAAMA,kBAAAA;AACR;AA+EA,MAAM,gBAAyB,CAAA;AAC/B,MAAM,iBAA2B,CAAA;AAI1B,SAAS,wBACd,iBACwB;AACxB,SAAOC,MAAAA;AAAAA,IACL,MAAMC,qBAAAA,4BAA4B,mBAAmB,aAAa;AAAA,IAClE,CAAC,eAAe;AAAA,EAAA;AAEpB;AAaO,SAAS,0BACd,QACiB;;AACjB,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA,YAAY;AAAA,IACZ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,QAAQ;AAAA,IACR,kBAAkB;AAAA,IAClB,kBAAkB;AAAA,IAClB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,gBAAgB;AAAA,IAChB;AAAA,IACA;AAAA,IACA;AAAA,IACA;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,IAAA;AAAA,IAEP,SAAS,CAAC,UAAU;AAClB,UAAI,CAACU,OAAAA,2BAA2B,KAAK,GAAG;AACtCV,0BAAAA,kBAAkB;AAAA,UAChB;AAAA,UACA;AAAA,UACA;AAAA,YACE,MAAM;AAAA,YACN,SAAS;AAAA,YACT,MAAM;AAAA,UAAA;AAAA,UAER,EAAE,WAAW,SAAA;AAAA,QAAS;AAAA,MAE1B;AACA,UAAI,SAAS;AACX,gBAAQ,KAAK;AACb;AAAA,MACF;AACAW,0BAAAA,2BAA2B,aAAa,KAAK;AAAA,IAC/C;AAAA,EAAA,CACD;AACH;;;;;"}
|
|
1
|
+
{"version":3,"file":"useAthenaStatewireRuntime.cjs","sources":["../../src/runtime/useAthenaStatewireRuntime.ts"],"sourcesContent":["import type { AssistantClient, Toolkit } from '@assistant-ui/react';\nimport { Tools, useAui } from '@assistant-ui/react';\nimport {\n DEEP_AGENT_DEFAULT_MESSAGE_WINDOW,\n type DeepAgentMessageWindowDeclaration,\n type DeepAgentStreamValues,\n type DeepAgentThreadElement,\n type DeepAgentThreadSnapshotCache,\n type DeepAgentToolOutputStore,\n isDeepAgentHostState,\n isStatewireChannelTeardown,\n logUnhandledStatewireError,\n type RegisteredClientTool,\n useDeepAgentRuntime,\n type UseDeepAgentThreadOptions,\n withStagedComposerMarkdown,\n} from '@athenaintel/agent-runtime';\nimport { useContext, useMemo, useRef } from 'react';\nimport { AthenaAuthContext } from '../auth/AthenaAuthContext';\nimport {\n collectStatewireClientTools,\n statewireClientToolWireEntries,\n} from '../chat/statewire-client-tools';\nimport { athenaDiagnostics } from '../diagnostics/athena-diagnostics';\nimport {\n type AthenaStatewireTokenGetter,\n resolveStatewireAuthHeaders,\n} from './statewire-auth-headers';\nimport { statewireSessionKey } from './statewire-session-key';\n\ntype AthenaDiagnosticsSpanStarter = typeof athenaDiagnostics.span;\nimport {\n buildStatewireRunConfig,\n DEFAULT_STATEWIRE_MODEL,\n resolveAgentProp,\n} from './statewire-run-config';\n\nexport { DEFAULT_STATEWIRE_MODEL };\n\n/**\n * The head interest every SDK attach states (`athena/interest`): the host\n * mounts the transcript's tail as message documents instead of every message\n * — megabytes on long threads, over the 1 MiB frame limit of stock websocket\n * clients. Older pages load from the `StatewireHistoryEdge` row the chat UI\n * mounts above the messages, and cut tool outputs are fetched back for the\n * cards that show them.\n */\nexport const ATHENA_SDK_MESSAGE_WINDOW: DeepAgentMessageWindowDeclaration = {\n size: DEEP_AGENT_DEFAULT_MESSAGE_WINDOW,\n};\n\nexport interface AthenaStatewireRuntimeConfig {\n /** Base URL of the statewire sync host (the `…/v2/threads` mount). */\n syncUrl: string;\n /** Thread ID the statewire session attaches to. */\n threadId: string;\n /** True only for a never-started local chat. Existing (or pre-assigned)\n * threads load until their server snapshot arrives. */\n isNewChat?: boolean;\n /** API key for authentication. Used when no auth token is provided. */\n apiKey?: string;\n /** Auth token. Takes priority over apiKey. */\n token?: string | null;\n /** Resolve the latest token immediately before a request (for expiring\n * clients). Called with `{ force: true }` right after the host refused the\n * previous credential (the transport's `staleAuth`), so a caching getter\n * mints a fresh token instead of returning the refused one. */\n getToken?: AthenaStatewireTokenGetter;\n /**\n * Per-provider LRU of each thread's last wire state. A switch back to a\n * remembered thread mounts with that snapshot and projects ready on the\n * first frame instead of a loading treatment; the attach snapshot then\n * replaces it. Owned above the per-thread mount so it survives switches.\n */\n snapshotCache?: DeepAgentThreadSnapshotCache;\n /** The head interest stated on the attach (see {@link ATHENA_SDK_MESSAGE_WINDOW}, the default). */\n messageWindow?: DeepAgentMessageWindowDeclaration;\n /**\n * Full tool outputs fetched back for a windowed wire's cut tool messages;\n * the thread re-converts when one lands. `AthenaProvider` owns one per\n * provider and hands the same store to `StatewireHistoryEdge`.\n */\n toolOutputs?: DeepAgentToolOutputStore;\n /** LLM model identifier. Defaults to the deep-agent default model. */\n model?: string;\n /** Agent selector: only `collab_agent:<asset_id>` refs are accepted (the run\n * executes AS that published collab agent). Any other non-empty value\n * throws — see `resolveAgentProp`. */\n agent?: string;\n /** Collab-agent channel id selecting that channel's overrides. */\n channel?: string;\n /** The agent's mode picked for this thread (`AthenaProvider` `modes`). */\n mode?: string;\n /** Backend toolkit IDs to enable. */\n tools?: string[];\n /** Frontend tool IDs to include in enabled_tools. */\n frontendToolIds?: string[];\n /** Frontend tools registered on the assistant client. Tools with a local\n * `execute` are also declared as `client_tools` and executed through the\n * statewire client-tool bridge. */\n frontendToolkit?: Toolkit;\n /** Asset IDs to include in the workbench. */\n workbench?: string[];\n /** Knowledge base IDs for RAG context. */\n knowledgeBase?: string[];\n /** System prompt override. */\n systemPrompt?: string;\n /** Client app identifier for session filtering. Sent as app_id in runConfig.custom. */\n appId?: string;\n /** Additional fields merged into runConfig.custom. */\n extraRunConfig?: Record<string, unknown>;\n /** Called on statewire transport errors (send rejections, stream failures). */\n onError?: (error: Error) => void;\n /** Projected connection status changes (deduped; null on unmount). */\n onConnectionChange?: UseDeepAgentThreadOptions['onConnectionChange'];\n /** Raw connection observer — carries the transport's reconnect handle. */\n onRawConnectionChange?: UseDeepAgentThreadOptions['onRawConnectionChange'];\n /** Notified when a run starts/stops. */\n onRunningChange?: UseDeepAgentThreadOptions['onRunningChange'];\n /**\n * Observes the host's own state: called with the attach snapshot and then on\n * every later frame (`isDeepAgentHostState`) — never with the placeholder or\n * remembered snapshot a thread renders before its snapshot applies, which\n * can be after the connection reports `connected`. Called per streamed\n * token, so keep it cheap.\n */\n onServerState?: (state: DeepAgentStreamValues) => void;\n}\n\nconst EMPTY_TOOLKIT: Toolkit = {};\nconst EMPTY_TOOL_IDS: string[] = [];\n\n/** The client tools derived from the runtime's frontend toolkit — exposed so\n * the provider can mount the client-tool bridge with the same set. */\nexport function useStatewireClientTools(\n frontendToolkit: Toolkit | undefined,\n): RegisteredClientTool[] {\n return useMemo(\n () => collectStatewireClientTools(frontendToolkit ?? EMPTY_TOOLKIT),\n [frontendToolkit],\n );\n}\n\n/**\n * Statewire runtime for the Athena SDK — a thin shim over the shared\n * `@athenaintel/agent-runtime` `useDeepAgentRuntime`: it attaches to the\n * agora-hosted deep-agent thread at `${syncUrl}/${threadId}` and returns the\n * `AssistantClient` to mount via `AuiProvider` — the same integration shape as\n * the Olympus, Chrome extension, Office, and mobile statewire hosts.\n *\n * Auth: a token (resolved live through `getToken` when provided) rides\n * `Authorization: Bearer`, and an API key falls back to `X-API-KEY` — both\n * accepted by the statewire host.\n */\nexport function useAthenaStatewireRuntime(\n config: AthenaStatewireRuntimeConfig,\n): AssistantClient {\n const {\n syncUrl,\n threadId,\n isNewChat = false,\n apiKey,\n token,\n getToken,\n model,\n agent,\n channel,\n mode,\n tools = EMPTY_TOOL_IDS,\n frontendToolIds = EMPTY_TOOL_IDS,\n frontendToolkit = EMPTY_TOOLKIT,\n workbench,\n knowledgeBase,\n systemPrompt,\n appId,\n extraRunConfig,\n snapshotCache,\n messageWindow = ATHENA_SDK_MESSAGE_WINDOW,\n toolOutputs,\n onError,\n onConnectionChange,\n onRawConnectionChange,\n onRunningChange,\n onServerState,\n } = config;\n\n // Fail loud at mount, not at first send: the statewire host always runs the\n // Athena deep agent, so an `agent` outside the collab_agent namespace can\n // never apply. Throwing here (render time) is what makes a misconfigured\n // integration visible instead of quietly answering as the wrong agent.\n resolveAgentProp({ agent });\n\n const clientTools = useStatewireClientTools(frontendToolkit);\n\n // The persisted command lane is keyed by WHO is signed in as well as by host\n // and thread (see `statewireSessionKey`).\n const authContext = useContext(AthenaAuthContext);\n const principal = authContext?.user?.userId ?? '';\n\n // Attach → first server snapshot span, keyed per thread attach.\n const attachSpanRef = useRef<ReturnType<AthenaDiagnosticsSpanStarter> | null>(null);\n const attachThreadRef = useRef<string | null>(null);\n if (attachThreadRef.current !== threadId) {\n attachThreadRef.current = threadId;\n attachSpanRef.current = athenaDiagnostics.span(\n `statewire.attach:${threadId}`,\n 'statewire.attach.start',\n { thread_id: threadId, is_new_chat: isNewChat },\n );\n }\n\n // Built every render so its JSON signature can key the model-context\n // registration below: consumers commonly pass fresh array literals per\n // render, which must not thrash registration, while a changed value (a new\n // `model`, channel, tool list, system prompt, …) must re-sync the context\n // before the next send. The core pulls this value only on model-context\n // notifications, which a key change triggers.\n const runConfigValue = buildStatewireRunConfig({\n model,\n agent,\n channel,\n mode,\n tools,\n frontendToolIds,\n workbench,\n knowledgeBase,\n systemPrompt,\n appId,\n extraRunConfig,\n clientTools: statewireClientToolWireEntries(clientTools),\n });\n const runConfigKey = JSON.stringify(runConfigValue);\n\n const auiTools = useMemo(() => Tools({ toolkit: frontendToolkit }), [frontendToolkit]);\n // Web client for the shared runtime core (a `use*` name so the\n // rules-of-hooks lint sees the `useAui` call inside a custom hook; the core\n // invokes it unconditionally every render).\n const useSdkClient = (thread: DeepAgentThreadElement) => useAui({ thread, tools: auiTools });\n\n return useDeepAgentRuntime({\n surface: 'AthenaSDK',\n threadId,\n baseUrl: syncUrl,\n // Option closures are re-read per render by the core, so credential\n // rotation (new `token`/`getToken`/`apiKey` props) reaches the next\n // request without remounting the thread. The transport's `staleAuth`\n // (true right after a refused credential) is forwarded as `force`.\n headers: (ctx) => resolveStatewireAuthHeaders({ apiKey, token, getToken }, ctx),\n isNewChat,\n // Queued entries render in the SDK's queue panel, so only the steer lane\n // projects into the message tail.\n laneProjection: 'steer-only',\n // Durable session: a reload resumes the lane and resends whatever the\n // server has not marked durable. Scoped by host AND principal — a thread\n // id is only meaningful against the backend that minted it, and a stored\n // lane must never resend against another signed-in user. (Consumers\n // server-render this SDK; the core's availability probe keeps those\n // sessions process-local, as before the seam existed.)\n session: {\n kind: 'local-storage',\n key: (id) => statewireSessionKey({ syncUrl, principal, threadId: id }),\n },\n snapshotCache,\n // Head interest (see `ATHENA_SDK_MESSAGE_WINDOW`): the tail of the\n // transcript instead of every message; the chat UI's history edge pages\n // older ranges in and fetches cut tool outputs into `toolOutputs`.\n messageWindow,\n toolOutputs,\n capabilities: { edit: true, reload: true, continue: true },\n // The composer stages the draft each send came from right before it\n // sends; the message carries it as its composer markdown, so its bubble\n // shows the text exactly as typed (`UserMessageText`).\n getMessageMetadata: withStagedComposerMarkdown({ threadId }),\n useClient: useSdkClient,\n onStateChange: (state) => {\n // Statewire publishes what the thread renders before its attach snapshot\n // through here too (the placeholder, a remembered snapshot, and a replay\n // boundary's pre-stream default), and on a thread mid-run it reports\n // `connected` before the snapshot applies: only a state the host sent\n // counts, whatever the connection says.\n if (!isDeepAgentHostState(state)) return;\n // The attach's first one ends the attach span (time-to-history).\n const endSpan = attachSpanRef.current;\n if (endSpan) {\n attachSpanRef.current = null;\n endSpan('statewire.snapshot', { data: { thread_id: threadId } });\n }\n onServerState?.(state);\n },\n onConnectionChange: (connection) => {\n athenaDiagnostics.gauge('statewire.connection', connection?.status ?? null);\n if (connection?.status === 'stopped') {\n athenaDiagnostics.emit('statewire.connection', {\n level: 'warn',\n data: {\n status: connection.status,\n reason: connection.reason,\n message: connection.message,\n },\n });\n }\n onConnectionChange?.(connection);\n },\n onRawConnectionChange,\n onRunningChange,\n // Each model-context notification pulls the latest getter through the\n // core's per-render ref; the value-stable key re-registers (and so\n // notifies) only when the built runConfig actually changed. On a thread\n // with a server config lane, agora keeps only the per-send keys of what\n // this carries; `StatewireThreadConfigLaneSync` writes a changed model,\n // system prompt, tool list, workbench or knowledge base to the lane itself.\n runConfig: {\n get: () => runConfigValue,\n key: runConfigKey,\n },\n onError: (error) => {\n if (!isStatewireChannelTeardown(error)) {\n athenaDiagnostics.error(\n 'statewire.error',\n error,\n {\n code: 'statewire_rejected',\n message: 'The statewire host rejected a command',\n hint: 'Inspect error.detail — agora rejections carry a structured {code, message}.',\n },\n { thread_id: threadId },\n );\n }\n if (onError) {\n onError(error);\n return;\n }\n logUnhandledStatewireError('AthenaSDK', error);\n },\n });\n}\n"],"names":["DEEP_AGENT_DEFAULT_MESSAGE_WINDOW","useMemo","collectStatewireClientTools","resolveAgentProp","useContext","AthenaAuthContext","useRef","athenaDiagnostics","buildStatewireRunConfig","statewireClientToolWireEntries","Tools","useAui","useDeepAgentRuntime","resolveStatewireAuthHeaders","statewireSessionKey","withStagedComposerMarkdown","isDeepAgentHostState","isStatewireChannelTeardown","logUnhandledStatewireError"],"mappings":";;;;;;;;;;;;;;;AA+CO,MAAM,4BAA+D;AAAA,EAC1E,MAAMA,kBAAAA;AACR;AAgFA,MAAM,gBAAyB,CAAA;AAC/B,MAAM,iBAA2B,CAAA;AAI1B,SAAS,wBACd,iBACwB;AACxB,SAAOC,MAAAA;AAAAA,IACL,MAAMC,qBAAAA,4BAA4B,mBAAmB,aAAa;AAAA,IAClE,CAAC,eAAe;AAAA,EAAA;AAEpB;AAaO,SAAS,0BACd,QACiB;;AACjB,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA,YAAY;AAAA,IACZ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,QAAQ;AAAA,IACR,kBAAkB;AAAA,IAClB,kBAAkB;AAAA,IAClB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,gBAAgB;AAAA,IAChB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA,IACE;AAMJC,qBAAAA,iBAAiB,EAAE,OAAO;AAE1B,QAAM,cAAc,wBAAwB,eAAe;AAI3D,QAAM,cAAcC,MAAAA,WAAWC,mCAAiB;AAChD,QAAM,cAAY,gDAAa,SAAb,mBAAmB,WAAU;AAG/C,QAAM,gBAAgBC,MAAAA,OAAwD,IAAI;AAClF,QAAM,kBAAkBA,MAAAA,OAAsB,IAAI;AAClD,MAAI,gBAAgB,YAAY,UAAU;AACxC,oBAAgB,UAAU;AAC1B,kBAAc,UAAUC,kBAAAA,kBAAkB;AAAA,MACxC,oBAAoB,QAAQ;AAAA,MAC5B;AAAA,MACA,EAAE,WAAW,UAAU,aAAa,UAAA;AAAA,IAAU;AAAA,EAElD;AAQA,QAAM,iBAAiBC,mBAAAA,wBAAwB;AAAA,IAC7C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kBAAkB,MAAM,yBAAwB,yCAAY,WAAU,IAAI;AAC1E,WAAI,yCAAY,YAAW,WAAW;AACpCA,0BAAAA,kBAAkB,KAAK,wBAAwB;AAAA,UAC7C,OAAO;AAAA,UACP,MAAM;AAAA,YACJ,QAAQ,WAAW;AAAA,YACnB,QAAQ,WAAW;AAAA,YACnB,SAAS,WAAW;AAAA,UAAA;AAAA,QACtB,CACD;AAAA,MACH;AACA,+DAAqB;AAAA,IACvB;AAAA,IACA;AAAA,IACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOA,WAAW;AAAA,MACT,KAAK,MAAM;AAAA,MACX,KAAK;AAAA,IAAA;AAAA,IAEP,SAAS,CAAC,UAAU;AAClB,UAAI,CAACU,OAAAA,2BAA2B,KAAK,GAAG;AACtCV,0BAAAA,kBAAkB;AAAA,UAChB;AAAA,UACA;AAAA,UACA;AAAA,YACE,MAAM;AAAA,YACN,SAAS;AAAA,YACT,MAAM;AAAA,UAAA;AAAA,UAER,EAAE,WAAW,SAAA;AAAA,QAAS;AAAA,MAE1B;AACA,UAAI,SAAS;AACX,gBAAQ,KAAK;AACb;AAAA,MACF;AACAW,0BAAAA,2BAA2B,aAAa,KAAK;AAAA,IAC/C;AAAA,EAAA,CACD;AACH;;;;;"}
|
|
@@ -81,10 +81,11 @@ export interface AthenaStatewireRuntimeConfig {
|
|
|
81
81
|
/** Notified when a run starts/stops. */
|
|
82
82
|
onRunningChange?: UseDeepAgentThreadOptions['onRunningChange'];
|
|
83
83
|
/**
|
|
84
|
-
* Observes the host's own state: called
|
|
85
|
-
*
|
|
86
|
-
*
|
|
87
|
-
*
|
|
84
|
+
* Observes the host's own state: called with the attach snapshot and then on
|
|
85
|
+
* every later frame (`isDeepAgentHostState`) — never with the placeholder or
|
|
86
|
+
* remembered snapshot a thread renders before its snapshot applies, which
|
|
87
|
+
* can be after the connection reports `connected`. Called per streamed
|
|
88
|
+
* token, so keep it cheap.
|
|
88
89
|
*/
|
|
89
90
|
onServerState?: (state: DeepAgentStreamValues) => void;
|
|
90
91
|
}
|
|
@@ -10,7 +10,7 @@ import { DEFAULT_STATEWIRE_MODEL } from "./statewire-run-config.js";
|
|
|
10
10
|
import { DEEP_AGENT_DEFAULT_MESSAGE_WINDOW } from "../agent-runtime/src/generated/runconfig-contract.js";
|
|
11
11
|
import { useDeepAgentRuntime, logUnhandledStatewireError } from "../agent-runtime/src/use-deep-agent-runtime.js";
|
|
12
12
|
import { isStatewireChannelTeardown } from "../agent-runtime/src/errors.js";
|
|
13
|
-
import {
|
|
13
|
+
import { isDeepAgentHostState } from "../agent-runtime/src/protocol.js";
|
|
14
14
|
import { withStagedComposerMarkdown } from "../agent-runtime/src/composer-markdown.js";
|
|
15
15
|
const ATHENA_SDK_MESSAGE_WINDOW = {
|
|
16
16
|
size: DEEP_AGENT_DEFAULT_MESSAGE_WINDOW
|
|
@@ -82,8 +82,6 @@ function useAthenaStatewireRuntime(config) {
|
|
|
82
82
|
clientTools: statewireClientToolWireEntries(clientTools)
|
|
83
83
|
});
|
|
84
84
|
const runConfigKey = JSON.stringify(runConfigValue);
|
|
85
|
-
const lastStateRef = useRef(null);
|
|
86
|
-
const helloLandedRef = useRef(false);
|
|
87
85
|
const auiTools = useMemo(() => Tools({ toolkit: frontendToolkit }), [frontendToolkit]);
|
|
88
86
|
const useSdkClient = (thread) => useAui({ thread, tools: auiTools });
|
|
89
87
|
return useDeepAgentRuntime({
|
|
@@ -122,14 +120,13 @@ function useAthenaStatewireRuntime(config) {
|
|
|
122
120
|
getMessageMetadata: withStagedComposerMarkdown({ threadId }),
|
|
123
121
|
useClient: useSdkClient,
|
|
124
122
|
onStateChange: (state) => {
|
|
123
|
+
if (!isDeepAgentHostState(state)) return;
|
|
125
124
|
const endSpan = attachSpanRef.current;
|
|
126
125
|
if (endSpan) {
|
|
127
126
|
attachSpanRef.current = null;
|
|
128
127
|
endSpan("statewire.snapshot", { data: { thread_id: threadId } });
|
|
129
128
|
}
|
|
130
|
-
|
|
131
|
-
lastStateRef.current = state;
|
|
132
|
-
if (helloLandedRef.current) onServerState == null ? void 0 : onServerState(state);
|
|
129
|
+
onServerState == null ? void 0 : onServerState(state);
|
|
133
130
|
},
|
|
134
131
|
onConnectionChange: (connection) => {
|
|
135
132
|
athenaDiagnostics.gauge("statewire.connection", (connection == null ? void 0 : connection.status) ?? null);
|
|
@@ -145,14 +142,7 @@ function useAthenaStatewireRuntime(config) {
|
|
|
145
142
|
}
|
|
146
143
|
onConnectionChange == null ? void 0 : onConnectionChange(connection);
|
|
147
144
|
},
|
|
148
|
-
onRawConnectionChange
|
|
149
|
-
if (connection.status === "connected" && !helloLandedRef.current) {
|
|
150
|
-
helloLandedRef.current = true;
|
|
151
|
-
const helloState = lastStateRef.current;
|
|
152
|
-
if (helloState) onServerState == null ? void 0 : onServerState(helloState);
|
|
153
|
-
}
|
|
154
|
-
onRawConnectionChange == null ? void 0 : onRawConnectionChange(connection);
|
|
155
|
-
},
|
|
145
|
+
onRawConnectionChange,
|
|
156
146
|
onRunningChange,
|
|
157
147
|
// Each model-context notification pulls the latest getter through the
|
|
158
148
|
// core's per-render ref; the value-stable key re-registers (and so
|