@athenaintel/react 0.30.0 → 0.35.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.
Files changed (210) hide show
  1. package/README.md +160 -9
  2. package/dist/agent-runtime/src/athena-asset-drag.cjs +44 -0
  3. package/dist/agent-runtime/src/athena-asset-drag.cjs.map +1 -0
  4. package/dist/agent-runtime/src/athena-asset-drag.js +44 -0
  5. package/dist/agent-runtime/src/athena-asset-drag.js.map +1 -0
  6. package/dist/agent-runtime/src/composer-markdown.cjs.map +1 -1
  7. package/dist/agent-runtime/src/composer-markdown.js.map +1 -1
  8. package/dist/agent-runtime/src/config-mutations.cjs +59 -0
  9. package/dist/agent-runtime/src/config-mutations.cjs.map +1 -0
  10. package/dist/agent-runtime/src/config-mutations.js +59 -0
  11. package/dist/agent-runtime/src/config-mutations.js.map +1 -0
  12. package/dist/agent-runtime/src/deep-agent-transport-recipe.cjs +2 -3
  13. package/dist/agent-runtime/src/deep-agent-transport-recipe.cjs.map +1 -1
  14. package/dist/agent-runtime/src/deep-agent-transport-recipe.js +3 -4
  15. package/dist/agent-runtime/src/deep-agent-transport-recipe.js.map +1 -1
  16. package/dist/agent-runtime/src/edit-command.cjs.map +1 -1
  17. package/dist/agent-runtime/src/edit-command.js.map +1 -1
  18. package/dist/agent-runtime/src/generated/runconfig-contract.cjs +6 -0
  19. package/dist/agent-runtime/src/generated/runconfig-contract.cjs.map +1 -1
  20. package/dist/agent-runtime/src/generated/runconfig-contract.js +6 -0
  21. package/dist/agent-runtime/src/generated/runconfig-contract.js.map +1 -1
  22. package/dist/agent-runtime/src/messages.cjs +57 -2
  23. package/dist/agent-runtime/src/messages.cjs.map +1 -1
  24. package/dist/agent-runtime/src/messages.js +57 -2
  25. package/dist/agent-runtime/src/messages.js.map +1 -1
  26. package/dist/agent-runtime/src/quota-safe-local-storage-session.cjs +72 -3
  27. package/dist/agent-runtime/src/quota-safe-local-storage-session.cjs.map +1 -1
  28. package/dist/agent-runtime/src/quota-safe-local-storage-session.js +73 -4
  29. package/dist/agent-runtime/src/quota-safe-local-storage-session.js.map +1 -1
  30. package/dist/agent-runtime/src/statewire-transport.cjs +4 -13
  31. package/dist/agent-runtime/src/statewire-transport.cjs.map +1 -1
  32. package/dist/agent-runtime/src/statewire-transport.js +5 -14
  33. package/dist/agent-runtime/src/statewire-transport.js.map +1 -1
  34. package/dist/agent-runtime/src/tool-metadata.cjs +26 -7
  35. package/dist/agent-runtime/src/tool-metadata.cjs.map +1 -1
  36. package/dist/agent-runtime/src/tool-metadata.js +26 -7
  37. package/dist/agent-runtime/src/tool-metadata.js.map +1 -1
  38. package/dist/agent-runtime/src/use-deep-agent-config.cjs +117 -1
  39. package/dist/agent-runtime/src/use-deep-agent-config.cjs.map +1 -1
  40. package/dist/agent-runtime/src/use-deep-agent-config.js +118 -2
  41. package/dist/agent-runtime/src/use-deep-agent-config.js.map +1 -1
  42. package/dist/agent-runtime/src/use-deep-agent-thread.cjs.map +1 -1
  43. package/dist/agent-runtime/src/use-deep-agent-thread.js.map +1 -1
  44. package/dist/assets/AthenaAssetEmbed.cjs +9 -2
  45. package/dist/assets/AthenaAssetEmbed.cjs.map +1 -1
  46. package/dist/assets/AthenaAssetEmbed.d.ts +9 -0
  47. package/dist/assets/AthenaAssetEmbed.js +11 -4
  48. package/dist/assets/AthenaAssetEmbed.js.map +1 -1
  49. package/dist/assets/asset-embed-messages.cjs +6 -0
  50. package/dist/assets/asset-embed-messages.cjs.map +1 -1
  51. package/dist/assets/asset-embed-messages.d.ts +7 -0
  52. package/dist/assets/asset-embed-messages.js +6 -0
  53. package/dist/assets/asset-embed-messages.js.map +1 -1
  54. package/dist/assets/use-asset-embed.cjs +71 -71
  55. package/dist/assets/use-asset-embed.cjs.map +1 -1
  56. package/dist/assets/use-asset-embed.d.ts +20 -7
  57. package/dist/assets/use-asset-embed.js +72 -72
  58. package/dist/assets/use-asset-embed.js.map +1 -1
  59. package/dist/catalog/agent-model-options.cjs +122 -0
  60. package/dist/catalog/agent-model-options.cjs.map +1 -0
  61. package/dist/catalog/agent-model-options.d.ts +115 -0
  62. package/dist/catalog/agent-model-options.js +122 -0
  63. package/dist/catalog/agent-model-options.js.map +1 -0
  64. package/dist/catalog/chat-pickers.cjs +184 -4
  65. package/dist/catalog/chat-pickers.cjs.map +1 -1
  66. package/dist/catalog/chat-pickers.d.ts +27 -3
  67. package/dist/catalog/chat-pickers.js +187 -7
  68. package/dist/catalog/chat-pickers.js.map +1 -1
  69. package/dist/catalog/runtime-catalog.cjs +117 -3
  70. package/dist/catalog/runtime-catalog.cjs.map +1 -1
  71. package/dist/catalog/runtime-catalog.d.ts +104 -0
  72. package/dist/catalog/runtime-catalog.js +119 -5
  73. package/dist/catalog/runtime-catalog.js.map +1 -1
  74. package/dist/chat/AthenaChat.cjs +41 -26
  75. package/dist/chat/AthenaChat.cjs.map +1 -1
  76. package/dist/chat/AthenaChat.d.ts +8 -7
  77. package/dist/chat/AthenaChat.js +41 -26
  78. package/dist/chat/AthenaChat.js.map +1 -1
  79. package/dist/chat/super-grouping/SuperGroupingCard.cjs +61 -14
  80. package/dist/chat/super-grouping/SuperGroupingCard.cjs.map +1 -1
  81. package/dist/chat/super-grouping/SuperGroupingCard.d.ts +26 -12
  82. package/dist/chat/super-grouping/SuperGroupingCard.js +63 -16
  83. package/dist/chat/super-grouping/SuperGroupingCard.js.map +1 -1
  84. package/dist/chat/super-grouping/SuperGroupingTranscript.cjs +80 -53
  85. package/dist/chat/super-grouping/SuperGroupingTranscript.cjs.map +1 -1
  86. package/dist/chat/super-grouping/SuperGroupingTranscript.d.ts +10 -10
  87. package/dist/chat/super-grouping/SuperGroupingTranscript.js +81 -54
  88. package/dist/chat/super-grouping/SuperGroupingTranscript.js.map +1 -1
  89. package/dist/chat/super-grouping/activity-timeline.cjs +19 -4
  90. package/dist/chat/super-grouping/activity-timeline.cjs.map +1 -1
  91. package/dist/chat/super-grouping/activity-timeline.d.ts +24 -5
  92. package/dist/chat/super-grouping/activity-timeline.js +19 -4
  93. package/dist/chat/super-grouping/activity-timeline.js.map +1 -1
  94. package/dist/chat/super-grouping/index.cjs +2 -0
  95. package/dist/chat/super-grouping/index.cjs.map +1 -1
  96. package/dist/chat/super-grouping/index.d.ts +7 -6
  97. package/dist/chat/super-grouping/index.js +3 -1
  98. package/dist/chat/super-grouping/toolkit-map.cjs +4 -1
  99. package/dist/chat/super-grouping/toolkit-map.cjs.map +1 -1
  100. package/dist/chat/super-grouping/toolkit-map.js +4 -1
  101. package/dist/chat/super-grouping/toolkit-map.js.map +1 -1
  102. package/dist/chat-ui/composer/tiptap-composer.cjs +40 -4
  103. package/dist/chat-ui/composer/tiptap-composer.cjs.map +1 -1
  104. package/dist/chat-ui/composer/tiptap-composer.js +40 -4
  105. package/dist/chat-ui/composer/tiptap-composer.js.map +1 -1
  106. package/dist/chat-ui/index.cjs +1 -0
  107. package/dist/chat-ui/index.cjs.map +1 -1
  108. package/dist/chat-ui/index.d.ts +1 -1
  109. package/dist/chat-ui/index.js +2 -1
  110. package/dist/chat-ui/mentions/mention-chip.cjs +29 -2
  111. package/dist/chat-ui/mentions/mention-chip.cjs.map +1 -1
  112. package/dist/chat-ui/mentions/mention-chip.d.ts +2 -5
  113. package/dist/chat-ui/mentions/mention-chip.js +30 -3
  114. package/dist/chat-ui/mentions/mention-chip.js.map +1 -1
  115. package/dist/chat-ui/mentions/mention-extension.cjs +1 -1
  116. package/dist/chat-ui/mentions/mention-extension.cjs.map +1 -1
  117. package/dist/chat-ui/mentions/mention-extension.js +1 -1
  118. package/dist/chat-ui/mentions/mention-extension.js.map +1 -1
  119. package/dist/chat-ui/mentions/suggestions/data/api-client.cjs +33 -2
  120. package/dist/chat-ui/mentions/suggestions/data/api-client.cjs.map +1 -1
  121. package/dist/chat-ui/mentions/suggestions/data/api-client.d.ts +14 -0
  122. package/dist/chat-ui/mentions/suggestions/data/api-client.js +33 -2
  123. package/dist/chat-ui/mentions/suggestions/data/api-client.js.map +1 -1
  124. package/dist/chat-ui/mentions/use-account-workspace-id.cjs +61 -0
  125. package/dist/chat-ui/mentions/use-account-workspace-id.cjs.map +1 -0
  126. package/dist/chat-ui/mentions/use-account-workspace-id.d.ts +3 -0
  127. package/dist/chat-ui/mentions/use-account-workspace-id.js +61 -0
  128. package/dist/chat-ui/mentions/use-account-workspace-id.js.map +1 -0
  129. package/dist/chat-ui/mentions/use-member-avatar.cjs +75 -0
  130. package/dist/chat-ui/mentions/use-member-avatar.cjs.map +1 -0
  131. package/dist/chat-ui/mentions/use-member-avatar.d.ts +2 -0
  132. package/dist/chat-ui/mentions/use-member-avatar.js +75 -0
  133. package/dist/chat-ui/mentions/use-member-avatar.js.map +1 -0
  134. package/dist/collab/client.cjs +80 -19
  135. package/dist/collab/client.cjs.map +1 -1
  136. package/dist/collab/client.d.ts +22 -0
  137. package/dist/collab/client.js +80 -19
  138. package/dist/collab/client.js.map +1 -1
  139. package/dist/diagnostics/athena-diagnostics.cjs.map +1 -1
  140. package/dist/diagnostics/athena-diagnostics.d.ts +3 -1
  141. package/dist/diagnostics/athena-diagnostics.js.map +1 -1
  142. package/dist/index.cjs +5 -0
  143. package/dist/index.cjs.map +1 -1
  144. package/dist/index.d.ts +6 -3
  145. package/dist/index.js +7 -2
  146. package/dist/index.js.map +1 -1
  147. package/dist/lib/use-athena-rest-query.cjs +4 -0
  148. package/dist/lib/use-athena-rest-query.cjs.map +1 -1
  149. package/dist/lib/use-athena-rest-query.d.ts +6 -0
  150. package/dist/lib/use-athena-rest-query.js +4 -0
  151. package/dist/lib/use-athena-rest-query.js.map +1 -1
  152. package/dist/provider/AthenaProvider.cjs +57 -6
  153. package/dist/provider/AthenaProvider.cjs.map +1 -1
  154. package/dist/provider/AthenaProvider.d.ts +21 -5
  155. package/dist/provider/AthenaProvider.js +59 -8
  156. package/dist/provider/AthenaProvider.js.map +1 -1
  157. package/dist/provider/agent-selection-context.cjs +6 -0
  158. package/dist/provider/agent-selection-context.cjs.map +1 -0
  159. package/dist/provider/agent-selection-context.d.ts +14 -0
  160. package/dist/provider/agent-selection-context.js +6 -0
  161. package/dist/provider/agent-selection-context.js.map +1 -0
  162. package/dist/react/package.json.cjs +1 -1
  163. package/dist/react/package.json.js +1 -1
  164. package/dist/runtime/StatewireThreadConfigLaneSync.cjs +125 -0
  165. package/dist/runtime/StatewireThreadConfigLaneSync.cjs.map +1 -0
  166. package/dist/runtime/StatewireThreadConfigLaneSync.d.ts +54 -0
  167. package/dist/runtime/StatewireThreadConfigLaneSync.js +125 -0
  168. package/dist/runtime/StatewireThreadConfigLaneSync.js.map +1 -0
  169. package/dist/runtime/statewire-lifecycle.cjs +5 -2
  170. package/dist/runtime/statewire-lifecycle.cjs.map +1 -1
  171. package/dist/runtime/statewire-lifecycle.d.ts +5 -0
  172. package/dist/runtime/statewire-lifecycle.js +5 -2
  173. package/dist/runtime/statewire-lifecycle.js.map +1 -1
  174. package/dist/runtime/statewire-model-lane.cjs +16 -0
  175. package/dist/runtime/statewire-model-lane.cjs.map +1 -0
  176. package/dist/runtime/statewire-model-lane.d.ts +66 -0
  177. package/dist/runtime/statewire-model-lane.js +16 -0
  178. package/dist/runtime/statewire-model-lane.js.map +1 -0
  179. package/dist/runtime/statewire-run-config.cjs +16 -2
  180. package/dist/runtime/statewire-run-config.cjs.map +1 -1
  181. package/dist/runtime/statewire-run-config.d.ts +10 -0
  182. package/dist/runtime/statewire-run-config.js +16 -2
  183. package/dist/runtime/statewire-run-config.js.map +1 -1
  184. package/dist/runtime/statewire-server-lane-context.cjs +24 -0
  185. package/dist/runtime/statewire-server-lane-context.cjs.map +1 -0
  186. package/dist/runtime/statewire-server-lane-context.d.ts +30 -0
  187. package/dist/runtime/statewire-server-lane-context.js +24 -0
  188. package/dist/runtime/statewire-server-lane-context.js.map +1 -0
  189. package/dist/runtime/statewire-thread-config-lane.cjs +84 -0
  190. package/dist/runtime/statewire-thread-config-lane.cjs.map +1 -0
  191. package/dist/runtime/statewire-thread-config-lane.d.ts +94 -0
  192. package/dist/runtime/statewire-thread-config-lane.js +84 -0
  193. package/dist/runtime/statewire-thread-config-lane.js.map +1 -0
  194. package/dist/runtime/useAthenaStatewireRuntime.cjs +38 -18
  195. package/dist/runtime/useAthenaStatewireRuntime.cjs.map +1 -1
  196. package/dist/runtime/useAthenaStatewireRuntime.d.ts +8 -1
  197. package/dist/runtime/useAthenaStatewireRuntime.js +39 -19
  198. package/dist/runtime/useAthenaStatewireRuntime.js.map +1 -1
  199. package/dist/styles.css +1 -1
  200. package/dist/threads/api.cjs +2 -1
  201. package/dist/threads/api.cjs.map +1 -1
  202. package/dist/threads/api.d.ts +1 -0
  203. package/dist/threads/api.js +2 -1
  204. package/dist/threads/api.js.map +1 -1
  205. package/dist/threads/use-athena-thread-model.cjs +22 -0
  206. package/dist/threads/use-athena-thread-model.cjs.map +1 -0
  207. package/dist/threads/use-athena-thread-model.d.ts +27 -0
  208. package/dist/threads/use-athena-thread-model.js +22 -0
  209. package/dist/threads/use-athena-thread-model.js.map +1 -0
  210. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"api.cjs","sources":["../../src/threads/api.ts"],"sourcesContent":["/**\n * Athena thread API client.\n * Calls existing REST endpoints for thread CRUD.\n */\n\nimport type {\n ConversationAttention,\n ConversationAttentionSource,\n} from '@athenaintel/agent-runtime';\nimport { athenaDiagnostics } from '../diagnostics/athena-diagnostics';\nimport { AthenaSdkError, type AthenaSdkErrorCode, isAthenaSdkError } from '../diagnostics/errors';\n\n/**\n * Live GitHub state of a pull request the thread opened, read by the server\n * when the list renders (agora `agent_pr_threads` is the only stored link).\n */\nexport interface ThreadPullRequest {\n /** `owner/repo` the pull request lives in. */\n repo_full_name: string;\n number: number;\n url: string;\n title: string;\n state: 'OPEN' | 'CLOSED' | 'MERGED';\n is_draft: boolean;\n /** GitHub's review decision (APPROVED, CHANGES_REQUESTED, REVIEW_REQUIRED) or null. */\n review_decision: string | null;\n /** Combined state of the checks on the head commit. */\n checks_state: 'SUCCESS' | 'FAILURE' | 'PENDING' | 'NONE';\n /** ISO 8601 timestamp of the pull request's last update on GitHub. */\n updated_at: string;\n}\n\n/** The last event that woke a resting thread (a GitHub webhook, a schedule, a handoff). */\nexport interface ThreadWake {\n source: string | null;\n reason: string | null;\n /** ISO 8601 timestamp of the wake. */\n at: string | null;\n}\n\nexport interface ThreadSummary {\n thread_id: string;\n title: string;\n created_at: string;\n updated_at: string;\n last_message: string | null;\n message_count: number;\n state: string | null;\n start_channel?: string | null;\n last_channel?: string | null;\n /** Client app that created the session (SESSION_APP_ID_GUIDE). */\n app_id?: string | null;\n /** Collab agent and channel the session started on; older servers omit them. */\n collab_agent_id?: string | null;\n collab_channel_id?: string | null;\n /** Trigger marker for automated/background sessions. */\n trigger_type?: string | null;\n /** Whether the calling user has seen this thread since it last changed. */\n is_unread?: boolean;\n /**\n * Canonical status_v2 planes (`idle | active | needs_input | error` and\n * `scheduled | queued | running | needs_input | completed | failed |\n * canceled`); older servers omit them.\n */\n session_status?: string | null;\n run_status?: string | null;\n /**\n * The viewer's attention state, the one-line next action (≤ 80 chars) and\n * the signal that produced them, derived server-side; older servers omit them.\n */\n attention?: ConversationAttention | null;\n next_action?: string | null;\n attention_source?: ConversationAttentionSource | null;\n /** Whether the calling user favorited (pinned) the thread; older servers omit it. */\n is_favorited?: boolean;\n /** The last wake of a resting thread; older servers omit it. */\n last_wake?: ThreadWake | null;\n /** Whether the calling user started the thread (`false`: shared with them); older servers omit it. */\n created_by_me?: boolean;\n /**\n * Pull requests the thread opened with their live GitHub state. `[]` when\n * it opened none, `null` when the state could not be read right now;\n * older servers omit the field.\n */\n pull_requests?: ThreadPullRequest[] | null;\n}\n\n/**\n * True for fetch cancellations (unmount/remount aborts, StrictMode double\n * effects). These are lifecycle noise, not failures: emitting them as\n * `*.error` diagnostics floods the console with\n * \"signal is aborted without reason\" for requests the caller itself aborted.\n */\nfunction isAbortError(error: unknown): boolean {\n return (\n (error instanceof DOMException && error.name === 'AbortError') ||\n (error instanceof Error && error.name === 'AbortError')\n );\n}\n\nexport interface ThreadListResponse {\n threads: ThreadSummary[];\n /** Server lookahead result. Older servers may omit this field. */\n has_more?: boolean;\n /**\n * Every request field the server applies beyond paging. The server ignores\n * fields it does not know, so a filter missing from this list came back\n * unapplied; servers that predate the list omit it (none of the\n * `ThreadListFilterBody` fields are applied there).\n */\n supported_filters?: string[];\n}\n\n/**\n * The server-side filters and order of `POST /api/conversations/threads/list`\n * beyond the original `app_id` / `start_channel` / `search` /\n * `exclude_triggered` set. Each is a predicate of the server's one page\n * statement, so a page is exact; a server that predates a field ignores it\n * (check `ThreadListResponse.supported_filters`).\n */\nexport interface ThreadListFilterBody {\n /** Original fields, accepted here too so one body can carry a whole query. */\n search?: string;\n exclude_triggered?: boolean;\n app_ids?: string[];\n start_channels?: string[];\n created_after?: string;\n created_before?: string;\n updated_after?: string;\n updated_before?: string;\n collab_agent_ids?: string[];\n /** `'default'` matches the agent's default channel (no channel stamp); needs `collab_agent_ids`. */\n collab_channel_ids?: string[];\n favorites_only?: boolean;\n unread_only?: boolean;\n run_statuses?: string[];\n session_statuses?: string[];\n has_pull_requests?: boolean;\n created_by_me?: boolean;\n exclude_dismissed?: boolean;\n sort?: 'updated' | 'created';\n direction?: 'desc' | 'asc';\n}\n\nexport interface ThreadCreateResponse {\n thread_id: string;\n}\n\ninterface AuthConfig {\n apiKey?: string;\n token?: string | null;\n}\n\nfunction getAuthHeaders(auth: AuthConfig): Record<string, string> {\n if (auth.token) {\n return { Authorization: `Bearer ${auth.token}` };\n }\n if (auth.apiKey) {\n return { 'X-API-KEY': auth.apiKey };\n }\n return {};\n}\n\n/**\n * Resolves the Athena API base URL from backendUrl.\n * Thread endpoints live under `/api/conversations/threads/*` and `/api/unstable/threads/`.\n * If backendUrl points at a nested Athena endpoint, trim it back to the API base first.\n */\nfunction getAthenaApiBaseUrl(backendUrl: string): string {\n const stripped = backendUrl.replace(/\\/api\\/assistant-ui\\/?$/, '');\n // If the suffix wasn't found, assume the URL already points to the API base\n if (stripped === backendUrl) {\n return backendUrl.replace(/\\/$/, '');\n }\n return stripped;\n}\n\nexport async function listThreads(\n backendUrl: string,\n auth: AuthConfig,\n opts: {\n limit?: number;\n offset?: number;\n exclude_triggered?: boolean;\n app_id?: string;\n start_channel?: string;\n search?: string;\n /** Ask the server for live GitHub state on `pull_requests` (off by default: it costs a lookup). */\n include_pull_requests?: boolean;\n /** Server-side filters and order beyond the original set (see `ThreadListFilterBody`). */\n filters?: ThreadListFilterBody;\n signal?: AbortSignal;\n } = {},\n): Promise<ThreadListResponse> {\n const base = getAthenaApiBaseUrl(backendUrl);\n const endSpan = athenaDiagnostics.span('threads.list', 'threads.list.start', {\n auth_mode: getAuthMode(auth),\n app_id: opts.app_id,\n });\n try {\n const res = await fetch(`${base}/api/conversations/threads/list`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...getAuthHeaders(auth) },\n signal: opts.signal ?? null,\n body: JSON.stringify({\n limit: opts.limit ?? 50,\n offset: opts.offset ?? 0,\n // Default to the full recent-conversations set unless a caller\n // explicitly asks to hide triggered/background sessions.\n exclude_triggered: opts.exclude_triggered ?? false,\n ...(opts.app_id ? { app_id: opts.app_id } : {}),\n ...(opts.start_channel ? { start_channel: opts.start_channel } : {}),\n ...(opts.search ? { search: opts.search } : {}),\n ...(opts.include_pull_requests ? { include_pull_requests: true } : {}),\n ...opts.filters,\n }),\n });\n if (!res.ok) {\n throw new AthenaSdkError({\n code: res.status === 401 || res.status === 403 ? 'auth_rejected' : 'threads_list_failed',\n message: `Failed to list threads: ${res.status}`,\n status: res.status,\n hint:\n res.status === 401 || res.status === 403\n ? 'The credential was refused. Check the token/API key and that the user belongs to the workspace.'\n : 'Check backendUrl points at the Agora API base.',\n context: { auth_mode: getAuthMode(auth) },\n });\n }\n const data = (await res.json()) as ThreadListResponse;\n endSpan('threads.list.done', { data: { count: data.threads?.length ?? 0 } });\n return data;\n } catch (error) {\n // Cancellation is lifecycle noise (unmount/remount aborts): log it as an\n // informational abort, not an error — passing `error` would force the\n // span end to error level and spam the console.\n if (isAbortError(error)) {\n endSpan('threads.list.aborted', { data: { reason: 'request aborted' } });\n } else {\n endSpan('threads.list.error', { error });\n }\n throw error;\n }\n}\n\n/** The `(workspace, user)` pair the credential resolves to on the backend. */\nexport interface AccountIdentity {\n userId: string;\n /** `null` for a user with no current workspace. */\n workspaceId: string | null;\n}\n\n/**\n * Resolve the credential's agora identity. The conversation index is one\n * statewire instance per `(workspace, user)`, and neither half is knowable\n * from the credential alone: the SDK's auth context carries an identity\n * provider user id, not agora's, and never a workspace.\n */\nexport async function fetchAccountIdentity(\n backendUrl: string,\n auth: AuthConfig,\n opts: { signal?: AbortSignal } = {},\n): Promise<AccountIdentity> {\n const base = getAthenaApiBaseUrl(backendUrl);\n const res = await fetch(`${base}/api/v0/me`, {\n headers: getAuthHeaders(auth),\n signal: opts.signal ?? null,\n });\n if (!res.ok) {\n throw new AthenaSdkError({\n code: res.status === 401 || res.status === 403 ? 'auth_rejected' : 'threads_list_failed',\n message: `Failed to resolve account identity: ${res.status}`,\n status: res.status,\n hint:\n res.status === 401 || res.status === 403\n ? 'The credential was refused. Check the token/API key and that the user belongs to the workspace.'\n : 'Check backendUrl points at the Agora API base.',\n context: { auth_mode: getAuthMode(auth) },\n });\n }\n const body = (await res.json()) as { user_id?: unknown; workspace_id?: unknown };\n if (typeof body.user_id !== 'string' || body.user_id.length === 0) {\n throw new AthenaSdkError({\n code: 'threads_list_failed',\n message: 'Account identity lookup returned no user id.',\n context: { auth_mode: getAuthMode(auth) },\n });\n }\n return {\n userId: body.user_id,\n workspaceId: typeof body.workspace_id === 'string' ? body.workspace_id : null,\n };\n}\n\nexport interface ThreadReadStateResponse {\n thread_id: string;\n is_unread: boolean;\n}\n\n/** Store the calling user's read receipt for a thread. */\nexport async function setThreadReadState(\n backendUrl: string,\n auth: AuthConfig,\n opts: { threadId: string; isUnread: boolean },\n): Promise<ThreadReadStateResponse> {\n const base = getAthenaApiBaseUrl(backendUrl);\n const res = await fetch(`${base}/api/conversations/threads/read-state`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...getAuthHeaders(auth) },\n body: JSON.stringify({\n thread_id: opts.threadId,\n is_unread: opts.isUnread,\n }),\n });\n if (!res.ok) {\n throw new AthenaSdkError({\n code: res.status === 401 || res.status === 403 ? 'auth_rejected' : 'unknown',\n message: `Failed to set thread read state: ${res.status}`,\n status: res.status,\n });\n }\n return res.json();\n}\n\nexport interface ThreadInboxDismissResponse {\n success: boolean;\n dismissed: boolean;\n}\n\n/**\n * Dismiss a session from the inbox, or bring it back\n * (`POST /api/conversations/threads/notifications/dismiss`). A dismissed\n * session returns on its own with its next message. The state lives on the\n * session for its creator's inbox, so the route takes EDIT on the session\n * (403 for a VIEW share).\n */\nexport async function dismissThreadFromInbox(\n backendUrl: string,\n auth: AuthConfig,\n opts: { threadId: string; dismissed: boolean },\n): Promise<ThreadInboxDismissResponse> {\n const base = getAthenaApiBaseUrl(backendUrl);\n const res = await fetch(`${base}/api/conversations/threads/notifications/dismiss`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...getAuthHeaders(auth) },\n body: JSON.stringify({ thread_id: opts.threadId, dismissed: opts.dismissed }),\n });\n if (!res.ok) {\n throw new AthenaSdkError({\n code: res.status === 401 || res.status === 403 ? 'auth_rejected' : 'unknown',\n message: `Failed to ${opts.dismissed ? 'dismiss' : 'restore'} the session: ${res.status}`,\n status: res.status,\n hint:\n res.status === 403\n ? 'Only someone who can edit the session (its creator, usually) can dismiss it from the inbox.'\n : undefined,\n context: { thread_id: opts.threadId, auth_mode: getAuthMode(auth) },\n });\n }\n return res.json();\n}\n\nexport interface ThreadFavoriteResponse {\n thread_id: string;\n /** The server's state after the write. */\n is_favorited: boolean;\n}\n\n/**\n * Classify a 4xx from one of the per-thread write routes (`favorite`,\n * `rename`, `archive`). A 404 there is ambiguous: FastAPI answers\n * `{\"detail\":\"Not Found\"}` for a route an older agora does not have, the\n * archive route answers `\"Endpoint not available\"` on an agora without the\n * checkpointer — and each route answers 404 for a thread that no longer\n * exists (`\"Thread <id> not found\"`, `\"Conversation with langchain thread id\n * <id> not found\"`). The routes' own not-found answers name the thread, so a\n * body that does not is the ROUTE missing, and only that withdraws the\n * feature; a stale row must not disable the action for every other row.\n */\nfunction classifyThreadRouteRejection(\n status: number,\n body: string,\n threadId: string,\n): { routeMissing: boolean; detail: unknown } {\n let detail: unknown = body || undefined;\n try {\n const parsed: unknown = JSON.parse(body);\n if (parsed && typeof parsed === 'object') {\n const record = parsed as { detail?: unknown; message?: unknown };\n detail = record.detail ?? record.message ?? parsed;\n }\n } catch {\n // A non-JSON body (a proxy page) is kept as text.\n }\n const routeMissing = status === 405 || (status === 404 && !mentionsThread(body, threadId));\n return { routeMissing, detail };\n}\n\n/**\n * Whether an error body names the thread as a whole token (the routes embed\n * the id between spaces: `Thread <id> not found`); a substring match would\n * let a short id match a letter inside `\"detail\"`.\n */\nfunction mentionsThread(body: string, threadId: string): boolean {\n if (!threadId) return false;\n const escaped = threadId.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return new RegExp(`(^|[^A-Za-z0-9_-])${escaped}($|[^A-Za-z0-9_-])`).test(body);\n}\n\n/** True when a per-thread write was rejected because the backend has no such route. */\nfunction isThreadRouteUnavailableError(error: unknown, code: AthenaSdkErrorCode): boolean {\n return isAthenaSdkError(error) && error.code === code && error.context.route_missing === true;\n}\n\n/**\n * Pin (favorite) or unpin a thread for the calling user. The response is the\n * server's truth after the write. Rejections: 401 / 403 when the caller\n * cannot view the thread (`auth_rejected`), otherwise `thread_favorite_failed`\n * with the HTTP status — 404 / 405 from an agora that predates the route,\n * which `isThreadFavoriteUnavailableError` recognizes so callers can fall\n * back to a read-only pin.\n */\nexport async function setThreadFavorite(\n backendUrl: string,\n auth: AuthConfig,\n opts: { threadId: string; isFavorited: boolean },\n): Promise<ThreadFavoriteResponse> {\n const base = getAthenaApiBaseUrl(backendUrl);\n const res = await fetch(`${base}/api/conversations/threads/favorite`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...getAuthHeaders(auth) },\n body: JSON.stringify({\n thread_id: opts.threadId,\n is_favorited: opts.isFavorited,\n }),\n });\n if (!res.ok) {\n const refused = res.status === 401 || res.status === 403;\n const { routeMissing, detail } = classifyThreadRouteRejection(\n res.status,\n await getResponseErrorBody(res),\n opts.threadId,\n );\n throw new AthenaSdkError({\n code: refused ? 'auth_rejected' : 'thread_favorite_failed',\n message: `Failed to set thread favorite: ${res.status}`,\n status: res.status,\n detail,\n hint: refused\n ? 'The credential cannot view this thread.'\n : routeMissing\n ? 'The backend has no favorite route yet (older agora); the pin stays read-only until it deploys.'\n : res.status === 404\n ? 'The thread no longer exists on the server (archived or deleted elsewhere); refresh the list.'\n : 'Check backendUrl points at the Agora API base.',\n context: { thread_id: opts.threadId, auth_mode: getAuthMode(auth), route_missing: routeMissing },\n });\n }\n return res.json();\n}\n\n/**\n * True when `setThreadFavorite` failed because the backend has no favorite\n * route (a 405, or a 404 whose body does not name the thread — see\n * `classifyThreadRouteRejection`); a 404 for a thread that is gone is a\n * per-row failure and leaves the toggle available.\n */\nexport function isThreadFavoriteUnavailableError(error: unknown): boolean {\n return isThreadRouteUnavailableError(error, 'thread_favorite_failed');\n}\n\nexport interface ThreadRenameResponse {\n thread_id: string;\n /** The stored title after the write (trimmed by the server). */\n title: string;\n}\n\n/** The longest title the rename route accepts; the server answers 422 past it. */\nexport const THREAD_TITLE_MAX_LENGTH = 200;\n\n/**\n * Rename a thread for every viewer (`POST /api/conversations/threads/rename`).\n * The server trims the title and stores 1–200 characters; the response is the\n * row's title after the write. Rejections: 401 / 403 when the caller cannot\n * edit the thread (`auth_rejected` — a viewer can pin a shared session but not\n * retitle it), otherwise `thread_rename_failed` with the HTTP status — 404 /\n * 405 from an agora that predates the route, which\n * `isThreadRenameUnavailableError` recognizes so callers can drop the action.\n */\nexport async function renameThread(\n backendUrl: string,\n auth: AuthConfig,\n opts: { threadId: string; title: string },\n): Promise<ThreadRenameResponse> {\n const base = getAthenaApiBaseUrl(backendUrl);\n const res = await fetch(`${base}/api/conversations/threads/rename`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...getAuthHeaders(auth) },\n body: JSON.stringify({\n thread_id: opts.threadId,\n title: opts.title,\n }),\n });\n if (!res.ok) {\n const refused = res.status === 401 || res.status === 403;\n const { routeMissing, detail } = classifyThreadRouteRejection(\n res.status,\n await getResponseErrorBody(res),\n opts.threadId,\n );\n throw new AthenaSdkError({\n code: refused ? 'auth_rejected' : 'thread_rename_failed',\n message: `Failed to rename thread: ${res.status}`,\n status: res.status,\n detail,\n hint: refused\n ? 'The credential cannot edit this thread (a viewer can pin a shared session, not retitle it).'\n : routeMissing\n ? 'The backend has no rename route yet (older agora); sessions cannot be renamed from here until it deploys.'\n : res.status === 404\n ? 'The thread no longer exists on the server (archived or deleted elsewhere); refresh the list.'\n : res.status === 422\n ? `The title must be 1–${THREAD_TITLE_MAX_LENGTH} characters after trimming.`\n : 'Check backendUrl points at the Agora API base.',\n context: { thread_id: opts.threadId, auth_mode: getAuthMode(auth), route_missing: routeMissing },\n });\n }\n return res.json();\n}\n\n/**\n * True when `renameThread` failed because the backend has no rename route\n * (a 405, or a 404 whose body does not name the thread); a 404 for a thread\n * that is gone is a per-row failure and leaves the action offered.\n */\nexport function isThreadRenameUnavailableError(error: unknown): boolean {\n return isThreadRouteUnavailableError(error, 'thread_rename_failed');\n}\n\n/**\n * True when `archiveThread` failed because the backend offers no archive\n * route: a 405, FastAPI's bare 404 on an agora without the route, or the\n * route's own `\"Endpoint not available\"` 404 on an agora without the\n * checkpointer. The route's `\"Thread <id> not found\"` 404 for a stale row is\n * a per-row failure and leaves the action offered on every other row.\n */\nexport function isThreadArchiveUnavailableError(error: unknown): boolean {\n return isThreadRouteUnavailableError(error, 'thread_archive_failed');\n}\n\nexport async function createThread(\n backendUrl: string,\n auth: AuthConfig,\n opts: { systemPrompt?: string; enabledTools?: string[]; appId?: string } = {},\n): Promise<ThreadCreateResponse> {\n const base = getAthenaApiBaseUrl(backendUrl);\n const res = await fetch(`${base}/api/unstable/threads/`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...getAuthHeaders(auth) },\n body: JSON.stringify({\n config: {\n system_prompt: opts.systemPrompt ?? '',\n enabled_tools: opts.enabledTools,\n ...(opts.appId ? { app_id: opts.appId } : {}),\n },\n }),\n });\n if (!res.ok) {\n throw new Error(`[AthenaSDK] Failed to create thread: ${res.status}`);\n }\n return res.json();\n}\n\nexport interface ThreadStateResponse {\n thread_id: string;\n messages: unknown[];\n status?: string;\n [key: string]: unknown;\n}\n\ninterface ConversationThreadResponse {\n thread?: {\n thread_id?: string;\n state?: string | null;\n channel_values?: Record<string, unknown> | null;\n messages?: unknown[] | null;\n } | null;\n thread_found?: boolean;\n}\n\n/**\n * Deserialize a LangChain serialized message.\n * The API returns messages in `{lc, type: \"constructor\", id, kwargs}` format.\n * We need the plain format: `{type: \"human\", content: \"...\", id: \"...\"}`.\n */\nfunction deserializeMessage(msg: unknown): unknown {\n if (\n msg &&\n typeof msg === 'object' &&\n 'lc' in msg &&\n 'kwargs' in msg &&\n (msg as Record<string, unknown>).type === 'constructor'\n ) {\n const kwargs = (msg as { kwargs: Record<string, unknown> }).kwargs;\n\n // Recursively deserialize nested content without mutating the original\n const deserializedToolCalls = Array.isArray(kwargs.tool_calls)\n ? kwargs.tool_calls.map((tc: unknown) => {\n if (tc && typeof tc === 'object' && 'lc' in tc && 'kwargs' in tc) {\n return (tc as { kwargs: unknown }).kwargs;\n }\n return tc;\n })\n : kwargs.tool_calls;\n\n return { ...kwargs, tool_calls: deserializedToolCalls };\n }\n return msg;\n}\n\n/** Return a non-sensitive auth label for request diagnostics. */\nfunction getAuthMode(auth: AuthConfig): 'bearer' | 'api-key' | 'none' {\n if (auth.token) {\n return 'bearer';\n }\n if (auth.apiKey) {\n return 'api-key';\n }\n return 'none';\n}\n\n/** Safely read a response body for error messages without masking the root failure. */\nfunction getResponseErrorBody(response: Response): Promise<string> {\n return response.text().catch(() => '');\n}\n\n/**\n * Fetch persisted thread state from the conversations API.\n *\n * This endpoint is the same source used by Athena's conversation sidebar and\n * supports API-key auth plus BYO SSO session tokens sent as Bearer tokens.\n */\nexport async function getThreadState(\n backendUrl: string,\n auth: AuthConfig,\n threadId: string,\n opts: {\n /**\n * Bypass the server's Redis thread cache and read the checkpoint (default\n * `true`, the history load's contract). A warm-up read that only seeds a\n * first paint passes `false`: the cached copy is cheaper and the attach\n * snapshot replaces it anyway.\n */\n skipCache?: boolean;\n signal?: AbortSignal;\n } = {},\n): Promise<ThreadStateResponse> {\n const base = getAthenaApiBaseUrl(backendUrl);\n const authMode = getAuthMode(auth);\n const endpoint = `${base}/api/conversations/threads/get`;\n\n const endSpan = athenaDiagnostics.span('threads.history', 'threads.history.start', {\n thread_id: threadId,\n auth_mode: authMode,\n });\n\n let res: Response;\n try {\n res = await fetch(endpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...getAuthHeaders(auth) },\n signal: opts.signal ?? null,\n body: JSON.stringify({\n thread_id: threadId,\n skip_cache: opts.skipCache ?? true,\n }),\n });\n } catch (error) {\n if (isAbortError(error)) {\n endSpan('threads.history.aborted', {\n data: { thread_id: threadId, reason: 'request aborted' },\n });\n } else {\n endSpan('threads.history.error', { error, data: { thread_id: threadId } });\n }\n throw error;\n }\n if (!res.ok) {\n const body = await getResponseErrorBody(res);\n const error = new AthenaSdkError({\n code: res.status === 401 || res.status === 403 ? 'auth_rejected' : 'thread_load_failed',\n message: `Failed to get thread state: ${res.status} (${authMode})${\n body ? `: ${body.slice(0, 300)}` : ''\n }`,\n status: res.status,\n hint: 'A brand-new thread may not be persisted yet; anything else means the credential or backendUrl is wrong.',\n context: { thread_id: threadId, auth_mode: authMode },\n });\n endSpan('threads.history.error', { error, data: { thread_id: threadId } });\n throw error;\n }\n const data = (await res.json()) as ConversationThreadResponse;\n const channelMessages = data.thread?.channel_values?.messages;\n endSpan('threads.history.done', {\n data: {\n thread_id: threadId,\n found: data.thread_found !== false,\n message_count: Array.isArray(channelMessages)\n ? channelMessages.length\n : (data.thread?.messages?.length ?? 0),\n },\n });\n const thread = data.thread;\n\n if (data.thread_found === false || !thread) {\n return {\n thread_id: threadId,\n messages: [],\n };\n }\n\n const channelValues = thread.channel_values ?? {};\n const rawMessages = Array.isArray(channelValues.messages)\n ? channelValues.messages\n : Array.isArray(thread.messages)\n ? thread.messages\n : [];\n\n return {\n ...channelValues,\n thread_id: thread.thread_id ?? threadId,\n messages: rawMessages.map(deserializeMessage),\n ...(thread.state ? { status: thread.state } : {}),\n };\n}\n\n/**\n * Archive a thread (`POST /api/conversations/threads/archive`): it leaves\n * every list but keeps its state. Rejections: 401 / 403 when the caller\n * cannot access the thread (`auth_rejected`), otherwise\n * `thread_archive_failed` with the HTTP status — 404 / 405 when the backend\n * has no archive route, which `isThreadArchiveUnavailableError` recognizes.\n */\nexport async function archiveThread(\n backendUrl: string,\n auth: AuthConfig,\n threadId: string,\n): Promise<void> {\n const base = getAthenaApiBaseUrl(backendUrl);\n const res = await fetch(`${base}/api/conversations/threads/archive`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...getAuthHeaders(auth) },\n body: JSON.stringify({ thread_id: threadId }),\n });\n if (!res.ok) {\n const refused = res.status === 401 || res.status === 403;\n const { routeMissing, detail } = classifyThreadRouteRejection(\n res.status,\n await getResponseErrorBody(res),\n threadId,\n );\n throw new AthenaSdkError({\n code: refused ? 'auth_rejected' : 'thread_archive_failed',\n message: `Failed to archive thread: ${res.status}`,\n status: res.status,\n detail,\n hint: refused\n ? 'The credential cannot access this thread.'\n : routeMissing\n ? 'The backend has no archive route (no checkpointer, or an older agora).'\n : res.status === 404\n ? 'The thread no longer exists on the server (archived or deleted elsewhere); refresh the list.'\n : 'Check backendUrl points at the Agora API base.',\n context: { thread_id: threadId, auth_mode: getAuthMode(auth), route_missing: routeMissing },\n });\n }\n}\n"],"names":["athenaDiagn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,IACL,GAAG;AAAA,IACH,WAAW,OAAO,aAAa;AAAA,IAC/B,UAAU,YAAY,IAAI,kBAAkB;AAAA,IAC5C,GAAI,OAAO,QAAQ,EAAE,QAAQ,OAAO,MAAA,IAAU,CAAA;AAAA,EAAC;AAEnD;AASA,eAAsB,cACpB,YACA,MACA,UACe;AACf,QAAM,OAAO,oBAAoB,UAAU;AAC3C,QAAM,MAAM,MAAM,MAAM,GAAG,IAAI,sCAAsC;AAAA,IACnE,QAAQ;AAAA,IACR,SAAS,EAAE,gBAAgB,oBAAoB,GAAG,eAAe,IAAI,EAAA;AAAA,IACrE,MAAM,KAAK,UAAU,EAAE,WAAW,UAAU;AAAA,EAAA,CAC7C;AACD,MAAI,CAAC,IAAI,IAAI;AACX,UAAM,UAAU,IAAI,WAAW,OAAO,IAAI,WAAW;AACrD,UAAM,EAAE,cAAc,OAAA,IAAW;AAAA,MAC/B,IAAI;AAAA,MACJ,MAAM,qBAAqB,GAAG;AAAA,MAC9B;AAAA,IAAA;AAEF,UAAM,IAAIA,OAAAA,eAAe;AAAA,MACvB,MAAM,UAAU,kBAAkB;AAAA,MAClC,SAAS,6BAA6B,IAAI,MAAM;AAAA,MAChD,QAAQ,IAAI;AAAA,MACZ;AAAA,MACA,MAAM,UACF,8CACA,eACE,2EACA,IAAI,WAAW,MACb,iGACA;AAAA,MACR,SAAS,EAAE,WAAW,UAAU,WAAW,YAAY,IAAI,GAAG,eAAe,aAAA;AAAA,IAAa,CAC3F;AAAA,EACH;AACF;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"api.cjs","sources":["../../src/threads/api.ts"],"sourcesContent":["/**\n * Athena thread API client.\n * Calls existing REST endpoints for thread CRUD.\n */\n\nimport type {\n ConversationAttention,\n ConversationAttentionSource,\n} from '@athenaintel/agent-runtime';\nimport { athenaDiagnostics } from '../diagnostics/athena-diagnostics';\nimport { AthenaSdkError, type AthenaSdkErrorCode, isAthenaSdkError } from '../diagnostics/errors';\n\n/**\n * Live GitHub state of a pull request the thread opened, read by the server\n * when the list renders (agora `agent_pr_threads` is the only stored link).\n */\nexport interface ThreadPullRequest {\n /** `owner/repo` the pull request lives in. */\n repo_full_name: string;\n number: number;\n url: string;\n title: string;\n state: 'OPEN' | 'CLOSED' | 'MERGED';\n is_draft: boolean;\n /** GitHub's review decision (APPROVED, CHANGES_REQUESTED, REVIEW_REQUIRED) or null. */\n review_decision: string | null;\n /** Combined state of the checks on the head commit. */\n checks_state: 'SUCCESS' | 'FAILURE' | 'PENDING' | 'NONE';\n /** ISO 8601 timestamp of the pull request's last update on GitHub. */\n updated_at: string;\n}\n\n/** The last event that woke a resting thread (a GitHub webhook, a schedule, a handoff). */\nexport interface ThreadWake {\n source: string | null;\n reason: string | null;\n /** ISO 8601 timestamp of the wake. */\n at: string | null;\n}\n\nexport interface ThreadSummary {\n thread_id: string;\n title: string;\n created_at: string;\n updated_at: string;\n last_message: string | null;\n message_count: number;\n state: string | null;\n start_channel?: string | null;\n last_channel?: string | null;\n /** Client app that created the session (SESSION_APP_ID_GUIDE). */\n app_id?: string | null;\n /** Collab agent and channel the session started on; older servers omit them. */\n collab_agent_id?: string | null;\n collab_channel_id?: string | null;\n /** Trigger marker for automated/background sessions. */\n trigger_type?: string | null;\n /** Whether the calling user has seen this thread since it last changed. */\n is_unread?: boolean;\n /**\n * Canonical status_v2 planes (`idle | active | needs_input | error` and\n * `scheduled | queued | running | needs_input | completed | failed |\n * canceled`); older servers omit them.\n */\n session_status?: string | null;\n run_status?: string | null;\n /**\n * The viewer's attention state, the one-line next action (≤ 80 chars) and\n * the signal that produced them, derived server-side; older servers omit them.\n */\n attention?: ConversationAttention | null;\n next_action?: string | null;\n attention_source?: ConversationAttentionSource | null;\n /** Whether the calling user favorited (pinned) the thread; older servers omit it. */\n is_favorited?: boolean;\n /** The last wake of a resting thread; older servers omit it. */\n last_wake?: ThreadWake | null;\n /** Whether the calling user started the thread (`false`: shared with them); older servers omit it. */\n created_by_me?: boolean;\n /**\n * Pull requests the thread opened with their live GitHub state. `[]` when\n * it opened none, `null` when the state could not be read right now;\n * older servers omit the field.\n */\n pull_requests?: ThreadPullRequest[] | null;\n}\n\n/**\n * True for fetch cancellations (unmount/remount aborts, StrictMode double\n * effects). These are lifecycle noise, not failures: emitting them as\n * `*.error` diagnostics floods the console with\n * \"signal is aborted without reason\" for requests the caller itself aborted.\n */\nfunction isAbortError(error: unknown): boolean {\n return (\n (error instanceof DOMException && error.name === 'AbortError') ||\n (error instanceof Error && error.name === 'AbortError')\n );\n}\n\nexport interface ThreadListResponse {\n threads: ThreadSummary[];\n /** Server lookahead result. Older servers may omit this field. */\n has_more?: boolean;\n /**\n * Every request field the server applies beyond paging. The server ignores\n * fields it does not know, so a filter missing from this list came back\n * unapplied; servers that predate the list omit it (none of the\n * `ThreadListFilterBody` fields are applied there).\n */\n supported_filters?: string[];\n}\n\n/**\n * The server-side filters and order of `POST /api/conversations/threads/list`\n * beyond the original `app_id` / `start_channel` / `search` /\n * `exclude_triggered` set. Each is a predicate of the server's one page\n * statement, so a page is exact; a server that predates a field ignores it\n * (check `ThreadListResponse.supported_filters`).\n */\nexport interface ThreadListFilterBody {\n /** Original fields, accepted here too so one body can carry a whole query. */\n search?: string;\n exclude_triggered?: boolean;\n app_ids?: string[];\n start_channels?: string[];\n created_after?: string;\n created_before?: string;\n updated_after?: string;\n updated_before?: string;\n collab_agent_ids?: string[];\n /** `'default'` matches the agent's default channel (no channel stamp); needs `collab_agent_ids`. */\n collab_channel_ids?: string[];\n favorites_only?: boolean;\n unread_only?: boolean;\n run_statuses?: string[];\n session_statuses?: string[];\n has_pull_requests?: boolean;\n created_by_me?: boolean;\n exclude_dismissed?: boolean;\n sort?: 'updated' | 'created';\n direction?: 'desc' | 'asc';\n}\n\nexport interface ThreadCreateResponse {\n thread_id: string;\n}\n\ninterface AuthConfig {\n apiKey?: string;\n token?: string | null;\n credentials?: RequestCredentials;\n}\n\nfunction getAuthHeaders(auth: AuthConfig): Record<string, string> {\n if (auth.token) {\n return { Authorization: `Bearer ${auth.token}` };\n }\n if (auth.apiKey) {\n return { 'X-API-KEY': auth.apiKey };\n }\n return {};\n}\n\n/**\n * Resolves the Athena API base URL from backendUrl.\n * Thread endpoints live under `/api/conversations/threads/*` and `/api/unstable/threads/`.\n * If backendUrl points at a nested Athena endpoint, trim it back to the API base first.\n */\nfunction getAthenaApiBaseUrl(backendUrl: string): string {\n const stripped = backendUrl.replace(/\\/api\\/assistant-ui\\/?$/, '');\n // If the suffix wasn't found, assume the URL already points to the API base\n if (stripped === backendUrl) {\n return backendUrl.replace(/\\/$/, '');\n }\n return stripped;\n}\n\nexport async function listThreads(\n backendUrl: string,\n auth: AuthConfig,\n opts: {\n limit?: number;\n offset?: number;\n exclude_triggered?: boolean;\n app_id?: string;\n start_channel?: string;\n search?: string;\n /** Ask the server for live GitHub state on `pull_requests` (off by default: it costs a lookup). */\n include_pull_requests?: boolean;\n /** Server-side filters and order beyond the original set (see `ThreadListFilterBody`). */\n filters?: ThreadListFilterBody;\n signal?: AbortSignal;\n } = {},\n): Promise<ThreadListResponse> {\n const base = getAthenaApiBaseUrl(backendUrl);\n const endSpan = athenaDiagnostics.span('threads.list', 'threads.list.start', {\n auth_mode: getAuthMode(auth),\n app_id: opts.app_id,\n });\n try {\n const res = await fetch(`${base}/api/conversations/threads/list`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...getAuthHeaders(auth) },\n signal: opts.signal ?? null,\n body: JSON.stringify({\n limit: opts.limit ?? 50,\n offset: opts.offset ?? 0,\n // Default to the full recent-conversations set unless a caller\n // explicitly asks to hide triggered/background sessions.\n exclude_triggered: opts.exclude_triggered ?? false,\n ...(opts.app_id ? { app_id: opts.app_id } : {}),\n ...(opts.start_channel ? { start_channel: opts.start_channel } : {}),\n ...(opts.search ? { search: opts.search } : {}),\n ...(opts.include_pull_requests ? { include_pull_requests: true } : {}),\n ...opts.filters,\n }),\n });\n if (!res.ok) {\n throw new AthenaSdkError({\n code: res.status === 401 || res.status === 403 ? 'auth_rejected' : 'threads_list_failed',\n message: `Failed to list threads: ${res.status}`,\n status: res.status,\n hint:\n res.status === 401 || res.status === 403\n ? 'The credential was refused. Check the token/API key and that the user belongs to the workspace.'\n : 'Check backendUrl points at the Agora API base.',\n context: { auth_mode: getAuthMode(auth) },\n });\n }\n const data = (await res.json()) as ThreadListResponse;\n endSpan('threads.list.done', { data: { count: data.threads?.length ?? 0 } });\n return data;\n } catch (error) {\n // Cancellation is lifecycle noise (unmount/remount aborts): log it as an\n // informational abort, not an error — passing `error` would force the\n // span end to error level and spam the console.\n if (isAbortError(error)) {\n endSpan('threads.list.aborted', { data: { reason: 'request aborted' } });\n } else {\n endSpan('threads.list.error', { error });\n }\n throw error;\n }\n}\n\n/** The `(workspace, user)` pair the credential resolves to on the backend. */\nexport interface AccountIdentity {\n userId: string;\n /** `null` for a user with no current workspace. */\n workspaceId: string | null;\n}\n\n/**\n * Resolve the credential's agora identity. The conversation index is one\n * statewire instance per `(workspace, user)`, and neither half is knowable\n * from the credential alone: the SDK's auth context carries an identity\n * provider user id, not agora's, and never a workspace.\n */\nexport async function fetchAccountIdentity(\n backendUrl: string,\n auth: AuthConfig,\n opts: { signal?: AbortSignal } = {},\n): Promise<AccountIdentity> {\n const base = getAthenaApiBaseUrl(backendUrl);\n const res = await fetch(`${base}/api/v0/me`, {\n headers: getAuthHeaders(auth),\n signal: opts.signal ?? null,\n credentials: auth.credentials,\n });\n if (!res.ok) {\n throw new AthenaSdkError({\n code: res.status === 401 || res.status === 403 ? 'auth_rejected' : 'threads_list_failed',\n message: `Failed to resolve account identity: ${res.status}`,\n status: res.status,\n hint:\n res.status === 401 || res.status === 403\n ? 'The credential was refused. Check the token/API key and that the user belongs to the workspace.'\n : 'Check backendUrl points at the Agora API base.',\n context: { auth_mode: getAuthMode(auth) },\n });\n }\n const body = (await res.json()) as { user_id?: unknown; workspace_id?: unknown };\n if (typeof body.user_id !== 'string' || body.user_id.length === 0) {\n throw new AthenaSdkError({\n code: 'threads_list_failed',\n message: 'Account identity lookup returned no user id.',\n context: { auth_mode: getAuthMode(auth) },\n });\n }\n return {\n userId: body.user_id,\n workspaceId: typeof body.workspace_id === 'string' ? body.workspace_id : null,\n };\n}\n\nexport interface ThreadReadStateResponse {\n thread_id: string;\n is_unread: boolean;\n}\n\n/** Store the calling user's read receipt for a thread. */\nexport async function setThreadReadState(\n backendUrl: string,\n auth: AuthConfig,\n opts: { threadId: string; isUnread: boolean },\n): Promise<ThreadReadStateResponse> {\n const base = getAthenaApiBaseUrl(backendUrl);\n const res = await fetch(`${base}/api/conversations/threads/read-state`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...getAuthHeaders(auth) },\n body: JSON.stringify({\n thread_id: opts.threadId,\n is_unread: opts.isUnread,\n }),\n });\n if (!res.ok) {\n throw new AthenaSdkError({\n code: res.status === 401 || res.status === 403 ? 'auth_rejected' : 'unknown',\n message: `Failed to set thread read state: ${res.status}`,\n status: res.status,\n });\n }\n return res.json();\n}\n\nexport interface ThreadInboxDismissResponse {\n success: boolean;\n dismissed: boolean;\n}\n\n/**\n * Dismiss a session from the inbox, or bring it back\n * (`POST /api/conversations/threads/notifications/dismiss`). A dismissed\n * session returns on its own with its next message. The state lives on the\n * session for its creator's inbox, so the route takes EDIT on the session\n * (403 for a VIEW share).\n */\nexport async function dismissThreadFromInbox(\n backendUrl: string,\n auth: AuthConfig,\n opts: { threadId: string; dismissed: boolean },\n): Promise<ThreadInboxDismissResponse> {\n const base = getAthenaApiBaseUrl(backendUrl);\n const res = await fetch(`${base}/api/conversations/threads/notifications/dismiss`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...getAuthHeaders(auth) },\n body: JSON.stringify({ thread_id: opts.threadId, dismissed: opts.dismissed }),\n });\n if (!res.ok) {\n throw new AthenaSdkError({\n code: res.status === 401 || res.status === 403 ? 'auth_rejected' : 'unknown',\n message: `Failed to ${opts.dismissed ? 'dismiss' : 'restore'} the session: ${res.status}`,\n status: res.status,\n hint:\n res.status === 403\n ? 'Only someone who can edit the session (its creator, usually) can dismiss it from the inbox.'\n : undefined,\n context: { thread_id: opts.threadId, auth_mode: getAuthMode(auth) },\n });\n }\n return res.json();\n}\n\nexport interface ThreadFavoriteResponse {\n thread_id: string;\n /** The server's state after the write. */\n is_favorited: boolean;\n}\n\n/**\n * Classify a 4xx from one of the per-thread write routes (`favorite`,\n * `rename`, `archive`). A 404 there is ambiguous: FastAPI answers\n * `{\"detail\":\"Not Found\"}` for a route an older agora does not have, the\n * archive route answers `\"Endpoint not available\"` on an agora without the\n * checkpointer — and each route answers 404 for a thread that no longer\n * exists (`\"Thread <id> not found\"`, `\"Conversation with langchain thread id\n * <id> not found\"`). The routes' own not-found answers name the thread, so a\n * body that does not is the ROUTE missing, and only that withdraws the\n * feature; a stale row must not disable the action for every other row.\n */\nfunction classifyThreadRouteRejection(\n status: number,\n body: string,\n threadId: string,\n): { routeMissing: boolean; detail: unknown } {\n let detail: unknown = body || undefined;\n try {\n const parsed: unknown = JSON.parse(body);\n if (parsed && typeof parsed === 'object') {\n const record = parsed as { detail?: unknown; message?: unknown };\n detail = record.detail ?? record.message ?? parsed;\n }\n } catch {\n // A non-JSON body (a proxy page) is kept as text.\n }\n const routeMissing = status === 405 || (status === 404 && !mentionsThread(body, threadId));\n return { routeMissing, detail };\n}\n\n/**\n * Whether an error body names the thread as a whole token (the routes embed\n * the id between spaces: `Thread <id> not found`); a substring match would\n * let a short id match a letter inside `\"detail\"`.\n */\nfunction mentionsThread(body: string, threadId: string): boolean {\n if (!threadId) return false;\n const escaped = threadId.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return new RegExp(`(^|[^A-Za-z0-9_-])${escaped}($|[^A-Za-z0-9_-])`).test(body);\n}\n\n/** True when a per-thread write was rejected because the backend has no such route. */\nfunction isThreadRouteUnavailableError(error: unknown, code: AthenaSdkErrorCode): boolean {\n return isAthenaSdkError(error) && error.code === code && error.context.route_missing === true;\n}\n\n/**\n * Pin (favorite) or unpin a thread for the calling user. The response is the\n * server's truth after the write. Rejections: 401 / 403 when the caller\n * cannot view the thread (`auth_rejected`), otherwise `thread_favorite_failed`\n * with the HTTP status — 404 / 405 from an agora that predates the route,\n * which `isThreadFavoriteUnavailableError` recognizes so callers can fall\n * back to a read-only pin.\n */\nexport async function setThreadFavorite(\n backendUrl: string,\n auth: AuthConfig,\n opts: { threadId: string; isFavorited: boolean },\n): Promise<ThreadFavoriteResponse> {\n const base = getAthenaApiBaseUrl(backendUrl);\n const res = await fetch(`${base}/api/conversations/threads/favorite`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...getAuthHeaders(auth) },\n body: JSON.stringify({\n thread_id: opts.threadId,\n is_favorited: opts.isFavorited,\n }),\n });\n if (!res.ok) {\n const refused = res.status === 401 || res.status === 403;\n const { routeMissing, detail } = classifyThreadRouteRejection(\n res.status,\n await getResponseErrorBody(res),\n opts.threadId,\n );\n throw new AthenaSdkError({\n code: refused ? 'auth_rejected' : 'thread_favorite_failed',\n message: `Failed to set thread favorite: ${res.status}`,\n status: res.status,\n detail,\n hint: refused\n ? 'The credential cannot view this thread.'\n : routeMissing\n ? 'The backend has no favorite route yet (older agora); the pin stays read-only until it deploys.'\n : res.status === 404\n ? 'The thread no longer exists on the server (archived or deleted elsewhere); refresh the list.'\n : 'Check backendUrl points at the Agora API base.',\n context: { thread_id: opts.threadId, auth_mode: getAuthMode(auth), route_missing: routeMissing },\n });\n }\n return res.json();\n}\n\n/**\n * True when `setThreadFavorite` failed because the backend has no favorite\n * route (a 405, or a 404 whose body does not name the thread — see\n * `classifyThreadRouteRejection`); a 404 for a thread that is gone is a\n * per-row failure and leaves the toggle available.\n */\nexport function isThreadFavoriteUnavailableError(error: unknown): boolean {\n return isThreadRouteUnavailableError(error, 'thread_favorite_failed');\n}\n\nexport interface ThreadRenameResponse {\n thread_id: string;\n /** The stored title after the write (trimmed by the server). */\n title: string;\n}\n\n/** The longest title the rename route accepts; the server answers 422 past it. */\nexport const THREAD_TITLE_MAX_LENGTH = 200;\n\n/**\n * Rename a thread for every viewer (`POST /api/conversations/threads/rename`).\n * The server trims the title and stores 1–200 characters; the response is the\n * row's title after the write. Rejections: 401 / 403 when the caller cannot\n * edit the thread (`auth_rejected` — a viewer can pin a shared session but not\n * retitle it), otherwise `thread_rename_failed` with the HTTP status — 404 /\n * 405 from an agora that predates the route, which\n * `isThreadRenameUnavailableError` recognizes so callers can drop the action.\n */\nexport async function renameThread(\n backendUrl: string,\n auth: AuthConfig,\n opts: { threadId: string; title: string },\n): Promise<ThreadRenameResponse> {\n const base = getAthenaApiBaseUrl(backendUrl);\n const res = await fetch(`${base}/api/conversations/threads/rename`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...getAuthHeaders(auth) },\n body: JSON.stringify({\n thread_id: opts.threadId,\n title: opts.title,\n }),\n });\n if (!res.ok) {\n const refused = res.status === 401 || res.status === 403;\n const { routeMissing, detail } = classifyThreadRouteRejection(\n res.status,\n await getResponseErrorBody(res),\n opts.threadId,\n );\n throw new AthenaSdkError({\n code: refused ? 'auth_rejected' : 'thread_rename_failed',\n message: `Failed to rename thread: ${res.status}`,\n status: res.status,\n detail,\n hint: refused\n ? 'The credential cannot edit this thread (a viewer can pin a shared session, not retitle it).'\n : routeMissing\n ? 'The backend has no rename route yet (older agora); sessions cannot be renamed from here until it deploys.'\n : res.status === 404\n ? 'The thread no longer exists on the server (archived or deleted elsewhere); refresh the list.'\n : res.status === 422\n ? `The title must be 1–${THREAD_TITLE_MAX_LENGTH} characters after trimming.`\n : 'Check backendUrl points at the Agora API base.',\n context: { thread_id: opts.threadId, auth_mode: getAuthMode(auth), route_missing: routeMissing },\n });\n }\n return res.json();\n}\n\n/**\n * True when `renameThread` failed because the backend has no rename route\n * (a 405, or a 404 whose body does not name the thread); a 404 for a thread\n * that is gone is a per-row failure and leaves the action offered.\n */\nexport function isThreadRenameUnavailableError(error: unknown): boolean {\n return isThreadRouteUnavailableError(error, 'thread_rename_failed');\n}\n\n/**\n * True when `archiveThread` failed because the backend offers no archive\n * route: a 405, FastAPI's bare 404 on an agora without the route, or the\n * route's own `\"Endpoint not available\"` 404 on an agora without the\n * checkpointer. The route's `\"Thread <id> not found\"` 404 for a stale row is\n * a per-row failure and leaves the action offered on every other row.\n */\nexport function isThreadArchiveUnavailableError(error: unknown): boolean {\n return isThreadRouteUnavailableError(error, 'thread_archive_failed');\n}\n\nexport async function createThread(\n backendUrl: string,\n auth: AuthConfig,\n opts: { systemPrompt?: string; enabledTools?: string[]; appId?: string } = {},\n): Promise<ThreadCreateResponse> {\n const base = getAthenaApiBaseUrl(backendUrl);\n const res = await fetch(`${base}/api/unstable/threads/`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...getAuthHeaders(auth) },\n body: JSON.stringify({\n config: {\n system_prompt: opts.systemPrompt ?? '',\n enabled_tools: opts.enabledTools,\n ...(opts.appId ? { app_id: opts.appId } : {}),\n },\n }),\n });\n if (!res.ok) {\n throw new Error(`[AthenaSDK] Failed to create thread: ${res.status}`);\n }\n return res.json();\n}\n\nexport interface ThreadStateResponse {\n thread_id: string;\n messages: unknown[];\n status?: string;\n [key: string]: unknown;\n}\n\ninterface ConversationThreadResponse {\n thread?: {\n thread_id?: string;\n state?: string | null;\n channel_values?: Record<string, unknown> | null;\n messages?: unknown[] | null;\n } | null;\n thread_found?: boolean;\n}\n\n/**\n * Deserialize a LangChain serialized message.\n * The API returns messages in `{lc, type: \"constructor\", id, kwargs}` format.\n * We need the plain format: `{type: \"human\", content: \"...\", id: \"...\"}`.\n */\nfunction deserializeMessage(msg: unknown): unknown {\n if (\n msg &&\n typeof msg === 'object' &&\n 'lc' in msg &&\n 'kwargs' in msg &&\n (msg as Record<string, unknown>).type === 'constructor'\n ) {\n const kwargs = (msg as { kwargs: Record<string, unknown> }).kwargs;\n\n // Recursively deserialize nested content without mutating the original\n const deserializedToolCalls = Array.isArray(kwargs.tool_calls)\n ? kwargs.tool_calls.map((tc: unknown) => {\n if (tc && typeof tc === 'object' && 'lc' in tc && 'kwargs' in tc) {\n return (tc as { kwargs: unknown }).kwargs;\n }\n return tc;\n })\n : kwargs.tool_calls;\n\n return { ...kwargs, tool_calls: deserializedToolCalls };\n }\n return msg;\n}\n\n/** Return a non-sensitive auth label for request diagnostics. */\nfunction getAuthMode(auth: AuthConfig): 'bearer' | 'api-key' | 'none' {\n if (auth.token) {\n return 'bearer';\n }\n if (auth.apiKey) {\n return 'api-key';\n }\n return 'none';\n}\n\n/** Safely read a response body for error messages without masking the root failure. */\nfunction getResponseErrorBody(response: Response): Promise<string> {\n return response.text().catch(() => '');\n}\n\n/**\n * Fetch persisted thread state from the conversations API.\n *\n * This endpoint is the same source used by Athena's conversation sidebar and\n * supports API-key auth plus BYO SSO session tokens sent as Bearer tokens.\n */\nexport async function getThreadState(\n backendUrl: string,\n auth: AuthConfig,\n threadId: string,\n opts: {\n /**\n * Bypass the server's Redis thread cache and read the checkpoint (default\n * `true`, the history load's contract). A warm-up read that only seeds a\n * first paint passes `false`: the cached copy is cheaper and the attach\n * snapshot replaces it anyway.\n */\n skipCache?: boolean;\n signal?: AbortSignal;\n } = {},\n): Promise<ThreadStateResponse> {\n const base = getAthenaApiBaseUrl(backendUrl);\n const authMode = getAuthMode(auth);\n const endpoint = `${base}/api/conversations/threads/get`;\n\n const endSpan = athenaDiagnostics.span('threads.history', 'threads.history.start', {\n thread_id: threadId,\n auth_mode: authMode,\n });\n\n let res: Response;\n try {\n res = await fetch(endpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...getAuthHeaders(auth) },\n signal: opts.signal ?? null,\n body: JSON.stringify({\n thread_id: threadId,\n skip_cache: opts.skipCache ?? true,\n }),\n });\n } catch (error) {\n if (isAbortError(error)) {\n endSpan('threads.history.aborted', {\n data: { thread_id: threadId, reason: 'request aborted' },\n });\n } else {\n endSpan('threads.history.error', { error, data: { thread_id: threadId } });\n }\n throw error;\n }\n if (!res.ok) {\n const body = await getResponseErrorBody(res);\n const error = new AthenaSdkError({\n code: res.status === 401 || res.status === 403 ? 'auth_rejected' : 'thread_load_failed',\n message: `Failed to get thread state: ${res.status} (${authMode})${\n body ? `: ${body.slice(0, 300)}` : ''\n }`,\n status: res.status,\n hint: 'A brand-new thread may not be persisted yet; anything else means the credential or backendUrl is wrong.',\n context: { thread_id: threadId, auth_mode: authMode },\n });\n endSpan('threads.history.error', { error, data: { thread_id: threadId } });\n throw error;\n }\n const data = (await res.json()) as ConversationThreadResponse;\n const channelMessages = data.thread?.channel_values?.messages;\n endSpan('threads.history.done', {\n data: {\n thread_id: threadId,\n found: data.thread_found !== false,\n message_count: Array.isArray(channelMessages)\n ? channelMessages.length\n : (data.thread?.messages?.length ?? 0),\n },\n });\n const thread = data.thread;\n\n if (data.thread_found === false || !thread) {\n return {\n thread_id: threadId,\n messages: [],\n };\n }\n\n const channelValues = thread.channel_values ?? {};\n const rawMessages = Array.isArray(channelValues.messages)\n ? channelValues.messages\n : Array.isArray(thread.messages)\n ? thread.messages\n : [];\n\n return {\n ...channelValues,\n thread_id: thread.thread_id ?? threadId,\n messages: rawMessages.map(deserializeMessage),\n ...(thread.state ? { status: thread.state } : {}),\n };\n}\n\n/**\n * Archive a thread (`POST /api/conversations/threads/archive`): it leaves\n * every list but keeps its state. Rejections: 401 / 403 when the caller\n * cannot access the thread (`auth_rejected`), otherwise\n * `thread_archive_failed` with the HTTP status — 404 / 405 when the backend\n * has no archive route, which `isThreadArchiveUnavailableError` recognizes.\n */\nexport async function archiveThread(\n backendUrl: string,\n auth: AuthConfig,\n threadId: string,\n): Promise<void> {\n const base = getAthenaApiBaseUrl(backendUrl);\n const res = await fetch(`${base}/api/conversations/threads/archive`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...getAuthHeaders(auth) },\n body: JSON.stringify({ thread_id: threadId }),\n });\n if (!res.ok) {\n const refused = res.status === 401 || res.status === 403;\n const { routeMissing, detail } = classifyThreadRouteRejection(\n res.status,\n await getResponseErrorBody(res),\n threadId,\n );\n throw new AthenaSdkError({\n code: refused ? 'auth_rejected' : 'thread_archive_failed',\n message: `Failed to archive thread: ${res.status}`,\n status: res.status,\n detail,\n hint: refused\n ? 'The credential cannot access this thread.'\n : routeMissing\n ? 'The backend has no archive route (no checkpointer, or an older agora).'\n : res.status === 404\n ? 'The thread no longer exists on the server (archived or deleted elsewhere); refresh the list.'\n : 'Check backendUrl points at the Agora API base.',\n context: { thread_id: threadId, auth_mode: getAuthMode(auth), route_missing: routeMissing },\n });\n }\n}\n"],"names":["athenaDiagnostics","AthenaSdkError","isAthenaSdkError"],"mappings":";;;;AA6FA,SAAS,aAAa,OAAyB;AAC7C,SACG,iBAAiB,gBAAgB,MAAM,SAAS,gBAChD,iBAAiB,SAAS,MAAM,SAAS;AAE9C;AAwDA,SAAS,eAAe,MAA0C;AAChE,MAAI,KAAK,OAAO;AACd,WAAO,EAAE,eAAe,UAAU,KAAK,KAAK,GAAA;AAAA,EAC9C;AACA,MAAI,KAAK,QAAQ;AACf,WAAO,EAAE,aAAa,KAAK,OAAA;AAAA,EAC7B;AACA,SAAO,CAAA;AACT;AAOA,SAAS,oBAAoB,YAA4B;AACvD,QAAM,WAAW,WAAW,QAAQ,2BAA2B,EAAE;AAEjE,MAAI,aAAa,YAAY;AAC3B,WAAO,WAAW,QAAQ,OAAO,EAAE;AAAA,EACrC;AACA,SAAO;AACT;AAEA,eAAsB,YACpB,YACA,MACA,OAYI,CAAA,GACyB;;AAC7B,QAAM,OAAO,oBAAoB,UAAU;AAC3C,QAAM,UAAUA,kBAAAA,kBAAkB,KAAK,gBAAgB,sBAAsB;AAAA,IAC3E,WAAW,YAAY,IAAI;AAAA,IAC3B,QAAQ,KAAK;AAAA,EAAA,CACd;AACD,MAAI;AACF,UAAM,MAAM,MAAM,MAAM,GAAG,IAAI,mCAAmC;AAAA,MAChE,QAAQ;AAAA,MACR,SAAS,EAAE,gBAAgB,oBAAoB,GAAG,eAAe,IAAI,EAAA;AAAA,MACrE,QAAQ,KAAK,UA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GAAG,eAAe,aAAA;AAAA,IAAa,CAC3F;AAAA,EACH;AACF;;;;;;;;;;;;;;"}
@@ -123,6 +123,7 @@ export interface ThreadCreateResponse {
123
123
  interface AuthConfig {
124
124
  apiKey?: string;
125
125
  token?: string | null;
126
+ credentials?: RequestCredentials;
126
127
  }
127
128
  export declare function listThreads(backendUrl: string, auth: AuthConfig, opts?: {
128
129
  limit?: number;
@@ -69,7 +69,8 @@ async function fetchAccountIdentity(backendUrl, auth, opts = {}) {
69
69
  const base = getAthenaApiBaseUrl(backendUrl);
70
70
  const res = await fetch(`${base}/api/v0/me`, {
71
71
  headers: getAuthHeaders(auth),
72
- signal: opts.signal ?? null
72
+ signal: opts.signal ?? null,
73
+ credentials: auth.credentials
73
74
  });
74
75
  if (!res.ok) {
75
76
  throw new AthenaSdkError({
@@ -1 +1 @@
1
- {"version":3,"file":"api.js","sources":["../../src/threads/api.ts"],"sourcesContent":["/**\n * Athena thread API client.\n * Calls existing REST endpoints for thread CRUD.\n */\n\nimport type {\n ConversationAttention,\n ConversationAttentionSource,\n} from '@athenaintel/agent-runtime';\nimport { athenaDiagnostics } from '../diagnostics/athena-diagnostics';\nimport { AthenaSdkError, type AthenaSdkErrorCode, isAthenaSdkError } from '../diagnostics/errors';\n\n/**\n * Live GitHub state of a pull request the thread opened, read by the server\n * when the list renders (agora `agent_pr_threads` is the only stored link).\n */\nexport interface ThreadPullRequest {\n /** `owner/repo` the pull request lives in. */\n repo_full_name: string;\n number: number;\n url: string;\n title: string;\n state: 'OPEN' | 'CLOSED' | 'MERGED';\n is_draft: boolean;\n /** GitHub's review decision (APPROVED, CHANGES_REQUESTED, REVIEW_REQUIRED) or null. */\n review_decision: string | null;\n /** Combined state of the checks on the head commit. */\n checks_state: 'SUCCESS' | 'FAILURE' | 'PENDING' | 'NONE';\n /** ISO 8601 timestamp of the pull request's last update on GitHub. */\n updated_at: string;\n}\n\n/** The last event that woke a resting thread (a GitHub webhook, a schedule, a handoff). */\nexport interface ThreadWake {\n source: string | null;\n reason: string | null;\n /** ISO 8601 timestamp of the wake. */\n at: string | null;\n}\n\nexport interface ThreadSummary {\n thread_id: string;\n title: string;\n created_at: string;\n updated_at: string;\n last_message: string | null;\n message_count: number;\n state: string | null;\n start_channel?: string | null;\n last_channel?: string | null;\n /** Client app that created the session (SESSION_APP_ID_GUIDE). */\n app_id?: string | null;\n /** Collab agent and channel the session started on; older servers omit them. */\n collab_agent_id?: string | null;\n collab_channel_id?: string | null;\n /** Trigger marker for automated/background sessions. */\n trigger_type?: string | null;\n /** Whether the calling user has seen this thread since it last changed. */\n is_unread?: boolean;\n /**\n * Canonical status_v2 planes (`idle | active | needs_input | error` and\n * `scheduled | queued | running | needs_input | completed | failed |\n * canceled`); older servers omit them.\n */\n session_status?: string | null;\n run_status?: string | null;\n /**\n * The viewer's attention state, the one-line next action (≤ 80 chars) and\n * the signal that produced them, derived server-side; older servers omit them.\n */\n attention?: ConversationAttention | null;\n next_action?: string | null;\n attention_source?: ConversationAttentionSource | null;\n /** Whether the calling user favorited (pinned) the thread; older servers omit it. */\n is_favorited?: boolean;\n /** The last wake of a resting thread; older servers omit it. */\n last_wake?: ThreadWake | null;\n /** Whether the calling user started the thread (`false`: shared with them); older servers omit it. */\n created_by_me?: boolean;\n /**\n * Pull requests the thread opened with their live GitHub state. `[]` when\n * it opened none, `null` when the state could not be read right now;\n * older servers omit the field.\n */\n pull_requests?: ThreadPullRequest[] | null;\n}\n\n/**\n * True for fetch cancellations (unmount/remount aborts, StrictMode double\n * effects). These are lifecycle noise, not failures: emitting them as\n * `*.error` diagnostics floods the console with\n * \"signal is aborted without reason\" for requests the caller itself aborted.\n */\nfunction isAbortError(error: unknown): boolean {\n return (\n (error instanceof DOMException && error.name === 'AbortError') ||\n (error instanceof Error && error.name === 'AbortError')\n );\n}\n\nexport interface ThreadListResponse {\n threads: ThreadSummary[];\n /** Server lookahead result. Older servers may omit this field. */\n has_more?: boolean;\n /**\n * Every request field the server applies beyond paging. The server ignores\n * fields it does not know, so a filter missing from this list came back\n * unapplied; servers that predate the list omit it (none of the\n * `ThreadListFilterBody` fields are applied there).\n */\n supported_filters?: string[];\n}\n\n/**\n * The server-side filters and order of `POST /api/conversations/threads/list`\n * beyond the original `app_id` / `start_channel` / `search` /\n * `exclude_triggered` set. Each is a predicate of the server's one page\n * statement, so a page is exact; a server that predates a field ignores it\n * (check `ThreadListResponse.supported_filters`).\n */\nexport interface ThreadListFilterBody {\n /** Original fields, accepted here too so one body can carry a whole query. */\n search?: string;\n exclude_triggered?: boolean;\n app_ids?: string[];\n start_channels?: string[];\n created_after?: string;\n created_before?: string;\n updated_after?: string;\n updated_before?: string;\n collab_agent_ids?: string[];\n /** `'default'` matches the agent's default channel (no channel stamp); needs `collab_agent_ids`. */\n collab_channel_ids?: string[];\n favorites_only?: boolean;\n unread_only?: boolean;\n run_statuses?: string[];\n session_statuses?: string[];\n has_pull_requests?: boolean;\n created_by_me?: boolean;\n exclude_dismissed?: boolean;\n sort?: 'updated' | 'created';\n direction?: 'desc' | 'asc';\n}\n\nexport interface ThreadCreateResponse {\n thread_id: string;\n}\n\ninterface AuthConfig {\n apiKey?: string;\n token?: string | null;\n}\n\nfunction getAuthHeaders(auth: AuthConfig): Record<string, string> {\n if (auth.token) {\n return { Authorization: `Bearer ${auth.token}` };\n }\n if (auth.apiKey) {\n return { 'X-API-KEY': auth.apiKey };\n }\n return {};\n}\n\n/**\n * Resolves the Athena API base URL from backendUrl.\n * Thread endpoints live under `/api/conversations/threads/*` and `/api/unstable/threads/`.\n * If backendUrl points at a nested Athena endpoint, trim it back to the API base first.\n */\nfunction getAthenaApiBaseUrl(backendUrl: string): string {\n const stripped = backendUrl.replace(/\\/api\\/assistant-ui\\/?$/, '');\n // If the suffix wasn't found, assume the URL already points to the API base\n if (stripped === backendUrl) {\n return backendUrl.replace(/\\/$/, '');\n }\n return stripped;\n}\n\nexport async function listThreads(\n backendUrl: string,\n auth: AuthConfig,\n opts: {\n limit?: number;\n offset?: number;\n exclude_triggered?: boolean;\n app_id?: string;\n start_channel?: string;\n search?: string;\n /** Ask the server for live GitHub state on `pull_requests` (off by default: it costs a lookup). */\n include_pull_requests?: boolean;\n /** Server-side filters and order beyond the original set (see `ThreadListFilterBody`). */\n filters?: ThreadListFilterBody;\n signal?: AbortSignal;\n } = {},\n): Promise<ThreadListResponse> {\n const base = getAthenaApiBaseUrl(backendUrl);\n const endSpan = athenaDiagnostics.span('threads.list', 'threads.list.start', {\n auth_mode: getAuthMode(auth),\n app_id: opts.app_id,\n });\n try {\n const res = await fetch(`${base}/api/conversations/threads/list`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...getAuthHeaders(auth) },\n signal: opts.signal ?? null,\n body: JSON.stringify({\n limit: opts.limit ?? 50,\n offset: opts.offset ?? 0,\n // Default to the full recent-conversations set unless a caller\n // explicitly asks to hide triggered/background sessions.\n exclude_triggered: opts.exclude_triggered ?? false,\n ...(opts.app_id ? { app_id: opts.app_id } : {}),\n ...(opts.start_channel ? { start_channel: opts.start_channel } : {}),\n ...(opts.search ? { search: opts.search } : {}),\n ...(opts.include_pull_requests ? { include_pull_requests: true } : {}),\n ...opts.filters,\n }),\n });\n if (!res.ok) {\n throw new AthenaSdkError({\n code: res.status === 401 || res.status === 403 ? 'auth_rejected' : 'threads_list_failed',\n message: `Failed to list threads: ${res.status}`,\n status: res.status,\n hint:\n res.status === 401 || res.status === 403\n ? 'The credential was refused. Check the token/API key and that the user belongs to the workspace.'\n : 'Check backendUrl points at the Agora API base.',\n context: { auth_mode: getAuthMode(auth) },\n });\n }\n const data = (await res.json()) as ThreadListResponse;\n endSpan('threads.list.done', { data: { count: data.threads?.length ?? 0 } });\n return data;\n } catch (error) {\n // Cancellation is lifecycle noise (unmount/remount aborts): log it as an\n // informational abort, not an error — passing `error` would force the\n // span end to error level and spam the console.\n if (isAbortError(error)) {\n endSpan('threads.list.aborted', { data: { reason: 'request aborted' } });\n } else {\n endSpan('threads.list.error', { error });\n }\n throw error;\n }\n}\n\n/** The `(workspace, user)` pair the credential resolves to on the backend. */\nexport interface AccountIdentity {\n userId: string;\n /** `null` for a user with no current workspace. */\n workspaceId: string | null;\n}\n\n/**\n * Resolve the credential's agora identity. The conversation index is one\n * statewire instance per `(workspace, user)`, and neither half is knowable\n * from the credential alone: the SDK's auth context carries an identity\n * provider user id, not agora's, and never a workspace.\n */\nexport async function fetchAccountIdentity(\n backendUrl: string,\n auth: AuthConfig,\n opts: { signal?: AbortSignal } = {},\n): Promise<AccountIdentity> {\n const base = getAthenaApiBaseUrl(backendUrl);\n const res = await fetch(`${base}/api/v0/me`, {\n headers: getAuthHeaders(auth),\n signal: opts.signal ?? null,\n });\n if (!res.ok) {\n throw new AthenaSdkError({\n code: res.status === 401 || res.status === 403 ? 'auth_rejected' : 'threads_list_failed',\n message: `Failed to resolve account identity: ${res.status}`,\n status: res.status,\n hint:\n res.status === 401 || res.status === 403\n ? 'The credential was refused. Check the token/API key and that the user belongs to the workspace.'\n : 'Check backendUrl points at the Agora API base.',\n context: { auth_mode: getAuthMode(auth) },\n });\n }\n const body = (await res.json()) as { user_id?: unknown; workspace_id?: unknown };\n if (typeof body.user_id !== 'string' || body.user_id.length === 0) {\n throw new AthenaSdkError({\n code: 'threads_list_failed',\n message: 'Account identity lookup returned no user id.',\n context: { auth_mode: getAuthMode(auth) },\n });\n }\n return {\n userId: body.user_id,\n workspaceId: typeof body.workspace_id === 'string' ? body.workspace_id : null,\n };\n}\n\nexport interface ThreadReadStateResponse {\n thread_id: string;\n is_unread: boolean;\n}\n\n/** Store the calling user's read receipt for a thread. */\nexport async function setThreadReadState(\n backendUrl: string,\n auth: AuthConfig,\n opts: { threadId: string; isUnread: boolean },\n): Promise<ThreadReadStateResponse> {\n const base = getAthenaApiBaseUrl(backendUrl);\n const res = await fetch(`${base}/api/conversations/threads/read-state`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...getAuthHeaders(auth) },\n body: JSON.stringify({\n thread_id: opts.threadId,\n is_unread: opts.isUnread,\n }),\n });\n if (!res.ok) {\n throw new AthenaSdkError({\n code: res.status === 401 || res.status === 403 ? 'auth_rejected' : 'unknown',\n message: `Failed to set thread read state: ${res.status}`,\n status: res.status,\n });\n }\n return res.json();\n}\n\nexport interface ThreadInboxDismissResponse {\n success: boolean;\n dismissed: boolean;\n}\n\n/**\n * Dismiss a session from the inbox, or bring it back\n * (`POST /api/conversations/threads/notifications/dismiss`). A dismissed\n * session returns on its own with its next message. The state lives on the\n * session for its creator's inbox, so the route takes EDIT on the session\n * (403 for a VIEW share).\n */\nexport async function dismissThreadFromInbox(\n backendUrl: string,\n auth: AuthConfig,\n opts: { threadId: string; dismissed: boolean },\n): Promise<ThreadInboxDismissResponse> {\n const base = getAthenaApiBaseUrl(backendUrl);\n const res = await fetch(`${base}/api/conversations/threads/notifications/dismiss`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...getAuthHeaders(auth) },\n body: JSON.stringify({ thread_id: opts.threadId, dismissed: opts.dismissed }),\n });\n if (!res.ok) {\n throw new AthenaSdkError({\n code: res.status === 401 || res.status === 403 ? 'auth_rejected' : 'unknown',\n message: `Failed to ${opts.dismissed ? 'dismiss' : 'restore'} the session: ${res.status}`,\n status: res.status,\n hint:\n res.status === 403\n ? 'Only someone who can edit the session (its creator, usually) can dismiss it from the inbox.'\n : undefined,\n context: { thread_id: opts.threadId, auth_mode: getAuthMode(auth) },\n });\n }\n return res.json();\n}\n\nexport interface ThreadFavoriteResponse {\n thread_id: string;\n /** The server's state after the write. */\n is_favorited: boolean;\n}\n\n/**\n * Classify a 4xx from one of the per-thread write routes (`favorite`,\n * `rename`, `archive`). A 404 there is ambiguous: FastAPI answers\n * `{\"detail\":\"Not Found\"}` for a route an older agora does not have, the\n * archive route answers `\"Endpoint not available\"` on an agora without the\n * checkpointer — and each route answers 404 for a thread that no longer\n * exists (`\"Thread <id> not found\"`, `\"Conversation with langchain thread id\n * <id> not found\"`). The routes' own not-found answers name the thread, so a\n * body that does not is the ROUTE missing, and only that withdraws the\n * feature; a stale row must not disable the action for every other row.\n */\nfunction classifyThreadRouteRejection(\n status: number,\n body: string,\n threadId: string,\n): { routeMissing: boolean; detail: unknown } {\n let detail: unknown = body || undefined;\n try {\n const parsed: unknown = JSON.parse(body);\n if (parsed && typeof parsed === 'object') {\n const record = parsed as { detail?: unknown; message?: unknown };\n detail = record.detail ?? record.message ?? parsed;\n }\n } catch {\n // A non-JSON body (a proxy page) is kept as text.\n }\n const routeMissing = status === 405 || (status === 404 && !mentionsThread(body, threadId));\n return { routeMissing, detail };\n}\n\n/**\n * Whether an error body names the thread as a whole token (the routes embed\n * the id between spaces: `Thread <id> not found`); a substring match would\n * let a short id match a letter inside `\"detail\"`.\n */\nfunction mentionsThread(body: string, threadId: string): boolean {\n if (!threadId) return false;\n const escaped = threadId.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return new RegExp(`(^|[^A-Za-z0-9_-])${escaped}($|[^A-Za-z0-9_-])`).test(body);\n}\n\n/** True when a per-thread write was rejected because the backend has no such route. */\nfunction isThreadRouteUnavailableError(error: unknown, code: AthenaSdkErrorCode): boolean {\n return isAthenaSdkError(error) && error.code === code && error.context.route_missing === true;\n}\n\n/**\n * Pin (favorite) or unpin a thread for the calling user. The response is the\n * server's truth after the write. Rejections: 401 / 403 when the caller\n * cannot view the thread (`auth_rejected`), otherwise `thread_favorite_failed`\n * with the HTTP status — 404 / 405 from an agora that predates the route,\n * which `isThreadFavoriteUnavailableError` recognizes so callers can fall\n * back to a read-only pin.\n */\nexport async function setThreadFavorite(\n backendUrl: string,\n auth: AuthConfig,\n opts: { threadId: string; isFavorited: boolean },\n): Promise<ThreadFavoriteResponse> {\n const base = getAthenaApiBaseUrl(backendUrl);\n const res = await fetch(`${base}/api/conversations/threads/favorite`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...getAuthHeaders(auth) },\n body: JSON.stringify({\n thread_id: opts.threadId,\n is_favorited: opts.isFavorited,\n }),\n });\n if (!res.ok) {\n const refused = res.status === 401 || res.status === 403;\n const { routeMissing, detail } = classifyThreadRouteRejection(\n res.status,\n await getResponseErrorBody(res),\n opts.threadId,\n );\n throw new AthenaSdkError({\n code: refused ? 'auth_rejected' : 'thread_favorite_failed',\n message: `Failed to set thread favorite: ${res.status}`,\n status: res.status,\n detail,\n hint: refused\n ? 'The credential cannot view this thread.'\n : routeMissing\n ? 'The backend has no favorite route yet (older agora); the pin stays read-only until it deploys.'\n : res.status === 404\n ? 'The thread no longer exists on the server (archived or deleted elsewhere); refresh the list.'\n : 'Check backendUrl points at the Agora API base.',\n context: { thread_id: opts.threadId, auth_mode: getAuthMode(auth), route_missing: routeMissing },\n });\n }\n return res.json();\n}\n\n/**\n * True when `setThreadFavorite` failed because the backend has no favorite\n * route (a 405, or a 404 whose body does not name the thread — see\n * `classifyThreadRouteRejection`); a 404 for a thread that is gone is a\n * per-row failure and leaves the toggle available.\n */\nexport function isThreadFavoriteUnavailableError(error: unknown): boolean {\n return isThreadRouteUnavailableError(error, 'thread_favorite_failed');\n}\n\nexport interface ThreadRenameResponse {\n thread_id: string;\n /** The stored title after the write (trimmed by the server). */\n title: string;\n}\n\n/** The longest title the rename route accepts; the server answers 422 past it. */\nexport const THREAD_TITLE_MAX_LENGTH = 200;\n\n/**\n * Rename a thread for every viewer (`POST /api/conversations/threads/rename`).\n * The server trims the title and stores 1–200 characters; the response is the\n * row's title after the write. Rejections: 401 / 403 when the caller cannot\n * edit the thread (`auth_rejected` — a viewer can pin a shared session but not\n * retitle it), otherwise `thread_rename_failed` with the HTTP status — 404 /\n * 405 from an agora that predates the route, which\n * `isThreadRenameUnavailableError` recognizes so callers can drop the action.\n */\nexport async function renameThread(\n backendUrl: string,\n auth: AuthConfig,\n opts: { threadId: string; title: string },\n): Promise<ThreadRenameResponse> {\n const base = getAthenaApiBaseUrl(backendUrl);\n const res = await fetch(`${base}/api/conversations/threads/rename`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...getAuthHeaders(auth) },\n body: JSON.stringify({\n thread_id: opts.threadId,\n title: opts.title,\n }),\n });\n if (!res.ok) {\n const refused = res.status === 401 || res.status === 403;\n const { routeMissing, detail } = classifyThreadRouteRejection(\n res.status,\n await getResponseErrorBody(res),\n opts.threadId,\n );\n throw new AthenaSdkError({\n code: refused ? 'auth_rejected' : 'thread_rename_failed',\n message: `Failed to rename thread: ${res.status}`,\n status: res.status,\n detail,\n hint: refused\n ? 'The credential cannot edit this thread (a viewer can pin a shared session, not retitle it).'\n : routeMissing\n ? 'The backend has no rename route yet (older agora); sessions cannot be renamed from here until it deploys.'\n : res.status === 404\n ? 'The thread no longer exists on the server (archived or deleted elsewhere); refresh the list.'\n : res.status === 422\n ? `The title must be 1–${THREAD_TITLE_MAX_LENGTH} characters after trimming.`\n : 'Check backendUrl points at the Agora API base.',\n context: { thread_id: opts.threadId, auth_mode: getAuthMode(auth), route_missing: routeMissing },\n });\n }\n return res.json();\n}\n\n/**\n * True when `renameThread` failed because the backend has no rename route\n * (a 405, or a 404 whose body does not name the thread); a 404 for a thread\n * that is gone is a per-row failure and leaves the action offered.\n */\nexport function isThreadRenameUnavailableError(error: unknown): boolean {\n return isThreadRouteUnavailableError(error, 'thread_rename_failed');\n}\n\n/**\n * True when `archiveThread` failed because the backend offers no archive\n * route: a 405, FastAPI's bare 404 on an agora without the route, or the\n * route's own `\"Endpoint not available\"` 404 on an agora without the\n * checkpointer. The route's `\"Thread <id> not found\"` 404 for a stale row is\n * a per-row failure and leaves the action offered on every other row.\n */\nexport function isThreadArchiveUnavailableError(error: unknown): boolean {\n return isThreadRouteUnavailableError(error, 'thread_archive_failed');\n}\n\nexport async function createThread(\n backendUrl: string,\n auth: AuthConfig,\n opts: { systemPrompt?: string; enabledTools?: string[]; appId?: string } = {},\n): Promise<ThreadCreateResponse> {\n const base = getAthenaApiBaseUrl(backendUrl);\n const res = await fetch(`${base}/api/unstable/threads/`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...getAuthHeaders(auth) },\n body: JSON.stringify({\n config: {\n system_prompt: opts.systemPrompt ?? '',\n enabled_tools: opts.enabledTools,\n ...(opts.appId ? { app_id: opts.appId } : {}),\n },\n }),\n });\n if (!res.ok) {\n throw new Error(`[AthenaSDK] Failed to create thread: ${res.status}`);\n }\n return res.json();\n}\n\nexport interface ThreadStateResponse {\n thread_id: string;\n messages: unknown[];\n status?: string;\n [key: string]: unknown;\n}\n\ninterface ConversationThreadResponse {\n thread?: {\n thread_id?: string;\n state?: string | null;\n channel_values?: Record<string, unknown> | null;\n messages?: unknown[] | null;\n } | null;\n thread_found?: boolean;\n}\n\n/**\n * Deserialize a LangChain serialized message.\n * The API returns messages in `{lc, type: \"constructor\", id, kwargs}` format.\n * We need the plain format: `{type: \"human\", content: \"...\", id: \"...\"}`.\n */\nfunction deserializeMessage(msg: unknown): unknown {\n if (\n msg &&\n typeof msg === 'object' &&\n 'lc' in msg &&\n 'kwargs' in msg &&\n (msg as Record<string, unknown>).type === 'constructor'\n ) {\n const kwargs = (msg as { kwargs: Record<string, unknown> }).kwargs;\n\n // Recursively deserialize nested content without mutating the original\n const deserializedToolCalls = Array.isArray(kwargs.tool_calls)\n ? kwargs.tool_calls.map((tc: unknown) => {\n if (tc && typeof tc === 'object' && 'lc' in tc && 'kwargs' in tc) {\n return (tc as { kwargs: unknown }).kwargs;\n }\n return tc;\n })\n : kwargs.tool_calls;\n\n return { ...kwargs, tool_calls: deserializedToolCalls };\n }\n return msg;\n}\n\n/** Return a non-sensitive auth label for request diagnostics. */\nfunction getAuthMode(auth: AuthConfig): 'bearer' | 'api-key' | 'none' {\n if (auth.token) {\n return 'bearer';\n }\n if (auth.apiKey) {\n return 'api-key';\n }\n return 'none';\n}\n\n/** Safely read a response body for error messages without masking the root failure. */\nfunction getResponseErrorBody(response: Response): Promise<string> {\n return response.text().catch(() => '');\n}\n\n/**\n * Fetch persisted thread state from the conversations API.\n *\n * This endpoint is the same source used by Athena's conversation sidebar and\n * supports API-key auth plus BYO SSO session tokens sent as Bearer tokens.\n */\nexport async function getThreadState(\n backendUrl: string,\n auth: AuthConfig,\n threadId: string,\n opts: {\n /**\n * Bypass the server's Redis thread cache and read the checkpoint (default\n * `true`, the history load's contract). A warm-up read that only seeds a\n * first paint passes `false`: the cached copy is cheaper and the attach\n * snapshot replaces it anyway.\n */\n skipCache?: boolean;\n signal?: AbortSignal;\n } = {},\n): Promise<ThreadStateResponse> {\n const base = getAthenaApiBaseUrl(backendUrl);\n const authMode = getAuthMode(auth);\n const endpoint = `${base}/api/conversations/threads/get`;\n\n const endSpan = athenaDiagnostics.span('threads.history', 'threads.history.start', {\n thread_id: threadId,\n auth_mode: authMode,\n });\n\n let res: Response;\n try {\n res = await fetch(endpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...getAuthHeaders(auth) },\n signal: opts.signal ?? null,\n body: JSON.stringify({\n thread_id: threadId,\n skip_cache: opts.skipCache ?? true,\n }),\n });\n } catch (error) {\n if (isAbortError(error)) {\n endSpan('threads.history.aborted', {\n data: { thread_id: threadId, reason: 'request aborted' },\n });\n } else {\n endSpan('threads.history.error', { error, data: { thread_id: threadId } });\n }\n throw error;\n }\n if (!res.ok) {\n const body = await getResponseErrorBody(res);\n const error = new AthenaSdkError({\n code: res.status === 401 || res.status === 403 ? 'auth_rejected' : 'thread_load_failed',\n message: `Failed to get thread state: ${res.status} (${authMode})${\n body ? `: ${body.slice(0, 300)}` : ''\n }`,\n status: res.status,\n hint: 'A brand-new thread may not be persisted yet; anything else means the credential or backendUrl is wrong.',\n context: { thread_id: threadId, auth_mode: authMode },\n });\n endSpan('threads.history.error', { error, data: { thread_id: threadId } });\n throw error;\n }\n const data = (await res.json()) as ConversationThreadResponse;\n const channelMessages = data.thread?.channel_values?.messages;\n endSpan('threads.history.done', {\n data: {\n thread_id: threadId,\n found: data.thread_found !== false,\n message_count: Array.isArray(channelMessages)\n ? channelMessages.length\n : (data.thread?.messages?.length ?? 0),\n },\n });\n const thread = data.thread;\n\n if (data.thread_found === false || !thread) {\n return {\n thread_id: threadId,\n messages: [],\n };\n }\n\n const channelValues = thread.channel_values ?? {};\n const rawMessages = Array.isArray(channelValues.messages)\n ? channelValues.messages\n : Array.isArray(thread.messages)\n ? thread.messages\n : [];\n\n return {\n ...channelValues,\n thread_id: thread.thread_id ?? threadId,\n messages: rawMessages.map(deserializeMessage),\n ...(thread.state ? { status: thread.state } : {}),\n };\n}\n\n/**\n * Archive a thread (`POST /api/conversations/threads/archive`): it leaves\n * every list but keeps its state. Rejections: 401 / 403 when the caller\n * cannot access the thread (`auth_rejected`), otherwise\n * `thread_archive_failed` with the HTTP status — 404 / 405 when the backend\n * has no archive route, which `isThreadArchiveUnavailableError` recognizes.\n */\nexport async function archiveThread(\n backendUrl: string,\n auth: AuthConfig,\n threadId: string,\n): Promise<void> {\n const base = getAthenaApiBaseUrl(backendUrl);\n const res = await fetch(`${base}/api/conversations/threads/archive`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...getAuthHeaders(auth) },\n body: JSON.stringify({ thread_id: threadId }),\n });\n if (!res.ok) {\n const refused = res.status === 401 || res.status === 403;\n const { routeMissing, detail } = classifyThreadRouteRejection(\n res.status,\n await getResponseErrorBody(res),\n threadId,\n );\n throw new AthenaSdkError({\n code: refused ? 'auth_rejected' : 'thread_archive_failed',\n message: `Failed to archive thread: ${res.status}`,\n status: res.status,\n detail,\n hint: refused\n ? 'The credential cannot access this thread.'\n : routeMissing\n ? 'The backend has no archive route (no checkpointer, or an older agora).'\n : res.status === 404\n ? 'The thread no longer exists on the server (archived or deleted elsewhere); refresh the list.'\n : 'Check backendUrl points at the Agora API base.',\n context: { thread_id: threadId, auth_mode: getAuthMode(auth), route_missing: routeMissing },\n });\n }\n}\n"],"names":[],"mappings":";;AA6FA,SAAS,aAAa,OAAyB;AAC7C,SACG,iBAAiB,gBAAgB,MAAM,SAAS,gBAChD,iBAAiB,SAAS,MAAM,SAAS;AAE9C;AAuDA,SAAS,eAAe,MAA0C;AACh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GAAG,IAAI,sCAAsC;AAAA,IACnE,QAAQ;AAAA,IACR,SAAS,EAAE,gBAAgB,oBAAoB,GAAG,eAAe,IAAI,EAAA;AAAA,IACrE,MAAM,KAAK,UAAU,EAAE,WAAW,UAAU;AAAA,EAAA,CAC7C;AACD,MAAI,CAAC,IAAI,IAAI;AACX,UAAM,UAAU,IAAI,WAAW,OAAO,IAAI,WAAW;AACrD,UAAM,EAAE,cAAc,OAAA,IAAW;AAAA,MAC/B,IAAI;AAAA,MACJ,MAAM,qBAAqB,GAAG;AAAA,MAC9B;AAAA,IAAA;AAEF,UAAM,IAAI,eAAe;AAAA,MACvB,MAAM,UAAU,kBAAkB;AAAA,MAClC,SAAS,6BAA6B,IAAI,MAAM;AAAA,MAChD,QAAQ,IAAI;AAAA,MACZ;AAAA,MACA,MAAM,UACF,8CACA,eACE,2EACA,IAAI,WAAW,MACb,iGACA;AAAA,MACR,SAAS,EAAE,WAAW,UAAU,WAAW,YAAY,IAAI,GAAG,eAAe,aAAA;AAAA,IAAa,CAC3F;AAAA,EACH;AACF;"}
1
+ {"version":3,"file":"api.js","sources":["../../src/threads/api.ts"],"sourcesContent":["/**\n * Athena thread API client.\n * Calls existing REST endpoints for thread CRUD.\n */\n\nimport type {\n ConversationAttention,\n ConversationAttentionSource,\n} from '@athenaintel/agent-runtime';\nimport { athenaDiagnostics } from '../diagnostics/athena-diagnostics';\nimport { AthenaSdkError, type AthenaSdkErrorCode, isAthenaSdkError } from '../diagnostics/errors';\n\n/**\n * Live GitHub state of a pull request the thread opened, read by the server\n * when the list renders (agora `agent_pr_threads` is the only stored link).\n */\nexport interface ThreadPullRequest {\n /** `owner/repo` the pull request lives in. */\n repo_full_name: string;\n number: number;\n url: string;\n title: string;\n state: 'OPEN' | 'CLOSED' | 'MERGED';\n is_draft: boolean;\n /** GitHub's review decision (APPROVED, CHANGES_REQUESTED, REVIEW_REQUIRED) or null. */\n review_decision: string | null;\n /** Combined state of the checks on the head commit. */\n checks_state: 'SUCCESS' | 'FAILURE' | 'PENDING' | 'NONE';\n /** ISO 8601 timestamp of the pull request's last update on GitHub. */\n updated_at: string;\n}\n\n/** The last event that woke a resting thread (a GitHub webhook, a schedule, a handoff). */\nexport interface ThreadWake {\n source: string | null;\n reason: string | null;\n /** ISO 8601 timestamp of the wake. */\n at: string | null;\n}\n\nexport interface ThreadSummary {\n thread_id: string;\n title: string;\n created_at: string;\n updated_at: string;\n last_message: string | null;\n message_count: number;\n state: string | null;\n start_channel?: string | null;\n last_channel?: string | null;\n /** Client app that created the session (SESSION_APP_ID_GUIDE). */\n app_id?: string | null;\n /** Collab agent and channel the session started on; older servers omit them. */\n collab_agent_id?: string | null;\n collab_channel_id?: string | null;\n /** Trigger marker for automated/background sessions. */\n trigger_type?: string | null;\n /** Whether the calling user has seen this thread since it last changed. */\n is_unread?: boolean;\n /**\n * Canonical status_v2 planes (`idle | active | needs_input | error` and\n * `scheduled | queued | running | needs_input | completed | failed |\n * canceled`); older servers omit them.\n */\n session_status?: string | null;\n run_status?: string | null;\n /**\n * The viewer's attention state, the one-line next action (≤ 80 chars) and\n * the signal that produced them, derived server-side; older servers omit them.\n */\n attention?: ConversationAttention | null;\n next_action?: string | null;\n attention_source?: ConversationAttentionSource | null;\n /** Whether the calling user favorited (pinned) the thread; older servers omit it. */\n is_favorited?: boolean;\n /** The last wake of a resting thread; older servers omit it. */\n last_wake?: ThreadWake | null;\n /** Whether the calling user started the thread (`false`: shared with them); older servers omit it. */\n created_by_me?: boolean;\n /**\n * Pull requests the thread opened with their live GitHub state. `[]` when\n * it opened none, `null` when the state could not be read right now;\n * older servers omit the field.\n */\n pull_requests?: ThreadPullRequest[] | null;\n}\n\n/**\n * True for fetch cancellations (unmount/remount aborts, StrictMode double\n * effects). These are lifecycle noise, not failures: emitting them as\n * `*.error` diagnostics floods the console with\n * \"signal is aborted without reason\" for requests the caller itself aborted.\n */\nfunction isAbortError(error: unknown): boolean {\n return (\n (error instanceof DOMException && error.name === 'AbortError') ||\n (error instanceof Error && error.name === 'AbortError')\n );\n}\n\nexport interface ThreadListResponse {\n threads: ThreadSummary[];\n /** Server lookahead result. Older servers may omit this field. */\n has_more?: boolean;\n /**\n * Every request field the server applies beyond paging. The server ignores\n * fields it does not know, so a filter missing from this list came back\n * unapplied; servers that predate the list omit it (none of the\n * `ThreadListFilterBody` fields are applied there).\n */\n supported_filters?: string[];\n}\n\n/**\n * The server-side filters and order of `POST /api/conversations/threads/list`\n * beyond the original `app_id` / `start_channel` / `search` /\n * `exclude_triggered` set. Each is a predicate of the server's one page\n * statement, so a page is exact; a server that predates a field ignores it\n * (check `ThreadListResponse.supported_filters`).\n */\nexport interface ThreadListFilterBody {\n /** Original fields, accepted here too so one body can carry a whole query. */\n search?: string;\n exclude_triggered?: boolean;\n app_ids?: string[];\n start_channels?: string[];\n created_after?: string;\n created_before?: string;\n updated_after?: string;\n updated_before?: string;\n collab_agent_ids?: string[];\n /** `'default'` matches the agent's default channel (no channel stamp); needs `collab_agent_ids`. */\n collab_channel_ids?: string[];\n favorites_only?: boolean;\n unread_only?: boolean;\n run_statuses?: string[];\n session_statuses?: string[];\n has_pull_requests?: boolean;\n created_by_me?: boolean;\n exclude_dismissed?: boolean;\n sort?: 'updated' | 'created';\n direction?: 'desc' | 'asc';\n}\n\nexport interface ThreadCreateResponse {\n thread_id: string;\n}\n\ninterface AuthConfig {\n apiKey?: string;\n token?: string | null;\n credentials?: RequestCredentials;\n}\n\nfunction getAuthHeaders(auth: AuthConfig): Record<string, string> {\n if (auth.token) {\n return { Authorization: `Bearer ${auth.token}` };\n }\n if (auth.apiKey) {\n return { 'X-API-KEY': auth.apiKey };\n }\n return {};\n}\n\n/**\n * Resolves the Athena API base URL from backendUrl.\n * Thread endpoints live under `/api/conversations/threads/*` and `/api/unstable/threads/`.\n * If backendUrl points at a nested Athena endpoint, trim it back to the API base first.\n */\nfunction getAthenaApiBaseUrl(backendUrl: string): string {\n const stripped = backendUrl.replace(/\\/api\\/assistant-ui\\/?$/, '');\n // If the suffix wasn't found, assume the URL already points to the API base\n if (stripped === backendUrl) {\n return backendUrl.replace(/\\/$/, '');\n }\n return stripped;\n}\n\nexport async function listThreads(\n backendUrl: string,\n auth: AuthConfig,\n opts: {\n limit?: number;\n offset?: number;\n exclude_triggered?: boolean;\n app_id?: string;\n start_channel?: string;\n search?: string;\n /** Ask the server for live GitHub state on `pull_requests` (off by default: it costs a lookup). */\n include_pull_requests?: boolean;\n /** Server-side filters and order beyond the original set (see `ThreadListFilterBody`). */\n filters?: ThreadListFilterBody;\n signal?: AbortSignal;\n } = {},\n): Promise<ThreadListResponse> {\n const base = getAthenaApiBaseUrl(backendUrl);\n const endSpan = athenaDiagnostics.span('threads.list', 'threads.list.start', {\n auth_mode: getAuthMode(auth),\n app_id: opts.app_id,\n });\n try {\n const res = await fetch(`${base}/api/conversations/threads/list`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...getAuthHeaders(auth) },\n signal: opts.signal ?? null,\n body: JSON.stringify({\n limit: opts.limit ?? 50,\n offset: opts.offset ?? 0,\n // Default to the full recent-conversations set unless a caller\n // explicitly asks to hide triggered/background sessions.\n exclude_triggered: opts.exclude_triggered ?? false,\n ...(opts.app_id ? { app_id: opts.app_id } : {}),\n ...(opts.start_channel ? { start_channel: opts.start_channel } : {}),\n ...(opts.search ? { search: opts.search } : {}),\n ...(opts.include_pull_requests ? { include_pull_requests: true } : {}),\n ...opts.filters,\n }),\n });\n if (!res.ok) {\n throw new AthenaSdkError({\n code: res.status === 401 || res.status === 403 ? 'auth_rejected' : 'threads_list_failed',\n message: `Failed to list threads: ${res.status}`,\n status: res.status,\n hint:\n res.status === 401 || res.status === 403\n ? 'The credential was refused. Check the token/API key and that the user belongs to the workspace.'\n : 'Check backendUrl points at the Agora API base.',\n context: { auth_mode: getAuthMode(auth) },\n });\n }\n const data = (await res.json()) as ThreadListResponse;\n endSpan('threads.list.done', { data: { count: data.threads?.length ?? 0 } });\n return data;\n } catch (error) {\n // Cancellation is lifecycle noise (unmount/remount aborts): log it as an\n // informational abort, not an error — passing `error` would force the\n // span end to error level and spam the console.\n if (isAbortError(error)) {\n endSpan('threads.list.aborted', { data: { reason: 'request aborted' } });\n } else {\n endSpan('threads.list.error', { error });\n }\n throw error;\n }\n}\n\n/** The `(workspace, user)` pair the credential resolves to on the backend. */\nexport interface AccountIdentity {\n userId: string;\n /** `null` for a user with no current workspace. */\n workspaceId: string | null;\n}\n\n/**\n * Resolve the credential's agora identity. The conversation index is one\n * statewire instance per `(workspace, user)`, and neither half is knowable\n * from the credential alone: the SDK's auth context carries an identity\n * provider user id, not agora's, and never a workspace.\n */\nexport async function fetchAccountIdentity(\n backendUrl: string,\n auth: AuthConfig,\n opts: { signal?: AbortSignal } = {},\n): Promise<AccountIdentity> {\n const base = getAthenaApiBaseUrl(backendUrl);\n const res = await fetch(`${base}/api/v0/me`, {\n headers: getAuthHeaders(auth),\n signal: opts.signal ?? null,\n credentials: auth.credentials,\n });\n if (!res.ok) {\n throw new AthenaSdkError({\n code: res.status === 401 || res.status === 403 ? 'auth_rejected' : 'threads_list_failed',\n message: `Failed to resolve account identity: ${res.status}`,\n status: res.status,\n hint:\n res.status === 401 || res.status === 403\n ? 'The credential was refused. Check the token/API key and that the user belongs to the workspace.'\n : 'Check backendUrl points at the Agora API base.',\n context: { auth_mode: getAuthMode(auth) },\n });\n }\n const body = (await res.json()) as { user_id?: unknown; workspace_id?: unknown };\n if (typeof body.user_id !== 'string' || body.user_id.length === 0) {\n throw new AthenaSdkError({\n code: 'threads_list_failed',\n message: 'Account identity lookup returned no user id.',\n context: { auth_mode: getAuthMode(auth) },\n });\n }\n return {\n userId: body.user_id,\n workspaceId: typeof body.workspace_id === 'string' ? body.workspace_id : null,\n };\n}\n\nexport interface ThreadReadStateResponse {\n thread_id: string;\n is_unread: boolean;\n}\n\n/** Store the calling user's read receipt for a thread. */\nexport async function setThreadReadState(\n backendUrl: string,\n auth: AuthConfig,\n opts: { threadId: string; isUnread: boolean },\n): Promise<ThreadReadStateResponse> {\n const base = getAthenaApiBaseUrl(backendUrl);\n const res = await fetch(`${base}/api/conversations/threads/read-state`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...getAuthHeaders(auth) },\n body: JSON.stringify({\n thread_id: opts.threadId,\n is_unread: opts.isUnread,\n }),\n });\n if (!res.ok) {\n throw new AthenaSdkError({\n code: res.status === 401 || res.status === 403 ? 'auth_rejected' : 'unknown',\n message: `Failed to set thread read state: ${res.status}`,\n status: res.status,\n });\n }\n return res.json();\n}\n\nexport interface ThreadInboxDismissResponse {\n success: boolean;\n dismissed: boolean;\n}\n\n/**\n * Dismiss a session from the inbox, or bring it back\n * (`POST /api/conversations/threads/notifications/dismiss`). A dismissed\n * session returns on its own with its next message. The state lives on the\n * session for its creator's inbox, so the route takes EDIT on the session\n * (403 for a VIEW share).\n */\nexport async function dismissThreadFromInbox(\n backendUrl: string,\n auth: AuthConfig,\n opts: { threadId: string; dismissed: boolean },\n): Promise<ThreadInboxDismissResponse> {\n const base = getAthenaApiBaseUrl(backendUrl);\n const res = await fetch(`${base}/api/conversations/threads/notifications/dismiss`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...getAuthHeaders(auth) },\n body: JSON.stringify({ thread_id: opts.threadId, dismissed: opts.dismissed }),\n });\n if (!res.ok) {\n throw new AthenaSdkError({\n code: res.status === 401 || res.status === 403 ? 'auth_rejected' : 'unknown',\n message: `Failed to ${opts.dismissed ? 'dismiss' : 'restore'} the session: ${res.status}`,\n status: res.status,\n hint:\n res.status === 403\n ? 'Only someone who can edit the session (its creator, usually) can dismiss it from the inbox.'\n : undefined,\n context: { thread_id: opts.threadId, auth_mode: getAuthMode(auth) },\n });\n }\n return res.json();\n}\n\nexport interface ThreadFavoriteResponse {\n thread_id: string;\n /** The server's state after the write. */\n is_favorited: boolean;\n}\n\n/**\n * Classify a 4xx from one of the per-thread write routes (`favorite`,\n * `rename`, `archive`). A 404 there is ambiguous: FastAPI answers\n * `{\"detail\":\"Not Found\"}` for a route an older agora does not have, the\n * archive route answers `\"Endpoint not available\"` on an agora without the\n * checkpointer — and each route answers 404 for a thread that no longer\n * exists (`\"Thread <id> not found\"`, `\"Conversation with langchain thread id\n * <id> not found\"`). The routes' own not-found answers name the thread, so a\n * body that does not is the ROUTE missing, and only that withdraws the\n * feature; a stale row must not disable the action for every other row.\n */\nfunction classifyThreadRouteRejection(\n status: number,\n body: string,\n threadId: string,\n): { routeMissing: boolean; detail: unknown } {\n let detail: unknown = body || undefined;\n try {\n const parsed: unknown = JSON.parse(body);\n if (parsed && typeof parsed === 'object') {\n const record = parsed as { detail?: unknown; message?: unknown };\n detail = record.detail ?? record.message ?? parsed;\n }\n } catch {\n // A non-JSON body (a proxy page) is kept as text.\n }\n const routeMissing = status === 405 || (status === 404 && !mentionsThread(body, threadId));\n return { routeMissing, detail };\n}\n\n/**\n * Whether an error body names the thread as a whole token (the routes embed\n * the id between spaces: `Thread <id> not found`); a substring match would\n * let a short id match a letter inside `\"detail\"`.\n */\nfunction mentionsThread(body: string, threadId: string): boolean {\n if (!threadId) return false;\n const escaped = threadId.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return new RegExp(`(^|[^A-Za-z0-9_-])${escaped}($|[^A-Za-z0-9_-])`).test(body);\n}\n\n/** True when a per-thread write was rejected because the backend has no such route. */\nfunction isThreadRouteUnavailableError(error: unknown, code: AthenaSdkErrorCode): boolean {\n return isAthenaSdkError(error) && error.code === code && error.context.route_missing === true;\n}\n\n/**\n * Pin (favorite) or unpin a thread for the calling user. The response is the\n * server's truth after the write. Rejections: 401 / 403 when the caller\n * cannot view the thread (`auth_rejected`), otherwise `thread_favorite_failed`\n * with the HTTP status — 404 / 405 from an agora that predates the route,\n * which `isThreadFavoriteUnavailableError` recognizes so callers can fall\n * back to a read-only pin.\n */\nexport async function setThreadFavorite(\n backendUrl: string,\n auth: AuthConfig,\n opts: { threadId: string; isFavorited: boolean },\n): Promise<ThreadFavoriteResponse> {\n const base = getAthenaApiBaseUrl(backendUrl);\n const res = await fetch(`${base}/api/conversations/threads/favorite`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...getAuthHeaders(auth) },\n body: JSON.stringify({\n thread_id: opts.threadId,\n is_favorited: opts.isFavorited,\n }),\n });\n if (!res.ok) {\n const refused = res.status === 401 || res.status === 403;\n const { routeMissing, detail } = classifyThreadRouteRejection(\n res.status,\n await getResponseErrorBody(res),\n opts.threadId,\n );\n throw new AthenaSdkError({\n code: refused ? 'auth_rejected' : 'thread_favorite_failed',\n message: `Failed to set thread favorite: ${res.status}`,\n status: res.status,\n detail,\n hint: refused\n ? 'The credential cannot view this thread.'\n : routeMissing\n ? 'The backend has no favorite route yet (older agora); the pin stays read-only until it deploys.'\n : res.status === 404\n ? 'The thread no longer exists on the server (archived or deleted elsewhere); refresh the list.'\n : 'Check backendUrl points at the Agora API base.',\n context: { thread_id: opts.threadId, auth_mode: getAuthMode(auth), route_missing: routeMissing },\n });\n }\n return res.json();\n}\n\n/**\n * True when `setThreadFavorite` failed because the backend has no favorite\n * route (a 405, or a 404 whose body does not name the thread — see\n * `classifyThreadRouteRejection`); a 404 for a thread that is gone is a\n * per-row failure and leaves the toggle available.\n */\nexport function isThreadFavoriteUnavailableError(error: unknown): boolean {\n return isThreadRouteUnavailableError(error, 'thread_favorite_failed');\n}\n\nexport interface ThreadRenameResponse {\n thread_id: string;\n /** The stored title after the write (trimmed by the server). */\n title: string;\n}\n\n/** The longest title the rename route accepts; the server answers 422 past it. */\nexport const THREAD_TITLE_MAX_LENGTH = 200;\n\n/**\n * Rename a thread for every viewer (`POST /api/conversations/threads/rename`).\n * The server trims the title and stores 1–200 characters; the response is the\n * row's title after the write. Rejections: 401 / 403 when the caller cannot\n * edit the thread (`auth_rejected` — a viewer can pin a shared session but not\n * retitle it), otherwise `thread_rename_failed` with the HTTP status — 404 /\n * 405 from an agora that predates the route, which\n * `isThreadRenameUnavailableError` recognizes so callers can drop the action.\n */\nexport async function renameThread(\n backendUrl: string,\n auth: AuthConfig,\n opts: { threadId: string; title: string },\n): Promise<ThreadRenameResponse> {\n const base = getAthenaApiBaseUrl(backendUrl);\n const res = await fetch(`${base}/api/conversations/threads/rename`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...getAuthHeaders(auth) },\n body: JSON.stringify({\n thread_id: opts.threadId,\n title: opts.title,\n }),\n });\n if (!res.ok) {\n const refused = res.status === 401 || res.status === 403;\n const { routeMissing, detail } = classifyThreadRouteRejection(\n res.status,\n await getResponseErrorBody(res),\n opts.threadId,\n );\n throw new AthenaSdkError({\n code: refused ? 'auth_rejected' : 'thread_rename_failed',\n message: `Failed to rename thread: ${res.status}`,\n status: res.status,\n detail,\n hint: refused\n ? 'The credential cannot edit this thread (a viewer can pin a shared session, not retitle it).'\n : routeMissing\n ? 'The backend has no rename route yet (older agora); sessions cannot be renamed from here until it deploys.'\n : res.status === 404\n ? 'The thread no longer exists on the server (archived or deleted elsewhere); refresh the list.'\n : res.status === 422\n ? `The title must be 1–${THREAD_TITLE_MAX_LENGTH} characters after trimming.`\n : 'Check backendUrl points at the Agora API base.',\n context: { thread_id: opts.threadId, auth_mode: getAuthMode(auth), route_missing: routeMissing },\n });\n }\n return res.json();\n}\n\n/**\n * True when `renameThread` failed because the backend has no rename route\n * (a 405, or a 404 whose body does not name the thread); a 404 for a thread\n * that is gone is a per-row failure and leaves the action offered.\n */\nexport function isThreadRenameUnavailableError(error: unknown): boolean {\n return isThreadRouteUnavailableError(error, 'thread_rename_failed');\n}\n\n/**\n * True when `archiveThread` failed because the backend offers no archive\n * route: a 405, FastAPI's bare 404 on an agora without the route, or the\n * route's own `\"Endpoint not available\"` 404 on an agora without the\n * checkpointer. The route's `\"Thread <id> not found\"` 404 for a stale row is\n * a per-row failure and leaves the action offered on every other row.\n */\nexport function isThreadArchiveUnavailableError(error: unknown): boolean {\n return isThreadRouteUnavailableError(error, 'thread_archive_failed');\n}\n\nexport async function createThread(\n backendUrl: string,\n auth: AuthConfig,\n opts: { systemPrompt?: string; enabledTools?: string[]; appId?: string } = {},\n): Promise<ThreadCreateResponse> {\n const base = getAthenaApiBaseUrl(backendUrl);\n const res = await fetch(`${base}/api/unstable/threads/`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...getAuthHeaders(auth) },\n body: JSON.stringify({\n config: {\n system_prompt: opts.systemPrompt ?? '',\n enabled_tools: opts.enabledTools,\n ...(opts.appId ? { app_id: opts.appId } : {}),\n },\n }),\n });\n if (!res.ok) {\n throw new Error(`[AthenaSDK] Failed to create thread: ${res.status}`);\n }\n return res.json();\n}\n\nexport interface ThreadStateResponse {\n thread_id: string;\n messages: unknown[];\n status?: string;\n [key: string]: unknown;\n}\n\ninterface ConversationThreadResponse {\n thread?: {\n thread_id?: string;\n state?: string | null;\n channel_values?: Record<string, unknown> | null;\n messages?: unknown[] | null;\n } | null;\n thread_found?: boolean;\n}\n\n/**\n * Deserialize a LangChain serialized message.\n * The API returns messages in `{lc, type: \"constructor\", id, kwargs}` format.\n * We need the plain format: `{type: \"human\", content: \"...\", id: \"...\"}`.\n */\nfunction deserializeMessage(msg: unknown): unknown {\n if (\n msg &&\n typeof msg === 'object' &&\n 'lc' in msg &&\n 'kwargs' in msg &&\n (msg as Record<string, unknown>).type === 'constructor'\n ) {\n const kwargs = (msg as { kwargs: Record<string, unknown> }).kwargs;\n\n // Recursively deserialize nested content without mutating the original\n const deserializedToolCalls = Array.isArray(kwargs.tool_calls)\n ? kwargs.tool_calls.map((tc: unknown) => {\n if (tc && typeof tc === 'object' && 'lc' in tc && 'kwargs' in tc) {\n return (tc as { kwargs: unknown }).kwargs;\n }\n return tc;\n })\n : kwargs.tool_calls;\n\n return { ...kwargs, tool_calls: deserializedToolCalls };\n }\n return msg;\n}\n\n/** Return a non-sensitive auth label for request diagnostics. */\nfunction getAuthMode(auth: AuthConfig): 'bearer' | 'api-key' | 'none' {\n if (auth.token) {\n return 'bearer';\n }\n if (auth.apiKey) {\n return 'api-key';\n }\n return 'none';\n}\n\n/** Safely read a response body for error messages without masking the root failure. */\nfunction getResponseErrorBody(response: Response): Promise<string> {\n return response.text().catch(() => '');\n}\n\n/**\n * Fetch persisted thread state from the conversations API.\n *\n * This endpoint is the same source used by Athena's conversation sidebar and\n * supports API-key auth plus BYO SSO session tokens sent as Bearer tokens.\n */\nexport async function getThreadState(\n backendUrl: string,\n auth: AuthConfig,\n threadId: string,\n opts: {\n /**\n * Bypass the server's Redis thread cache and read the checkpoint (default\n * `true`, the history load's contract). A warm-up read that only seeds a\n * first paint passes `false`: the cached copy is cheaper and the attach\n * snapshot replaces it anyway.\n */\n skipCache?: boolean;\n signal?: AbortSignal;\n } = {},\n): Promise<ThreadStateResponse> {\n const base = getAthenaApiBaseUrl(backendUrl);\n const authMode = getAuthMode(auth);\n const endpoint = `${base}/api/conversations/threads/get`;\n\n const endSpan = athenaDiagnostics.span('threads.history', 'threads.history.start', {\n thread_id: threadId,\n auth_mode: authMode,\n });\n\n let res: Response;\n try {\n res = await fetch(endpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...getAuthHeaders(auth) },\n signal: opts.signal ?? null,\n body: JSON.stringify({\n thread_id: threadId,\n skip_cache: opts.skipCache ?? true,\n }),\n });\n } catch (error) {\n if (isAbortError(error)) {\n endSpan('threads.history.aborted', {\n data: { thread_id: threadId, reason: 'request aborted' },\n });\n } else {\n endSpan('threads.history.error', { error, data: { thread_id: threadId } });\n }\n throw error;\n }\n if (!res.ok) {\n const body = await getResponseErrorBody(res);\n const error = new AthenaSdkError({\n code: res.status === 401 || res.status === 403 ? 'auth_rejected' : 'thread_load_failed',\n message: `Failed to get thread state: ${res.status} (${authMode})${\n body ? `: ${body.slice(0, 300)}` : ''\n }`,\n status: res.status,\n hint: 'A brand-new thread may not be persisted yet; anything else means the credential or backendUrl is wrong.',\n context: { thread_id: threadId, auth_mode: authMode },\n });\n endSpan('threads.history.error', { error, data: { thread_id: threadId } });\n throw error;\n }\n const data = (await res.json()) as ConversationThreadResponse;\n const channelMessages = data.thread?.channel_values?.messages;\n endSpan('threads.history.done', {\n data: {\n thread_id: threadId,\n found: data.thread_found !== false,\n message_count: Array.isArray(channelMessages)\n ? channelMessages.length\n : (data.thread?.messages?.length ?? 0),\n },\n });\n const thread = data.thread;\n\n if (data.thread_found === false || !thread) {\n return {\n thread_id: threadId,\n messages: [],\n };\n }\n\n const channelValues = thread.channel_values ?? {};\n const rawMessages = Array.isArray(channelValues.messages)\n ? channelValues.messages\n : Array.isArray(thread.messages)\n ? thread.messages\n : [];\n\n return {\n ...channelValues,\n thread_id: thread.thread_id ?? threadId,\n messages: rawMessages.map(deserializeMessage),\n ...(thread.state ? { status: thread.state } : {}),\n };\n}\n\n/**\n * Archive a thread (`POST /api/conversations/threads/archive`): it leaves\n * every list but keeps its state. Rejections: 401 / 403 when the caller\n * cannot access the thread (`auth_rejected`), otherwise\n * `thread_archive_failed` with the HTTP status — 404 / 405 when the backend\n * has no archive route, which `isThreadArchiveUnavailableError` recognizes.\n */\nexport async function archiveThread(\n backendUrl: string,\n auth: AuthConfig,\n threadId: string,\n): Promise<void> {\n const base = getAthenaApiBaseUrl(backendUrl);\n const res = await fetch(`${base}/api/conversations/threads/archive`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...getAuthHeaders(auth) },\n body: JSON.stringify({ thread_id: threadId }),\n });\n if (!res.ok) {\n const refused = res.status === 401 || res.status === 403;\n const { routeMissing, detail } = classifyThreadRouteRejection(\n res.status,\n await getResponseErrorBody(res),\n threadId,\n );\n throw new AthenaSdkError({\n code: refused ? 'auth_rejected' : 'thread_archive_failed',\n message: `Failed to archive thread: ${res.status}`,\n status: res.status,\n detail,\n hint: refused\n ? 'The credential cannot access this thread.'\n : routeMissing\n ? 'The backend has no archive route (no checkpointer, or an older agora).'\n : res.status === 404\n ? 'The thread no longer exists on the server (archived or deleted elsewhere); refresh the list.'\n : 'Check backendUrl points at the Agora API base.',\n context: { thread_id: threadId, auth_mode: getAuthMode(auth), route_missing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Y,IAAI,kBAAkB;AAAA,IAC5C,GAAI,OAAO,QAAQ,EAAE,QAAQ,OAAO,MAAA,IAAU,CAAA;AAAA,EAAC;AAEnD;AASA,eAAsB,cACpB,YACA,MACA,UACe;AACf,QAAM,OAAO,oBAAoB,UAAU;AAC3C,QAAM,MAAM,MAAM,MAAM,GAAG,IAAI,sCAAsC;AAAA,IACnE,QAAQ;AAAA,IACR,SAAS,EAAE,gBAAgB,oBAAoB,GAAG,eAAe,IAAI,EAAA;AAAA,IACrE,MAAM,KAAK,UAAU,EAAE,WAAW,UAAU;AAAA,EAAA,CAC7C;AACD,MAAI,CAAC,IAAI,IAAI;AACX,UAAM,UAAU,IAAI,WAAW,OAAO,IAAI,WAAW;AACrD,UAAM,EAAE,cAAc,OAAA,IAAW;AAAA,MAC/B,IAAI;AAAA,MACJ,MAAM,qBAAqB,GAAG;AAAA,MAC9B;AAAA,IAAA;AAEF,UAAM,IAAI,eAAe;AAAA,MACvB,MAAM,UAAU,kBAAkB;AAAA,MAClC,SAAS,6BAA6B,IAAI,MAAM;AAAA,MAChD,QAAQ,IAAI;AAAA,MACZ;AAAA,MACA,MAAM,UACF,8CACA,eACE,2EACA,IAAI,WAAW,MACb,iGACA;AAAA,MACR,SAAS,EAAE,WAAW,UAAU,WAAW,YAAY,IAAI,GAAG,eAAe,aAAA;AAAA,IAAa,CAC3F;AAAA,EACH;AACF;"}
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const react = require("react");
4
+ const statewireModelLane = require("../runtime/statewire-model-lane.cjs");
5
+ const statewireServerLaneContext = require("../runtime/statewire-server-lane-context.cjs");
6
+ function useAthenaThreadModel() {
7
+ const threadModel = useOptionalAthenaThreadModel();
8
+ if (threadModel === null) {
9
+ throw new Error("[AthenaSDK] useAthenaThreadModel must be used within <AthenaProvider>");
10
+ }
11
+ return threadModel;
12
+ }
13
+ function useOptionalAthenaThreadModel() {
14
+ const lane = react.useContext(statewireServerLaneContext.AthenaStatewireServerLaneContext);
15
+ return react.useMemo(
16
+ () => lane === null ? null : statewireModelLane.threadModelFromLane({ lane: lane.config, ready: lane.landed }),
17
+ [lane]
18
+ );
19
+ }
20
+ exports.useAthenaThreadModel = useAthenaThreadModel;
21
+ exports.useOptionalAthenaThreadModel = useOptionalAthenaThreadModel;
22
+ //# sourceMappingURL=use-athena-thread-model.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-athena-thread-model.cjs","sources":["../../src/threads/use-athena-thread-model.ts"],"sourcesContent":["import { useContext, useMemo } from 'react';\nimport { type AthenaThreadModel, threadModelFromLane } from '../runtime/statewire-model-lane';\nimport { AthenaStatewireServerLaneContext } from '../runtime/statewire-server-lane-context';\n\nexport type { AthenaThreadModel };\n\n/**\n * The model the active thread's server config pins, read from the thread's\n * config lane (`state.config.custom.model`) as the statewire host sent it.\n *\n * Once a thread has run, its server config (not the provider's `model` prop)\n * decides which model each turn uses; another client (Olympus, a second tab)\n * can change it at any time. Read this hook when a session opens to show the\n * session's real model in your picker: `{ model: null, configured: true }` is\n * a thread that pins no model, so the collab agent's own model (or the\n * default) runs. Wait for `ready`: until the host's snapshot of the thread has\n * arrived every thread reads as unconfigured, and a never-started chat stays\n * not ready until its first send attaches it.\n *\n * The value is the server's: a model change the provider is still writing\n * shows here once the server has applied it. Seed the picker from it when the\n * thread opens, rather than mirroring it on every render.\n *\n * Must be used within `<AthenaProvider>`.\n */\nexport function useAthenaThreadModel(): AthenaThreadModel {\n const threadModel = useOptionalAthenaThreadModel();\n if (threadModel === null) {\n throw new Error('[AthenaSDK] useAthenaThreadModel must be used within <AthenaProvider>');\n }\n return threadModel;\n}\n\n/**\n * {@link useAthenaThreadModel}, or `null` outside `<AthenaProvider>` (a picker\n * a host renders beside the chat rather than in it). Internal.\n */\nexport function useOptionalAthenaThreadModel(): AthenaThreadModel | null {\n const lane = useContext(AthenaStatewireServerLaneContext);\n return useMemo(\n () => (lane === null ? null : threadModelFromLane({ lane: lane.config, ready: lane.landed })),\n [lane],\n );\n}\n"],"names":["useContext","AthenaStatewireServerLaneContext","useMemo","threadModelFromLane"],"mappings":";;;;;AAyBO,SAAS,uBAA0C;AACxD,QAAM,cAAc,6BAAA;AACpB,MAAI,gBAAgB,MAAM;AACxB,UAAM,IAAI,MAAM,uEAAuE;AAAA,EACzF;AACA,SAAO;AACT;AAMO,SAAS,+BAAyD;AACvE,QAAM,OAAOA,MAAAA,WAAWC,2DAAgC;AACxD,SAAOC,MAAAA;AAAAA,IACL,MAAO,SAAS,OAAO,OAAOC,mBAAAA,oBAAoB,EAAE,MAAM,KAAK,QAAQ,OAAO,KAAK,OAAA,CAAQ;AAAA,IAC3F,CAAC,IAAI;AAAA,EAAA;AAET;;;"}
@@ -0,0 +1,27 @@
1
+ import { type AthenaThreadModel } from '../runtime/statewire-model-lane';
2
+ export type { AthenaThreadModel };
3
+ /**
4
+ * The model the active thread's server config pins, read from the thread's
5
+ * config lane (`state.config.custom.model`) as the statewire host sent it.
6
+ *
7
+ * Once a thread has run, its server config (not the provider's `model` prop)
8
+ * decides which model each turn uses; another client (Olympus, a second tab)
9
+ * can change it at any time. Read this hook when a session opens to show the
10
+ * session's real model in your picker: `{ model: null, configured: true }` is
11
+ * a thread that pins no model, so the collab agent's own model (or the
12
+ * default) runs. Wait for `ready`: until the host's snapshot of the thread has
13
+ * arrived every thread reads as unconfigured, and a never-started chat stays
14
+ * not ready until its first send attaches it.
15
+ *
16
+ * The value is the server's: a model change the provider is still writing
17
+ * shows here once the server has applied it. Seed the picker from it when the
18
+ * thread opens, rather than mirroring it on every render.
19
+ *
20
+ * Must be used within `<AthenaProvider>`.
21
+ */
22
+ export declare function useAthenaThreadModel(): AthenaThreadModel;
23
+ /**
24
+ * {@link useAthenaThreadModel}, or `null` outside `<AthenaProvider>` (a picker
25
+ * a host renders beside the chat rather than in it). Internal.
26
+ */
27
+ export declare function useOptionalAthenaThreadModel(): AthenaThreadModel | null;
@@ -0,0 +1,22 @@
1
+ import { useContext, useMemo } from "react";
2
+ import { threadModelFromLane } from "../runtime/statewire-model-lane.js";
3
+ import { AthenaStatewireServerLaneContext } from "../runtime/statewire-server-lane-context.js";
4
+ function useAthenaThreadModel() {
5
+ const threadModel = useOptionalAthenaThreadModel();
6
+ if (threadModel === null) {
7
+ throw new Error("[AthenaSDK] useAthenaThreadModel must be used within <AthenaProvider>");
8
+ }
9
+ return threadModel;
10
+ }
11
+ function useOptionalAthenaThreadModel() {
12
+ const lane = useContext(AthenaStatewireServerLaneContext);
13
+ return useMemo(
14
+ () => lane === null ? null : threadModelFromLane({ lane: lane.config, ready: lane.landed }),
15
+ [lane]
16
+ );
17
+ }
18
+ export {
19
+ useAthenaThreadModel,
20
+ useOptionalAthenaThreadModel
21
+ };
22
+ //# sourceMappingURL=use-athena-thread-model.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-athena-thread-model.js","sources":["../../src/threads/use-athena-thread-model.ts"],"sourcesContent":["import { useContext, useMemo } from 'react';\nimport { type AthenaThreadModel, threadModelFromLane } from '../runtime/statewire-model-lane';\nimport { AthenaStatewireServerLaneContext } from '../runtime/statewire-server-lane-context';\n\nexport type { AthenaThreadModel };\n\n/**\n * The model the active thread's server config pins, read from the thread's\n * config lane (`state.config.custom.model`) as the statewire host sent it.\n *\n * Once a thread has run, its server config (not the provider's `model` prop)\n * decides which model each turn uses; another client (Olympus, a second tab)\n * can change it at any time. Read this hook when a session opens to show the\n * session's real model in your picker: `{ model: null, configured: true }` is\n * a thread that pins no model, so the collab agent's own model (or the\n * default) runs. Wait for `ready`: until the host's snapshot of the thread has\n * arrived every thread reads as unconfigured, and a never-started chat stays\n * not ready until its first send attaches it.\n *\n * The value is the server's: a model change the provider is still writing\n * shows here once the server has applied it. Seed the picker from it when the\n * thread opens, rather than mirroring it on every render.\n *\n * Must be used within `<AthenaProvider>`.\n */\nexport function useAthenaThreadModel(): AthenaThreadModel {\n const threadModel = useOptionalAthenaThreadModel();\n if (threadModel === null) {\n throw new Error('[AthenaSDK] useAthenaThreadModel must be used within <AthenaProvider>');\n }\n return threadModel;\n}\n\n/**\n * {@link useAthenaThreadModel}, or `null` outside `<AthenaProvider>` (a picker\n * a host renders beside the chat rather than in it). Internal.\n */\nexport function useOptionalAthenaThreadModel(): AthenaThreadModel | null {\n const lane = useContext(AthenaStatewireServerLaneContext);\n return useMemo(\n () => (lane === null ? null : threadModelFromLane({ lane: lane.config, ready: lane.landed })),\n [lane],\n );\n}\n"],"names":[],"mappings":";;;AAyBO,SAAS,uBAA0C;AACxD,QAAM,cAAc,6BAAA;AACpB,MAAI,gBAAgB,MAAM;AACxB,UAAM,IAAI,MAAM,uEAAuE;AAAA,EACzF;AACA,SAAO;AACT;AAMO,SAAS,+BAAyD;AACvE,QAAM,OAAO,WAAW,gCAAgC;AACxD,SAAO;AAAA,IACL,MAAO,SAAS,OAAO,OAAO,oBAAoB,EAAE,MAAM,KAAK,QAAQ,OAAO,KAAK,OAAA,CAAQ;AAAA,IAC3F,CAAC,IAAI;AAAA,EAAA;AAET;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@athenaintel/react",
3
- "version": "0.30.0",
3
+ "version": "0.35.0",
4
4
  "description": "Athena React SDK — Build AI-powered chat applications with the Athena platform",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -99,7 +99,7 @@
99
99
  "@assistant-ui/react": "0.15.28",
100
100
  "@assistant-ui/react-langgraph": "0.14.34",
101
101
  "@assistant-ui/react-markdown": "0.14.21",
102
- "@assistant-ui/react-statewire": "0.30.0",
102
+ "@assistant-ui/react-statewire": "0.31.0",
103
103
  "@assistant-ui/store": "0.3.21",
104
104
  "@assistant-ui/tap": "0.9.23",
105
105
  "@floating-ui/react": "^0.27.7",
@@ -120,14 +120,14 @@
120
120
  "@tiptap/starter-kit": "^3.31.3",
121
121
  "@tiptap/suggestion": "^3.31.3",
122
122
  "@y/websocket": "4.0.0-rc.2",
123
- "@y/y": "14.0.0-rc.28",
123
+ "@y/y": "14.0.0-rc.29",
124
124
  "assistant-stream": "0.3.50",
125
125
  "class-variance-authority": "^0.7.1",
126
126
  "cnfast": "0.0.8",
127
127
  "lucide-react": "^0.575.0",
128
128
  "radix-ui": "^1.4.3",
129
129
  "remark-gfm": "^4.0.0",
130
- "statewire": "0.20.0",
130
+ "statewire": "0.21.0",
131
131
  "tiptap-markdown": "^0.9.0",
132
132
  "zustand": "^5.0.11"
133
133
  },