@athenaintel/react 0.22.4 → 0.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +390 -4
- package/dist/chat/AthenaChat.cjs +346 -244
- package/dist/chat/AthenaChat.cjs.map +1 -1
- package/dist/chat/AthenaChat.d.ts +19 -8
- package/dist/chat/AthenaChat.js +350 -248
- package/dist/chat/AthenaChat.js.map +1 -1
- package/dist/chat/StatewireApprovalCard.cjs +2 -1
- package/dist/chat/StatewireApprovalCard.cjs.map +1 -1
- package/dist/chat/StatewireApprovalCard.js +2 -1
- package/dist/chat/StatewireApprovalCard.js.map +1 -1
- package/dist/chat/StatewireClientToolBridge.cjs +1 -0
- package/dist/chat/StatewireClientToolBridge.cjs.map +1 -1
- package/dist/chat/StatewireClientToolBridge.js +1 -0
- package/dist/chat/StatewireClientToolBridge.js.map +1 -1
- package/dist/chat/StatewireQueuedMessages.cjs +1 -0
- package/dist/chat/StatewireQueuedMessages.cjs.map +1 -1
- package/dist/chat/StatewireQueuedMessages.js +1 -0
- package/dist/chat/StatewireQueuedMessages.js.map +1 -1
- package/dist/chat/WaitingOnYouBanner.cjs +100 -0
- package/dist/chat/WaitingOnYouBanner.cjs.map +1 -0
- package/dist/chat/WaitingOnYouBanner.d.ts +29 -0
- package/dist/chat/WaitingOnYouBanner.js +100 -0
- package/dist/chat/WaitingOnYouBanner.js.map +1 -0
- package/dist/chat/athena-chat-welcome.cjs +148 -0
- package/dist/chat/athena-chat-welcome.cjs.map +1 -0
- package/dist/chat/athena-chat-welcome.d.ts +54 -0
- package/dist/chat/athena-chat-welcome.js +148 -0
- package/dist/chat/athena-chat-welcome.js.map +1 -0
- package/dist/chat/athena-composer-controls.cjs +76 -0
- package/dist/chat/athena-composer-controls.cjs.map +1 -0
- package/dist/chat/athena-composer-controls.d.ts +21 -0
- package/dist/chat/athena-composer-controls.js +76 -0
- package/dist/chat/athena-composer-controls.js.map +1 -0
- package/dist/chat/composer-keyboard-hint.cjs +61 -0
- package/dist/chat/composer-keyboard-hint.cjs.map +1 -0
- package/dist/chat/composer-keyboard-hint.d.ts +33 -0
- package/dist/chat/composer-keyboard-hint.js +61 -0
- package/dist/chat/composer-keyboard-hint.js.map +1 -0
- package/dist/chat/message-time.cjs +64 -0
- package/dist/chat/message-time.cjs.map +1 -0
- package/dist/chat/message-time.d.ts +45 -0
- package/dist/chat/message-time.js +64 -0
- package/dist/chat/message-time.js.map +1 -0
- package/dist/chat/run-activity.cjs +38 -7
- package/dist/chat/run-activity.cjs.map +1 -1
- package/dist/chat/run-activity.d.ts +14 -3
- package/dist/chat/run-activity.js +39 -8
- package/dist/chat/run-activity.js.map +1 -1
- package/dist/chat/statewire-client-tools.cjs +2 -1
- package/dist/chat/statewire-client-tools.cjs.map +1 -1
- package/dist/chat/statewire-client-tools.js +2 -1
- package/dist/chat/statewire-client-tools.js.map +1 -1
- package/dist/chat/super-grouping/activity-timeline.cjs +2 -1
- package/dist/chat/super-grouping/activity-timeline.cjs.map +1 -1
- package/dist/chat/super-grouping/activity-timeline.js +2 -1
- package/dist/chat/super-grouping/activity-timeline.js.map +1 -1
- package/dist/chat/thread-scroll-to-bottom.cjs +24 -0
- package/dist/chat/thread-scroll-to-bottom.cjs.map +1 -0
- package/dist/chat/thread-scroll-to-bottom.d.ts +11 -0
- package/dist/chat/thread-scroll-to-bottom.js +24 -0
- package/dist/chat/thread-scroll-to-bottom.js.map +1 -0
- package/dist/chat/tiptap-text.cjs +26 -95
- package/dist/chat/tiptap-text.cjs.map +1 -1
- package/dist/chat/tiptap-text.d.ts +13 -0
- package/dist/chat/tiptap-text.js +26 -95
- package/dist/chat/tiptap-text.js.map +1 -1
- package/dist/chat/use-athena-run-live.cjs +2 -1
- package/dist/chat/use-athena-run-live.cjs.map +1 -1
- package/dist/chat/use-athena-run-live.js +2 -1
- package/dist/chat/use-athena-run-live.js.map +1 -1
- package/dist/chat/use-statewire-approval-request.cjs +1 -0
- package/dist/chat/use-statewire-approval-request.cjs.map +1 -1
- package/dist/chat/use-statewire-approval-request.js +1 -0
- package/dist/chat/use-statewire-approval-request.js.map +1 -1
- package/dist/chat-ui/composer/tiptap-composer.cjs +39 -4
- package/dist/chat-ui/composer/tiptap-composer.cjs.map +1 -1
- package/dist/chat-ui/composer/tiptap-composer.d.ts +21 -0
- package/dist/chat-ui/composer/tiptap-composer.js +39 -4
- package/dist/chat-ui/composer/tiptap-composer.js.map +1 -1
- package/dist/chat-ui/index.cjs +15 -1
- package/dist/chat-ui/index.cjs.map +1 -1
- package/dist/chat-ui/index.d.ts +6 -3
- package/dist/chat-ui/index.js +16 -2
- package/dist/chat-ui/index.js.map +1 -1
- package/dist/chat-ui/mentions/mention-chip.cjs +31 -4
- package/dist/chat-ui/mentions/mention-chip.cjs.map +1 -1
- package/dist/chat-ui/mentions/mention-chip.js +31 -4
- package/dist/chat-ui/mentions/mention-chip.js.map +1 -1
- package/dist/chat-ui/messages/message-components.cjs +19 -1
- package/dist/chat-ui/messages/message-components.cjs.map +1 -1
- package/dist/chat-ui/messages/message-components.d.ts +13 -0
- package/dist/chat-ui/messages/message-components.js +19 -1
- package/dist/chat-ui/messages/message-components.js.map +1 -1
- package/dist/chat-ui/messages/runtime-message.cjs +2 -1
- package/dist/chat-ui/messages/runtime-message.cjs.map +1 -1
- package/dist/chat-ui/messages/runtime-message.js +2 -1
- package/dist/chat-ui/messages/runtime-message.js.map +1 -1
- package/dist/chat-ui/messages/statewire-continue-run.cjs +1 -0
- package/dist/chat-ui/messages/statewire-continue-run.cjs.map +1 -1
- package/dist/chat-ui/messages/statewire-continue-run.js +1 -0
- package/dist/chat-ui/messages/statewire-continue-run.js.map +1 -1
- package/dist/chat-ui/messages/user-edit-composer.cjs +3 -1
- package/dist/chat-ui/messages/user-edit-composer.cjs.map +1 -1
- package/dist/chat-ui/messages/user-edit-composer.js +3 -1
- package/dist/chat-ui/messages/user-edit-composer.js.map +1 -1
- package/dist/chat-ui/messages/wake-marker.cjs +84 -0
- package/dist/chat-ui/messages/wake-marker.cjs.map +1 -0
- package/dist/chat-ui/messages/wake-marker.d.ts +16 -0
- package/dist/chat-ui/messages/wake-marker.js +84 -0
- package/dist/chat-ui/messages/wake-marker.js.map +1 -0
- package/dist/chat-ui/rich-text/chat-blocks.cjs +177 -0
- package/dist/chat-ui/rich-text/chat-blocks.cjs.map +1 -0
- package/dist/chat-ui/rich-text/chat-blocks.d.ts +58 -0
- package/dist/chat-ui/rich-text/chat-blocks.js +177 -0
- package/dist/chat-ui/rich-text/chat-blocks.js.map +1 -0
- package/dist/chat-ui/rich-text/chat-link.cjs +69 -0
- package/dist/chat-ui/rich-text/chat-link.cjs.map +1 -0
- package/dist/chat-ui/rich-text/chat-link.d.ts +24 -0
- package/dist/chat-ui/rich-text/chat-link.js +69 -0
- package/dist/chat-ui/rich-text/chat-link.js.map +1 -0
- package/dist/chat-ui/rich-text/chat-message-body.cjs +144 -18
- package/dist/chat-ui/rich-text/chat-message-body.cjs.map +1 -1
- package/dist/chat-ui/rich-text/chat-message-body.d.ts +10 -1
- package/dist/chat-ui/rich-text/chat-message-body.js +149 -23
- package/dist/chat-ui/rich-text/chat-message-body.js.map +1 -1
- package/dist/chat-ui/rich-text/chat-node-views.cjs +38 -5
- package/dist/chat-ui/rich-text/chat-node-views.cjs.map +1 -1
- package/dist/chat-ui/rich-text/chat-node-views.d.ts +11 -0
- package/dist/chat-ui/rich-text/chat-node-views.js +39 -6
- package/dist/chat-ui/rich-text/chat-node-views.js.map +1 -1
- package/dist/chat-ui/rich-text/chat-text-schema.cjs +20 -3
- package/dist/chat-ui/rich-text/chat-text-schema.cjs.map +1 -1
- package/dist/chat-ui/rich-text/chat-text-schema.d.ts +15 -2
- package/dist/chat-ui/rich-text/chat-text-schema.js +20 -3
- package/dist/chat-ui/rich-text/chat-text-schema.js.map +1 -1
- package/dist/chat-ui/rich-text/citation-anchors.cjs +139 -0
- package/dist/chat-ui/rich-text/citation-anchors.cjs.map +1 -0
- package/dist/chat-ui/rich-text/citation-anchors.d.ts +74 -0
- package/dist/chat-ui/rich-text/citation-anchors.js +139 -0
- package/dist/chat-ui/rich-text/citation-anchors.js.map +1 -0
- package/dist/chat-ui/statewire.cjs +8 -1
- package/dist/chat-ui/statewire.cjs.map +1 -1
- package/dist/chat-ui/statewire.d.ts +2 -0
- package/dist/chat-ui/statewire.js +8 -1
- package/dist/chat-ui/statewire.js.map +1 -1
- package/dist/chat-ui/thread/chat-composer-dock.cjs +27 -6
- package/dist/chat-ui/thread/chat-composer-dock.cjs.map +1 -1
- package/dist/chat-ui/thread/chat-composer-dock.d.ts +21 -1
- package/dist/chat-ui/thread/chat-composer-dock.js +28 -7
- package/dist/chat-ui/thread/chat-composer-dock.js.map +1 -1
- package/dist/chat-ui/thread/statewire-history-edge.cjs +12 -13
- package/dist/chat-ui/thread/statewire-history-edge.cjs.map +1 -1
- package/dist/chat-ui/thread/statewire-history-edge.d.ts +11 -10
- package/dist/chat-ui/thread/statewire-history-edge.js +13 -14
- package/dist/chat-ui/thread/statewire-history-edge.js.map +1 -1
- package/dist/chat-ui/thread/thread-loading-overlay.cjs +31 -0
- package/dist/chat-ui/thread/thread-loading-overlay.cjs.map +1 -0
- package/dist/chat-ui/thread/thread-loading-overlay.d.ts +14 -0
- package/dist/chat-ui/thread/thread-loading-overlay.js +31 -0
- package/dist/chat-ui/thread/thread-loading-overlay.js.map +1 -0
- package/dist/composer/ComposerDropZone.cjs +8 -1
- package/dist/composer/ComposerDropZone.cjs.map +1 -1
- package/dist/composer/ComposerDropZone.d.ts +6 -0
- package/dist/composer/ComposerDropZone.js +9 -2
- package/dist/composer/ComposerDropZone.js.map +1 -1
- package/dist/diagnostics/errors.cjs +20 -0
- package/dist/diagnostics/errors.cjs.map +1 -1
- package/dist/diagnostics/errors.d.ts +20 -0
- package/dist/diagnostics/errors.js +20 -0
- package/dist/diagnostics/errors.js.map +1 -1
- package/dist/index.cjs +47 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +26 -7
- package/dist/index.js +51 -5
- package/dist/index.js.map +1 -1
- package/dist/lib/use-prefers-reduced-motion.cjs +29 -0
- package/dist/lib/use-prefers-reduced-motion.cjs.map +1 -0
- package/dist/lib/use-prefers-reduced-motion.d.ts +6 -0
- package/dist/lib/use-prefers-reduced-motion.js +29 -0
- package/dist/lib/use-prefers-reduced-motion.js.map +1 -0
- package/dist/packages/agent-runtime/src/conversation-index.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/conversation-index.js.map +1 -1
- package/dist/packages/agent-runtime/src/conversation-list.cjs +59 -0
- package/dist/packages/agent-runtime/src/conversation-list.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/conversation-list.js +60 -1
- package/dist/packages/agent-runtime/src/conversation-list.js.map +1 -1
- package/dist/packages/agent-runtime/src/deep-agent-transport-recipe.cjs +5 -3
- package/dist/packages/agent-runtime/src/deep-agent-transport-recipe.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/deep-agent-transport-recipe.js +5 -3
- package/dist/packages/agent-runtime/src/deep-agent-transport-recipe.js.map +1 -1
- package/dist/packages/agent-runtime/src/edit-command.cjs +21 -17
- package/dist/packages/agent-runtime/src/edit-command.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/edit-command.js +22 -18
- package/dist/packages/agent-runtime/src/edit-command.js.map +1 -1
- package/dist/packages/agent-runtime/src/generated/runconfig-contract.cjs +9 -11
- package/dist/packages/agent-runtime/src/generated/runconfig-contract.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/generated/runconfig-contract.js +9 -11
- package/dist/packages/agent-runtime/src/generated/runconfig-contract.js.map +1 -1
- package/dist/packages/agent-runtime/src/github-wake-event.cjs +86 -0
- package/dist/packages/agent-runtime/src/github-wake-event.cjs.map +1 -0
- package/dist/packages/agent-runtime/src/github-wake-event.js +86 -0
- package/dist/packages/agent-runtime/src/github-wake-event.js.map +1 -0
- package/dist/packages/agent-runtime/src/message-window.cjs +150 -42
- package/dist/packages/agent-runtime/src/message-window.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/message-window.js +151 -43
- package/dist/packages/agent-runtime/src/message-window.js.map +1 -1
- package/dist/packages/agent-runtime/src/quota-safe-local-storage-session.cjs +13 -9
- package/dist/packages/agent-runtime/src/quota-safe-local-storage-session.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/quota-safe-local-storage-session.js +13 -9
- package/dist/packages/agent-runtime/src/quota-safe-local-storage-session.js.map +1 -1
- package/dist/packages/agent-runtime/src/statewire-suspended.cjs +1 -3
- package/dist/packages/agent-runtime/src/statewire-suspended.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/statewire-suspended.js +1 -3
- package/dist/packages/agent-runtime/src/statewire-suspended.js.map +1 -1
- package/dist/packages/agent-runtime/src/use-deep-agent-edit-submit.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/use-deep-agent-edit-submit.js.map +1 -1
- package/dist/packages/agent-runtime/src/use-deep-agent-thread.cjs +61 -30
- package/dist/packages/agent-runtime/src/use-deep-agent-thread.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/use-deep-agent-thread.js +59 -28
- package/dist/packages/agent-runtime/src/use-deep-agent-thread.js.map +1 -1
- package/dist/packages/agent-runtime/src/use-deep-agent-window-sync.cjs +56 -36
- package/dist/packages/agent-runtime/src/use-deep-agent-window-sync.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/use-deep-agent-window-sync.js +59 -39
- package/dist/packages/agent-runtime/src/use-deep-agent-window-sync.js.map +1 -1
- package/dist/packages/react/package.json.cjs +1 -1
- package/dist/packages/react/package.json.js +1 -1
- package/dist/provider/AthenaContext.cjs.map +1 -1
- package/dist/provider/AthenaContext.d.ts +3 -0
- package/dist/provider/AthenaContext.js.map +1 -1
- package/dist/provider/AthenaProvider.cjs +93 -45
- package/dist/provider/AthenaProvider.cjs.map +1 -1
- package/dist/provider/AthenaProvider.d.ts +6 -1
- package/dist/provider/AthenaProvider.js +97 -49
- package/dist/provider/AthenaProvider.js.map +1 -1
- package/dist/runtime/statewire-lifecycle.cjs +2 -1
- package/dist/runtime/statewire-lifecycle.cjs.map +1 -1
- package/dist/runtime/statewire-lifecycle.js +2 -1
- package/dist/runtime/statewire-lifecycle.js.map +1 -1
- package/dist/runtime/useAthenaStatewireRuntime.cjs +3 -2
- package/dist/runtime/useAthenaStatewireRuntime.cjs.map +1 -1
- package/dist/runtime/useAthenaStatewireRuntime.d.ts +8 -12
- package/dist/runtime/useAthenaStatewireRuntime.js +3 -2
- package/dist/runtime/useAthenaStatewireRuntime.js.map +1 -1
- package/dist/search/useAthenaRepoSearch.cjs +94 -0
- package/dist/search/useAthenaRepoSearch.cjs.map +1 -0
- package/dist/search/useAthenaRepoSearch.d.ts +95 -0
- package/dist/search/useAthenaRepoSearch.js +94 -0
- package/dist/search/useAthenaRepoSearch.js.map +1 -0
- package/dist/styles.css +1 -1
- package/dist/threads/SessionList.cjs +486 -0
- package/dist/threads/SessionList.cjs.map +1 -0
- package/dist/threads/SessionList.d.ts +60 -0
- package/dist/threads/SessionList.js +486 -0
- package/dist/threads/SessionList.js.map +1 -0
- package/dist/threads/api.cjs +112 -4
- package/dist/threads/api.cjs.map +1 -1
- package/dist/threads/api.d.ts +128 -1
- package/dist/threads/api.js +113 -5
- package/dist/threads/api.js.map +1 -1
- package/dist/threads/conversation-list-fetcher.cjs +27 -3
- package/dist/threads/conversation-list-fetcher.cjs.map +1 -1
- package/dist/threads/conversation-list-fetcher.d.ts +16 -3
- package/dist/threads/conversation-list-fetcher.js +27 -3
- package/dist/threads/conversation-list-fetcher.js.map +1 -1
- package/dist/threads/index.d.ts +5 -1
- package/dist/threads/session-list-model.cjs +130 -0
- package/dist/threads/session-list-model.cjs.map +1 -0
- package/dist/threads/session-list-model.d.ts +62 -0
- package/dist/threads/session-list-model.js +130 -0
- package/dist/threads/session-list-model.js.map +1 -0
- package/dist/threads/statewire-thread-list.cjs +220 -38
- package/dist/threads/statewire-thread-list.cjs.map +1 -1
- package/dist/threads/statewire-thread-list.d.ts +152 -2
- package/dist/threads/statewire-thread-list.js +222 -40
- package/dist/threads/statewire-thread-list.js.map +1 -1
- package/dist/threads/thread-prefetcher.cjs +63 -0
- package/dist/threads/thread-prefetcher.cjs.map +1 -0
- package/dist/threads/thread-prefetcher.d.ts +54 -0
- package/dist/threads/thread-prefetcher.js +63 -0
- package/dist/threads/thread-prefetcher.js.map +1 -0
- package/dist/threads/use-athena-session-attention.cjs +22 -0
- package/dist/threads/use-athena-session-attention.cjs.map +1 -0
- package/dist/threads/use-athena-session-attention.d.ts +24 -0
- package/dist/threads/use-athena-session-attention.js +22 -0
- package/dist/threads/use-athena-session-attention.js.map +1 -0
- package/dist/threads/use-rest-conversation-history.cjs +25 -2
- package/dist/threads/use-rest-conversation-history.cjs.map +1 -1
- package/dist/threads/use-rest-conversation-history.d.ts +8 -1
- package/dist/threads/use-rest-conversation-history.js +25 -2
- package/dist/threads/use-rest-conversation-history.js.map +1 -1
- package/dist/threads/use-statewire-conversation-history.cjs +40 -16
- package/dist/threads/use-statewire-conversation-history.cjs.map +1 -1
- package/dist/threads/use-statewire-conversation-history.d.ts +13 -0
- package/dist/threads/use-statewire-conversation-history.js +40 -16
- package/dist/threads/use-statewire-conversation-history.js.map +1 -1
- package/dist/threads/use-thread-archive.cjs +128 -0
- package/dist/threads/use-thread-archive.cjs.map +1 -0
- package/dist/threads/use-thread-archive.d.ts +26 -0
- package/dist/threads/use-thread-archive.js +128 -0
- package/dist/threads/use-thread-archive.js.map +1 -0
- package/dist/threads/use-thread-favorite.cjs +53 -0
- package/dist/threads/use-thread-favorite.cjs.map +1 -0
- package/dist/threads/use-thread-favorite.d.ts +49 -0
- package/dist/threads/use-thread-favorite.js +53 -0
- package/dist/threads/use-thread-favorite.js.map +1 -0
- package/dist/threads/use-thread-field-override.cjs +184 -0
- package/dist/threads/use-thread-field-override.cjs.map +1 -0
- package/dist/threads/use-thread-field-override.d.ts +55 -0
- package/dist/threads/use-thread-field-override.js +184 -0
- package/dist/threads/use-thread-field-override.js.map +1 -0
- package/dist/threads/use-thread-rename.cjs +53 -0
- package/dist/threads/use-thread-rename.cjs.map +1 -0
- package/dist/threads/use-thread-rename.d.ts +48 -0
- package/dist/threads/use-thread-rename.js +53 -0
- package/dist/threads/use-thread-rename.js.map +1 -0
- package/dist/tools/index.cjs +5 -1
- package/dist/tools/index.cjs.map +1 -1
- package/dist/tools/index.d.ts +1 -1
- package/dist/tools/index.js +7 -3
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/misc-tool-uis.cjs +2 -1
- package/dist/tools/misc-tool-uis.cjs.map +1 -1
- package/dist/tools/misc-tool-uis.js +2 -1
- package/dist/tools/misc-tool-uis.js.map +1 -1
- package/dist/tools/primitives.cjs +25 -2
- package/dist/tools/primitives.cjs.map +1 -1
- package/dist/tools/primitives.d.ts +9 -2
- package/dist/tools/primitives.js +26 -3
- package/dist/tools/primitives.js.map +1 -1
- package/dist/tools/tool-appearance.cjs +11 -0
- package/dist/tools/tool-appearance.cjs.map +1 -0
- package/dist/tools/tool-appearance.d.ts +29 -0
- package/dist/tools/tool-appearance.js +11 -0
- package/dist/tools/tool-appearance.js.map +1 -0
- package/dist/tools/tool-fallback.cjs +211 -13
- package/dist/tools/tool-fallback.cjs.map +1 -1
- package/dist/tools/tool-fallback.d.ts +31 -4
- package/dist/tools/tool-fallback.js +214 -16
- package/dist/tools/tool-fallback.js.map +1 -1
- package/dist/tools/use-elapsed-seconds.cjs +24 -0
- package/dist/tools/use-elapsed-seconds.cjs.map +1 -0
- package/dist/tools/use-elapsed-seconds.d.ts +10 -0
- package/dist/tools/use-elapsed-seconds.js +24 -0
- package/dist/tools/use-elapsed-seconds.js.map +1 -0
- package/dist/tools/voice-update-tool-ui.cjs +2 -1
- package/dist/tools/voice-update-tool-ui.cjs.map +1 -1
- package/dist/tools/voice-update-tool-ui.js +2 -1
- package/dist/tools/voice-update-tool-ui.js.map +1 -1
- package/package.json +1 -1
- package/src/chat-ui/tailwind-preset.js +14 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-deep-agent-edit-submit.js","sources":["../../../../../agent-runtime/src/use-deep-agent-edit-submit.ts"],"sourcesContent":["import { useAui } from '@assistant-ui/store';\nimport type { StatewireThread } from '@assistant-ui/react-statewire';\nimport { useCallback, useEffect, useRef } from 'react';\nimport { readDeepAgentStatewireExtras, resolveDeepAgentEditCommand } from './edit-command';\n\n/**\n * The submit handler of a message's edit composer on a deep-agent thread: the\n * edited text leaves as a `run/edit` anchored on the host's own parent of the\n * message (see `edit-command.ts`) —
|
|
1
|
+
{"version":3,"file":"use-deep-agent-edit-submit.js","sources":["../../../../../agent-runtime/src/use-deep-agent-edit-submit.ts"],"sourcesContent":["import { useAui } from '@assistant-ui/store';\nimport type { StatewireThread } from '@assistant-ui/react-statewire';\nimport { useCallback, useEffect, useRef } from 'react';\nimport { readDeepAgentStatewireExtras, resolveDeepAgentEditCommand } from './edit-command';\n\n/**\n * The submit handler of a message's edit composer on a deep-agent thread: the\n * edited text leaves as a `run/edit` anchored on the host's own parent of the\n * message (see `edit-command.ts`) — older pages stated first for a message at\n * or below the loaded window's edge — instead of the library's\n * converted-message anchor, which the host rejects `wrong-anchor` after a\n * chunked assistant turn and at the window edge.\n *\n * Read inside the message scope (`aui.message()`): the library's optimistic\n * fold shows the edited bubble and rewinds the visible history the moment the\n * command is dispatched, so the edit composer closes right away. Falls back\n * to the composer's own `send()` when the thread is not a statewire thread or\n * the host has not settled the message yet. Resolves `false` for an empty\n * draft, a duplicate submission, or an edit cancelled during preparation.\n */\nexport function useDeepAgentMessageEditSubmit(): () => Promise<boolean> {\n const aui = useAui();\n const alive = useRef(true);\n const submitting = useRef(false);\n useEffect(() => {\n alive.current = true;\n return () => {\n alive.current = false;\n };\n }, []);\n return useCallback(async () => {\n if (submitting.current) return false;\n const composer = aui.message().composer();\n const draft = composer.getState();\n const text = draft.text.trim();\n if (!text && draft.attachments.length === 0) return false;\n const files: StatewireThread.FilePart[] = [];\n const texts = text ? [text] : [];\n // beginEdit lifts original inline images/files into completed composer\n // attachments. The anchored command must carry those too: a text-only\n // reconstruction silently deleted them when editing a cross-device turn.\n for (const attachment of draft.attachments) {\n if (attachment.status.type !== 'complete')\n throw new Error('Wait for attachments to finish before sending your edit.');\n for (const part of attachment.content ?? []) {\n if (part.type === 'text') texts.push(part.text);\n else if (part.type === 'image')\n files.push({ type: 'file', mediaType: 'image/*', url: part.image });\n else if (part.type === 'file')\n files.push({\n type: 'file',\n mediaType: part.mimeType,\n url: part.data,\n ...(part.filename && { filename: part.filename }),\n });\n else throw new Error('This attachment cannot be edited here.');\n }\n }\n submitting.current = true;\n try {\n const sourceId = aui.message().getState().id;\n const readExtras = () =>\n alive.current ? readDeepAgentStatewireExtras(aui.thread().getState().extras) : null;\n const extras = readExtras();\n if (extras) {\n const preparedMetadata = extras.prepareMessageMetadata?.();\n try {\n const command = await resolveDeepAgentEditCommand({\n readExtras,\n sourceId,\n text,\n });\n if (!alive.current || !composer.getState().isEditing) {\n if (preparedMetadata) extras.discardPreparedMessageMetadata?.(preparedMetadata);\n return false;\n }\n if (command) {\n void Promise.resolve(\n extras.sendCommand(\n {\n ...command,\n message: {\n ...command.message,\n parts: [\n ...files,\n ...(texts.length\n ? [{ type: 'text' as const, text: texts.join('\\n\\n') }]\n : []),\n ],\n },\n },\n preparedMetadata === undefined ? undefined : { preparedMetadata },\n ),\n ).catch(() => undefined);\n composer.cancel();\n return true;\n }\n if (preparedMetadata && extras.sendPreparedEdit) {\n extras.sendPreparedEdit(sourceId, preparedMetadata);\n return true;\n }\n } catch (error) {\n if (preparedMetadata) extras.discardPreparedMessageMetadata?.(preparedMetadata);\n throw error;\n }\n }\n composer.send();\n return true;\n } finally {\n submitting.current = false;\n }\n }, [aui]);\n}\n"],"names":[],"mappings":";;;AAoBO,SAAS,gCAAwD;AACtE,QAAM,MAAM,OAAA;AACZ,QAAM,QAAQ,OAAO,IAAI;AACzB,QAAM,aAAa,OAAO,KAAK;AAC/B,YAAU,MA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,UAAA,CACD;AACD,cAAI,CAAC,MAAM,WAAW,CAAC,SAAS,SAAA,EAAW,WAAW;AACpD,gBAAI,iBAAkB,cAAO,mCAAP,gCAAwC;AAC9D,mBAAO;AAAA,UACT;AACA,cAAI,SAAS;AACX,iBAAK,QAAQ;AAAA,cACX,OAAO;AAAA,gBACL;AAAA,kBACE,GAAG;AAAA,kBACH,SAAS;AAAA,oBACP,GAAG,QAAQ;AAAA,oBACX,OAAO;AAAA,sBACL,GAAG;AAAA,sBACH,GAAI,MAAM,SACN,CAAC,EAAE,MAAM,QAAiB,MAAM,MAAM,KAAK,MAAM,EAAA,CAAG,IACpD,CAAA;AAAA,oBAAC;AAAA,kBACP;AAAA,gBACF;AAAA,gBAEF,qBAAqB,SAAY,SAAY,EAAE,iBAAA;AAAA,cAAiB;AAAA,YAClE,EACA,MAAM,MAAM,MAAS;AACvB,qBAAS,OAAA;AACT,mBAAO;AAAA,UACT;AACA,cAAI,oBAAoB,OAAO,kBAAkB;AAC/C,mBAAO,iBAAiB,UAAU,gBAAgB;AAClD,mBAAO;AAAA,UACT;AAAA,QACF,SAAS,OAAO;AACd,cAAI,iBAAkB,cAAO,mCAAP,gCAAwC;AAC9D,gBAAM;AAAA,QACR;AAAA,MACF;AACA,eAAS,KAAA;AACT,aAAO;AAAA,IACT,UAAA;AACE,iBAAW,UAAU;AAAA,IACvB;AAAA,EACF,GAAG,CAAC,GAAG,CAAC;AACV;"}
|
|
@@ -7,6 +7,8 @@ const authDenial = require("./auth-denial.cjs");
|
|
|
7
7
|
const deepAgentTransportRecipe = require("./deep-agent-transport-recipe.cjs");
|
|
8
8
|
const errors = require("./errors.cjs");
|
|
9
9
|
const messageAuthor = require("./message-author.cjs");
|
|
10
|
+
const runconfigContract = require("./generated/runconfig-contract.cjs");
|
|
11
|
+
const messageWindow = require("./message-window.cjs");
|
|
10
12
|
const messages = require("./messages.cjs");
|
|
11
13
|
const protocol = require("./protocol.cjs");
|
|
12
14
|
const statewireState = require("./statewire-state.cjs");
|
|
@@ -38,7 +40,7 @@ function useDeepAgentThread({
|
|
|
38
40
|
adapters,
|
|
39
41
|
diagnostics,
|
|
40
42
|
snapshotCache,
|
|
41
|
-
messageWindow
|
|
43
|
+
messageWindow: messageWindow$1,
|
|
42
44
|
toolOutputs,
|
|
43
45
|
withdrawnTurns,
|
|
44
46
|
prewarmPool,
|
|
@@ -78,8 +80,10 @@ function useDeepAgentThread({
|
|
|
78
80
|
onRawConnectionChangeRef.current = onRawConnectionChange;
|
|
79
81
|
const headersRef = react.useRef(headers);
|
|
80
82
|
headersRef.current = headers;
|
|
81
|
-
const messageWindowRef = react.useRef(messageWindow);
|
|
82
|
-
messageWindowRef.current = messageWindow;
|
|
83
|
+
const messageWindowRef = react.useRef(messageWindow$1);
|
|
84
|
+
messageWindowRef.current = messageWindow$1;
|
|
85
|
+
const interestRef = react.useRef({ attachId: "", stated: false });
|
|
86
|
+
const lastMessagesRef = react.useRef(null);
|
|
83
87
|
const [toolOutputsVersion, setToolOutputsVersion] = react.useState(0);
|
|
84
88
|
react.useEffect(() => {
|
|
85
89
|
if (!toolOutputs) return void 0;
|
|
@@ -171,12 +175,15 @@ function useDeepAgentThread({
|
|
|
171
175
|
const notify = onRunningChangeRef.current;
|
|
172
176
|
if (notify) queueMicrotask(() => notify(isRunning));
|
|
173
177
|
}
|
|
174
|
-
return
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
178
|
+
return {
|
|
179
|
+
...messages.convertDeepAgentState(state, {
|
|
180
|
+
laneProjection,
|
|
181
|
+
selfAuthor: stableSelfAuthor,
|
|
182
|
+
toolOutputs,
|
|
183
|
+
withdrawnTurns
|
|
184
|
+
}),
|
|
185
|
+
state
|
|
186
|
+
};
|
|
180
187
|
},
|
|
181
188
|
[
|
|
182
189
|
laneProjection,
|
|
@@ -224,10 +231,44 @@ function useDeepAgentThread({
|
|
|
224
231
|
if (notifySource) queueMicrotask(() => notifySource({ threadId, source }));
|
|
225
232
|
}
|
|
226
233
|
const threadConverter = react.useCallback(
|
|
227
|
-
(
|
|
228
|
-
var _a2, _b, _c, _d;
|
|
234
|
+
(wireState, meta) => {
|
|
235
|
+
var _a2, _b, _c, _d, _e, _f, _g;
|
|
236
|
+
const values = statewireState.readDeepAgentStreamValues(wireState);
|
|
237
|
+
const window = messageWindow.readDeepAgentMessageWindow(meta.mounted);
|
|
238
|
+
const held = ((_a2 = lastMessagesRef.current) == null ? void 0 : _a2.attachId) === attachId ? lastMessagesRef.current.messages : null;
|
|
239
|
+
const messages2 = (window == null ? void 0 : window.messages) ?? values.messages ?? held ?? [];
|
|
240
|
+
if (window !== null || messages2.length > 0) lastMessagesRef.current = { attachId, messages: messages2 };
|
|
241
|
+
const state = { ...values, messages: [...messages2] };
|
|
242
|
+
materialize(state);
|
|
243
|
+
if (window !== null && statewireState.isDeepAgentStateHydrated(values)) {
|
|
244
|
+
(_b = snapshotCacheRef.current) == null ? void 0 : _b.remember(threadId, state);
|
|
245
|
+
}
|
|
246
|
+
if (interestRef.current.attachId !== attachId) {
|
|
247
|
+
interestRef.current = { attachId, stated: false };
|
|
248
|
+
}
|
|
249
|
+
if (meta.connection.status !== "connected") {
|
|
250
|
+
interestRef.current.stated = false;
|
|
251
|
+
} else if (!interestRef.current.stated) {
|
|
252
|
+
interestRef.current.stated = true;
|
|
253
|
+
const wanted = messageWindow.headInterestRequest((_c = messageWindowRef.current) == null ? void 0 : _c.size);
|
|
254
|
+
const head = window == null ? void 0 : window.requests[0];
|
|
255
|
+
const preloaded = head !== void 0 && head.at === void 0 && head.before >= wanted.before;
|
|
256
|
+
if (!preloaded) {
|
|
257
|
+
const requests = [
|
|
258
|
+
wanted,
|
|
259
|
+
...(window == null ? void 0 : window.requests.filter((request) => request.at !== void 0)) ?? []
|
|
260
|
+
];
|
|
261
|
+
queueMicrotask(() => {
|
|
262
|
+
if (attachIdRef.current !== attachId) return;
|
|
263
|
+
meta.invoke(runconfigContract.DEEP_AGENT_INTEREST_PROTOCOL, "set", [requests]).catch((error) => {
|
|
264
|
+
var _a3;
|
|
265
|
+
(_a3 = onErrorRef.current) == null ? void 0 : _a3.call(onErrorRef, error instanceof Error ? error : new Error(String(error)));
|
|
266
|
+
});
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
}
|
|
229
270
|
const connection = errors.projectDeepAgentConnection(meta.connection);
|
|
230
|
-
(
|
|
271
|
+
(_d = diagnosticsRef.current) == null ? void 0 : _d.observeConnection(meta.connection);
|
|
231
272
|
if (authDenialRef.current.attachId !== attachIdRef.current) {
|
|
232
273
|
authDenialRef.current = {
|
|
233
274
|
attachId: attachIdRef.current,
|
|
@@ -239,7 +280,7 @@ function useDeepAgentThread({
|
|
|
239
280
|
if (denial.park) {
|
|
240
281
|
const parkAttachId = attachIdRef.current;
|
|
241
282
|
const parkMessage = denial.state.message;
|
|
242
|
-
(
|
|
283
|
+
(_e = snapshotCacheRef.current) == null ? void 0 : _e.forget(threadId);
|
|
243
284
|
queueMicrotask(() => {
|
|
244
285
|
if (attachIdRef.current !== parkAttachId) return;
|
|
245
286
|
setAuthParked(
|
|
@@ -274,9 +315,9 @@ function useDeepAgentThread({
|
|
|
274
315
|
});
|
|
275
316
|
}
|
|
276
317
|
}
|
|
277
|
-
return converter(state, ((
|
|
318
|
+
return converter(state, ((_g = (_f = state.runs) == null ? void 0 : _f[0]) == null ? void 0 : _g.status) === "running");
|
|
278
319
|
},
|
|
279
|
-
[attachId, converter, threadId]
|
|
320
|
+
[attachId, converter, materialize, threadId]
|
|
280
321
|
);
|
|
281
322
|
return reactStatewire.StatewireThread({
|
|
282
323
|
// The transport stamps this protocol on every command; the thread client
|
|
@@ -326,6 +367,7 @@ function useDeepAgentThread({
|
|
|
326
367
|
sse,
|
|
327
368
|
isNew: preloadRef.current.preload,
|
|
328
369
|
headers: (ctx) => headersRef.current(ctx),
|
|
370
|
+
messageWindow: messageWindowRef.current,
|
|
329
371
|
sessionStore,
|
|
330
372
|
onAuthResolve: (ctx) => {
|
|
331
373
|
var _a2;
|
|
@@ -334,11 +376,7 @@ function useDeepAgentThread({
|
|
|
334
376
|
onAttachTiming: (event) => {
|
|
335
377
|
var _a2;
|
|
336
378
|
return (_a2 = onAttachTimingRef.current) == null ? void 0 : _a2.call(onAttachTimingRef, { threadId, event });
|
|
337
|
-
}
|
|
338
|
-
// Read once per attach: a declaration change applies to the next
|
|
339
|
-
// attach, never to a reconnect of this one (the view would be
|
|
340
|
-
// re-shaped under the client).
|
|
341
|
-
messageWindow: messageWindowRef.current
|
|
379
|
+
}
|
|
342
380
|
});
|
|
343
381
|
})()
|
|
344
382
|
),
|
|
@@ -350,9 +388,6 @@ function useDeepAgentThread({
|
|
|
350
388
|
// former `runs: true` opt-in is gone) — the converter only maps app-owned
|
|
351
389
|
// keys, including the `run/stop` runId stamp the lib projects itself.
|
|
352
390
|
converter: threadConverter,
|
|
353
|
-
// Makes the server's dispatch record concrete in state (after the
|
|
354
|
-
// optimistic folds); the lib's post-converter dispatch merge turns off.
|
|
355
|
-
materialize,
|
|
356
391
|
// Native message editing: an edited turn is resubmitted as a `run/edit`
|
|
357
392
|
// command, and the deep-agent backend rewinds the checkpointed thread to
|
|
358
393
|
// the edited message's parent before appending (route `plan_rewind`).
|
|
@@ -369,18 +404,14 @@ function useDeepAgentThread({
|
|
|
369
404
|
(_a2 = diagnosticsRef.current) == null ? void 0 : _a2.observeError(error);
|
|
370
405
|
(_b = onErrorRef.current) == null ? void 0 : _b.call(onErrorRef, error);
|
|
371
406
|
},
|
|
372
|
-
...
|
|
407
|
+
...onStateChange && {
|
|
373
408
|
// The lib types the observed state `NonNullable`, but the runtime
|
|
374
409
|
// delivers `undefined` where the wire has no snapshot (pre-attach and
|
|
375
410
|
// replay boundaries republish it) — normalize so the type is true and
|
|
376
411
|
// host observers never crash on a field read.
|
|
377
412
|
onStateChange: ((state, ctx) => {
|
|
378
|
-
var _a2
|
|
379
|
-
|
|
380
|
-
if (statewireState.isDeepAgentStateHydrated(values)) {
|
|
381
|
-
(_a2 = snapshotCacheRef.current) == null ? void 0 : _a2.remember(threadId, values);
|
|
382
|
-
}
|
|
383
|
-
(_b = onStateChangeRef.current) == null ? void 0 : _b.call(onStateChangeRef, values, ctx);
|
|
413
|
+
var _a2;
|
|
414
|
+
(_a2 = onStateChangeRef.current) == null ? void 0 : _a2.call(onStateChangeRef, statewireState.readDeepAgentStreamValues(state), ctx);
|
|
384
415
|
})
|
|
385
416
|
},
|
|
386
417
|
...(onCommandChange || diagnostics) && {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-deep-agent-thread.cjs","sources":["../../../../../agent-runtime/src/use-deep-agent-thread.ts"],"sourcesContent":["import { StatewireThread } from '@assistant-ui/react-statewire';\nimport { withKey } from '@assistant-ui/tap';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport {\n type AuthDenialTrackerState,\n initialAuthDenialTrackerState,\n observeAuthDenial,\n} from './auth-denial';\nimport {\n createDeepAgentAttachTransport,\n type DeepAgentHeadersResolver,\n} from './deep-agent-transport-recipe';\nimport { projectDeepAgentConnection } from './errors';\nimport { type DeepAgentMessageAuthor, isSameMessageAuthor } from './message-author';\nimport type { DeepAgentMessageWindowDeclaration } from './message-window';\nimport { convertDeepAgentState, createDeepAgentMaterialize } from './messages';\nimport { type DeepAgentProtocolStatus, projectDeepAgentProtocol } from './protocol';\nimport type { DeepAgentAttachTimingEvent } from './statewire-attach-observer';\nimport type { StatewireDiagnosticsRecorder } from './statewire-diagnostics';\nimport { isDeepAgentStateHydrated, readDeepAgentStreamValues } from './statewire-state';\nimport { StatewireSuspended } from './statewire-suspended';\nimport {\n DEEP_AGENT_STATEWIRE_PROTOCOL,\n type StatewireTransportOptions,\n} from './statewire-transport';\nimport type { DeepAgentThreadPrewarmPool } from './thread-prewarm';\nimport { type DeepAgentThreadSnapshotCache, toThreadSnapshotSeed } from './thread-snapshot-cache';\nimport type { DeepAgentToolOutputStore } from './tool-outputs';\nimport type { DeepAgentWithdrawnTurns } from './withdrawn-turns';\nimport type {\n DeepAgentConnectionState,\n DeepAgentLaneProjection,\n DeepAgentStreamValues,\n} from './types';\n\ntype ThreadOptions = StatewireThread.Options<DeepAgentStreamValues>;\n\nexport type { DeepAgentHeadersResolver } from './deep-agent-transport-recipe';\n\n/**\n * How an attach's FIRST frame is sourced, decided once per attach at mount: the\n * hello a pooled pre-dialed attach already replicated (`prewarm`), a remembered\n * snapshot seed (`snapshot`), or nothing (`none` — the thread loads until its\n * hello).\n */\nexport type DeepAgentAttachSource = 'prewarm' | 'snapshot' | 'none';\n\nexport interface UseDeepAgentThreadOptions {\n threadId: string;\n /** Base URL of the deep-agent statewire host (the `…/v2/threads` mount). */\n baseUrl: string;\n /** Transport selection: SSE when true, WebSocket otherwise. */\n sse?: boolean;\n /**\n * Auth headers for the transport. Statewire passes `{ staleAuth: true }`\n * when the previous credential was refused, so resolvers that can\n * force-renew should honor it.\n */\n headers: DeepAgentHeadersResolver;\n /**\n * Statewire session store for reconnect command-session recovery (e.g. the\n * mobile AsyncStorage-backed store). Host-resolved; omitted, sessions are\n * process-local.\n */\n sessionStore?: StatewireTransportOptions['sessionStore'];\n /**\n * Mounted storage seams for the thread: `session` holds the lane identity and\n * the commands still awaiting a durable verdict, so a reload resumes the lane\n * instead of minting a new client (browser hosts pass `LocalStorageSession`\n * from `@assistant-ui/react-statewire/local-storage`); `composer` persists the\n * draft. Mutually exclusive with `sessionStore` — statewire refuses a session\n * mounted twice.\n */\n storage?: ThreadOptions['storage'];\n /** True only for a never-started local chat; existing empty threads still load until their snapshot. */\n isNewChat?: boolean;\n /**\n * Extra transport-key discriminator for the SAME thread. The session is keyed\n * by `threadId` alone by default; hosts that must re-read the server snapshot\n * without a thread switch (a run dispatched outside this client, e.g. a\n * backgrounded AOP run writing the thread's first messages) bump this to\n * remount the session against the same URL.\n */\n attachKey?: string | number;\n /**\n * Host gate: park the transport instead of attaching — no socket, no retry\n * loop. The thread element stays mounted so assistant-ui consumers keep\n * rendering. Pass it when the host already knows every attach would be denied (e.g.\n * the signed-in user has no workspace yet), so a locked-out tab does not\n * hammer the attach endpoint on every backoff interval.\n */\n suspended?: { reason: string } | false;\n /**\n * Adapter capabilities the host UI exposes. Defaults preserve each client's\n * pre-extraction surface — pass what the product mounts.\n */\n capabilities?: {\n edit?: boolean;\n continue?: boolean;\n reload?: boolean;\n unstable_switchBranch?: boolean;\n };\n /** Which run lanes project into the message tail; see {@link DeepAgentLaneProjection}. */\n laneProjection?: DeepAgentLaneProjection;\n /**\n * The viewer, as the backend would stamp them (`metadata.custom.author`).\n * Stamped onto this client's own optimistic bubbles — a send still in flight\n * has no host `meta` yet — so a just-sent turn is attributed, and the\n * multi-author avatar gate flips for a second poster, without waiting for\n * the acknowledgment. Replicated entries carry the host's own stamp instead.\n * Compared field-wise, so callers need not memoize the object.\n */\n selfAuthor?: DeepAgentMessageAuthor | null;\n /**\n * Snapshot host context when each user message is submitted, before it is\n * journaled. Includes programmatic appends, keyboard sends, queued messages,\n * steering, and edits. The async getter starts immediately at submission;\n * sends retain their order while it resolves. Retries, queue text edits,\n * lane moves, reload, and continue preserve the original association.\n * Return JSON-serializable metadata; optional capture failures can\n * return an explicit null field rather than blocking the message.\n */\n getMessageMetadata?: ThreadOptions['getMessageMetadata'];\n /** Host-owned adapters: attachments (upload/mention choreography), speech, feedback. */\n adapters?: ThreadOptions['adapters'];\n /**\n * Transport lifecycle recorder (attach latency, reconnect loops, command\n * settle fates, stale-auth renewals) fed from the hook's own seams. Pass one\n * only when the host's diagnostics channel is enabled — the recorder is\n * observed on hot paths, and an absent recorder costs a single optional call.\n */\n diagnostics?: StatewireDiagnosticsRecorder;\n /**\n * Per-tab LRU of the last wire state seen per thread. When set, every\n * hydrated state the transport publishes is remembered, and a mount of a\n * remembered thread seeds `initialState` from the cache (through\n * {@link toThreadSnapshotSeed}) — the thread renders its last-known\n * messages on the first frame instead of holding a loading treatment for\n * the attach round-trip, and projects \"running\" when the run was live at\n * capture (else \"ready\"). The attach snapshot then\n * REPLACES the seeded state (statewire's `initialState` contract), so a\n * thread that advanced elsewhere reconciles in one round-trip. New chats\n * keep their preload and never read the cache.\n */\n snapshotCache?: DeepAgentThreadSnapshotCache;\n /**\n * Declare a message window on the attach (`x-athena-deep-agent-window`):\n * the hello carries the last `size` messages plus the `messagesWindow`\n * lane and the host re-addresses the op stream to that window; older\n * ranges load through `history/load` (see `message-window.ts`). Read once\n * per attach. `false` / omitted keeps the full snapshot — the surfaces\n * that have not adopted the window are untouched.\n */\n messageWindow?: DeepAgentMessageWindowDeclaration | false;\n /**\n * Full tool outputs fetched back for a windowed wire's cut tool messages\n * (`history/tool_output`); the thread re-converts when one lands. Only\n * meaningful together with `messageWindow`.\n */\n toolOutputs?: DeepAgentToolOutputStore;\n /**\n * User turns this client took back ahead of the wire (a user stop before\n * any assistant output); the thread re-converts when one opens or closes.\n */\n withdrawnTurns?: DeepAgentWithdrawnTurns;\n /**\n * Pre-dialed attaches (see `thread-prewarm.ts`). When the pool holds a root\n * for this thread at mount, the thread takes the hello it replicated as its\n * seed — the transcript is the first frame — and dials its own attach\n * against the instance the pool warmed; the pooled root is disposed in the\n * same step, so one socket is live per thread after mount. Never seeded for\n * a preloaded new chat or a suspended attach; such a root is discarded.\n */\n prewarmPool?: DeepAgentThreadPrewarmPool<DeepAgentStreamValues>;\n /**\n * Attach-path timing: socket open, hello size + handler cost, server retry\n * hints — attributed to the attach's own thread, since a late event from the\n * thread being left can land after the host has moved on.\n */\n onAttachTiming?: (info: { threadId: string; event: DeepAgentAttachTimingEvent }) => void;\n /** Where this attach's first frame comes from; once per attach, at mount. */\n onAttachSource?: (info: { threadId: string; source: DeepAgentAttachSource }) => void;\n /** Full transport error policy (paywall, toast, telemetry) — client-owned. */\n onError?: ThreadOptions['onError'];\n /**\n * Raw statewire state observer (first-attach latches, telemetry). The state\n * argument is never `undefined`/`null`: passes where the wire has no\n * snapshot yet (pre-attach, replay boundaries) deliver the typed\n * `DEEP_AGENT_PRE_STREAM_STATE` default — `isDeepAgentStateHydrated`\n * distinguishes them from a real (possibly empty) snapshot.\n */\n onStateChange?: ThreadOptions['onStateChange'];\n /** Raw command-lifecycle observer (send-failure salvage, telemetry). */\n onCommandChange?: ThreadOptions['onCommandChange'];\n /** Raw connection observer (reconnect handles, telemetry). */\n onRawConnectionChange?: ThreadOptions['onConnectionChange'];\n /**\n * Projected connection status changes, deduped per thread, with `null` on\n * unmount so an indicator never shows a stale status.\n */\n onConnectionChange?: (connection: DeepAgentConnectionState | null) => void;\n /** Notified when a run starts/stops so the page can reflect the running thread. */\n onRunningChange?: (isRunning: boolean) => void;\n /**\n * Notified once per thread with the `runConfig` carried by the statewire\n * snapshot (the backend's persisted panel config, seeded in `_load_history`),\n * so the host can hydrate its config store from the thread. Notified with\n * `null` (at most once per attach) when a server snapshot arrives WITHOUT a\n * persisted config, so a host waiting on hydration can stop waiting; a\n * config appearing on a later snapshot of the same attach (mirrored at run\n * start) still delivers the config notification.\n */\n onServerRunConfig?: (config: Record<string, unknown> | null) => void;\n /**\n * Notified when the snapshot's `outOfBandRunActive` flag changes: the host set\n * it while a run executing OUTSIDE this surface (an AOP / HTTP-route run)\n * is actively writing the thread's bare-namespace history, which the host\n * live-refreshes onto the wire. Lets the page show run-in-progress\n * treatment instead of an empty conversation, and stand down its own\n * re-attach polling. Change-notified per attach (an initial `false` before\n * the snapshot stays silent), mirroring `onRunningChange`.\n */\n onOutOfBandRunActive?: (outOfBandRunActive: boolean) => void;\n /**\n * Notified with the state's session-asset lifecycle flag\n * ({@link readSessionPersisted}) PAIRED with the thread it describes: `false`\n * while the thread's `session` asset provably does not exist yet (a\n * never-started chat's preload, a first run before the mint), `true` once\n * minted, `null` when the state carries no flag (a host that predates it).\n *\n * Fired from the converter pass, so the pair is read from the state of the\n * thread this attach was mounted for. A component reading the flag off the\n * client store instead lags the mounted thread id by one render on a switch\n * and can pair the new id with the previous thread's flag — releasing a\n * session-scoped read for a row the backend has not minted. Change-notified\n * per attach; the first pass of every attach notifies, so a host holding a\n * read back until it hears from the mounted thread always does.\n */\n onSessionPersistedChange?: (event: {\n threadId: string;\n sessionPersisted: boolean | null;\n }) => void;\n /**\n * Notified with the wire-contract status once the attach snapshot\n * advertises the `protocol` lane, and again whenever it changes (a\n * re-attach after a server roll can advertise a new `version`). Telemetry\n * and per-version behaviour only: the host has no minimum client version,\n * so nothing about the status gates a send. Never called for\n * pre-declaration servers (their snapshots carry no lane) — absence of a\n * call means \"no advertisement\", not \"compatible\".\n */\n onProtocolChange?: (status: DeepAgentProtocolStatus) => void;\n}\n\n/** One thread's replicated running state, keyed so a switch between two\n * threads with the same status still re-notifies (the host page clears its\n * per-thread state on selection, mirroring the connection dedupe below). */\nexport interface RunningSnapshot {\n threadId: string;\n isRunning: boolean;\n}\n\n/** Whether the thread's `session` asset exists, read off a statewire state, or\n * `null` when the state does not carry the flag.\n *\n * Absence is not absence of the asset: a snapshot from a host that predates\n * the flag has no such key, and reading that as \"the asset does not exist\"\n * would gate a read the client is entitled to make, with nothing left to\n * un-gate it. A new thread's preload seeds `false` (see `initialState`), so\n * the pre-attach pass of a chat that cannot have an asset yet still gates.\n *\n * Hosts pass this to `useStatewireState` so the flag and the thread it belongs\n * to are read in one component — a thread switch then cannot pair one thread's\n * id with the other's flag. */\nexport function readSessionPersisted(state: unknown): boolean | null {\n const flag = (state as { sessionPersisted?: unknown } | null)?.sessionPersisted;\n return typeof flag === 'boolean' ? flag : null;\n}\n\n/** Whether a converter pass must notify `onRunningChange`.\n *\n * The mount's very first status notifies only when it is `true` (a snapshot\n * carrying a live run) — an initial `false` before the snapshot must stay\n * silent so it cannot clear a still-valid indicator. After that, every\n * transition notifies, and so does the first status after a thread switch\n * (the host page clears its per-thread state on selection, so a switch\n * between two threads with the same status must still re-notify). */\nexport function shouldNotifyRunningChange(\n previous: RunningSnapshot | null,\n next: RunningSnapshot\n): boolean {\n if (previous === null) return next.isRunning;\n return previous.threadId !== next.threadId || previous.isRunning !== next.isRunning;\n}\n\n/**\n * The shared deep-agent Statewire thread.\n *\n * `StatewireThread` (from `@assistant-ui/react-statewire`) attaches to the\n * agora-hosted thread at `${baseUrl}/${threadId}` (WebSocket by default,\n * with SSE retained only as a host-selected compatibility switch): the backend\n * hosts the thread state and this client\n * replicates it live, so the server snapshot is the single source of history\n * (no local import, no `/status` resume probing) and run scheduling — queueing,\n * steering, stop, edit rewinds — rides the built-in `run/*` commands.\n *\n * The thread element is keyed by `threadId`, so a thread switch remounts the\n * session against the new URL instead of importing history in place.\n *\n * Returns the thread element for the host's own `useAui({ thread })` — web\n * hosts take `useAui` from `@assistant-ui/react`, React Native hosts from\n * `@assistant-ui/react-native`; this package imports neither.\n */\nexport function useDeepAgentThread({\n threadId,\n baseUrl,\n sse = false,\n headers,\n sessionStore,\n storage,\n isNewChat = false,\n attachKey,\n suspended = false,\n capabilities,\n laneProjection = 'both',\n selfAuthor = null,\n getMessageMetadata,\n adapters,\n diagnostics,\n snapshotCache,\n messageWindow = false,\n toolOutputs,\n withdrawnTurns,\n prewarmPool,\n onAttachTiming,\n onAttachSource,\n onError,\n onStateChange,\n onCommandChange,\n onRawConnectionChange,\n onConnectionChange,\n onRunningChange,\n onServerRunConfig,\n onOutOfBandRunActive,\n onSessionPersistedChange,\n onProtocolChange,\n}: UseDeepAgentThreadOptions) {\n const onRunningChangeRef = useRef(onRunningChange);\n onRunningChangeRef.current = onRunningChange;\n const onSessionPersistedChangeRef = useRef(onSessionPersistedChange);\n onSessionPersistedChangeRef.current = onSessionPersistedChange;\n const onConnectionChangeRef = useRef(onConnectionChange);\n onConnectionChangeRef.current = onConnectionChange;\n const onServerRunConfigRef = useRef(onServerRunConfig);\n onServerRunConfigRef.current = onServerRunConfig;\n const onOutOfBandRunActiveRef = useRef(onOutOfBandRunActive);\n onOutOfBandRunActiveRef.current = onOutOfBandRunActive;\n const onProtocolChangeRef = useRef(onProtocolChange);\n onProtocolChangeRef.current = onProtocolChange;\n const onErrorRef = useRef(onError);\n onErrorRef.current = onError;\n const onStateChangeRef = useRef(onStateChange);\n onStateChangeRef.current = onStateChange;\n const onCommandChangeRef = useRef(onCommandChange);\n onCommandChangeRef.current = onCommandChange;\n const onRawConnectionChangeRef = useRef(onRawConnectionChange);\n onRawConnectionChangeRef.current = onRawConnectionChange;\n const headersRef = useRef(headers);\n headersRef.current = headers;\n const messageWindowRef = useRef(messageWindow);\n messageWindowRef.current = messageWindow;\n // A fetched tool output must re-run the converter (the store is read inside\n // it); the version is the memo's signal that the store's contents moved.\n const [toolOutputsVersion, setToolOutputsVersion] = useState(0);\n useEffect(() => {\n if (!toolOutputs) return undefined;\n return toolOutputs.subscribe(() => setToolOutputsVersion((version) => version + 1));\n }, [toolOutputs]);\n const [withdrawnTurnsVersion, setWithdrawnTurnsVersion] = useState(0);\n useEffect(() => {\n if (!withdrawnTurns) return undefined;\n return withdrawnTurns.subscribe(() => setWithdrawnTurnsVersion((version) => version + 1));\n }, [withdrawnTurns]);\n const diagnosticsRef = useRef(diagnostics);\n diagnosticsRef.current = diagnostics;\n const onAttachTimingRef = useRef(onAttachTiming);\n onAttachTimingRef.current = onAttachTiming;\n const onAttachSourceRef = useRef(onAttachSource);\n onAttachSourceRef.current = onAttachSource;\n\n const lastRunningRef = useRef<RunningSnapshot | null>(null);\n // Out-of-band run activity (`outOfBandRunActive`), change-notified with the\n // same semantics as the running flag above.\n const lastOutOfBandRunActiveRef = useRef<RunningSnapshot | null>(null);\n // The session-asset lifecycle flag last notified, keyed by attach so every\n // attach's first pass notifies (a host holding a read back until it hears\n // from the mounted thread must always hear from it).\n const lastSessionPersistedRef = useRef<{\n attachId: string;\n threadId: string;\n sessionPersisted: boolean | null;\n } | null>(null);\n // The last wire-contract status notified, keyed by attach so a re-attach\n // re-notifies (the new snapshot may advertise a different version).\n // `status: null` = nothing advertised yet on this attach.\n const lastProtocolRef = useRef<{\n attachId: string;\n status: DeepAgentProtocolStatus | null;\n } | null>(null);\n // The thread whose statewire-carried runConfig has been surfaced to the host\n // (once per thread; later snapshots must not clobber edits).\n const appliedStateRunConfigThreadRef = useRef<string | null>(null);\n // The attach that already notified `onServerRunConfig(null)` (snapshot\n // arrived carrying no persisted config) — at most once per attach.\n const absentStateRunConfigAttachRef = useRef<string | null>(null);\n // Live thread id for the callbacks: they are created per render but may\n // settle after a switch, so they compare against the current id.\n const threadIdRef = useRef(threadId);\n threadIdRef.current = threadId;\n // Identity of the current attach. Every per-thread latch keys off this, so a\n // re-attach of the same thread (a bumped `attachKey`) re-notifies the host\n // exactly like a switch would — the host clears its per-thread state on\n // re-attach, so a snapshot that repeats the previous status must not dedupe.\n const attachId: string = attachKey === undefined ? threadId : `${threadId}:${attachKey}`;\n const attachIdRef = useRef(attachId);\n attachIdRef.current = attachId;\n\n // Auth-denial park: the server fins every denied attach `unauthorized` and\n // the reconnect loop would otherwise retry it every 30s forever (prod tabs\n // looped for hours against revoked/workspace-less credentials). After a\n // streak of denials the live transport is swapped for a parked one; a new\n // attach (thread switch, bumped attachKey) or the parked connection's\n // `reconnect()` re-arms it.\n const [authParked, setAuthParked] = useState<{\n attachId: string;\n message: string | undefined;\n } | null>(null);\n const authDenialRef = useRef<{ attachId: string; state: AuthDenialTrackerState }>({\n attachId,\n state: initialAuthDenialTrackerState(),\n });\n useEffect(() => {\n setAuthParked((prev) => (prev !== null && prev.attachId !== attachId ? null : prev));\n }, [attachId]);\n\n // Field-wise stable identity for the viewer stamp, so a host that rebuilds\n // the author object per render does not rebuild the converter (and with it\n // every message) per render. Adjusting state during render is React's\n // sanctioned derived-state pattern: it re-renders once with the new value.\n const [stableSelfAuthor, setStableSelfAuthor] = useState(selfAuthor);\n if (!isSameMessageAuthor(stableSelfAuthor, selfAuthor)) setStableSelfAuthor(selfAuthor);\n\n // biome-ignore lint/correctness/useExhaustiveDependencies: toolOutputsVersion / withdrawnTurnsVersion are the stores' change signals — the converter reads the stores' contents, not the counters.\n const converter = useMemo(\n () => (state: unknown, isRunning: boolean) => {\n // Statewire snapshots carry the thread's persisted panel config (the\n // backend seeds `runConfig` in `_load_history` and mirrors it on run\n // start). Surface it once per thread so the host can hydrate its config\n // store.\n const stateRunConfig = (state as { runConfig?: unknown } | null)?.runConfig;\n if (\n stateRunConfig &&\n typeof stateRunConfig === 'object' &&\n !Array.isArray(stateRunConfig) &&\n appliedStateRunConfigThreadRef.current !== attachIdRef.current\n ) {\n appliedStateRunConfigThreadRef.current = attachIdRef.current;\n const notifyRunConfig = onServerRunConfigRef.current;\n if (notifyRunConfig) {\n queueMicrotask(() => notifyRunConfig(stateRunConfig as Record<string, unknown>));\n }\n } else if (\n !stateRunConfig &&\n appliedStateRunConfigThreadRef.current !== attachIdRef.current &&\n absentStateRunConfigAttachRef.current !== attachIdRef.current &&\n projectDeepAgentProtocol(state) !== null\n ) {\n // No persisted config on a SERVER state: the protocol lane rides every\n // attach snapshot, so its presence distinguishes \"the server answered\n // without a config\" from the pre-attach `initialState` (which must not\n // end the host's hydration wait).\n absentStateRunConfigAttachRef.current = attachIdRef.current;\n const notifyRunConfig = onServerRunConfigRef.current;\n if (notifyRunConfig) {\n queueMicrotask(() => notifyRunConfig(null));\n }\n }\n // Out-of-band run activity: the host live-refreshes a bare-namespace\n // (AOP / HTTP-route) thread's transcript while its run is active and\n // flags the wire state so the page can reflect it.\n const stateOutOfBandRunActive =\n (state as { outOfBandRunActive?: unknown } | null)?.outOfBandRunActive === true;\n const outOfBandRunActiveSnapshot = {\n threadId: attachIdRef.current,\n isRunning: stateOutOfBandRunActive,\n };\n if (shouldNotifyRunningChange(lastOutOfBandRunActiveRef.current, outOfBandRunActiveSnapshot)) {\n lastOutOfBandRunActiveRef.current = outOfBandRunActiveSnapshot;\n const observedAttachId = attachIdRef.current;\n queueMicrotask(() => {\n // A re-attach or newer snapshot between the converter pass and this\n // microtask owns the channel now — a stale flag must not leak into\n // the new attach's per-thread state.\n if (\n attachIdRef.current !== observedAttachId ||\n lastOutOfBandRunActiveRef.current !== outOfBandRunActiveSnapshot\n ) {\n return;\n }\n onOutOfBandRunActiveRef.current?.(stateOutOfBandRunActive);\n });\n }\n // Wire-contract advertisement: the host publishes the `protocol` lane in\n // every attach snapshot. Notify on first advertisement and on change\n // (dedupe by value, re-keyed per attach), with the same stale-guard\n // microtask as the other observers.\n const protocolStatus = projectDeepAgentProtocol(state);\n if (protocolStatus !== null) {\n const previous =\n lastProtocolRef.current?.attachId === attachIdRef.current\n ? lastProtocolRef.current.status\n : null;\n if (previous === null || previous.protocolVersion !== protocolStatus.protocolVersion) {\n const update = { attachId: attachIdRef.current, status: protocolStatus };\n lastProtocolRef.current = update;\n queueMicrotask(() => {\n if (lastProtocolRef.current !== update || attachIdRef.current !== update.attachId) {\n return;\n }\n onProtocolChangeRef.current?.(protocolStatus);\n });\n }\n }\n const runningSnapshot = { threadId: attachIdRef.current, isRunning };\n if (shouldNotifyRunningChange(lastRunningRef.current, runningSnapshot)) {\n lastRunningRef.current = runningSnapshot;\n const notify = onRunningChangeRef.current;\n if (notify) queueMicrotask(() => notify(isRunning));\n }\n return convertDeepAgentState(state, {\n laneProjection,\n selfAuthor: stableSelfAuthor,\n toolOutputs,\n withdrawnTurns,\n });\n },\n [\n laneProjection,\n stableSelfAuthor,\n toolOutputs,\n toolOutputsVersion,\n withdrawnTurns,\n withdrawnTurnsVersion,\n ]\n );\n const materialize = useMemo(\n () => createDeepAgentMaterialize({ selfAuthor: stableSelfAuthor }),\n [stableSelfAuthor]\n );\n\n // Surface the statewire connection status through `onConnectionChange` (the\n // converter re-runs on connection changes), and clear it when the runtime\n // unmounts so an indicator never shows a stale status. Dedup is keyed by\n // thread: the runtime stays mounted across idle thread switches, so the new\n // thread's first status must notify even when it equals the previous\n // thread's last one.\n const lastConnectionRef = useRef<{\n threadId: string;\n connection: DeepAgentConnectionState;\n } | null>(null);\n useEffect(\n () => () => {\n lastConnectionRef.current = null;\n onConnectionChangeRef.current?.(null);\n },\n []\n );\n\n // The preload decision pins at thread entry: `isNewChat` flips once the\n // thread persists, but the mount that began as a new thread stays preloaded.\n const preloadRef = useRef({ threadId, preload: isNewChat });\n if (preloadRef.current.threadId !== threadId)\n preloadRef.current = { threadId, preload: isNewChat };\n\n const snapshotCacheRef = useRef(snapshotCache);\n snapshotCacheRef.current = snapshotCache;\n // The snapshot seed pins at attach identity, like the preload decision: the\n // cache is read once per mount, so a mid-session cache write (this thread's\n // own states being remembered) never changes what `initialState` was.\n //\n // A suspended attach never seeds: the suspended transport never dials, so a\n // seed would be served indefinitely — under a view-as lens that would paint\n // thread content the parked transport exists to withhold (the lens must\n // show what the LENSED identity is authorized to see, and only the server\n // can decide that).\n //\n // The pooled hello is taken the same way: exactly once, at the attach's\n // first render (the pool disposes its root in that step).\n const snapshotSeedRef = useRef<{\n attachId: string;\n seed: DeepAgentStreamValues | undefined;\n } | null>(null);\n if (snapshotSeedRef.current === null || snapshotSeedRef.current.attachId !== attachId) {\n const preload = preloadRef.current.preload;\n let pooledState: DeepAgentStreamValues | undefined;\n if (prewarmPool?.has(threadId)) {\n if (preload || suspended) {\n // This mount attaches on its own terms (or not at all): the pooled\n // dial must not linger as a second socket to the same session.\n prewarmPool.discard(threadId);\n } else {\n pooledState = prewarmPool.take(threadId)?.state;\n }\n }\n // The pooled hello outranks a remembered snapshot (it is newer by\n // construction); a pooled dial that had not landed seeds like a plain\n // attach and reconciles when this attach's own hello lands.\n const remembered =\n preload || suspended ? undefined : (pooledState ?? snapshotCache?.take(threadId));\n const seed = remembered ? toThreadSnapshotSeed(remembered) : undefined;\n snapshotSeedRef.current = { attachId, seed };\n const source: DeepAgentAttachSource =\n pooledState !== undefined ? 'prewarm' : seed ? 'snapshot' : 'none';\n const notifySource = onAttachSourceRef.current;\n if (notifySource) queueMicrotask(() => notifySource({ threadId, source }));\n }\n\n // react-statewire memoizes the converted thread on this function's\n // identity, so an inline closure would re-run `convertDeepAgentState` over\n // the whole transcript on every host render. Keyed on the attach identity (a\n // re-attach re-keys its per-thread latches); everything else the body needs\n // is read through the per-render refs above.\n const threadConverter = useCallback<ThreadOptions['converter']>(\n (state, meta) => {\n // Projected once per pass through the single seam; every fold below\n // consumes the projection (the recorder projects the raw connection\n // itself, so any host observer can feed it).\n const connection = projectDeepAgentConnection(meta.connection);\n // Transition-deduped inside the recorder, so this per-pass observation\n // is free while the connection is unchanged.\n diagnosticsRef.current?.observeConnection(meta.connection);\n // Fold this pass's connection into the denial streak (the converter\n // re-runs on every reconnect-attempt bump). Parking is deferred to a\n // microtask like every other notification here.\n if (authDenialRef.current.attachId !== attachIdRef.current) {\n authDenialRef.current = {\n attachId: attachIdRef.current,\n state: initialAuthDenialTrackerState(),\n };\n }\n const denial = observeAuthDenial(authDenialRef.current.state, connection);\n authDenialRef.current.state = denial.state;\n if (denial.park) {\n const parkAttachId = attachIdRef.current;\n const parkMessage = denial.state.message;\n // The server refused authorization for this thread: any remembered\n // snapshot must not warm-paint it on a later mount (permissions may\n // have been revoked since the state was captured).\n snapshotCacheRef.current?.forget(threadId);\n queueMicrotask(() => {\n if (attachIdRef.current !== parkAttachId) return;\n setAuthParked((prev) =>\n prev?.attachId === parkAttachId\n ? prev\n : { attachId: parkAttachId, message: parkMessage }\n );\n });\n }\n const previous = lastConnectionRef.current;\n if (\n previous?.threadId !== attachId ||\n !Object.keys({ ...previous.connection, ...connection }).every(\n (key) => Reflect.get(previous.connection, key) === Reflect.get(connection, key)\n )\n ) {\n const update = { threadId: attachId, connection };\n lastConnectionRef.current = update;\n queueMicrotask(() => {\n // A newer projection, a thread switch, or the unmount cleanup owns\n // the channel now.\n if (lastConnectionRef.current !== update || attachIdRef.current !== attachId) return;\n onConnectionChangeRef.current?.(connection);\n });\n }\n // Session-asset lifecycle, paired with THIS attach's thread by closure:\n // the state converted here is the state of the thread the element was\n // built for, so the pair can never straddle a switch (a client-store\n // read would). Deduped by value per attach. A pass from an attach the\n // host has already replaced never touches the latch — it could otherwise\n // cancel the current attach's still-queued verdict — and the microtask\n // guard drops a pass whose attach is replaced before it settles.\n if (attachIdRef.current === attachId) {\n const sessionPersisted = readSessionPersisted(state);\n const lastSession = lastSessionPersistedRef.current;\n if (\n lastSession?.attachId !== attachId ||\n lastSession.sessionPersisted !== sessionPersisted\n ) {\n const sessionUpdate = { attachId, threadId, sessionPersisted };\n lastSessionPersistedRef.current = sessionUpdate;\n queueMicrotask(() => {\n if (\n lastSessionPersistedRef.current !== sessionUpdate ||\n attachIdRef.current !== attachId\n ) {\n return;\n }\n onSessionPersistedChangeRef.current?.({ threadId, sessionPersisted });\n });\n }\n }\n // The replicated run status IS the running signal: the lib's run-dialect\n // fold flips it to \"running\" on the send, before the app converter runs,\n // so the optimistic window needs no hand-tracked flag.\n return converter(state, state?.runs?.[0]?.status === 'running');\n },\n [attachId, converter, threadId]\n );\n\n return StatewireThread<DeepAgentStreamValues>({\n // The transport stamps this protocol on every command; the thread client\n // must declare it too or the core skips the optimistic folds and a send\n // stays invisible until the server frame lands.\n protocol: DEEP_AGENT_STATEWIRE_PROTOCOL,\n // New threads preload an empty runs mount and report `deferred` — the\n // composer is interactive before the stream attaches and pre-attach sends\n // render through the optimistic folds. Existing threads omit the runs\n // mount and project \"loading\" until the attach snapshot: the server seeds\n // messages/todos/runConfig in `_load_history`.\n //\n // The preload also seeds `sessionPersisted: false`: a never-started chat\n // provably has no `session` asset until its first run mints one, so the\n // wire carries that from the first render and a host reading the flag off\n // the state needs no separate \"is this a new chat\" knowledge. An existing\n // thread leaves it absent (unknown) so its asset read is never gated.\n initialState:\n snapshotSeedRef.current.seed ??\n ({\n messages: [],\n todos: [],\n ...(preloadRef.current.preload && { runs: [], sessionPersisted: false }),\n } satisfies DeepAgentStreamValues),\n // Keyed by thread: a switch unmounts the previous thread's session and\n // remounts against the new URL, so the converter never sees the previous\n // thread's snapshot (a new thread serves its preload again, an existing\n // one loads until its snapshot). A host-suspended or auth-parked attach\n // swaps in the never-dialing transport instead.\n transport: withKey(\n attachId,\n (() => {\n if (suspended) return StatewireSuspended({ message: suspended.reason });\n if (authParked !== null && authParked.attachId === attachId) {\n return StatewireSuspended({\n message: authParked.message ?? 'Session authorization was refused.',\n onReconnectRequested: () => {\n authDenialRef.current = {\n attachId: attachIdRef.current,\n state: initialAuthDenialTrackerState(),\n };\n setAuthParked(null);\n },\n });\n }\n // The shared recipe (URL, auth + wire-contract headers, session lane,\n // attach instrumentation, retry-hint floor) — the same one the prewarm\n // pool dials with, so the instance a pooled attach warmed is the one\n // this dial reaches. A never-started chat dials nothing until its\n // first send.\n return createDeepAgentAttachTransport<DeepAgentStreamValues>({\n baseUrl,\n threadId,\n sse,\n isNew: preloadRef.current.preload,\n headers: (ctx) => headersRef.current(ctx),\n sessionStore,\n onAuthResolve: (ctx) => diagnosticsRef.current?.observeAuthResolve(ctx),\n onAttachTiming: (event) => onAttachTimingRef.current?.({ threadId, event }),\n // Read once per attach: a declaration change applies to the next\n // attach, never to a reconnect of this one (the view would be\n // re-shaped under the client).\n messageWindow: messageWindowRef.current,\n });\n })()\n ),\n // Survives the transport remounts above: a bumped attachKey re-attaches the\n // same lane, and a persistent session storage carries it across reloads.\n ...(storage && { storage }),\n // The run subsystem (status, lanes, input requests, runId) is mounted on\n // the state root and always replicated by react-statewire >= 0.14 (the\n // former `runs: true` opt-in is gone) — the converter only maps app-owned\n // keys, including the `run/stop` runId stamp the lib projects itself.\n converter: threadConverter,\n // Makes the server's dispatch record concrete in state (after the\n // optimistic folds); the lib's post-converter dispatch merge turns off.\n materialize,\n // Native message editing: an edited turn is resubmitted as a `run/edit`\n // command, and the deep-agent backend rewinds the checkpointed thread to\n // the edited message's parent before appending (route `plan_rewind`).\n capabilities: capabilities ?? { edit: true },\n ...(getMessageMetadata && { getMessageMetadata }),\n ...(adapters && { adapters }),\n contextSync: 'command-send',\n // The Stop control is the only `cancelRun()` caller — teardown paths\n // unmount the keyed transport instead — so every `run/stop` is a\n // deliberate user stop.\n stopPayload: () => ({ reason: 'user_stop' }),\n onError: (error) => {\n diagnosticsRef.current?.observeError(error);\n onErrorRef.current?.(error);\n },\n ...((onStateChange || snapshotCache) && {\n // The lib types the observed state `NonNullable`, but the runtime\n // delivers `undefined` where the wire has no snapshot (pre-attach and\n // replay boundaries republish it) — normalize so the type is true and\n // host observers never crash on a field read.\n onStateChange: ((state, ctx) => {\n const values = readDeepAgentStreamValues(state);\n // Remember under the closure's thread id, not a ref: a late delivery\n // from a previous thread's session must file under THAT thread.\n if (isDeepAgentStateHydrated(values)) {\n snapshotCacheRef.current?.remember(threadId, values);\n }\n onStateChangeRef.current?.(values, ctx);\n }) satisfies ThreadOptions['onStateChange'],\n }),\n ...((onCommandChange || diagnostics) && {\n onCommandChange: ((update, ctx) => {\n diagnosticsRef.current?.observeCommand(update);\n onCommandChangeRef.current?.(update, ctx);\n }) satisfies ThreadOptions['onCommandChange'],\n }),\n ...(onRawConnectionChange && {\n onConnectionChange: ((connection) =>\n onRawConnectionChangeRef.current?.(\n connection\n )) satisfies ThreadOptions['onConnectionChange'],\n }),\n });\n}\n"],"names":["useRef","useState","useEffect","initialAuthDenialTrackerState","isSameMessageAuthor","useMemo","projectDeepAgentProtocol","_a","convertDeepAgentState","createDeepAgentMaterialize","toThreadSnapshotSeed","useCallback","projectDeepAgentConnection","observeAuthDenial","StatewireThread","DEEP_AGENT_STATEWIRE_PROTOCOL","withKey","StatewireSuspended","createDeepAgentAttachTransport","readDeepAgentStreamValues","isDeepAgentStateHydrated"],"mappings":";;;;;;;;;;;;;;;AAkRO,SAAS,qBAAqB,OAAgC;AACnE,QAAM,OAAQ,+BAAiD;AAC/D,SAAO,OAAO,SAAS,YAAY,OAAO;AAC5C;AAUO,SAAS,0BACd,UACA,MACS;AACT,MAAI,aAAa,KAAM,QAAO,KAAK;AACnC,SAAO,SAAS,aAAa,KAAK,YAAY,SAAS,cAAc,KAAK;AAC5E;AAoBO,SAAS,mBAAmB;AAAA,EACjC;AAAA,EACA;AAAA,EACA,MAAM;AAAA,EACN;AAAA,EACA;AAAA,EACA;AAAA,EACA,YAAY;AAAA,EACZ;AAAA,EACA,YAAY;AAAA,EACZ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A;AAAA,IAClB,aAAa;AAAA;AAAA;AAAA;AAAA,IAIb,aAAa,OAAO,EAAE,QAAQ;IAC9B,SAAS,CAAC,UAAU;;AAClB,OAAAA,MAAA,eAAe,YAAf,gBAAAA,IAAwB,aAAa;AACrC,uBAAW,YAAX,oCAAqB;AAAA,IACvB;AAAA,IACA,IAAK,iBAAiB,kBAAkB;AAAA;AAAA;AAAA;AAAA;AAAA,MAKtC,gBAAgB,CAAC,OAAO,QAAQ;;AAC9B,cAAM,SAASY,eAAAA,0BAA0B,KAAK;AAG9C,YAAIC,eAAAA,yBAAyB,MAAM,GAAG;AACpC,WAAAb,MAAA,iBAAiB,YAAjB,gBAAAA,IAA0B,SAAS,UAAU;AAAA,QAC/C;AACA,+BAAiB,YAAjB,0CAA2B,QAAQ;AAAA,MACrC;AAAA,IAAA;AAAA,IAEF,IAAK,mBAAmB,gBAAgB;AAAA,MACtC,kBAAkB,CAAC,QAAQ,QAAQ;;AACjC,SAAAA,MAAA,eAAe,YAAf,gBAAAA,IAAwB,eAAe;AACvC,iCAAmB,YAAnB,4CAA6B,QAAQ;AAAA,MACvC;AAAA,IAAA;AAAA,IAEF,GAAI,yBAAyB;AAAA,MAC3B,qBAAqB,CAAC,eAAA;;AACpB,gBAAAA,MAAA,yBAAyB,YAAzB,gBAAAA,IAAA;AAAA;AAAA,UACE;AAAA;AAAA;AAAA,IACF;AAAA,EACJ,CACD;AACH;;;;"}
|
|
1
|
+
{"version":3,"file":"use-deep-agent-thread.cjs","sources":["../../../../../agent-runtime/src/use-deep-agent-thread.ts"],"sourcesContent":["import type { LangChainMessage } from '@assistant-ui/react-langgraph';\nimport { StatewireThread } from '@assistant-ui/react-statewire';\nimport { withKey } from '@assistant-ui/tap';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport {\n type AuthDenialTrackerState,\n initialAuthDenialTrackerState,\n observeAuthDenial,\n} from './auth-denial';\nimport {\n createDeepAgentAttachTransport,\n type DeepAgentHeadersResolver,\n} from './deep-agent-transport-recipe';\nimport { projectDeepAgentConnection } from './errors';\nimport { type DeepAgentMessageAuthor, isSameMessageAuthor } from './message-author';\nimport { DEEP_AGENT_INTEREST_PROTOCOL } from './generated/runconfig-contract';\nimport {\n type DeepAgentMessageWindowDeclaration,\n headInterestRequest,\n readDeepAgentMessageWindow,\n} from './message-window';\nimport { convertDeepAgentState, createDeepAgentMaterialize } from './messages';\nimport { type DeepAgentProtocolStatus, projectDeepAgentProtocol } from './protocol';\nimport type { DeepAgentAttachTimingEvent } from './statewire-attach-observer';\nimport type { StatewireDiagnosticsRecorder } from './statewire-diagnostics';\nimport { isDeepAgentStateHydrated, readDeepAgentStreamValues } from './statewire-state';\nimport { StatewireSuspended } from './statewire-suspended';\nimport {\n DEEP_AGENT_STATEWIRE_PROTOCOL,\n type StatewireTransportOptions,\n} from './statewire-transport';\nimport type { DeepAgentThreadPrewarmPool } from './thread-prewarm';\nimport { type DeepAgentThreadSnapshotCache, toThreadSnapshotSeed } from './thread-snapshot-cache';\nimport type { DeepAgentToolOutputStore } from './tool-outputs';\nimport type { DeepAgentWithdrawnTurns } from './withdrawn-turns';\nimport type {\n DeepAgentConnectionState,\n DeepAgentLaneProjection,\n DeepAgentStreamValues,\n} from './types';\n\ntype ThreadOptions = StatewireThread.Options<DeepAgentStreamValues>;\n\nexport type { DeepAgentHeadersResolver } from './deep-agent-transport-recipe';\n\n/**\n * How an attach's FIRST frame is sourced, decided once per attach at mount: the\n * hello a pooled pre-dialed attach already replicated (`prewarm`), a remembered\n * snapshot seed (`snapshot`), or nothing (`none` — the thread loads until its\n * hello).\n */\nexport type DeepAgentAttachSource = 'prewarm' | 'snapshot' | 'none';\n\nexport interface UseDeepAgentThreadOptions {\n threadId: string;\n /** Base URL of the deep-agent statewire host (the `…/v2/threads` mount). */\n baseUrl: string;\n /** Transport selection: SSE when true, WebSocket otherwise. */\n sse?: boolean;\n /**\n * Auth headers for the transport. Statewire passes `{ staleAuth: true }`\n * when the previous credential was refused, so resolvers that can\n * force-renew should honor it.\n */\n headers: DeepAgentHeadersResolver;\n /**\n * Statewire session store for reconnect command-session recovery (e.g. the\n * mobile AsyncStorage-backed store). Host-resolved; omitted, sessions are\n * process-local.\n */\n sessionStore?: StatewireTransportOptions['sessionStore'];\n /**\n * Mounted storage seams for the thread: `session` holds the lane identity and\n * the commands still awaiting a durable verdict, so a reload resumes the lane\n * instead of minting a new client (browser hosts pass `LocalStorageSession`\n * from `@assistant-ui/react-statewire/local-storage`); `composer` persists the\n * draft. Mutually exclusive with `sessionStore` — statewire refuses a session\n * mounted twice.\n */\n storage?: ThreadOptions['storage'];\n /** True only for a never-started local chat; existing empty threads still load until their snapshot. */\n isNewChat?: boolean;\n /**\n * Extra transport-key discriminator for the SAME thread. The session is keyed\n * by `threadId` alone by default; hosts that must re-read the server snapshot\n * without a thread switch (a run dispatched outside this client, e.g. a\n * backgrounded AOP run writing the thread's first messages) bump this to\n * remount the session against the same URL.\n */\n attachKey?: string | number;\n /**\n * Host gate: park the transport instead of attaching — no socket, no retry\n * loop. The thread element stays mounted so assistant-ui consumers keep\n * rendering. Pass it when the host already knows every attach would be denied (e.g.\n * the signed-in user has no workspace yet), so a locked-out tab does not\n * hammer the attach endpoint on every backoff interval.\n */\n suspended?: { reason: string } | false;\n /**\n * Adapter capabilities the host UI exposes. Defaults preserve each client's\n * pre-extraction surface — pass what the product mounts.\n */\n capabilities?: {\n edit?: boolean;\n continue?: boolean;\n reload?: boolean;\n unstable_switchBranch?: boolean;\n };\n /** Which run lanes project into the message tail; see {@link DeepAgentLaneProjection}. */\n laneProjection?: DeepAgentLaneProjection;\n /**\n * The viewer, as the backend would stamp them (`metadata.custom.author`).\n * Stamped onto this client's own optimistic bubbles — a send still in flight\n * has no host `meta` yet — so a just-sent turn is attributed, and the\n * multi-author avatar gate flips for a second poster, without waiting for\n * the acknowledgment. Replicated entries carry the host's own stamp instead.\n * Compared field-wise, so callers need not memoize the object.\n */\n selfAuthor?: DeepAgentMessageAuthor | null;\n /**\n * Snapshot host context when each user message is submitted, before it is\n * journaled. Includes programmatic appends, keyboard sends, queued messages,\n * steering, and edits. The async getter starts immediately at submission;\n * sends retain their order while it resolves. Retries, queue text edits,\n * lane moves, reload, and continue preserve the original association.\n * Return JSON-serializable metadata; optional capture failures can\n * return an explicit null field rather than blocking the message.\n */\n getMessageMetadata?: ThreadOptions['getMessageMetadata'];\n /** Host-owned adapters: attachments (upload/mention choreography), speech, feedback. */\n adapters?: ThreadOptions['adapters'];\n /**\n * Transport lifecycle recorder (attach latency, reconnect loops, command\n * settle fates, stale-auth renewals) fed from the hook's own seams. Pass one\n * only when the host's diagnostics channel is enabled — the recorder is\n * observed on hot paths, and an absent recorder costs a single optional call.\n */\n diagnostics?: StatewireDiagnosticsRecorder;\n /**\n * Per-tab LRU of the last wire state seen per thread. When set, every\n * hydrated state the transport publishes is remembered, and a mount of a\n * remembered thread seeds `initialState` from the cache (through\n * {@link toThreadSnapshotSeed}) — the thread renders its last-known\n * messages on the first frame instead of holding a loading treatment for\n * the attach round-trip, and projects \"running\" when the run was live at\n * capture (else \"ready\"). The attach snapshot then\n * REPLACES the seeded state (statewire's `initialState` contract), so a\n * thread that advanced elsewhere reconciles in one round-trip. New chats\n * keep their preload and never read the cache.\n */\n snapshotCache?: DeepAgentThreadSnapshotCache;\n /**\n * The head window this surface wants: declared on every attach\n * (`x-athena-deep-agent-window`, part of the transport recipe) so the hello\n * of a client the host does not remember carries the newest `size`\n * messages, and stated as `athena/interest` after the hello only when the\n * hello's head is narrower — never to shrink it (the host holds what a\n * viewer has loaded for the life of its connection). The resolved chain is\n * joined with the mounted message documents into the converted transcript\n * (see `message-window.ts`); older pages load through\n * `useDeepAgentWindowSync`. Read once per attach.\n */\n messageWindow?: DeepAgentMessageWindowDeclaration;\n /**\n * Full tool outputs fetched back for the wire's cut tool messages\n * (`history/tool_output`); the thread re-converts when one lands.\n */\n toolOutputs?: DeepAgentToolOutputStore;\n /**\n * User turns this client took back ahead of the wire (a user stop before\n * any assistant output); the thread re-converts when one opens or closes.\n */\n withdrawnTurns?: DeepAgentWithdrawnTurns;\n /**\n * Pre-dialed attaches (see `thread-prewarm.ts`). When the pool holds a root\n * for this thread at mount, the thread takes the hello it replicated as its\n * seed — the transcript is the first frame — and dials its own attach\n * against the instance the pool warmed; the pooled root is disposed in the\n * same step, so one socket is live per thread after mount. Never seeded for\n * a preloaded new chat or a suspended attach; such a root is discarded.\n */\n prewarmPool?: DeepAgentThreadPrewarmPool<DeepAgentStreamValues>;\n /**\n * Attach-path timing: socket open, hello size + handler cost, server retry\n * hints — attributed to the attach's own thread, since a late event from the\n * thread being left can land after the host has moved on.\n */\n onAttachTiming?: (info: { threadId: string; event: DeepAgentAttachTimingEvent }) => void;\n /** Where this attach's first frame comes from; once per attach, at mount. */\n onAttachSource?: (info: { threadId: string; source: DeepAgentAttachSource }) => void;\n /** Full transport error policy (paywall, toast, telemetry) — client-owned. */\n onError?: ThreadOptions['onError'];\n /**\n * Raw statewire state observer (first-attach latches, telemetry). The state\n * argument is never `undefined`/`null`: passes where the wire has no\n * snapshot yet (pre-attach, replay boundaries) deliver the typed\n * `DEEP_AGENT_PRE_STREAM_STATE` default — `isDeepAgentStateHydrated`\n * distinguishes them from a real (possibly empty) snapshot.\n */\n onStateChange?: ThreadOptions['onStateChange'];\n /** Raw command-lifecycle observer (send-failure salvage, telemetry). */\n onCommandChange?: ThreadOptions['onCommandChange'];\n /** Raw connection observer (reconnect handles, telemetry). */\n onRawConnectionChange?: ThreadOptions['onConnectionChange'];\n /**\n * Projected connection status changes, deduped per thread, with `null` on\n * unmount so an indicator never shows a stale status.\n */\n onConnectionChange?: (connection: DeepAgentConnectionState | null) => void;\n /** Notified when a run starts/stops so the page can reflect the running thread. */\n onRunningChange?: (isRunning: boolean) => void;\n /**\n * Notified once per thread with the `runConfig` carried by the statewire\n * snapshot (the backend's persisted panel config, seeded in `_load_history`),\n * so the host can hydrate its config store from the thread. Notified with\n * `null` (at most once per attach) when a server snapshot arrives WITHOUT a\n * persisted config, so a host waiting on hydration can stop waiting; a\n * config appearing on a later snapshot of the same attach (mirrored at run\n * start) still delivers the config notification.\n */\n onServerRunConfig?: (config: Record<string, unknown> | null) => void;\n /**\n * Notified when the snapshot's `outOfBandRunActive` flag changes: the host set\n * it while a run executing OUTSIDE this surface (an AOP / HTTP-route run)\n * is actively writing the thread's bare-namespace history, which the host\n * live-refreshes onto the wire. Lets the page show run-in-progress\n * treatment instead of an empty conversation, and stand down its own\n * re-attach polling. Change-notified per attach (an initial `false` before\n * the snapshot stays silent), mirroring `onRunningChange`.\n */\n onOutOfBandRunActive?: (outOfBandRunActive: boolean) => void;\n /**\n * Notified with the state's session-asset lifecycle flag\n * ({@link readSessionPersisted}) PAIRED with the thread it describes: `false`\n * while the thread's `session` asset provably does not exist yet (a\n * never-started chat's preload, a first run before the mint), `true` once\n * minted, `null` when the state carries no flag (a host that predates it).\n *\n * Fired from the converter pass, so the pair is read from the state of the\n * thread this attach was mounted for. A component reading the flag off the\n * client store instead lags the mounted thread id by one render on a switch\n * and can pair the new id with the previous thread's flag — releasing a\n * session-scoped read for a row the backend has not minted. Change-notified\n * per attach; the first pass of every attach notifies, so a host holding a\n * read back until it hears from the mounted thread always does.\n */\n onSessionPersistedChange?: (event: {\n threadId: string;\n sessionPersisted: boolean | null;\n }) => void;\n /**\n * Notified with the wire-contract status once the attach snapshot\n * advertises the `protocol` lane, and again whenever it changes (a\n * re-attach after a server roll can advertise a new `version`). Telemetry\n * and per-version behaviour only: the host has no minimum client version,\n * so nothing about the status gates a send. Never called for\n * pre-declaration servers (their snapshots carry no lane) — absence of a\n * call means \"no advertisement\", not \"compatible\".\n */\n onProtocolChange?: (status: DeepAgentProtocolStatus) => void;\n}\n\n/** One thread's replicated running state, keyed so a switch between two\n * threads with the same status still re-notifies (the host page clears its\n * per-thread state on selection, mirroring the connection dedupe below). */\nexport interface RunningSnapshot {\n threadId: string;\n isRunning: boolean;\n}\n\n/** Whether the thread's `session` asset exists, read off a statewire state, or\n * `null` when the state does not carry the flag.\n *\n * Absence is not absence of the asset: a snapshot from a host that predates\n * the flag has no such key, and reading that as \"the asset does not exist\"\n * would gate a read the client is entitled to make, with nothing left to\n * un-gate it. A new thread's preload seeds `false` (see `initialState`), so\n * the pre-attach pass of a chat that cannot have an asset yet still gates.\n *\n * Hosts pass this to `useStatewireState` so the flag and the thread it belongs\n * to are read in one component — a thread switch then cannot pair one thread's\n * id with the other's flag. */\nexport function readSessionPersisted(state: unknown): boolean | null {\n const flag = (state as { sessionPersisted?: unknown } | null)?.sessionPersisted;\n return typeof flag === 'boolean' ? flag : null;\n}\n\n/** Whether a converter pass must notify `onRunningChange`.\n *\n * The mount's very first status notifies only when it is `true` (a snapshot\n * carrying a live run) — an initial `false` before the snapshot must stay\n * silent so it cannot clear a still-valid indicator. After that, every\n * transition notifies, and so does the first status after a thread switch\n * (the host page clears its per-thread state on selection, so a switch\n * between two threads with the same status must still re-notify). */\nexport function shouldNotifyRunningChange(\n previous: RunningSnapshot | null,\n next: RunningSnapshot\n): boolean {\n if (previous === null) return next.isRunning;\n return previous.threadId !== next.threadId || previous.isRunning !== next.isRunning;\n}\n\n/**\n * The shared deep-agent Statewire thread.\n *\n * `StatewireThread` (from `@assistant-ui/react-statewire`) attaches to the\n * agora-hosted thread at `${baseUrl}/${threadId}` (WebSocket by default,\n * with SSE retained only as a host-selected compatibility switch): the backend\n * hosts the thread state and this client\n * replicates it live, so the server snapshot is the single source of history\n * (no local import, no `/status` resume probing) and run scheduling — queueing,\n * steering, stop, edit rewinds — rides the built-in `run/*` commands.\n *\n * The thread element is keyed by `threadId`, so a thread switch remounts the\n * session against the new URL instead of importing history in place.\n *\n * Returns the thread element for the host's own `useAui({ thread })` — web\n * hosts take `useAui` from `@assistant-ui/react`, React Native hosts from\n * `@assistant-ui/react-native`; this package imports neither.\n */\nexport function useDeepAgentThread({\n threadId,\n baseUrl,\n sse = false,\n headers,\n sessionStore,\n storage,\n isNewChat = false,\n attachKey,\n suspended = false,\n capabilities,\n laneProjection = 'both',\n selfAuthor = null,\n getMessageMetadata,\n adapters,\n diagnostics,\n snapshotCache,\n messageWindow,\n toolOutputs,\n withdrawnTurns,\n prewarmPool,\n onAttachTiming,\n onAttachSource,\n onError,\n onStateChange,\n onCommandChange,\n onRawConnectionChange,\n onConnectionChange,\n onRunningChange,\n onServerRunConfig,\n onOutOfBandRunActive,\n onSessionPersistedChange,\n onProtocolChange,\n}: UseDeepAgentThreadOptions) {\n const onRunningChangeRef = useRef(onRunningChange);\n onRunningChangeRef.current = onRunningChange;\n const onSessionPersistedChangeRef = useRef(onSessionPersistedChange);\n onSessionPersistedChangeRef.current = onSessionPersistedChange;\n const onConnectionChangeRef = useRef(onConnectionChange);\n onConnectionChangeRef.current = onConnectionChange;\n const onServerRunConfigRef = useRef(onServerRunConfig);\n onServerRunConfigRef.current = onServerRunConfig;\n const onOutOfBandRunActiveRef = useRef(onOutOfBandRunActive);\n onOutOfBandRunActiveRef.current = onOutOfBandRunActive;\n const onProtocolChangeRef = useRef(onProtocolChange);\n onProtocolChangeRef.current = onProtocolChange;\n const onErrorRef = useRef(onError);\n onErrorRef.current = onError;\n const onStateChangeRef = useRef(onStateChange);\n onStateChangeRef.current = onStateChange;\n const onCommandChangeRef = useRef(onCommandChange);\n onCommandChangeRef.current = onCommandChange;\n const onRawConnectionChangeRef = useRef(onRawConnectionChange);\n onRawConnectionChangeRef.current = onRawConnectionChange;\n const headersRef = useRef(headers);\n headersRef.current = headers;\n const messageWindowRef = useRef(messageWindow);\n messageWindowRef.current = messageWindow;\n // The head interest is checked once per connected session, after the hello\n // negotiated the lane (a statement before that would be minted durable):\n // the hello carries the host's head — the attach header's size, or what\n // this client id held — and a set goes out only to widen it.\n const interestRef = useRef({ attachId: '', stated: false });\n // The last joined transcript, held across the gap between a hello and its\n // interest answer (and across a reconnect) so the thread never blanks.\n const lastMessagesRef = useRef<{ attachId: string; messages: LangChainMessage[] } | null>(null);\n // A fetched tool output must re-run the converter (the store is read inside\n // it); the version is the memo's signal that the store's contents moved.\n const [toolOutputsVersion, setToolOutputsVersion] = useState(0);\n useEffect(() => {\n if (!toolOutputs) return undefined;\n return toolOutputs.subscribe(() => setToolOutputsVersion((version) => version + 1));\n }, [toolOutputs]);\n const [withdrawnTurnsVersion, setWithdrawnTurnsVersion] = useState(0);\n useEffect(() => {\n if (!withdrawnTurns) return undefined;\n return withdrawnTurns.subscribe(() => setWithdrawnTurnsVersion((version) => version + 1));\n }, [withdrawnTurns]);\n const diagnosticsRef = useRef(diagnostics);\n diagnosticsRef.current = diagnostics;\n const onAttachTimingRef = useRef(onAttachTiming);\n onAttachTimingRef.current = onAttachTiming;\n const onAttachSourceRef = useRef(onAttachSource);\n onAttachSourceRef.current = onAttachSource;\n\n const lastRunningRef = useRef<RunningSnapshot | null>(null);\n // Out-of-band run activity (`outOfBandRunActive`), change-notified with the\n // same semantics as the running flag above.\n const lastOutOfBandRunActiveRef = useRef<RunningSnapshot | null>(null);\n // The session-asset lifecycle flag last notified, keyed by attach so every\n // attach's first pass notifies (a host holding a read back until it hears\n // from the mounted thread must always hear from it).\n const lastSessionPersistedRef = useRef<{\n attachId: string;\n threadId: string;\n sessionPersisted: boolean | null;\n } | null>(null);\n // The last wire-contract status notified, keyed by attach so a re-attach\n // re-notifies (the new snapshot may advertise a different version).\n // `status: null` = nothing advertised yet on this attach.\n const lastProtocolRef = useRef<{\n attachId: string;\n status: DeepAgentProtocolStatus | null;\n } | null>(null);\n // The thread whose statewire-carried runConfig has been surfaced to the host\n // (once per thread; later snapshots must not clobber edits).\n const appliedStateRunConfigThreadRef = useRef<string | null>(null);\n // The attach that already notified `onServerRunConfig(null)` (snapshot\n // arrived carrying no persisted config) — at most once per attach.\n const absentStateRunConfigAttachRef = useRef<string | null>(null);\n // Live thread id for the callbacks: they are created per render but may\n // settle after a switch, so they compare against the current id.\n const threadIdRef = useRef(threadId);\n threadIdRef.current = threadId;\n // Identity of the current attach. Every per-thread latch keys off this, so a\n // re-attach of the same thread (a bumped `attachKey`) re-notifies the host\n // exactly like a switch would — the host clears its per-thread state on\n // re-attach, so a snapshot that repeats the previous status must not dedupe.\n const attachId: string = attachKey === undefined ? threadId : `${threadId}:${attachKey}`;\n const attachIdRef = useRef(attachId);\n attachIdRef.current = attachId;\n\n // Auth-denial park: the server fins every denied attach `unauthorized` and\n // the reconnect loop would otherwise retry it every 30s forever (prod tabs\n // looped for hours against revoked/workspace-less credentials). After a\n // streak of denials the live transport is swapped for a parked one; a new\n // attach (thread switch, bumped attachKey) or the parked connection's\n // `reconnect()` re-arms it.\n const [authParked, setAuthParked] = useState<{\n attachId: string;\n message: string | undefined;\n } | null>(null);\n const authDenialRef = useRef<{ attachId: string; state: AuthDenialTrackerState }>({\n attachId,\n state: initialAuthDenialTrackerState(),\n });\n useEffect(() => {\n setAuthParked((prev) => (prev !== null && prev.attachId !== attachId ? null : prev));\n }, [attachId]);\n\n // Field-wise stable identity for the viewer stamp, so a host that rebuilds\n // the author object per render does not rebuild the converter (and with it\n // every message) per render. Adjusting state during render is React's\n // sanctioned derived-state pattern: it re-renders once with the new value.\n const [stableSelfAuthor, setStableSelfAuthor] = useState(selfAuthor);\n if (!isSameMessageAuthor(stableSelfAuthor, selfAuthor)) setStableSelfAuthor(selfAuthor);\n\n // biome-ignore lint/correctness/useExhaustiveDependencies: toolOutputsVersion / withdrawnTurnsVersion are the stores' change signals — the converter reads the stores' contents, not the counters.\n const converter = useMemo(\n () => (state: unknown, isRunning: boolean) => {\n // Statewire snapshots carry the thread's persisted panel config (the\n // backend seeds `runConfig` in `_load_history` and mirrors it on run\n // start). Surface it once per thread so the host can hydrate its config\n // store.\n const stateRunConfig = (state as { runConfig?: unknown } | null)?.runConfig;\n if (\n stateRunConfig &&\n typeof stateRunConfig === 'object' &&\n !Array.isArray(stateRunConfig) &&\n appliedStateRunConfigThreadRef.current !== attachIdRef.current\n ) {\n appliedStateRunConfigThreadRef.current = attachIdRef.current;\n const notifyRunConfig = onServerRunConfigRef.current;\n if (notifyRunConfig) {\n queueMicrotask(() => notifyRunConfig(stateRunConfig as Record<string, unknown>));\n }\n } else if (\n !stateRunConfig &&\n appliedStateRunConfigThreadRef.current !== attachIdRef.current &&\n absentStateRunConfigAttachRef.current !== attachIdRef.current &&\n projectDeepAgentProtocol(state) !== null\n ) {\n // No persisted config on a SERVER state: the protocol lane rides every\n // attach snapshot, so its presence distinguishes \"the server answered\n // without a config\" from the pre-attach `initialState` (which must not\n // end the host's hydration wait).\n absentStateRunConfigAttachRef.current = attachIdRef.current;\n const notifyRunConfig = onServerRunConfigRef.current;\n if (notifyRunConfig) {\n queueMicrotask(() => notifyRunConfig(null));\n }\n }\n // Out-of-band run activity: the host live-refreshes a bare-namespace\n // (AOP / HTTP-route) thread's transcript while its run is active and\n // flags the wire state so the page can reflect it.\n const stateOutOfBandRunActive =\n (state as { outOfBandRunActive?: unknown } | null)?.outOfBandRunActive === true;\n const outOfBandRunActiveSnapshot = {\n threadId: attachIdRef.current,\n isRunning: stateOutOfBandRunActive,\n };\n if (shouldNotifyRunningChange(lastOutOfBandRunActiveRef.current, outOfBandRunActiveSnapshot)) {\n lastOutOfBandRunActiveRef.current = outOfBandRunActiveSnapshot;\n const observedAttachId = attachIdRef.current;\n queueMicrotask(() => {\n // A re-attach or newer snapshot between the converter pass and this\n // microtask owns the channel now — a stale flag must not leak into\n // the new attach's per-thread state.\n if (\n attachIdRef.current !== observedAttachId ||\n lastOutOfBandRunActiveRef.current !== outOfBandRunActiveSnapshot\n ) {\n return;\n }\n onOutOfBandRunActiveRef.current?.(stateOutOfBandRunActive);\n });\n }\n // Wire-contract advertisement: the host publishes the `protocol` lane in\n // every attach snapshot. Notify on first advertisement and on change\n // (dedupe by value, re-keyed per attach), with the same stale-guard\n // microtask as the other observers.\n const protocolStatus = projectDeepAgentProtocol(state);\n if (protocolStatus !== null) {\n const previous =\n lastProtocolRef.current?.attachId === attachIdRef.current\n ? lastProtocolRef.current.status\n : null;\n if (previous === null || previous.protocolVersion !== protocolStatus.protocolVersion) {\n const update = { attachId: attachIdRef.current, status: protocolStatus };\n lastProtocolRef.current = update;\n queueMicrotask(() => {\n if (lastProtocolRef.current !== update || attachIdRef.current !== update.attachId) {\n return;\n }\n onProtocolChangeRef.current?.(protocolStatus);\n });\n }\n }\n const runningSnapshot = { threadId: attachIdRef.current, isRunning };\n if (shouldNotifyRunningChange(lastRunningRef.current, runningSnapshot)) {\n lastRunningRef.current = runningSnapshot;\n const notify = onRunningChangeRef.current;\n if (notify) queueMicrotask(() => notify(isRunning));\n }\n return {\n ...convertDeepAgentState(state, {\n laneProjection,\n selfAuthor: stableSelfAuthor,\n toolOutputs,\n withdrawnTurns,\n }),\n state: state as StatewireThread.State['state'],\n };\n },\n [\n laneProjection,\n stableSelfAuthor,\n toolOutputs,\n toolOutputsVersion,\n withdrawnTurns,\n withdrawnTurnsVersion,\n ]\n );\n const materialize = useMemo(\n () => createDeepAgentMaterialize({ selfAuthor: stableSelfAuthor }),\n [stableSelfAuthor]\n );\n\n // Surface the statewire connection status through `onConnectionChange` (the\n // converter re-runs on connection changes), and clear it when the runtime\n // unmounts so an indicator never shows a stale status. Dedup is keyed by\n // thread: the runtime stays mounted across idle thread switches, so the new\n // thread's first status must notify even when it equals the previous\n // thread's last one.\n const lastConnectionRef = useRef<{\n threadId: string;\n connection: DeepAgentConnectionState;\n } | null>(null);\n useEffect(\n () => () => {\n lastConnectionRef.current = null;\n onConnectionChangeRef.current?.(null);\n },\n []\n );\n\n // The preload decision pins at thread entry: `isNewChat` flips once the\n // thread persists, but the mount that began as a new thread stays preloaded.\n const preloadRef = useRef({ threadId, preload: isNewChat });\n if (preloadRef.current.threadId !== threadId)\n preloadRef.current = { threadId, preload: isNewChat };\n\n const snapshotCacheRef = useRef(snapshotCache);\n snapshotCacheRef.current = snapshotCache;\n // The snapshot seed pins at attach identity, like the preload decision: the\n // cache is read once per mount, so a mid-session cache write (this thread's\n // own states being remembered) never changes what `initialState` was.\n //\n // A suspended attach never seeds: the suspended transport never dials, so a\n // seed would be served indefinitely — under a view-as lens that would paint\n // thread content the parked transport exists to withhold (the lens must\n // show what the LENSED identity is authorized to see, and only the server\n // can decide that).\n //\n // The pooled hello is taken the same way: exactly once, at the attach's\n // first render (the pool disposes its root in that step).\n const snapshotSeedRef = useRef<{\n attachId: string;\n seed: DeepAgentStreamValues | undefined;\n } | null>(null);\n if (snapshotSeedRef.current === null || snapshotSeedRef.current.attachId !== attachId) {\n const preload = preloadRef.current.preload;\n let pooledState: DeepAgentStreamValues | undefined;\n if (prewarmPool?.has(threadId)) {\n if (preload || suspended) {\n // This mount attaches on its own terms (or not at all): the pooled\n // dial must not linger as a second socket to the same session.\n prewarmPool.discard(threadId);\n } else {\n pooledState = prewarmPool.take(threadId)?.state;\n }\n }\n // The pooled hello outranks a remembered snapshot (it is newer by\n // construction); a pooled dial that had not landed seeds like a plain\n // attach and reconciles when this attach's own hello lands.\n const remembered =\n preload || suspended ? undefined : (pooledState ?? snapshotCache?.take(threadId));\n const seed = remembered ? toThreadSnapshotSeed(remembered) : undefined;\n snapshotSeedRef.current = { attachId, seed };\n const source: DeepAgentAttachSource =\n pooledState !== undefined ? 'prewarm' : seed ? 'snapshot' : 'none';\n const notifySource = onAttachSourceRef.current;\n if (notifySource) queueMicrotask(() => notifySource({ threadId, source }));\n }\n\n // react-statewire memoizes the converted thread on this function's\n // identity, so an inline closure would re-run `convertDeepAgentState` over\n // the whole transcript on every host render. Keyed on the attach identity (a\n // re-attach re-keys its per-thread latches); everything else the body needs\n // is read through the per-render refs above.\n const threadConverter = useCallback<ThreadOptions['converter']>(\n (wireState, meta) => {\n // The wire main document carries no messages: join the interest window\n // off the mounted documents, fold the dispatch record onto it, and hand\n // the composite on as the thread state every reader sees.\n const values = readDeepAgentStreamValues(wireState);\n const window = readDeepAgentMessageWindow(meta.mounted);\n const held =\n lastMessagesRef.current?.attachId === attachId ? lastMessagesRef.current.messages : null;\n const messages = window?.messages ?? values.messages ?? held ?? [];\n if (window !== null || messages.length > 0) lastMessagesRef.current = { attachId, messages };\n const state: DeepAgentStreamValues = { ...values, messages: [...messages] };\n materialize(state);\n if (window !== null && isDeepAgentStateHydrated(values)) {\n snapshotCacheRef.current?.remember(threadId, state);\n }\n if (interestRef.current.attachId !== attachId) {\n interestRef.current = { attachId, stated: false };\n }\n if (meta.connection.status !== 'connected') {\n interestRef.current.stated = false;\n } else if (!interestRef.current.stated) {\n interestRef.current.stated = true;\n const wanted = headInterestRequest(messageWindowRef.current?.size);\n const head = window?.requests[0];\n // The hello's head is kept whenever it is at least what this surface\n // wants (a remembered client's wider view, the declared header):\n // stating a narrower head would shrink what the viewer holds. A\n // narrower head — or none, a host without the lane — is widened, the\n // hello's pages kept alongside.\n const preloaded = head !== undefined && head.at === undefined && head.before >= wanted.before;\n if (!preloaded) {\n const requests = [\n wanted,\n ...(window?.requests.filter((request) => request.at !== undefined) ?? []),\n ];\n queueMicrotask(() => {\n if (attachIdRef.current !== attachId) return;\n meta\n .invoke(DEEP_AGENT_INTEREST_PROTOCOL, 'set', [requests])\n .catch((error: unknown) => {\n onErrorRef.current?.(error instanceof Error ? error : new Error(String(error)));\n });\n });\n }\n }\n // Projected once per pass through the single seam; every fold below\n // consumes the projection (the recorder projects the raw connection\n // itself, so any host observer can feed it).\n const connection = projectDeepAgentConnection(meta.connection);\n // Transition-deduped inside the recorder, so this per-pass observation\n // is free while the connection is unchanged.\n diagnosticsRef.current?.observeConnection(meta.connection);\n // Fold this pass's connection into the denial streak (the converter\n // re-runs on every reconnect-attempt bump). Parking is deferred to a\n // microtask like every other notification here.\n if (authDenialRef.current.attachId !== attachIdRef.current) {\n authDenialRef.current = {\n attachId: attachIdRef.current,\n state: initialAuthDenialTrackerState(),\n };\n }\n const denial = observeAuthDenial(authDenialRef.current.state, connection);\n authDenialRef.current.state = denial.state;\n if (denial.park) {\n const parkAttachId = attachIdRef.current;\n const parkMessage = denial.state.message;\n // The server refused authorization for this thread: any remembered\n // snapshot must not warm-paint it on a later mount (permissions may\n // have been revoked since the state was captured).\n snapshotCacheRef.current?.forget(threadId);\n queueMicrotask(() => {\n if (attachIdRef.current !== parkAttachId) return;\n setAuthParked((prev) =>\n prev?.attachId === parkAttachId\n ? prev\n : { attachId: parkAttachId, message: parkMessage }\n );\n });\n }\n const previous = lastConnectionRef.current;\n if (\n previous?.threadId !== attachId ||\n !Object.keys({ ...previous.connection, ...connection }).every(\n (key) => Reflect.get(previous.connection, key) === Reflect.get(connection, key)\n )\n ) {\n const update = { threadId: attachId, connection };\n lastConnectionRef.current = update;\n queueMicrotask(() => {\n // A newer projection, a thread switch, or the unmount cleanup owns\n // the channel now.\n if (lastConnectionRef.current !== update || attachIdRef.current !== attachId) return;\n onConnectionChangeRef.current?.(connection);\n });\n }\n // Session-asset lifecycle, paired with THIS attach's thread by closure:\n // the state converted here is the state of the thread the element was\n // built for, so the pair can never straddle a switch (a client-store\n // read would). Deduped by value per attach. A pass from an attach the\n // host has already replaced never touches the latch — it could otherwise\n // cancel the current attach's still-queued verdict — and the microtask\n // guard drops a pass whose attach is replaced before it settles.\n if (attachIdRef.current === attachId) {\n const sessionPersisted = readSessionPersisted(state);\n const lastSession = lastSessionPersistedRef.current;\n if (\n lastSession?.attachId !== attachId ||\n lastSession.sessionPersisted !== sessionPersisted\n ) {\n const sessionUpdate = { attachId, threadId, sessionPersisted };\n lastSessionPersistedRef.current = sessionUpdate;\n queueMicrotask(() => {\n if (\n lastSessionPersistedRef.current !== sessionUpdate ||\n attachIdRef.current !== attachId\n ) {\n return;\n }\n onSessionPersistedChangeRef.current?.({ threadId, sessionPersisted });\n });\n }\n }\n // The replicated run status IS the running signal: the lib's run-dialect\n // fold flips it to \"running\" on the send, before the app converter runs,\n // so the optimistic window needs no hand-tracked flag.\n return converter(state, state.runs?.[0]?.status === 'running');\n },\n [attachId, converter, materialize, threadId]\n );\n\n return StatewireThread<DeepAgentStreamValues>({\n // The transport stamps this protocol on every command; the thread client\n // must declare it too or the core skips the optimistic folds and a send\n // stays invisible until the server frame lands.\n protocol: DEEP_AGENT_STATEWIRE_PROTOCOL,\n // New threads preload an empty runs mount and report `deferred` — the\n // composer is interactive before the stream attaches and pre-attach sends\n // render through the optimistic folds. Existing threads omit the runs\n // mount and project \"loading\" until the attach snapshot: the server seeds\n // messages/todos/runConfig in `_load_history`.\n //\n // The preload also seeds `sessionPersisted: false`: a never-started chat\n // provably has no `session` asset until its first run mints one, so the\n // wire carries that from the first render and a host reading the flag off\n // the state needs no separate \"is this a new chat\" knowledge. An existing\n // thread leaves it absent (unknown) so its asset read is never gated.\n initialState:\n snapshotSeedRef.current.seed ??\n ({\n messages: [],\n todos: [],\n ...(preloadRef.current.preload && { runs: [], sessionPersisted: false }),\n } satisfies DeepAgentStreamValues),\n // Keyed by thread: a switch unmounts the previous thread's session and\n // remounts against the new URL, so the converter never sees the previous\n // thread's snapshot (a new thread serves its preload again, an existing\n // one loads until its snapshot). A host-suspended or auth-parked attach\n // swaps in the never-dialing transport instead.\n transport: withKey(\n attachId,\n (() => {\n if (suspended) return StatewireSuspended({ message: suspended.reason });\n if (authParked !== null && authParked.attachId === attachId) {\n return StatewireSuspended({\n message: authParked.message ?? 'Session authorization was refused.',\n onReconnectRequested: () => {\n authDenialRef.current = {\n attachId: attachIdRef.current,\n state: initialAuthDenialTrackerState(),\n };\n setAuthParked(null);\n },\n });\n }\n // The shared recipe (URL, auth + wire-contract headers, session lane,\n // attach instrumentation, retry-hint floor) — the same one the prewarm\n // pool dials with, so the instance a pooled attach warmed is the one\n // this dial reaches. A never-started chat dials nothing until its\n // first send.\n return createDeepAgentAttachTransport<DeepAgentStreamValues>({\n baseUrl,\n threadId,\n sse,\n isNew: preloadRef.current.preload,\n headers: (ctx) => headersRef.current(ctx),\n messageWindow: messageWindowRef.current,\n sessionStore,\n onAuthResolve: (ctx) => diagnosticsRef.current?.observeAuthResolve(ctx),\n onAttachTiming: (event) => onAttachTimingRef.current?.({ threadId, event }),\n });\n })()\n ),\n // Survives the transport remounts above: a bumped attachKey re-attaches the\n // same lane, and a persistent session storage carries it across reloads.\n ...(storage && { storage }),\n // The run subsystem (status, lanes, input requests, runId) is mounted on\n // the state root and always replicated by react-statewire >= 0.14 (the\n // former `runs: true` opt-in is gone) — the converter only maps app-owned\n // keys, including the `run/stop` runId stamp the lib projects itself.\n converter: threadConverter,\n // Native message editing: an edited turn is resubmitted as a `run/edit`\n // command, and the deep-agent backend rewinds the checkpointed thread to\n // the edited message's parent before appending (route `plan_rewind`).\n capabilities: capabilities ?? { edit: true },\n ...(getMessageMetadata && { getMessageMetadata }),\n ...(adapters && { adapters }),\n contextSync: 'command-send',\n // The Stop control is the only `cancelRun()` caller — teardown paths\n // unmount the keyed transport instead — so every `run/stop` is a\n // deliberate user stop.\n stopPayload: () => ({ reason: 'user_stop' }),\n onError: (error) => {\n diagnosticsRef.current?.observeError(error);\n onErrorRef.current?.(error);\n },\n ...(onStateChange && {\n // The lib types the observed state `NonNullable`, but the runtime\n // delivers `undefined` where the wire has no snapshot (pre-attach and\n // replay boundaries republish it) — normalize so the type is true and\n // host observers never crash on a field read.\n onStateChange: ((state, ctx) => {\n onStateChangeRef.current?.(readDeepAgentStreamValues(state), ctx);\n }) satisfies ThreadOptions['onStateChange'],\n }),\n ...((onCommandChange || diagnostics) && {\n onCommandChange: ((update, ctx) => {\n diagnosticsRef.current?.observeCommand(update);\n onCommandChangeRef.current?.(update, ctx);\n }) satisfies ThreadOptions['onCommandChange'],\n }),\n ...(onRawConnectionChange && {\n onConnectionChange: ((connection) =>\n onRawConnectionChangeRef.current?.(\n connection\n )) satisfies ThreadOptions['onConnectionChange'],\n }),\n });\n}\n"],"names":["messageWindow","useRef","useState","useEffect","initialAuthDenialTrackerState","isSameMessageAuthor","useMemo","projectDeepAgentProtocol","_a","convertDeepAgentState","createDeepAgentMaterialize","toThreadSnapshotSeed","useCallback","readDeepAgentStreamValues","readDeepAgentMessageWindow","messages","isDeepAgentStateHydrated","headInterestRequest","DEEP_AGENT_INTEREST_PROTOCOL","projectDeepAgentConnection","observeAuthDenial","StatewireThread","DEEP_AGENT_STATEWIRE_PROTOCOL","withKey","StatewireSuspended","createDeepAgentAttachTransport"],"mappings":";;;;;;;;;;;;;;;;;AA0RO,SAAS,qBAAqB,OAAgC;AACnE,QAAM,OAAQ,+BAAiD;AAC/D,SAAO,OAAO,SAAS,YAAY,OAAO;AAC5C;AAUO,SAAS,0BACd,UACA,MACS;AACT,MAAI,aAAa,KAAM,QAAO,KAAK;AACnC,SAAO,SAAS,aAAa,KAAK,YAAY,SAAS,cAAc,KAAK;AAC5E;AAoBO,SAAS,mBAAmB;AAAA,EACjC;AAAA,EACA;AAAA,EACA,MAAM;AAAA,EACN;AAAA,EACA;AAAA,EACA;AAAA,EACA,YAAY;AAAA,EACZ;AAAA,EACA,YAAY;AAAA,EACZ;AAAA,EACA,iBAAiB;AAAA,EACjB,aAAa;AAAA,EACb;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAAA,eACAA;AAAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAA8B;;AAC5B,QAAM,qBAAqBC,MAAAA,OAAO,eAAe;AACjD,qBAAmB,UAAU;AAC7B,QAAM,8BAA8BA,MAAAA,OAAO,wBAAwB;AACnE,8BAA4B,UAAU;AACtC,QAAM,wBAAwBA,MAAAA,OAAO,kBAAkB;AACvD,wBAAsB,UAAU;AAChC,QAAM,uBAAuBA,MAAAA,OAAO,iBAAiB;AACrD,uBAAqB,UAAU;AAC/B,QAAM,0BAA0BA,MAAAA,OAAO,oBAAoB;AAC3D,0BAAwB,UAAU;AAClC,QAAM,sBAAsBA,MAAAA,OAAO,gBAAgB;AACnD,sBAAoB,UAAU;AAC9B,QAAM,aAAaA,MAAAA,OAAO,OAAO;AACjC,aAAW,UAAU;AACrB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