stageflow 0.42.0 → 0.46.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 (315) hide show
  1. package/README.md +12 -3
  2. package/dist/agent/activity.d.ts +18 -0
  3. package/dist/agent/claudeAdapter.js +7 -0
  4. package/dist/agent/claudeTools.d.ts +27 -18
  5. package/dist/agent/claudeTools.js +54 -15
  6. package/dist/agent/compactionEvents.d.ts +34 -0
  7. package/dist/agent/compactionEvents.js +37 -0
  8. package/dist/agent/openRouterRouting.d.ts +7 -0
  9. package/dist/agent/openRouterRouting.js +23 -0
  10. package/dist/agent/piAdapter.d.ts +6 -0
  11. package/dist/agent/piAdapter.js +128 -27
  12. package/dist/agent/piSettings.d.ts +7 -0
  13. package/dist/agent/piSettings.js +9 -0
  14. package/dist/agent/sandboxPiTools.d.ts +3 -1
  15. package/dist/agent/sandboxPiTools.js +8 -2
  16. package/dist/agent/stageTurnDriver.d.ts +11 -2
  17. package/dist/agent/stageTurnDriver.js +45 -4
  18. package/dist/agent/toolOutputBudget.d.ts +15 -1
  19. package/dist/agent/toolOutputBudget.js +18 -0
  20. package/dist/agent/toolOutputBudgetExtension.d.ts +2 -0
  21. package/dist/agent/toolOutputBudgetExtension.js +40 -3
  22. package/dist/agents/authorChat.d.ts +1 -0
  23. package/dist/agents/authorChat.js +7 -0
  24. package/dist/agents/authorSessionStore.d.ts +3 -0
  25. package/dist/agents/authorSessionStore.js +17 -2
  26. package/dist/agents/evalGate.js +1 -0
  27. package/dist/agents/hostContext.d.ts +1 -1
  28. package/dist/agents/runtime/piRuntime.d.ts +5 -1
  29. package/dist/agents/runtime/piRuntime.js +46 -12
  30. package/dist/agents/service.js +3 -2
  31. package/dist/agents/sessions.js +3 -1
  32. package/dist/cli/evalCommand.d.ts +1 -1
  33. package/dist/cli/evalCommand.js +39 -2
  34. package/dist/cli/hostClient.d.ts +6 -0
  35. package/dist/cli/hostClient.js +4 -0
  36. package/dist/compaction/directives.d.ts +18 -0
  37. package/dist/compaction/directives.js +119 -0
  38. package/dist/compaction/extension.d.ts +20 -0
  39. package/dist/compaction/extension.js +78 -0
  40. package/dist/compaction/mask.d.ts +18 -0
  41. package/dist/compaction/mask.js +155 -0
  42. package/dist/compaction/pin.d.ts +21 -0
  43. package/dist/compaction/pin.js +270 -0
  44. package/dist/compaction/scrub.d.ts +7 -0
  45. package/dist/compaction/scrub.js +26 -0
  46. package/dist/compaction/sessionWiring.d.ts +22 -0
  47. package/dist/compaction/sessionWiring.js +26 -0
  48. package/dist/compaction/summarize.d.ts +79 -0
  49. package/dist/compaction/summarize.js +171 -0
  50. package/dist/compaction/toolPolicy.d.ts +3 -0
  51. package/dist/compaction/toolPolicy.js +33 -0
  52. package/dist/compaction/types.d.ts +45 -0
  53. package/dist/compaction/types.js +7 -0
  54. package/dist/compaction/workingState.d.ts +56 -0
  55. package/dist/compaction/workingState.js +198 -0
  56. package/dist/config/createPipeline.js +2 -0
  57. package/dist/config/createTrigger.js +7 -1
  58. package/dist/config/ensureCatalogScanRoot.d.ts +2 -0
  59. package/dist/config/ensureCatalogScanRoot.js +6 -0
  60. package/dist/config/evalCatalog.js +30 -2
  61. package/dist/config/githubTriggerAction.d.ts +8 -0
  62. package/dist/config/githubTriggerAction.js +29 -0
  63. package/dist/config/hostConfig.js +2 -0
  64. package/dist/config/loadEval.d.ts +3 -1
  65. package/dist/config/loadEval.js +96 -10
  66. package/dist/config/pipelineNeeds.d.ts +2 -0
  67. package/dist/config/pipelineNeeds.js +16 -3
  68. package/dist/config/pipelineRoute.js +5 -4
  69. package/dist/config/validateCatalog.d.ts +1 -1
  70. package/dist/config/validateCatalog.js +12 -0
  71. package/dist/config/validateEval.js +60 -3
  72. package/dist/config/writeEval.js +2 -2
  73. package/dist/envelope/assertEmittedArtifacts.d.ts +12 -0
  74. package/dist/envelope/assertEmittedArtifacts.js +43 -0
  75. package/dist/envelope/preEmitChecks.d.ts +3 -0
  76. package/dist/evals/calibration.d.ts +21 -0
  77. package/dist/evals/calibration.js +69 -0
  78. package/dist/evals/calibrationSuggest.d.ts +29 -0
  79. package/dist/evals/calibrationSuggest.js +72 -0
  80. package/dist/evals/calibrator.d.ts +46 -0
  81. package/dist/evals/calibrator.js +148 -0
  82. package/dist/evals/compare.d.ts +1 -1
  83. package/dist/evals/compare.js +3 -0
  84. package/dist/evals/constants.d.ts +7 -3
  85. package/dist/evals/constants.js +7 -1
  86. package/dist/evals/engine/FakeEngine.d.ts +2 -1
  87. package/dist/evals/engine/FakeEngine.js +9 -3
  88. package/dist/evals/engine/promptfoo/PromptfooEngine.d.ts +1 -1
  89. package/dist/evals/engine/promptfoo/PromptfooEngine.js +4 -2
  90. package/dist/evals/engine/promptfoo/generate.d.ts +3 -1
  91. package/dist/evals/engine/promptfoo/generate.js +43 -23
  92. package/dist/evals/engine/promptfoo/judgeProviders.js +2 -1
  93. package/dist/evals/engine/promptfoo/normalize.d.ts +4 -1
  94. package/dist/evals/engine/promptfoo/normalize.js +16 -3
  95. package/dist/evals/engine/promptfoo/rubricPrompt.d.ts +3 -1
  96. package/dist/evals/engine/promptfoo/rubricPrompt.js +15 -5
  97. package/dist/evals/errors.d.ts +7 -0
  98. package/dist/evals/errors.js +10 -0
  99. package/dist/evals/judgeProviders.d.ts +6 -0
  100. package/dist/evals/judgeProviders.js +14 -0
  101. package/dist/evals/judged.d.ts +7 -0
  102. package/dist/evals/judged.js +7 -0
  103. package/dist/evals/manager.d.ts +27 -8
  104. package/dist/evals/manager.js +73 -12
  105. package/dist/evals/plan.d.ts +10 -1
  106. package/dist/evals/plan.js +33 -13
  107. package/dist/evals/planInternalAgent.d.ts +19 -0
  108. package/dist/evals/planInternalAgent.js +201 -0
  109. package/dist/evals/read/api.d.ts +18 -0
  110. package/dist/evals/read/api.js +10 -1
  111. package/dist/evals/read/labelQueue.d.ts +45 -0
  112. package/dist/evals/read/labelQueue.js +83 -0
  113. package/dist/evals/read/list.js +10 -1
  114. package/dist/evals/read/runs.d.ts +5 -0
  115. package/dist/evals/read/runs.js +7 -1
  116. package/dist/evals/runner/caseRunner.d.ts +2 -1
  117. package/dist/evals/runner/caseRunner.js +16 -5
  118. package/dist/evals/runner/internalAgentCaseRunner.d.ts +6 -0
  119. package/dist/evals/runner/internalAgentCaseRunner.js +250 -0
  120. package/dist/evals/snapshot.d.ts +10 -2
  121. package/dist/evals/snapshot.js +8 -3
  122. package/dist/evals/stats.d.ts +40 -0
  123. package/dist/evals/stats.js +69 -0
  124. package/dist/evals/storeTypes.d.ts +42 -0
  125. package/dist/evals/types.d.ts +25 -2
  126. package/dist/evals/types.js +4 -1
  127. package/dist/evals/votes.d.ts +10 -0
  128. package/dist/evals/votes.js +60 -0
  129. package/dist/guide/cardContract.d.ts +133 -0
  130. package/dist/guide/cardContract.js +156 -0
  131. package/dist/guide/chat.d.ts +45 -0
  132. package/dist/guide/chat.js +378 -0
  133. package/dist/guide/knowledge/index.d.ts +14 -0
  134. package/dist/guide/knowledge/index.js +109 -0
  135. package/dist/guide/knowledge/topics/agents.d.ts +2 -0
  136. package/dist/guide/knowledge/topics/agents.js +58 -0
  137. package/dist/guide/knowledge/topics/bestPractices.d.ts +2 -0
  138. package/dist/guide/knowledge/topics/bestPractices.js +67 -0
  139. package/dist/guide/knowledge/topics/connections.d.ts +2 -0
  140. package/dist/guide/knowledge/topics/connections.js +66 -0
  141. package/dist/guide/knowledge/topics/consoleMap.d.ts +2 -0
  142. package/dist/guide/knowledge/topics/consoleMap.js +55 -0
  143. package/dist/guide/knowledge/topics/evals.d.ts +2 -0
  144. package/dist/guide/knowledge/topics/evals.js +72 -0
  145. package/dist/guide/knowledge/topics/limitations.d.ts +2 -0
  146. package/dist/guide/knowledge/topics/limitations.js +84 -0
  147. package/dist/guide/knowledge/topics/mcpSkillsBrowser.d.ts +2 -0
  148. package/dist/guide/knowledge/topics/mcpSkillsBrowser.js +57 -0
  149. package/dist/guide/knowledge/topics/memories.d.ts +2 -0
  150. package/dist/guide/knowledge/topics/memories.js +63 -0
  151. package/dist/guide/knowledge/topics/modelsAndProviders.d.ts +2 -0
  152. package/dist/guide/knowledge/topics/modelsAndProviders.js +56 -0
  153. package/dist/guide/knowledge/topics/overview.d.ts +2 -0
  154. package/dist/guide/knowledge/topics/overview.js +56 -0
  155. package/dist/guide/knowledge/topics/pipelines.d.ts +2 -0
  156. package/dist/guide/knowledge/topics/pipelines.js +93 -0
  157. package/dist/guide/knowledge/topics/stages.d.ts +2 -0
  158. package/dist/guide/knowledge/topics/stages.js +54 -0
  159. package/dist/guide/knowledge/topics/tasks.d.ts +2 -0
  160. package/dist/guide/knowledge/topics/tasks.js +52 -0
  161. package/dist/guide/knowledge/topics/triggers.d.ts +2 -0
  162. package/dist/guide/knowledge/topics/triggers.js +68 -0
  163. package/dist/guide/knowledge/topics/troubleshooting.d.ts +2 -0
  164. package/dist/guide/knowledge/topics/troubleshooting.js +85 -0
  165. package/dist/guide/knowledgeTools.d.ts +2 -0
  166. package/dist/guide/knowledgeTools.js +56 -0
  167. package/dist/guide/showUi.d.ts +6 -0
  168. package/dist/guide/showUi.js +546 -0
  169. package/dist/guide/threadStore.d.ts +48 -0
  170. package/dist/guide/threadStore.js +189 -0
  171. package/dist/guide/writeRoot.d.ts +11 -0
  172. package/dist/guide/writeRoot.js +70 -0
  173. package/dist/hosted/translate.js +2 -0
  174. package/dist/mcp/agentTools.js +12 -0
  175. package/dist/mcp/catalogTools.js +18 -20
  176. package/dist/mcp/catalogWriteTools.d.ts +8 -0
  177. package/dist/mcp/catalogWriteTools.js +225 -0
  178. package/dist/mcp/connectionTools.d.ts +3 -0
  179. package/dist/mcp/connectionTools.js +85 -0
  180. package/dist/mcp/controlTools.js +34 -1
  181. package/dist/mcp/deps.d.ts +9 -0
  182. package/dist/mcp/evalTools.js +723 -21
  183. package/dist/mcp/memoryHostTools.d.ts +3 -0
  184. package/dist/mcp/memoryHostTools.js +72 -0
  185. package/dist/mcp/pipelineAuthorTools.js +14 -1
  186. package/dist/mcp/server.js +5 -0
  187. package/dist/mcp/tools.js +6 -0
  188. package/dist/mcp/triggerTools.js +77 -31
  189. package/dist/operatorAgent/evalGate.d.ts +22 -0
  190. package/dist/operatorAgent/evalGate.js +77 -0
  191. package/dist/operatorAgent/fakeHost.js +10 -2
  192. package/dist/operatorAgent/host.js +18 -2
  193. package/dist/operatorAgent/index.d.ts +1 -0
  194. package/dist/operatorAgent/index.js +1 -0
  195. package/dist/operatorAgent/internalAgents.d.ts +11 -0
  196. package/dist/operatorAgent/internalAgents.js +13 -0
  197. package/dist/operatorAgent/piModel.d.ts +5 -1
  198. package/dist/operatorAgent/piModel.js +15 -10
  199. package/dist/operatorAgent/profiles/agentAuthor.js +66 -22
  200. package/dist/operatorAgent/profiles/agentAuthorPlaybook.d.ts +1 -1
  201. package/dist/operatorAgent/profiles/agentAuthorPlaybook.js +1 -1
  202. package/dist/operatorAgent/profiles/guideConfirm.d.ts +21 -0
  203. package/dist/operatorAgent/profiles/guideConfirm.js +100 -0
  204. package/dist/operatorAgent/profiles/guideTools.d.ts +7 -0
  205. package/dist/operatorAgent/profiles/guideTools.js +123 -0
  206. package/dist/operatorAgent/profiles/stageflowGuide.d.ts +7 -0
  207. package/dist/operatorAgent/profiles/stageflowGuide.js +133 -0
  208. package/dist/operatorAgent/profiles/workshopAuthor.js +23 -0
  209. package/dist/operatorAgent/profiles/workshopAuthorPlaybook.d.ts +1 -1
  210. package/dist/operatorAgent/profiles/workshopAuthorPlaybook.js +9 -1
  211. package/dist/operatorAgent/profiles/workshopAuthorTools.d.ts +2 -0
  212. package/dist/operatorAgent/profiles/workshopAuthorTools.js +197 -9
  213. package/dist/operatorAgent/types.d.ts +23 -0
  214. package/dist/package-meta.d.ts +1 -1
  215. package/dist/package-meta.js +1 -1
  216. package/dist/runstore/port.d.ts +13 -1
  217. package/dist/runstore/retention.d.ts +2 -1
  218. package/dist/runstore/retention.js +3 -7
  219. package/dist/runstore/runStatusClock.d.ts +17 -0
  220. package/dist/runstore/runStatusClock.js +19 -0
  221. package/dist/runstore/sqlite/SqliteRunStore.d.ts +11 -1
  222. package/dist/runstore/sqlite/SqliteRunStore.js +70 -45
  223. package/dist/runstore/sqlite/calibrationStore.d.ts +10 -0
  224. package/dist/runstore/sqlite/calibrationStore.js +106 -0
  225. package/dist/runstore/sqlite/evalStore.d.ts +5 -0
  226. package/dist/runstore/sqlite/evalStore.js +7 -0
  227. package/dist/runstore/sqlite/migrations/018-eval-grader-labels.d.ts +11 -0
  228. package/dist/runstore/sqlite/migrations/018-eval-grader-labels.js +43 -0
  229. package/dist/runstore/sqlite/migrations/index.js +2 -0
  230. package/dist/runstore/workspaceLayout.js +6 -1
  231. package/dist/runtime/artifactDiskInspect.d.ts +14 -0
  232. package/dist/runtime/artifactDiskInspect.js +52 -0
  233. package/dist/runtime/artifactPath.d.ts +24 -0
  234. package/dist/runtime/artifactPath.js +84 -0
  235. package/dist/runtime/completionCheckRunner.js +15 -43
  236. package/dist/runtime/githubPollSource.d.ts +22 -4
  237. package/dist/runtime/githubPollSource.js +93 -8
  238. package/dist/runtime/priorArtifactGrants.d.ts +8 -0
  239. package/dist/runtime/priorArtifactGrants.js +105 -0
  240. package/dist/runtime/runActionEligibility.d.ts +46 -0
  241. package/dist/runtime/runActionEligibility.js +123 -0
  242. package/dist/runtime/runManager.d.ts +4 -1
  243. package/dist/runtime/runManager.js +52 -10
  244. package/dist/runtime/runRetryCoordinator.d.ts +2 -14
  245. package/dist/runtime/runRetryCoordinator.js +3 -67
  246. package/dist/runtime/sandboxContainer.d.ts +7 -0
  247. package/dist/runtime/sandboxContainer.js +48 -6
  248. package/dist/runtime/sandboxDesk.d.ts +2 -1
  249. package/dist/runtime/sandboxDesk.js +11 -12
  250. package/dist/runtime/stageEnvironment.js +1 -0
  251. package/dist/runtime/stageRoots.d.ts +12 -0
  252. package/dist/runtime/stageSandbox.d.ts +2 -1
  253. package/dist/runtime/stageSandbox.js +18 -2
  254. package/dist/runtime/stageWorker.js +20 -0
  255. package/dist/server/agentAuthorRoutes.js +12 -3
  256. package/dist/server/bootstrap.d.ts +5 -0
  257. package/dist/server/bootstrap.js +14 -1
  258. package/dist/server/evalRoutes.js +251 -12
  259. package/dist/server/guideRoutes.d.ts +5 -0
  260. package/dist/server/guideRoutes.js +166 -0
  261. package/dist/server/http.d.ts +10 -0
  262. package/dist/server/http.js +35 -1
  263. package/dist/server/internalAgentRoutes.d.ts +6 -0
  264. package/dist/server/internalAgentRoutes.js +12 -0
  265. package/dist/server/mcpHost.js +2 -0
  266. package/dist/toolkit/meta.d.ts +1 -1
  267. package/dist/toolkit/meta.js +41 -1
  268. package/dist/toolkit/profiles.d.ts +5 -0
  269. package/dist/toolkit/profiles.js +12 -0
  270. package/dist/tools/askOperator.js +2 -1
  271. package/dist/tools/emitStageEnvelope.d.ts +17 -16
  272. package/dist/tools/emitStageEnvelope.js +46 -32
  273. package/dist/tools/stageToolNames.d.ts +4 -0
  274. package/dist/tools/stageToolNames.js +4 -0
  275. package/dist/tools/workingState.d.ts +40 -0
  276. package/dist/tools/workingState.js +108 -0
  277. package/dist/tools/writeStageArtifact.d.ts +0 -9
  278. package/dist/tools/writeStageArtifact.js +2 -1
  279. package/dist/ui/assets/{MarkdownText-BTrOqu5J.js → MarkdownText-BS2BBbCx.js} +2 -2
  280. package/dist/ui/assets/adapters-DPD-cAsy.js +17 -0
  281. package/dist/ui/assets/chat-BD1-VTT6.js +2 -0
  282. package/dist/ui/assets/chat-DXnQv9st.css +2 -0
  283. package/dist/ui/assets/main-AX5XNLtX.js +278 -0
  284. package/dist/ui/assets/{main-CHlmTNJe.css → main-CFX0_n8J.css} +1 -1
  285. package/dist/ui/chat.html +3 -4
  286. package/dist/ui/index.html +3 -4
  287. package/dist/workshop/chatTurn.js +1 -1
  288. package/dist/workshop/workshopPin.d.ts +3 -3
  289. package/dist/workshop/workshopPin.js +16 -15
  290. package/examples/compaction-stress/README.md +30 -0
  291. package/examples/compaction-stress/check-run.mjs +53 -0
  292. package/examples/compaction-stress/collect-evidence.yaml +60 -0
  293. package/examples/compaction-stress/compaction-stress.pipeline.yaml +141 -0
  294. package/examples/compaction-stress/compaction-stress.task.yaml +15 -0
  295. package/examples/compaction-stress/generate-evidence.mjs +110 -0
  296. package/examples/compaction-stress/root-cause.yaml +26 -0
  297. package/examples/compaction-stress/stageflow.yaml +9 -0
  298. package/examples/compaction-stress/write-postmortem.yaml +40 -0
  299. package/examples/evals/README.md +18 -0
  300. package/examples/evals/guide-behavior.dataset.jsonl +15 -0
  301. package/examples/evals/guide-behavior.eval.yaml +35 -0
  302. package/examples/evals/guide-depth.dataset.jsonl +35 -0
  303. package/examples/evals/guide-depth.eval.yaml +169 -0
  304. package/examples/memory/evals/guide-behavior.dataset.jsonl +15 -0
  305. package/examples/memory/evals/guide-behavior.eval.yaml +35 -0
  306. package/examples/memory/evals/guide-depth.dataset.jsonl +35 -0
  307. package/examples/memory/evals/guide-depth.eval.yaml +169 -0
  308. package/package.json +1 -1
  309. package/skills/stageflow/references/control-surface.md +1 -1
  310. package/skills/stageflow/references/evals.md +1 -0
  311. package/dist/ui/assets/AssistantRuntimeProvider-qIX1xNoH.js +0 -9
  312. package/dist/ui/assets/ReadonlyStore-BfXqHykm.js +0 -6
  313. package/dist/ui/assets/chat-Df_wCpak.js +0 -5
  314. package/dist/ui/assets/chat-P7KQznHm.css +0 -2
  315. package/dist/ui/assets/main-CvVfxmMd.js +0 -271
@@ -1,6 +0,0 @@
1
- import{n as e,o as t,r as n,t as r}from"./jsx-runtime-iVoFAvQ_.js";var i=null;function a(e,t){e.currentIndex=0,e.wipContextDeps=null,e.wipCommitCallbacks=[];let n=i;i=e;try{if(t(),e.isFirstRender=!1,e.cells.length!==e.currentIndex)throw Error(`Rendered ${e.currentIndex} hooks but expected ${e.cells.length}. Hooks must be called in the exact same order in every render.`)}finally{i=n}}function o(){if(!i)throw Error(`No resource fiber available`);return i}function s(){return i}var c=typeof process<`u`&&!1,l=e=>({version:0,committedVersion:0,dispatchUpdate:e,changelog:[],committedLog:[],unsettledCount:0,rollbackCallbacks:[]}),u=e=>{e.committedVersion=e.version;for(let t of e.changelog)t.logged=!1,t.settled||(t.settled=!0,e.unsettledCount--),e.committedLog.push(t);e.changelog.length=0,e.unsettledCount===0&&(e.committedLog.length=0),e.rollbackCallbacks.length=0},d=(e,t)=>{let n=e.version>t;if(e.version=t,n){for(let t=0;t<e.rollbackCallbacks.length;t++)e.rollbackCallbacks[t]();if(e.rollbackCallbacks.length=0,t<=e.committedVersion){let n=[];for(;e.committedVersion-n.length>t;){let t=e.committedLog.pop();if(t===void 0){if(c)throw Error(`tap: committed history is shorter than the replay base.`);break}h(t.fiber,t.cell),t.cell.workInProgress=t.prevState,n.push({record:t,prevState:t.prevState,eagerState:t.eagerState,hasEagerState:t.hasEagerState})}if(n.length>0){let t=e.committedVersion;m(e,()=>{for(let t=n.length-1;t>=0;t--){let r=n[t];r.record.prevState=r.prevState,r.record.eagerState=r.eagerState,r.record.hasEagerState=r.hasEagerState,e.committedLog.push(r.record)}e.committedVersion=t})}e.committedVersion=t;for(let t of e.changelog)t.logged=!1;e.changelog.length=0}else{for(;e.committedVersion+e.changelog.length>t;)e.changelog.pop().logged=!1;for(let t=0;t<e.changelog.length;t++)f(e.changelog[t]);u(e)}}},f=e=>{h(e.fiber,e.cell),e.queued||(e.queued=!0,(e.cell.queue??=[]).push(e))},p=(e,t)=>{e.wipCommitCallbacks.push(t)},m=(e,t)=>{e.rollbackCallbacks.push(t)},h=(e,t)=>{t.isDirty||(t.isDirty=!0,e.markDirty?.(),m(e.root,()=>{if(t.queue!==null){for(let e of t.queue)e.queued=!1;t.queue=null}t.workInProgress=t.current,t.isDirty=!1}))},g=Symbol.for(`react.memo_cache_sentinel`),_=e=>Array(e).fill(g),v=(e,t)=>{let n=e.memoCache,r=n.workInProgress;if(r===null){let t=n.current;r=t===null?[]:t.map(e=>e.slice()),n.workInProgress=r,m(e.root,()=>{n.workInProgress=null,n.refreshedIndices=null})}let i=n.index++,a=r[i];return n.refreshedIndices?.has(i)&&!e.isRefreshing&&(n.refreshedIndices.delete(i),a=n.current?.[i]?.slice()??_(t),r[i]=a),a===void 0||e.isRefreshing?(a=_(t),r[i]=a,e.isRefreshing&&(n.refreshedIndices??=new Set).add(i)):c&&a.length!==t&&console.error(`Expected a constant size argument for each invocation of c(). The previous cache was allocated with size ${a.length} but size ${t} was requested.`),a},y=e=>v(o(),e),b=t(e(),1),ee=b.default.__COMPILER_RUNTIME?.c??(e=>(0,b.useMemo)(()=>{let t=_(e);return t[g]=!0,t},[])),te=()=>s()!==null,x=e=>te()?y(e):ee(e),S=r(),C=(e,...t)=>Object.assign(Object.create(null),e,...t),w=()=>{throw Error(`Rendered more hooks than during the previous render. Hooks must be called in the exact same order in every render.`)},T=()=>{throw Error(`Hook order changed between renders`)},ne=e=>({type:e,setup:void 0,setupDeps:void 0,cleanup:void 0,deps:null,generation:0});function re(e,t,n){let r=o(),i=r.currentIndex++,a=r.cells[i],s=a===void 0?ne(n):a.type===n?a:T();if(a===void 0&&(r.isFirstRender||w(),r.cells[i]=s,n===`insertion`?(r.insertionCells??=[]).push(s):r.effectCells.push(s)),s.deps!==null&&!!t!=!!s.deps)throw Error(`useEffect called with and without dependencies across re-renders`);let c=r.isRefreshing;p(r,()=>{s.setup=e,s.setupDeps=t,c&&(s.deps=null),s.generation++})}function E(e,t){re(e,t,`effect`)}function ie(e){let t=o(),n=t.currentIndex++,r=t.cells[n];if(r===void 0){t.isFirstRender||w();let r={current:e};return t.cells[n]={type:`ref`,ref:r},r}return r.type===`ref`?r.ref:T()}var ae=Symbol(`tap.Context.defaultValue`),oe=e=>e,D=new Map,se=new Set,ce=()=>new Map(D),le=(e,t)=>{let n=D;D=e;try{return t()}finally{D=n}},ue=(e,t)=>{e[ae]=t},de=e=>typeof e==`object`&&!!e&&ae in e,fe=e=>typeof e==`object`&&!!e&&`$$typeof`in e&&e.$$typeof===Symbol.for(`react.context`),pe=e=>de(e)||fe(e),me=e=>{if(!de(e)){if(fe(e)){ue(e,e._currentValue??e._currentValue2);return}throw Error("A tap resource's `use()` only accepts a tap context.")}},he=(e,t,n)=>{if(typeof e!=`object`||!e)throw Error(`useContextProvider only accepts a React context.`);me(e);let r=e,i=o(),a=ie(void 0),s=a.current===void 0||!Object.is(a.current.value,t);E(()=>{a.current={value:t}},[t]);let c=D.get(r),l=c!==void 0||D.has(r);D.set(r,{value:t,source:i});try{return ge(r,s,n)}finally{l?D.set(r,c):D.delete(r)}},ge=(e,t,n)=>{let r=se.has(e);t?se.add(e):se.delete(e);try{return n()}finally{r?se.add(e):se.delete(e)}},_e=e=>{me(e);let t=e,n=ve(t,e),r=o();return(r.wipContextDeps??=new Map).set(t,n.source),n.value},ve=(e,t)=>D.get(e)??{value:oe(t)[ae],source:null},ye=(e,t,n,r)=>{if(!r)return n;let i=n;for(let[n,a]of r)a!==t&&a!==e&&(i??=new Map).set(n,a);return i},be=(e,t=e.wipContextDeps)=>{let n=s();!n||!t||(n.wipContextDeps=ye(n,e,n.wipContextDeps,t))},xe=()=>se.size>0,Se=e=>{if(!e.contextDeps||!xe())return!1;for(let t of se.keys())if(e.contextDeps.has(t))return!0;return!1},Ce=(e,t,n)=>{if(e.isNeverMounted)throw Error(`Resource updated before mount`);let r=!1,i=!0;e.root.unsettledCount++,e.root.dispatchUpdate(()=>r?i:(r=!0,n&&e.root.changelog.length===0&&!t.cell.isDirty&&!t.hasEagerState&&(t.prevState=t.cell.workInProgress,t.eagerState=n(t.cell.workInProgress,t.action),t.hasEagerState=!0,i=!Object.is(t.cell.current,t.eagerState),!i&&!t.settled&&(t.settled=!0,e.root.unsettledCount--)),i),()=>(r=!0,i=!0,f(t),t.logged||(t.logged=!0,e.root.changelog.push(t)),!0))},we=(e,t,n,r,i)=>{let a=r?r(n):n;c&&e.devStrictMode&&r&&r(n);let o={type:`reducer`,workInProgress:a,current:a,isDirty:!1,queue:null,renderQueue:null,reducer:t,dispatch:n=>{let r=s();if(r!==null){if(r!==e)throw Error(`Cannot update a resource while rendering a different resource.`);(e.renderPendingCells??=new Set).add(o),(o.renderQueue??=[]).push(n)}else Ce(e,{fiber:e,cell:o,action:n,hasEagerState:!1,eagerState:void 0,prevState:o.current,settled:!1,queued:!1,logged:!1},i?t:void 0)}};return o};function Te(e,t,n,r){let i=o(),a=i.currentIndex++,s=i.cells[a],l=(()=>{if(s!==void 0)return s.type===`reducer`?s:T();i.isFirstRender||w();let o=we(i,e,t,n,r);return i.cells[a]=o,o})(),u=l.queue;if(u!==null){let t=e===l.reducer;for(let n=0;n<u.length;n++){let r=u[n];!r.hasEagerState||!t||!Object.is(r.prevState,l.workInProgress)?(r.prevState=l.workInProgress,r.eagerState=e(l.workInProgress,r.action),r.hasEagerState=!0,c&&i.devStrictMode&&(r.eagerState=e(l.workInProgress,r.action))):c&&i.devStrictMode&&e(l.workInProgress,r.action),r.queued=!1,l.workInProgress=r.eagerState}l.queue=null}if(l.reducer=e,l.renderQueue!==null){let t=l.workInProgress;for(let n of l.renderQueue)t=e(t,n);l.renderQueue=null,i.renderPendingCells?.delete(l),Object.is(t,l.workInProgress)||(h(i,l),l.workInProgress=t)}return l.isDirty&&p(i,()=>{l.current=l.workInProgress,l.isDirty=!1}),[l.workInProgress,l.dispatch]}function Ee(e,t,n){return Te(e,t,n,!1)}var De=(e,t)=>typeof t==`function`?t(e):t,Oe=e=>e===void 0?void 0:typeof e==`function`?e():e;function ke(e){return Te(De,e,Oe,!0)}var Ae=(e,t)=>{c&&e.length!==t.length&&console.error(`The final argument passed to a hook changed size between renders. The order and size of this array must remain constant.
2
-
3
- Previous: [${e.join(`, `)}]\nIncoming: [${t.join(`, `)}]`);for(let n=0;n<e.length&&n<t.length;n++)if(!Object.is(e[n],t[n]))return!1;return!0},je=(e,t)=>{p(e,()=>{t.current=t.wip,t.currentDeps=t.wipDeps,t.wipIsRefreshing=!1,t.isDirty=!1})},Me=(e,t)=>{let n=o(),r=n.currentIndex++,i=n.cells[r];if(i===void 0){n.isFirstRender||w();let a=e();return c&&n.devStrictMode&&e(),i={type:`memo`,current:a,currentDeps:t,wip:a,wipDeps:t,wipIsRefreshing:!1,isDirty:!1},n.cells[r]=i,a}i.type!==`memo`&&T();let a=i;if(a.wipIsRefreshing&&!n.isRefreshing&&(a.wip=a.current,a.wipDeps=a.currentDeps,a.wipIsRefreshing=!1,a.isDirty=!1),!n.isRefreshing&&Ae(a.wipDeps,t))return a.isDirty&&je(n,a),a.wip;let s=e();return c&&n.devStrictMode&&e(),a.wip=s,a.wipDeps=t,a.wipIsRefreshing=n.isRefreshing,a.isDirty||(a.isDirty=!0,m(n.root,()=>{a.wip=a.current,a.wipDeps=a.currentDeps,a.wipIsRefreshing=!1,a.isDirty=!1})),je(n,a),s},Ne=(e,t)=>Me(()=>e,t);function Pe(e,t){re(e,t,`insertion`)}function Fe(e){let t=o(),n=ie(e);return n.current!==e&&p(t,()=>{n.current=e}),ie(((...e)=>{if(c&&s())throw Error(`useEffectEvent cannot be called during render`);return n.current(...e)})).current}var Ie=e=>typeof e==`object`&&!!e&&typeof e.then==`function`,Le=()=>{},Re=e=>{let t=e;switch(typeof t.status==`string`?t.status!==`fulfilled`&&t.status!==`rejected`&&e.then(Le,Le):(t.status=`pending`,e.then(e=>{t.status===`pending`&&(t.status=`fulfilled`,t.value=e)},e=>{t.status===`pending`&&(t.status=`rejected`,t.reason=e)})),t.status){case`fulfilled`:return t.value;case`rejected`:throw t.reason;default:throw e}},ze=e=>Ie(e)?Re(e):_e(e),Be=!1,Ve=(e,t,n=t)=>{let r=o().isNeverMounted,i=r?n():t();c&&!Be&&(!r||n===t)&&(Object.is(i,t())||(Be=!0,console.error(`The result of getSnapshot should be cached to avoid an infinite loop`)));let[,a]=Ee(e=>e+1,0),s=ie(0),l=Fe(()=>{try{if(Object.is(i,t()))return s.current=0,!1}catch{}return!0});return E(()=>e(()=>{l()&&a()}),[e]),E(()=>{if(l()){if(++s.current>50)throw s.current=0,Error(`Maximum update depth exceeded. The result of getSnapshot should be cached to avoid an infinite loop.`);a()}},[e,i,t]),i},He=(e,t)=>{},Ue=0,We=()=>{let e=ie(null);return e.current??=`:tap${Ue++}:`,e.current},Ge=(e,t,n)=>{let r=()=>{if(!e)return;let n=t();if(typeof e==`function`){let t=e(n);return typeof t==`function`?t:()=>e(null)}return e.current=n,()=>{e.current=null}};n==null?E(r):E(r,[...n,e])},Ke=b.default;function qe(e){let t=(0,b.useRef)(e);return(0,b.useInsertionEffect)(()=>{t.current=e}),(0,b.useCallback)(((...e)=>t.current(...e)),[])}var Je=Ke.useEffectEvent??qe,O=()=>s()!==null,k=b.default,A=e=>O()?ke(e):k.useState(e),Ye=(e,t,n)=>O()?Ee(e,t,n):k.useReducer(e,t,n),j=e=>O()?ie(e):k.useRef(e),M=(e,t)=>O()?Me(e,t):k.useMemo(e,t),Xe=(e,t)=>O()?Ne(e,t):k.useCallback(e,t),N=(e,t)=>O()?E(e,t):k.useEffect(e,t),Ze=(e,t)=>O()?E(e,t):k.useLayoutEffect(e,t),Qe=e=>O()?Fe(e):Je(e),$e=(e,t,n)=>O()?Ve(e,t,n):k.useSyncExternalStore(e,t,n),et=(e,t)=>O()?void 0:k.useDebugValue(e,t),P=(e,t)=>O()?Pe(e,t):k.useInsertionEffect(e,t),tt=()=>O()?We():k.useId(),nt=(e,t,n)=>O()?Ge(e,t,n):k.useImperativeHandle(e,t,n),rt=e=>k.forwardRef(e),it=(e,t)=>k.memo(e,t),at=k.Fragment,ot=(...e)=>k.createElement(...e),st=(...e)=>k.cloneElement(...e),ct=e=>k.isValidElement(e);k.Children,k.Suspense;var lt=e=>{let t=k.createContext(e);return ue(t,e),t},ut=e=>O()&&pe(e)?ze(e):k.use(e),dt=e=>O()&&pe(e)?ze(e):k.useContext(e),F=(e,t)=>{if(e.length!==0){if(e.length===1)throw e[0];for(let t of e)console.error(t);throw AggregateError(e,t)}},ft=50,I={schedulers:new Set,isScheduled:!1},L=null,pt=[],mt=class{_isDirty=!1;_task;constructor(e){this._task=e}get isDirty(){return this._isDirty}markDirty(){if(L&&(L.get(this)??0)>=ft)throw Error(`Maximum update depth exceeded. This can happen when a resource repeatedly calls setState inside useEffect.`);this._isDirty=!0,I.schedulers.add(this),_t()}runTask(){L?.set(this,(L.get(this)??0)+1),this._isDirty=!1,this._task()}settle(){this._isDirty=!1}},ht=[];new mt(()=>{let e=ht.splice(0),t=[];for(let n of e)try{n()}catch(e){t.push(e)}F(t,`Errors occurred while running scheduled tasks`)});var gt=e=>{if(L!==null){pt.push(e);return}e()},_t=()=>{I.isScheduled||(I.isScheduled=!0,yt())},vt=()=>{let e=L;L=new Map;let t=[];try{for(let e of I.schedulers)if(I.schedulers.delete(e),e.isDirty)try{e.runTask()}catch(e){t.push(e)}}finally{if(L=e,I.schedulers.clear(),I.isScheduled=!1,L===null)for(;pt.length>0;)try{pt.shift()()}catch(e){t.push(e)}}F(t,`Errors occurred during flushSync`)},yt=(()=>{if(typeof MessageChannel<`u`){let e=null,t;return()=>{if(!e){let n=new MessageChannel;n.port1.onmessage=()=>{e?.unref?.(),vt()},e=n.port1,t=n.port2}e.ref?.(),t.postMessage(null)}}return()=>setTimeout(vt,0)})(),bt=e=>{if(L!==null)return c&&console.warn(`flushTapSync was called from inside a render or commit. The flush is deferred until the current pass completes.`),e();let t=I;I={schedulers:new Set,isScheduled:!0};try{let t=e();return vt(),t}finally{let e=I.schedulers;if(I=t,e.size>0){for(let t of e)I.schedulers.add(t);_t()}}};function xt(e){if(e.length===0)return;let t;for(let n=0;n<e.length;n++)try{e[n]()}catch(e){(t??=[]).push(e)}t!==void 0&&F(t,`Errors during commit`)}function St(e){let t=e.setup,n=e.setupDeps,r=e.generation,i;try{let e=t();if(e!==void 0&&typeof e!=`function`)throw Error(`An effect function must either return a cleanup function or nothing. Received: ${typeof e}`);i=e}finally{e.generation===r?(e.cleanup=i,e.deps=n):i?.()}}var Ct=e=>e.setup===void 0?!1:e.deps===null||e.setupDeps===void 0||!Ae(e.deps,e.setupDeps);function wt(e,t){let n;for(let t of e)Ct(t)&&(n??=[]).push(t);if(n===void 0)return t;for(let e of n)if(e.deps=null,e.cleanup!==void 0)try{e.cleanup()}catch(e){(t??=[]).push(e)}finally{e.cleanup=void 0}for(let e of n)try{St(e)}catch(e){(t??=[]).push(e)}return t}function Tt(e,t=!0){let n;e.insertionCells!==null&&t&&(n=wt(e.insertionCells,n)),n=wt(e.effectCells,n),n!==void 0&&F(n,`Errors during commit`)}function Et(e){let t;for(let n of e)if(n.deps=null,n.cleanup)try{n.cleanup?.()}catch(e){(t??=[]).push(e)}finally{n.cleanup=void 0}t!==void 0&&F(t,`Errors during cleanup`)}var Dt={useState:ke,useReducer:Ee,useRef:ie,useMemo:Me,useCallback:Ne,useEffect:E,useLayoutEffect:E,useInsertionEffect:Pe,useEffectEvent:Fe,useContext:_e,use:ze,useSyncExternalStore:Ve,useDebugValue:He,useId:We,useImperativeHandle:Ge,useMemoCache:y},Ot=b.default,kt=Ot.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE??Ot.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,At=kt==null?null:`H`in kt?{get current(){return kt.H},set current(e){kt.H=e}}:`ReactCurrentDispatcher`in kt?{get current(){return kt.ReactCurrentDispatcher.current},set current(e){kt.ReactCurrentDispatcher.current=e}}:null;function jt(e){if(!At)return e();let t=At.current;At.current=Dt;try{return e()}finally{At.current=t}}function Mt(e,t,n=void 0,r){return{hook:e,root:t,markDirty:n,devStrictMode:r,cells:[],effectCells:[],insertionCells:null,hostCells:null,contextDeps:null,wipContextDeps:null,wipCommitCallbacks:null,memoCache:{current:null,workInProgress:null,refreshedIndices:null,index:0},renderPendingCells:null,currentIndex:0,isRefreshing:!1,isFirstRender:!0,isMounted:!1,isReleased:!1,isNeverMounted:!0}}function Nt(e){e.wipCommitCallbacks=null,e.wipContextDeps=null,e.memoCache.workInProgress=null,e.memoCache.refreshedIndices=null}function Pt(e,t,n){try{t?(e.isReleased=!0,e.insertionCells!==null&&Et(e.insertionCells)):e.isMounted&&(e.isMounted=!1,Et(e.effectCells))}catch(e){(n??=[]).push(e)}if(e.hostCells!==null){for(let r of e.hostCells)if(r.fiber!==null&&(n=Pt(r.fiber,t,n)),r.fibers!==null)for(let{fiber:e}of r.fibers.values())n=Pt(e,t,n)}return n}function Ft(e,t=!0){let n;t&&(n=Pt(e,!0,n)),n=Pt(e,!1,n),n!==void 0&&F(n,`Errors during cleanup`)}function It(e){let t;for(let n of e)n.isReleased&&(t=Pt(n,!0,t));for(let n of e)t=Pt(n,!1,t);t!==void 0&&F(t,`Errors during cleanup`)}function R(e,t){if(e.renderPendingCells!==null){for(let t of e.renderPendingCells)t.renderQueue=null;e.renderPendingCells.clear()}let n=0,r,i=e.isRefreshing;e.isRefreshing=i||(s()?.isRefreshing??!1);try{do{if(++n>25)throw Error(`Too many re-renders. tap limits the number of renders to prevent an infinite loop.`);e.memoCache.index=0,a(e,()=>{r=jt(()=>e.hook(...t))})}while((e.renderPendingCells?.size??0)>0)}catch(t){throw Nt(e),t}finally{e.isRefreshing=i}return be(e),r}function Lt(e){let t=e.wipCommitCallbacks;e.wipCommitCallbacks=null;let n=c&&!e.isMounted&&e.devStrictMode===`root`;e.isMounted=!0,e.isNeverMounted=!1,t!==null&&(e.contextDeps=e.wipContextDeps,u(e.root),e.memoCache.workInProgress!==null&&(e.memoCache.current=e.memoCache.workInProgress,e.memoCache.workInProgress=null,e.memoCache.refreshedIndices=null),xt(t)),n&&(Tt(e,t!==null),Ft(e,!1),e.isMounted=!0),Tt(e,!n&&t!==null)}var Rt=()=>{let e=o();return e.devStrictMode?e.isFirstRender?`child`:`root`:null},zt=()=>`child`,Bt=()=>null,Vt=()=>{if(!c)return Bt;let e=j(0);return A(()=>e.current++),e.current===2?zt:Bt},Ht=()=>s()?Rt:Vt(),Ut=e=>{let t=o(),n=t.currentIndex++,r=t.cells[n],i;if(r===void 0){t.isFirstRender||w();let r=e instanceof Map;i={type:`host`,fiber:r?null:e,fibers:r?e:null},t.cells[n]=i,(t.hostCells??=[]).push(i)}else r.type!==`host`&&T(),i=r;return i.fibers===null&&i.fiber!==e&&p(t,()=>{i.fiber=e}),i},Wt=(e,t)=>{if(!(e instanceof Map))return t(e);for(let{fiber:n}of e.values())t(n)},Gt=e=>{e.isReleased=!1},Kt=e=>{e.isReleased=!0,e.isMounted||queueMicrotask(()=>{e.isReleased&&Ft(e,!0)})},qt=e=>{P(()=>(Wt(e,Gt),()=>Wt(e,Kt)),[e]),N(()=>()=>{It(e instanceof Map?Array.from(e.values(),({fiber:e})=>e):[e])},[e])},Jt=e=>s()?Ut(e):(qt(e),null),Yt=()=>{let e=j(0),t=e.current,n=o();return{version:t,markDirty:M(()=>()=>{e.current++,n.markDirty?.()},[n]),root:n.root}},Xt=()=>{let[e]=A(()=>l((e,t)=>{let i=!1;r(t=>(i=!e(),i?t:t+1)),i||n(()=>e()&&t())})),[t,n]=Ye((t,n)=>(d(e,t),t+ +!!n()),0),[,r]=A(0);return d(e,t),{root:e,version:t,markDirty:void 0}},Zt=()=>{let e=Ht(),{root:t,version:n,markDirty:r}=s()?Yt():Xt();return{version:n,createFiber:Xe((n,i,a)=>Mt(n,t,a?()=>{a(),r?.()}:r,e()),[])}},Qt=e=>e(),$t=e=>{let t=[];for(let n of e)try{n()}catch(e){t.push(e)}F(t,`Errors occurred while notifying Tap root subscribers`)},en=(e,t,n)=>{let r=new mt(()=>s.handleUpdate()),i=[],a=l((e,t)=>{i.length===0&&!e()||(i.push(t),r.markDirty())}),o=Mt(Qt,a,void 0,t),s={scheduler:r,queue:i,fiber:o,subscribers:new Set,pendingHostRender:!1,isMounted:!1,hasRendered:!1,committedRender:e,context:new Map,value:void 0,applyQueue:()=>{d(a,a.committedVersion);for(let e of i)c&&o.devStrictMode&&e(),e();return d(a,a.committedVersion+a.changelog.length),i.length},publish:(e,t)=>{r.isDirty||a.committedVersion!==t||s.value===e||(s.value=e,gt(()=>$t(s.subscribers)))},finishFlush:(e,t,n)=>{u(a),i.splice(0,n),s.pendingHostRender=!1,i.length===0&&r.settle(),s.isMounted&&Lt(o),s.publish(e,t)},handleUpdate:()=>{let e=s.applyQueue(),t;try{c&&o.devStrictMode&&le(s.context,()=>R(o,[s.committedRender])),t=le(s.context,()=>R(o,[s.committedRender]))}catch(e){if(d(a,a.committedVersion),Ie(e)){let t=()=>{s.isMounted&&r.markDirty()};e.then(t,t);return}if(s.isMounted){s.pendingHostRender=!0,n(e=>e+1);return}throw e}if(r.isDirty)throw Error(`Scheduler is dirty, this should never happen`);s.finishFlush(t,a.version,e)}};return s},tn=e=>{let[,t]=A(0),n=Ht(),r=j(null),i=r.current??=en(e,n(),t),a=ce(),o=i.scheduler.isDirty||i.pendingHostRender?i.applyQueue():0,s=le(a,()=>R(i.fiber,[e])),c={render:e,context:a,value:s,drained:o,wip:i.fiber.wipCommitCallbacks,version:i.fiber.root.version,processed:!1};return i.hasRendered||(i.hasRendered=!0,i.committedRender=e,i.context=a,i.value=s),N(()=>(i.isMounted=!0,()=>{i.isMounted=!1}),[i]),Jt(i.fiber),N(()=>{if(c.processed){i.fiber.isMounted||(Lt(i.fiber),i.queue.length&&!i.scheduler.isDirty&&i.scheduler.markDirty());return}if(c.processed=!0,i.committedRender=c.render,i.context=c.context,i.fiber.wipCommitCallbacks!==c.wip){i.scheduler.isDirty||i.handleUpdate();return}if(c.drained>0&&i.fiber.root.version===c.version){i.finishFlush(c.value,c.version,c.drained);return}Lt(i.fiber),i.publish(c.value,c.version)}),M(()=>({getValue:()=>i.value,subscribe:e=>(i.subscribers.add(e),()=>i.subscribers.delete(e))}),[i])};function nn(e){return(...t)=>({hook:e,args:t})}function rn(e,t,n){return typeof t==`function`?(...n)=>rn(e,t(...n)):n?{...t,key:e,deps:n}:{...t,key:e}}var an=(e,t)=>({fiber:e,key:t,currentDeps:null,current:null,wipDeps:null,wip:null});function on(e){let{version:t,createFiber:n}=Zt(),r=j(null),i=r.current??=an(n(e.hook,e.key),e.key),a=M(()=>i.fiber.hook===e.hook&&i.key===e.key&&!i.fiber.isReleased?i.fiber:n(e.hook,e.key),[i,e.hook,e.key,n]);i.wipDeps=i.currentDeps,i.wip=i.current;let o=[a,t,e.args];(s()?.isRefreshing||Se(a)||i.currentDeps===null||!Ae(i.currentDeps,o))&&(i.wipDeps=o,i.wip={value:R(a,e.args)});let c=i.wip,l=Jt(a);return N(()=>{if(i.currentDeps=i.wipDeps,i.current=i.wip,i.fiber=a,i.key=e.key,Lt(a),l!==null)return()=>{l.fiber!==a&&Ft(a,!0)}},[i,l,a,e.key,c]),c.value}var sn=(e,t,n)=>{let r=j(null),i=r.current??={currentDeps:null,current:null},a=!n&&i.currentDeps&&Ae(i.currentDeps,t)?i.current:e();return N(()=>{i.currentDeps=t,i.current=a}),a},cn=(e,t)=>{let n=e.get(t);n&&(n.isDirty=!0)},ln=(e,t)=>!e.isDirty&&!Se(e.fiber)&&t!==void 0&&e.committedDeps!==void 0&&Ae(e.committedDeps,t),un=e=>{if(!xe())return!1;for(let{fiber:t}of e.values())if(Se(t))return!0;return!1};function dn(e){let[t]=A(()=>new Map),{version:n,createFiber:r}=Zt(),i=s()?.isRefreshing??!1,a=un(t),o=!1,c=sn(()=>{let n=new Set,a=[],s=0;for(let c=0;c<e.length;c++){let l=e[c],u=l.key;if(u===void 0)throw Error(`useResources did not provide a key for array at index ${c}`);if(n.has(u))throw Error(`Duplicate key ${u} in useResources`);n.add(u);let d=t.get(u);if(!d){let e=r(l.hook,l.key,()=>cn(t,u));d={fiber:e,next:{value:R(e,l.args),deps:l.deps},isDirty:!1,committedDeps:void 0,committedValue:void 0},s++,t.set(u,d)}else if(d.fiber.hook!==l.hook){let e=r(l.hook,l.key,()=>cn(t,u)),n=R(e,l.args);d.next={value:n,deps:l.deps,remount:e},o=!0}else if(!i&&ln(d,l.deps))typeof d.next==`object`&&Nt(d.fiber),d.fiber.contextDeps&&be(d.fiber,d.fiber.contextDeps),d.next=`skip`;else{let e=R(d.fiber,l.args);d.next={value:e,deps:l.deps}}a.push(typeof d.next==`object`?d.next.value:d.committedValue)}if(t.size>a.length-s)for(let e of t.keys())n.has(e)||(t.get(e).next=`delete`,o=!0);return a},[e,t,r,n],i||a);return Jt(t),N(()=>{if(o){let e=[];for(let[n,r]of t.entries()){let i=r.next;i===`delete`?(e.push(r.fiber),t.delete(n)):i!==`skip`&&i.remount&&(e.push(r.fiber),r.fiber=i.remount)}for(let t of e)t.isReleased=!0;It(e)}for(let e of t.values()){let t=e.next;t===`skip`?!e.fiber.isNeverMounted&&!e.fiber.isMounted&&Lt(e.fiber):t!==`delete`&&(Lt(e.fiber),e.committedDeps=t.deps,e.committedValue=t.value,e.isDirty=!1,e.next=`skip`)}},[c,t,o]),i?c.slice():c}var fn=e=>e(),pn=e=>{let{createFiber:t}=Zt(),[n]=A(()=>t(fn,void 0)),r=R(n,[e]);Jt(n);let i=!1,a=()=>{i&&n.isMounted||(i=!0,Lt(n))};return N(a),{value:r,effects:a}},z=(e,t,n)=>{let r=e=>{console.error(`[assistant-ui] ${n} listener threw an error`,e)};for(let n of e)try{let e=n(typeof t==`function`?t():t);e!==null&&(typeof e==`object`||typeof e==`function`)&&`then`in e&&typeof e.then==`function`&&Promise.resolve(e).catch(r)}catch(e){r(e)}},mn=e=>e,hn=new Set([`$$typeof`,`nodeType`,`then`,`__v_raw`,`__v_isRef`,`__v_isReactive`,`__v_isReadonly`,`__v_isShallow`,`__v_skip`]),gn=(e,t)=>{if(e===Symbol.toStringTag)return t;if(typeof e!=`symbol`){if(e===`toJSON`)return()=>t;if(!hn.has(e))return!1}},_n=class{getOwnPropertyDescriptor(e,t){let n=this.get(e,t);if(n!==void 0)return{value:n,writable:!1,enumerable:!0,configurable:!0}}set(){return!1}setPrototypeOf(){return!1}defineProperty(){return!1}deleteProperty(){return!1}preventExtensions(){return!1}},vn=Symbol(`assistant-ui.store.clientId`),yn=Symbol(`assistant-ui.store.instanceTag`),bn=(e,t)=>{let n=new Proxy((()=>{}),{apply:()=>(t(),n),get:(n,r)=>r===`source`?e.source:r===`query`?e.query:r===`name`?e.name:r===vn?wn(t()):t()[r],has:(e,n)=>n===`source`||n===`query`||n===`name`||n===vn||n in t(),ownKeys:()=>Reflect.ownKeys(t()),getOwnPropertyDescriptor:(e,n)=>{if(!(typeof n==`symbol`||!(n in t())))return{value:t()[n],writable:!1,enumerable:!0,configurable:!0}}});return n},xn=(e,t)=>{let n=()=>{throw Error(e)};return new Proxy((()=>{}),{apply:n,get:(e,r)=>{if(r===`source`||r===`query`)return null;if(r===`name`)return t;if(r===vn)return n();let i=gn(r,`AssistantClientAccessor`);return i===!1?n():i},has:(e,t)=>t===`source`||t===`query`||t===`name`,ownKeys:()=>[],getOwnPropertyDescriptor:()=>void 0})},Sn=e=>e?.source!=null,Cn=e=>e?.source===null,wn=e=>e[vn]??e,Tn=e=>e[yn]??wn(e),En=e=>e===`optional`||e===`subscribe`||e===`on`||e===`__proto__`||typeof e==`symbol`,Dn=e=>{let t=[];for(let n in e)En(n)||t.push(n);return t},On=class extends _n{#e;constructor(e){super(),this.#e=e}get(e,t){let n=gn(t,`OptionalAssistantClient`);if(n!==!1)return n;if(En(t))return;let r=this.#e[t];return Sn(r)?r:void 0}ownKeys(){return Dn(this.#e)}has(e,t){return!En(t)&&t in this.#e}},kn=e=>new Proxy({},new On(e)),An=()=>()=>{},jn=`You are using a component or hook that requires an AuiProvider. Wrap your component in an <AuiProvider> component.`,Mn=class extends _n{#e;#t;#n;#r;constructor(e,t,n){super(),this.#e=e,this.#t=t,this.#n=n}get(e,t){if(t===`subscribe`||t===`on`)return An;if(t===`optional`)return this.#r??=kn(this.#n());let n=gn(t,this.#e);return n===!1?xn(this.#t(String(t)),String(t)):n}ownKeys(){return[`subscribe`,`on`,`optional`]}getOwnPropertyDescriptor(e,t){if(t!==`optional`)return super.getOwnPropertyDescriptor(e,t);let n=this.get(e,t);if(n!==void 0)return{value:n,writable:!1,enumerable:!1,configurable:!0}}has(e,t){return t===`subscribe`||t===`on`||t===`optional`}},Nn=((e,t)=>{let n=new Proxy({},new Mn(e,t,()=>n));return n})(`DefaultAssistantClient`,()=>jn),Pn=()=>new Proxy({},{get(e,t){let n=gn(t,`AssistantClient`);return n===!1?xn(`The current scope does not have a "${String(t)}" property.`,String(t)):n}}),Fn=lt(Nn),In=()=>{},Ln=new WeakMap,Rn=e=>Ln.get(e)??In,zn=(e,t)=>{Ln.set(e,t)},Bn=()=>dt(Fn),Vn=(e,t)=>he(Fn,e,t),Hn=Symbol(`assistant-ui.transform-scopes`);function Un(e,t){let n=e;if(n[Hn])throw Error(`transformScopes is already attached to this resource`);n[Hn]=t}function Wn(e){return e[Hn]}var Gn=e=>typeof e==`string`?{scope:e.split(`.`)[0],event:e}:{scope:e.scope,event:e.event},Kn=Symbol(`assistant-ui.store.clientIndex`),qn=e=>e[Kn],Jn=lt([]),Yn=()=>ut(Jn),Xn=(e,t)=>{let n=x(3),r=Yn(),i;return n[0]!==e||n[1]!==r?(i=[...r,e],n[0]=e,n[1]=r,n[2]=i):i=n[2],he(Jn,i,t)},Zn=Symbol(`assistant-ui.store.getValue`),Qn=e=>{let t=e[Zn];if(!t)throw Error(`Client scope contains a non-client resource. Ensure your Derived get() returns a client created with useClientResource(), not a plain resource.`);return t.getState?.()},$n=new Map;function er(e){let t=$n.get(e);return t||(t=function(...t){if(!this||typeof this!=`object`)throw Error(`Method "${String(e)}" called without proper context. This may indicate the function was called incorrectly.`);let n=this[Zn];if(!n)throw Error(`Method "${String(e)}" called on invalid client proxy. Ensure you are calling this method on a valid client instance.`);let r=n[e];if(!r)throw Error(`Method "${String(e)}" is not implemented.`);if(typeof r!=`function`)throw Error(`"${String(e)}" is not a function.`);return r(...t)},$n.set(e,t)),t}var tr=class extends _n{boundFns;cachedReceiver;outputRef;tagRef;index;self;constructor(e,t,n){super(),this.outputRef=e,this.tagRef=t,this.index=n}get(e,t,n){if(t===Zn)return this.outputRef.current;if(t===Kn)return this.index;if(t===vn)return this.self;if(t===yn)return this.tagRef.current;let r=gn(t,`ClientProxy`);if(r!==!1)return r;let i=this.outputRef.current[t];if(typeof i==`function`){if(n===void 0)return i;(!this.boundFns||this.cachedReceiver!==n)&&(this.boundFns=new Map,this.cachedReceiver=n);let e=this.boundFns.get(t);return e||(e=er(t).bind(n),this.boundFns.set(t,e)),e}return i}ownKeys(){return Object.keys(this.outputRef.current)}has(e,t){return t===Zn||t===Kn||t===vn||t===yn||t in this.outputRef.current}},nr=e=>{let t=j(null),n=j(null),r=M(()=>({}),[e.hook,e.key]),i=Yn().length,a=M(()=>{let e=new tr(t,n,i),r=new Proxy({},e);return e.self=r,r},[i]),o=Xn(a,function(){return on(e)});return t.current||(t.current=o,n.current=r),N(()=>{t.current=o,n.current=r}),{methods:a,state:o.getState?.(),key:e.key}},rr=nn(nr),ir=0,ar=0,or=e=>{ir++,ar++;try{return e()}finally{ar--,ir++}},sr=e=>{let t,n=new Map,r=-1,i=t=>{if(ar===0)return Qn(e[t]());if(r!==ir)n.clear(),r=ir;else if(n.has(t))return n.get(t);let i=Qn(e[t]());return n.set(t,i),i};class a extends _n{get(t,n){let r=gn(n,`OptionalAssistantState`);if(r!==!1)return r;let a=n;if(!En(a)&&Sn(e[a]))return i(a)}ownKeys(){return Dn(e)}has(t,n){return!En(n)&&n in e}}class o extends _n{get(e,n){let r=gn(n,`AssistantState`);if(r!==!1)return r;if(n===`optional`)return t??=new Proxy({},new a);let o=n;if(!En(o))return i(o)}ownKeys(){return[...Dn(e),`optional`]}has(t,n){return n===`optional`||!En(n)&&n in e}}return new Proxy({},new o)},cr=new WeakMap,lr=e=>{let t=cr.get(e);return t||(t=sr(e),cr.set(e,t)),t},ur=lt(null),dr=Symbol(`aui.scope-effect-unapplied`),fr=(e,t)=>he(ur,e,t),pr=()=>{let e=ut(ur);if(!e)throw Error(`AssistantTapContext is not available`);return e},mr=()=>pr().clientRef,hr=(e,t,n)=>{let r=x(8),{clientRef:i}=pr(),a;r[0]!==i||r[1]!==t||r[2]!==e?(a=()=>{let n=i.current;if(n===null)throw Error(`useAssistantScopeEffect ran before the client was committed. This is likely an internal bug in assistant-ui.`);let r=()=>{let t=i.current?.[e];return t!==void 0&&Sn(t)?Tn(t):void 0},a=dr,o,s=e=>{if(o?.(),o=void 0,a=dr,e!==void 0){let e=t();o=typeof e==`function`?e:void 0}a=e};s(r());let c=n.subscribe(()=>{let e=r();e!==a&&s(e)});return()=>{c(),o?.()}},r[0]=i,r[1]=t,r[2]=e,r[3]=a):a=r[3];let o;r[4]!==i||r[5]!==n||r[6]!==e?(o=[i,e,...n],r[4]=i,r[5]=n,r[6]=e,r[7]=o):o=r[7],N(a,o)},gr=()=>{let e=x(3),{emit:t}=pr(),n=Yn(),r;return e[0]!==n||e[1]!==t?(r=(e,r)=>{t(e,r,n)},e[0]=n,e[1]=t,e[2]=r):r=e[2],Qe(r)},_r=lt(void 0),vr=(e,t)=>{let n=ut(_r);return he(_r,e??n,t)},yr=(e,t)=>{if(Array.isArray(e)!==Array.isArray(t))return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!Object.is(e[n],t[n]))return!1;return!0}let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Object.hasOwn(t,n)&&Object.is(e[n],t[n]))},br=Symbol(`assistant-ui.derived-hook`),xr=e=>{e[br]=!0},Sr=e=>e[br]===!0,Cr=e=>{console.error(`NotificationManager: event listener error`,e)},wr=(e,t,n)=>{try{let r=e(t,n);r!==null&&(typeof r==`object`||typeof r==`function`)&&typeof r.then==`function`&&Promise.resolve(r).catch(Cr)}catch(e){Cr(e)}},Tr=()=>{let e=new Map,t=new Set,n=new Set;return{on(n,r){let i=r;if(n===`*`)return t.add(i),()=>t.delete(i);let a=e.get(n);return a||(a=new Set,e.set(n,a)),a.add(i),()=>{a.delete(i),a.size===0&&e.get(n)===a&&e.delete(n)}},emit(n,r,i){!e.has(n)&&t.size===0||queueMicrotask(()=>{let a=e.get(n);if(a)for(let e of a)wr(e,r,i);if(t.size>0){let e={event:n,payload:r};for(let n of t)wr(n,e,i)}})},subscribe(e){return n.add(e),()=>n.delete(e)},notifySubscribers(){or(()=>{for(let e of n)try{e()}catch(e){console.error(`NotificationManager: subscriber callback error`,e)}})}}},Er=()=>A(Tr)[0],Dr=()=>{let[e]=A(()=>({controller:new AbortController,generation:0}));return P(()=>{let t=++e.generation;return()=>queueMicrotask(()=>{e.generation===t&&e.controller.abort()})},[e]),e.controller.signal},Or=e=>{let t=M(()=>({}),[]);return t.v!==void 0&&yr(t.v,e)?t.v:(t.v=e,e)},kr=e=>{let t=x(2),n=j(void 0),r;return t[0]===e?r=t[1]:(r=t=>{let r=e(t);return n.current!==void 0&&yr(n.current,r)?n.current:(n.current=r,r)},t[0]=e,t[1]=r),r},Ar=(()=>{try{return!1}catch{return!1}})(),jr=(e,t)=>{let n={...e},r=new Set,i=!0;for(;i;){i=!1;for(let e of Object.values(n)){if(r.has(e.hook))continue;r.add(e.hook);let a=Wn(e.hook);if(a){a(n,t),i=!0;break}}}return n},Mr=e=>Sr(e.hook),Nr=e=>{if(!Mr(e))return{source:`root`,query:{}};let t=e.args[0];return{source:t.source,query:t.query??{}}},Pr=Symbol.for(`aui.event-receiver-ref`),Fr=(e,t)=>{let n=e===Nn?Pn():e,r=Object.create(n);Object.assign(r,t);let i;return Object.defineProperty(r,"optional",{get:()=>i??=kn(r),enumerable:!1}),r},Ir=({notifications:e,clientRef:t})=>M(()=>({subscribe:e.subscribe,on:function(n,r){if(!this)throw Error(`const { on } = useAui() is not supported. Use aui.on() instead.`);let{scope:i,event:a}=Gn(n),o=n[Pr];if(i!==`*`&&!o&&Cn(this[i]))throw Error(`Scope "${i}" is not available. Use { scope: "*", event: "${a}" } to listen globally.`);let s=e.on(a,(e,n)=>{if(i===`*`)return r(e);let a=((o??t).current??this)[i];if(!Sn(a))return;let s=wn(a);if(s===n[qn(s)])return r(e)});if(i!==`*`){if(o){if(t.parent===Nn)return s}else if(Cn(t.parent[i]))return s}let c=t.parent.on(n,r);return()=>{s(),c()}}}),[e,t]),Lr=e=>{let t=x(5),n;t[0]===e?n=t[1]:(n=Nr(e),t[0]=e,t[1]=n);let{source:r,query:i}=n,a=Or(i),o;return t[2]!==r||t[3]!==a?(o={source:r,query:a},t[2]=r,t[3]=a,t[4]=o):o=t[4],Or(o)},Rr=(e,t)=>{let n=x(3),r;return n[0]!==t||n[1]!==e?(r=t?e:rr(e),n[0]=t,n[1]=e,n[2]=r):r=n[2],on(r)},zr=nn((e,t)=>{let n=Bn(),r=Mr(t),i=Rr(t,r),a=r?i:i.methods,o=Lr(t),s=M(()=>bn({name:e,...o},()=>a),[e,o,a]);return n[e]=s,s}),Br=e=>{let t=x(2),n;return t[0]===e?n=t[1]:(n=e.map(Zr),t[0]=e,t[1]=n),dn(n)},Vr=(e,t)=>{let n=Or(t),r=M(()=>({}),[]);return r.deps!==n&&(r.deps=n,r.client=e),r.client},Hr=({parent:e,entries:t,clientRef:n,notifications:r})=>{let i=Fr(e,Ir({notifications:r,clientRef:n}));return{client:Vr(i,[e,...fr(M(()=>({clientRef:n,emit:r.emit}),[n,r.emit]),function(){return Vn(i,function(){return Br(t)})})])}},Ur=({parent:e,entries:t,destroySignal:n})=>{let r=j({parent:e,current:null}).current,{value:i,effects:a}=pn(function(){let i=Er(),{client:a}=vr(n,function(){return Hr({parent:e,entries:t,clientRef:r,notifications:i})});return N(()=>e.subscribe(i.notifySubscribers),[e,i]),N(()=>i.notifySubscribers()),a});return P(()=>{r.parent=e,r.current=i},[i,e,r]),{client:i,effects:a}},Wr=({parent:e,entries:t,destroySignal:n})=>{let r=j({parent:e,current:null}).current,{value:i,effects:a}=pn(function(){let i=Er(),a=tn(function(){return vr(n,function(){return Hr({parent:e,entries:t,clientRef:r,notifications:i})})}),o=$e(a.subscribe,()=>a.getValue().client,()=>a.getValue().client);return N(()=>{let t=()=>bt(()=>{r.current=a.getValue().client,i.notifySubscribers()}),n=a.subscribe(t),o=e.subscribe(t);return()=>{n(),o()}},[a,e,i]),o});return P(()=>{r.parent=e,r.current=i},[i,e,r]),{client:i,effects:a}},Gr=(e,t,n,r)=>{let{get:i}=r.args[0],a=$e(e.subscribe,()=>i(e),()=>i(e)),o=Lr(r),s=M(()=>bn({name:n,...o},()=>a),[n,o,a]);return t[n]=s,s},Kr=(e,t)=>{if(Ar){let[e]=A(()=>t.map(([e])=>e).join(`,`)),n=t.find(([,e])=>!Mr(e));if(n)throw Error(`Scope "${n[0]}" is a root scope but this useAui mounted derived-only; remount with a new key to change scope kinds.`);let r=t.map(([e])=>e).join(`,`);if(r!==e)throw Error(`A derived-only config mounted scopes [${e}] but now has [${r}]; remount with a new key to change the scope set.`)}let n=j({parent:e,current:null}).current,r=Fr(e,{subscribe:e.subscribe,on:function(t,r){if(!this)throw Error(`const { on } = useAui() is not supported. Use aui.on() instead.`);let{scope:i,event:a}=Gn(t);if(i===`*`)return e.on(t,r);let o=t[Pr];if(!o&&Cn(this[i]))throw Error(`Scope "${i}" is not available. Use { scope: "*", event: "${a}" } to listen globally.`);return e.on({scope:i,event:a,[Pr]:o??n},r)}}),i=Vr(r,[e,...t.map(([t,n])=>Gr(e,r,t,n))]);return P(()=>{n.parent=e,n.current=i},[i,e,n]),i},qr=(e,t)=>{let n=x(8),r;n[0]!==t||n[1]!==e?(r=Object.entries(jr(t,e)),n[0]=t,n[1]=e,n[2]=r):r=n[2];let i=r,a;n[3]===i?a=n[4]:(a=()=>i.length===0||i.some(Qr),n[3]=i,n[4]=a);let[o]=A(a),s;return n[5]!==i||n[6]!==o?(s={entries:i,rooted:o},n[5]=i,n[6]=o,n[7]=s):s=n[7],s},Jr=(e,t,n,r)=>{let{entries:i,rooted:a}=qr(e,t);return a?n({parent:e,entries:i,destroySignal:r}):{client:Kr(e,i)}},Yr=(e,t,n)=>Jr(e,t,Ur,n);function Xr(e){let t=Bn();if(e){let{client:n,effects:r}=Jr(t,e,Wr,Dr());return r&&zn(n,r),n}return t}function Zr(e){let[t,n]=e;return rn(t,zr(t,n))}function Qr(e){let[,t]=e;return!Mr(t)}var $r=e=>{let t=x(6),n=Xr(),r;t[0]===n?r=t[1]:(r=lr(n),t[0]=n,t[1]=r);let i=r,a,o;t[2]!==i||t[3]!==e?(a=()=>e(i),o=()=>e(i),t[2]=i,t[3]=e,t[4]=a,t[5]=o):(a=t[4],o=t[5]);let s=$e(n.subscribe,a,o);if(typeof s==`object`&&s&&(s===i||s===i.optional))throw Error(`You tried to return the entire AssistantState. This is not supported due to technical limitations.`);return et(s),s},B=Symbol(`skip-update`),V=(e,...t)=>{let n=[];for(let r of e)try{r(...t)}catch(e){n.push(e)}if(n.length===1)throw n[0];if(n.length>1){for(let e of n)console.error(e);throw AggregateError(n)}},ei=e=>{V(e)},ti=(e,t)=>{try{e()}catch(e){console.error(`[assistant-ui] Subscription rollback cleanup threw`,e)}throw t},ni=(e,t)=>e===void 0||t===void 0?e===t:yr(e,t),ri=class{_subscribers=new Set;subscribe(e){return this._subscribers.add(e),()=>this._subscribers.delete(e)}waitForUpdate(){return new Promise(e=>{let t=this.subscribe(()=>{t(),e()})})}_notifySubscribers(){V(this._subscribers)}},ii=class extends ri{_state;constructor(e){super(),this._state=e,this.subscribe=this.subscribe.bind(this),this.getState=this.getState.bind(this),this.getServerSnapshot=()=>e}getState(){return this._state}getServerSnapshot;setState(e){Object.is(e,this._state)||(this._state=e,this._notifySubscribers())}},ai=class{_subscriptions=new Set;_connection;get isConnected(){return!!this._connection}notifySubscribers(e,t){if(t){z(this._subscriptions,e,t);return}V(this._subscriptions,e)}_updateConnection(){if(this._subscriptions.size>0){if(this._connection)return;this._connection=this._connect()}else{let e=this._connection;this._connection=void 0,e?.()}}subscribe(e){this._subscriptions.add(e);try{this._updateConnection()}catch(t){throw this._subscriptions.delete(e),t}return()=>{this._subscriptions.delete(e),this._updateConnection()}}},H=class extends ai{get path(){return this.binding.path}binding;constructor(e){super(),this.binding=e;let t=e.getState();if(t===B)throw Error(`Entry not available in the store`);this._previousState=t}_previousState;getState=()=>(this.isConnected||this._syncState(),this._previousState);_syncState(){let e=this.binding.getState();return e===B||ni(e,this._previousState)?!1:(this._previousState=e,!0)}_connect(){let e=this.binding.subscribe(()=>{this._syncState()&&this.notifySubscribers()});try{return this._syncState(),e}catch(t){throw ti(e,t)}}},oi=class extends ai{get path(){return this.binding.path}binding;constructor(e){super(),this.binding=e}_previousStateDirty=!0;_previousState;getState=()=>{if(!this.isConnected||this._previousStateDirty){let e=this.binding.getState();e!==B&&(this._previousState===void 0||!ni(e,this._previousState))&&(this._previousState=e),this._previousStateDirty=!1}if(this._previousState===void 0)throw Error(`Entry not available in the store`);return this._previousState};_connect(){let e=this.binding.subscribe(()=>{this._previousStateDirty=!0,this.notifySubscribers()});return this._previousStateDirty=!0,e}},si=class extends ai{get path(){return this.binding.path}binding;constructor(e){super(),this.binding=e}getState(){return this.binding.getState()}outerSubscribe(e){return this.binding.subscribe(e)}_connect(){let e=()=>{this.notifySubscribers()},t=this.binding.getState(),n=t?.subscribe(e),r=()=>{let r=this.binding.getState();if(r===t)return;t=r;let i=n;n=void 0;try{i?.()}finally{n=r?.subscribe(e),e()}},i;try{i=this.outerSubscribe(r)}catch(e){throw ti(()=>n?.(),e)}return()=>ei([()=>i(),()=>n?.()])}},ci=class extends ai{config;constructor(e){super(),this.config=e}getState(){return this.config.binding.getState()}outerSubscribe(e){return this.config.binding.subscribe(e)}_connect(){let e=`Runtime event "${this.config.event}"`,t=t=>{this.notifySubscribers(t,e)},n=this.config.binding.getState(),r=n?.unstable_on(this.config.event,t),i=()=>{let e=this.config.binding.getState();if(e===n)return;n=e;let i=r;r=void 0;try{i?.()}finally{r=e?.unstable_on(this.config.event,t),this.config.notifyOnRebind&&t({})}},a;try{a=this.outerSubscribe(i)}catch(e){throw ti(()=>r?.(),e)}return()=>ei([()=>a(),()=>r?.()])}},li=e=>{if(!e.overwrite)return e;let{overwrite:t,...n}=e;return n},ui=e=>{let t=Array.from(e).map(e=>e.getModelContext()).sort((e,t)=>(t.priority??0)-(e.priority??0)),n=C();return t.reduce((e,t)=>{let r=t.priority??0;if(t.system&&(e.system?e.system+=`\n\n${t.system}`:e.system=t.system),t.tools)for(let[i,a]of Object.entries(t.tools)){let t=e.tools!==void 0&&Object.hasOwn(e.tools,i)?e.tools[i]:void 0;if(t&&t!==a){let o=n[i];if(o===r){if(!a.overwrite)throw Error(`You tried to define a tool with the name ${i}, but it already exists.`);e.tools[i]=li(a);continue}let s=o>r?t:a,c=o>r?a:t;e.tools[i]=li({...c,...s}),n[i]=Math.max(o,r);continue}e.tools||=C(),e.tools[i]=li(a),Object.hasOwn(n,i)||(n[i]=r)}return t.config&&(e.config={...t.config,...e.config}),t.callSettings&&(e.callSettings={...t.callSettings,...e.callSettings}),t.unstable_composerMetadata&&(e.unstable_composerMetadata={...t.unstable_composerMetadata,...e.unstable_composerMetadata}),e},{})},di=class{_providers=new Map;_providerUnsubscribes=new Map;getModelContext(){return ui(new Set(this._providers.values()))}registerModelContextProvider(e){let t=Symbol();this._providers.set(t,e);let n;try{n=e.subscribe?.(()=>{this.notifySubscribers()})}catch(e){this._providers.delete(t);try{this.notifySubscribers()}catch(e){console.error(e)}throw e}this._providerUnsubscribes.set(t,n),this.notifySubscribers();let r=!1;return()=>{if(r)return;r=!0,this._providers.delete(t);let e=this._providerUnsubscribes.get(t);this._providerUnsubscribes.delete(t);let n=!1,i,a=e=>{try{e()}catch(e){n?console.error(e):(n=!0,i=e)}};if(e&&a(e),a(()=>this.notifySubscribers()),n)throw i}}_subscribers=new Set;notifySubscribers(){V(this._subscribers)}subscribe(e){return this._subscribers.add(e),()=>{this._subscribers.delete(e)}}},fi=(e,t)=>e.length===t.length&&e.every((e,n)=>Object.is(e,t[n])),pi=(e,t)=>{let[n]=A(()=>({pending:void 0}));N(()=>{let r=n.pending;n.pending=void 0;let i;return r!==void 0&&fi(r.deps,t)?i=r:(r?.cleanup?.(),i={deps:t,cleanup:e()}),()=>{n.pending=i,queueMicrotask(()=>{n.pending===i&&(n.pending=void 0,i.cleanup?.())})}},t)},U=e=>$e(e.subscribe,e.getState,e.getServerSnapshot),mi=Symbol.for(`assistant-ui.silent-runtime-action`),hi=e=>typeof e==`object`&&!!e&&mi in e,gi=(e,t)=>{let n=t();return n.catch(t=>{hi(t)||console.error(`[assistant-ui] ${e} failed:`,t)}),n},_i=e=>e.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
4
-
5
- `),vi=Object.freeze({type:`complete`}),yi=Object.freeze({type:`running`}),bi=Object.freeze({cancelled:Object.freeze({type:`incomplete`,reason:`cancelled`}),length:Object.freeze({type:`incomplete`,reason:`length`}),"content-filter":Object.freeze({type:`incomplete`,reason:`content-filter`}),other:Object.freeze({type:`incomplete`,reason:`other`}),error:Object.freeze({type:`incomplete`,reason:`error`})}),xi=e=>{let t=e.status;if(!t||typeof t!=`object`)return;let{type:n}=t;if(n===`running`)return yi;if(n===`complete`)return vi;if(n!==`incomplete`)return;let{reason:r}=t;return bi[r===`cancelled`||r===`length`||r===`content-filter`||r===`other`||r===`error`?r:`other`]},Si=e=>e.interrupt!=null||e.approval!=null&&e.approval.approved===void 0&&e.approval.resolution===void 0,Ci=(e,t,n)=>{if(e.role!==`assistant`)return vi;if(n.type===`tool-call`)return n.result===void 0||n.isPreliminary||Si(n)?e.status:vi;if(e.status.type===`running`){let e=xi(n);if(e)return e}let r=t===Math.max(0,e.content.length-1);return e.status.type===`requires-action`?vi:r?e.status:vi},W=((e,t=21)=>(n=t)=>{let r=``,i=n|0;for(;i-->0;)r+=e[Math.random()*e.length|0];return r})(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,7);function wi(e){let t=e.match(/^data:([^;,]*)(?:;[^;,]+)*;base64,(.*)$/i);return t?{mimeType:t[1].toLowerCase()||`text/plain`,data:t[2]}:null}function Ti(e){return/^data:([^;,]+)(?:[;,])/i.exec(e)?.[1]?.toLowerCase()}var Ei={entries:32,payloadLength:16384,logLength:65536},Di=64,Oi=e=>{let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},ki=(e,t,n)=>{if(e===null)return!0;switch(typeof e){case`string`:case`boolean`:return!0;case`number`:return Number.isFinite(e);case`object`:break;default:return!1}if(n>Di||t.has(e))return!1;t.add(e);let r=Array.isArray(e)?e.every(e=>ki(e,t,n+1)):Oi(e)&&Object.values(e).every(e=>ki(e,t,n+1));return t.delete(e),r},Ai=e=>typeof e==`object`&&!!e&&!Array.isArray(e),ji=e=>e===`action`||e===`human-response`;function Mi(e,t=Date.now()){let{type:n,payload:r}=e;if(!ji(n))throw Error(`Unknown tool interaction type: ${String(n)}`);if(!ki(r,new Set,0))throw Error(`A tool interaction payload must be plain JSON.`);if(n===`action`&&!Ai(r))throw Error(`An action interaction payload must be a JSON object.`);let i=JSON.stringify(r);if(i.length>Ei.payloadLength)throw Error(`A tool interaction payload is limited to ${Ei.payloadLength} characters of JSON.`);return{type:n,occurredAt:t,payload:JSON.parse(i)}}function Ni(e,t){let n=[...e?.entries??[],t],r=e?.omitted??0;for(;n.length>1&&(n.length>Ei.entries||JSON.stringify(n).length>Ei.logLength);)n.shift(),r+=1;return r>0?{entries:n,omitted:r}:{entries:n}}var Pi=e=>{if(!Ai(e))return;let{type:t,occurredAt:n,payload:r}=e;if(ji(t)&&!(typeof n!=`number`||!Number.isFinite(n))&&ki(r,new Set,0))return t===`action`?Ai(r)?{type:t,occurredAt:n,payload:r}:void 0:{type:t,occurredAt:n,payload:r}};function Fi(e){if(!Ai(e))return;let{entries:t,omitted:n}=e,r=Array.isArray(t)?t.flatMap(e=>{let t=Pi(e);return t?[t]:[]}):[],i=typeof n==`number`&&Number.isInteger(n)&&n>0?n:0;for(;r.length>1&&(r.length>Ei.entries||JSON.stringify(r).length>Ei.logLength);)r.shift(),i+=1;if(r.length!==0||i!==0)return i>0?{entries:r,omitted:i}:{entries:r}}async function*Ii(){let e=this.getReader(),t=!0;try{for(;;){let n;try{n=await e.read()}catch(e){throw t=!1,e}if(n.done){t=!1;break}let{value:r}=n;yield r}}finally{try{t&&await e.cancel()}finally{e.releaseLock()}}}function Li(e){return e[Symbol.asyncIterator]??=Ii,e}var Ri=/[0-9a-fA-F]/;function zi(e){let t=[`ROOT`],n=-1,r=null,i=0,a=[],o;function s(){o!==void 0&&(a.push(JSON.parse(`"${o}"`)),o=void 0)}function c(e,i,a){switch(e){case`"`:n=i,t.pop(),t.push(a),t.push(`INSIDE_STRING`),s();break;case`f`:case`t`:case`n`:n=i,r=i,t.pop(),t.push(a),t.push(`INSIDE_LITERAL`);break;case`-`:t.pop(),t.push(a),t.push(`INSIDE_NUMBER`),s();break;case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n=i,t.pop(),t.push(a),t.push(`INSIDE_NUMBER`),s();break;case`{`:n=i,t.pop(),t.push(a),t.push(`INSIDE_OBJECT_START`),s();break;case`[`:n=i,t.pop(),t.push(a),t.push(`INSIDE_ARRAY_START`),s()}}function l(e,r){switch(e){case`,`:t.pop(),t.push(`INSIDE_OBJECT_AFTER_COMMA`);break;case`}`:n=r,t.pop(),o=a.pop()}}function u(e,r){switch(e){case`,`:t.pop(),t.push(`INSIDE_ARRAY_AFTER_COMMA`),o=(Number(o)+1).toString();break;case`]`:n=r,t.pop(),o=a.pop()}}for(let s=0;s<e.length;s++){let d=e[s];switch(t[t.length-1]){case`ROOT`:c(d,s,`FINISH`);break;case`INSIDE_OBJECT_START`:switch(d){case`"`:t.pop(),t.push(`INSIDE_OBJECT_KEY`),o=``;break;case`}`:n=s,t.pop(),o=a.pop()}break;case`INSIDE_OBJECT_AFTER_COMMA`:d===`"`&&(t.pop(),t.push(`INSIDE_OBJECT_KEY`),o=``);break;case`INSIDE_OBJECT_KEY`:switch(d){case`"`:t.pop(),t.push(`INSIDE_OBJECT_AFTER_KEY`);break;case`\\`:t.push(`INSIDE_STRING_ESCAPE`),o+=d;break;default:o+=d}break;case`INSIDE_OBJECT_AFTER_KEY`:d===`:`&&(t.pop(),t.push(`INSIDE_OBJECT_BEFORE_VALUE`));break;case`INSIDE_OBJECT_BEFORE_VALUE`:c(d,s,`INSIDE_OBJECT_AFTER_VALUE`);break;case`INSIDE_OBJECT_AFTER_VALUE`:l(d,s);break;case`INSIDE_STRING`:switch(d){case`"`:t.pop(),n=s,o=a.pop();break;case`\\`:t.push(`INSIDE_STRING_ESCAPE`);break;default:n=s}break;case`INSIDE_ARRAY_START`:switch(d){case`]`:n=s,t.pop(),o=a.pop();break;default:o=`0`,c(d,s,`INSIDE_ARRAY_AFTER_VALUE`)}break;case`INSIDE_ARRAY_AFTER_VALUE`:switch(d){case`,`:t.pop(),t.push(`INSIDE_ARRAY_AFTER_COMMA`),o=(Number(o)+1).toString();break;case`]`:n=s,t.pop(),o=a.pop();break;default:n=s}break;case`INSIDE_ARRAY_AFTER_COMMA`:c(d,s,`INSIDE_ARRAY_AFTER_VALUE`);break;case`INSIDE_STRING_ESCAPE`:{t.pop();let e=t[t.length-1];d===`u`?(t.push(`INSIDE_STRING_UNICODE_ESCAPE`),i=0):e===`INSIDE_STRING`&&(n=s),e===`INSIDE_OBJECT_KEY`&&(o+=d);break}case`INSIDE_STRING_UNICODE_ESCAPE`:{let e=t[t.length-2];if(!Ri.test(d)){t.pop(),s--;break}i++,i===4&&(t.pop(),e===`INSIDE_STRING`&&(n=s)),e===`INSIDE_OBJECT_KEY`&&(o+=d);break}case`INSIDE_NUMBER`:switch(d){case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n=s;break;case`e`:case`E`:case`-`:case`+`:case`.`:break;case`,`:t.pop(),o=a.pop(),t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&u(d,s),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`&&l(d,s);break;case`}`:t.pop(),o=a.pop(),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`&&l(d,s);break;case`]`:t.pop(),o=a.pop(),t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&u(d,s);break;default:t.pop(),o=a.pop()}break;case`INSIDE_LITERAL`:{let i=e.substring(r,s+1);!`false`.startsWith(i)&&!`true`.startsWith(i)&&!`null`.startsWith(i)?(t.pop(),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`?l(d,s):t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&u(d,s)):n=s;break}}}let d=e.slice(0,n+1);for(let n=t.length-1;n>=0;n--)switch(t[n]){case`INSIDE_STRING`:d+=`"`;break;case`INSIDE_OBJECT_KEY`:case`INSIDE_OBJECT_AFTER_KEY`:case`INSIDE_OBJECT_AFTER_COMMA`:case`INSIDE_OBJECT_START`:case`INSIDE_OBJECT_BEFORE_VALUE`:case`INSIDE_OBJECT_AFTER_VALUE`:d+=`}`;break;case`INSIDE_ARRAY_START`:case`INSIDE_ARRAY_AFTER_COMMA`:case`INSIDE_ARRAY_AFTER_VALUE`:d+=`]`;break;case`INSIDE_LITERAL`:{let t=e.substring(r,e.length);`true`.startsWith(t)?d+=`true`.slice(t.length):`false`.startsWith(t)?d+=`false`.slice(t.length):`null`.startsWith(t)&&(d+=`null`.slice(t.length))}}return[d,a]}var Bi=t(n(((e,t)=>{var n=typeof Buffer<`u`,r=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,i=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function a(e,t,a){a==null&&typeof t==`object`&&t&&(a=t,t=void 0),n&&Buffer.isBuffer(e)&&(e=e.toString()),e&&e.charCodeAt(0)===65279&&(e=e.slice(1));let s=JSON.parse(e,t);if(typeof s!=`object`||!s)return s;let c=a&&a.protoAction||`error`,l=a&&a.constructorAction||`error`;if(c===`ignore`&&l===`ignore`)return s;if(c!==`ignore`&&l!==`ignore`){if(r.test(e)===!1&&i.test(e)===!1)return s}else if(c!==`ignore`&&l===`ignore`){if(r.test(e)===!1)return s}else if(i.test(e)===!1)return s;return o(s,{protoAction:c,constructorAction:l,safe:a&&a.safe})}function o(e,{protoAction:t=`error`,constructorAction:n=`error`,safe:r}={}){let i=[e];for(;i.length;){let e=i;i=[];for(let a of e){if(t!==`ignore`&&Object.prototype.hasOwnProperty.call(a,`__proto__`)){if(r===!0)return null;if(t===`error`)throw SyntaxError(`Object contains forbidden prototype property`);delete a.__proto__}if(n!==`ignore`&&Object.prototype.hasOwnProperty.call(a,`constructor`)&&a.constructor!==null&&typeof a.constructor==`object`&&Object.prototype.hasOwnProperty.call(a.constructor,`prototype`)){if(r===!0)return null;if(n===`error`)throw SyntaxError(`Object contains forbidden prototype property`);delete a.constructor}for(let e in a){let t=a[e];t&&typeof t==`object`&&i.push(t)}}}return e}function s(e,t,n){let{stackTraceLimit:r}=Error;Error.stackTraceLimit=0;try{return a(e,t,n)}finally{Error.stackTraceLimit=r}}function c(e,t){let{stackTraceLimit:n}=Error;Error.stackTraceLimit=0;try{return a(e,t,{safe:!0})}catch{return}finally{Error.stackTraceLimit=n}}t.exports=s,t.exports.default=s,t.exports.parse=s,t.exports.safeParse=c,t.exports.scan=o}))(),1),Vi=Symbol(`aui.parse-partial-json-object.meta`),Hi=e=>{if(e.length===0)return{[Vi]:{state:`partial`,partialPath:[]}};try{let t=Bi.default.parse(e);if(typeof t!=`object`||!t)throw Error(`argsText is expected to be an object`);return t[Vi]={state:`complete`,partialPath:[]},t}catch{try{let[t,n]=zi(e),r=Bi.default.parse(t);if(typeof r!=`object`||!r)throw Error(`argsText is expected to be an object`);return r[Vi]={state:`partial`,partialPath:n},r}catch{return}}},Ui=((e,t=21)=>(n=t)=>{let r=``,i=n|0;for(;i-->0;)r+=e[Math.random()*e.length|0];return r})(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,7),Wi=()=>{let e,t,n=new Promise((n,r)=>{e=n,t=r});if(!e||!t)throw Error(`Failed to create promise`);return{promise:n,resolve:e,reject:t}},Gi=()=>{let e=[],t=!1,n=!1,r=!1,i,a,o=0,s,c,l=()=>(a=void 0,c??=Promise.all(e.splice(0).map(async e=>{try{await e.reader.cancel().catch(()=>void 0),await e.pipeTask}finally{e.reader.releaseLock()}})).then(()=>void 0),c),u=e=>{n||r||(r=!0,console.error(e),l(),i.error(e),s?.reject(e),s=void 0)},d=a=>{a.promise||=a.reader.read().then(({done:c,value:l})=>{a.promise=void 0,!(n||r)&&(c?(e.splice(e.indexOf(a),1),a.reader.releaseLock(),t&&e.length===0&&o===0&&i.close()):i.enqueue(l),s?.resolve(),s=void 0)}).catch(u)},f=new ReadableStream({start(e){i=e},pull(){return s=Wi(),e.forEach(e=>{d(e)}),s.promise},async cancel(){n=!0;let e=l();s?.resolve(),s=void 0,await e}}),p=c=>{if(e.length>0&&(a=void 0),!a){let c=[];a=c,o++,Promise.resolve().then(()=>{if(o--,a===c&&(a=void 0),!(n||r)){for(let e of c)i.enqueue(e);t&&e.length===0&&o===0&&i.close(),s?.resolve(),s=void 0}}).catch(u)}a.push(c)};return{readable:f,isSealed(){return t},isCancelled(){return n},isErrored(){return r},seal(){t||n||r||(t=!0,e.length===0&&o===0&&i.close())},addStream:(i,o)=>{let s=o?.catch(()=>void 0);if(n||r){i.cancel().catch(()=>void 0);return}if(t)throw i.cancel().catch(()=>void 0),Error(`Cannot add streams after the run callback has settled.`);a=void 0;let c={reader:i.getReader(),pipeTask:s};e.push(c),d(c)},enqueue(e){if(!(n||r)){if(t)throw Error(`Cannot add streams after the run callback has settled.`);p(e)}}}},Ki=(e,t)=>new ReadableStream({start(n){return e.start?.(t(n))},pull(n){return e.pull?.(t(n))},cancel(t){return e.cancel?.(t)}}),qi=(e,t)=>{let n;return[Ki({start(e){n=e},cancel(e){return t?.(n,e)}},e),n]},Ji=e=>e instanceof TypeError,Yi=(e,t,n)=>{try{e.enqueue(t)}catch(e){if(!Ji(e))throw e;n?.(e)}},Xi=e=>{try{e.close()}catch(e){if(!Ji(e))throw e}},Zi=class{_controller;_strict;_isClosed=!1;_warnedDropped=!1;constructor(e,t={}){this._controller=e,this._strict=t.strict??!0}append(e){let t={type:`text-delta`,path:[],textDelta:e};if(this._isClosed){if(this._strict)throw TypeError(`Cannot append to a closed TextStreamController`);return Yi(this._controller,t,this._warnDroppedAfterClose),this}return Yi(this._controller,t),this}_warnDroppedAfterClose=e=>{this._warnedDropped||(this._warnedDropped=!0,console.error(`Dropped text delta for closed stream: ${String(e)}`))};close(){this._isClosed||(this._isClosed=!0,Yi(this._controller,{type:`part-finish`,path:[]}),Xi(this._controller))}},Qi=(e,t={})=>Ki(e,e=>new Zi(e,t)),$i=(e={})=>qi(t=>new Zi(t,e)),ea=Symbol.for(`aui.tool-response`),ta=`<no result>`,na=class e{get[ea](){return!0}artifact;result;isError;isPreliminary;modelContent;messages;constructor(e){e.artifact!==void 0&&(this.artifact=e.artifact);let t=e.result;this.result=t===void 0?ta:t,this.isError=e.isError??!1,e.isPreliminary&&(this.isPreliminary=!0),e.modelContent!==void 0&&(this.modelContent=e.modelContent),e.messages!==void 0&&(this.messages=e.messages)}static[Symbol.hasInstance](e){return typeof e==`object`&&!!e&&ea in e}static toResponse(t){return t instanceof e?t:new e({result:t===void 0?ta:t})}},ra=class{_isClosed=!1;_mergeTask;_controller;constructor(e,t={}){this._controller=e;let n=Qi({start:e=>{this._argsTextController=e}},t),r=!1;this._mergeTask=n.pipeTo(new WritableStream({write:e=>{switch(e.type){case`text-delta`:r=!0,Yi(this._controller,e);break;case`part-finish`:r||Yi(this._controller,{type:`text-delta`,textDelta:`{}`,path:[]}),Yi(this._controller,{type:`tool-call-args-text-finish`,path:[]});break;default:throw Error(`Unexpected chunk type: ${e.type}`)}}}))}get argsText(){return this._argsTextController}_argsTextController;async setResponse(e){if(this._isClosed)return;let t=e.result;Yi(this._controller,{type:`result`,path:[],...e.artifact===void 0?{}:{artifact:e.artifact},result:t===void 0?ta:t,isError:e.isError??!1,...e.isPreliminary?{isPreliminary:!0}:{},...e.modelContent===void 0?{}:{modelContent:e.modelContent},...e.messages===void 0?{}:{messages:e.messages}}),e.isPreliminary?this._argsTextController.close():await this.close()}async close(){this._isClosed||(this._isClosed=!0,this._argsTextController.close(),await this._mergeTask,Yi(this._controller,{type:`part-finish`,path:[]}),Xi(this._controller))}},ia=(e={})=>qi(t=>new ra(t,e)),aa=class{value=-1;up(){return++this.value}},oa=class extends TransformStream{constructor(e){super({transform(t,n){n.enqueue({...t,path:[e,...t.path]})}})}};TransformStream;var sa=class extends TransformStream{constructor(e){let t=new aa,n=new Map;super({transform(r,i){r.type===`part-start`&&r.path.length===0&&n.set(t.up(),e.up());let[a,...o]=r.path;if(a===void 0){i.enqueue(r);return}let s=n.get(a);if(s===void 0)throw Error(`Path not found`);i.enqueue({...r,path:[s,...o]})}})}},ca=class e{_state;_parentId;constructor(e,t={}){this._state=e||{strict:t.strict??!0,merger:Gi(),contentCounter:new aa}}get __internal_isClosed(){return this._state.merger.isSealed()||this._state.merger.isCancelled()||this._state.merger.isErrored()}get __internal_isCancelled(){return this._state.merger.isCancelled()}__internal_getReadable(){return this._state.merger.readable}__internal_subscribeToClose(e){this._state.closeSubscriber=e}_addTransformedStream(e,t){if(e.locked)throw TypeError(`Cannot merge a stream that is already locked to a reader.`);let n=e.pipeTo(t.writable).catch(async e=>{throw await t.writable.abort(e).catch(()=>void 0),e});this._state.merger.addStream(t.readable,n)}_addPart(e,t){this._state.append&&(this._state.append.controller.close(),this._state.append=void 0),this.enqueue({type:`part-start`,part:e,path:[]}),this._addTransformedStream(t,new oa(this._state.contentCounter.value))}merge(e){this._addTransformedStream(e,new sa(this._state.contentCounter))}appendText(e){(this._state.append?.kind!==`text`||this._state.append.parentId!==this._parentId)&&(this._state.append={kind:`text`,parentId:this._parentId,controller:this.addTextPart()}),this._state.append.controller.append(e)}appendReasoning(e,t){(t!==void 0||this._state.append?.kind!==`reasoning`||this._state.append.parentId!==this._parentId)&&(this._state.append={kind:`reasoning`,parentId:this._parentId,controller:this.addReasoningPart(t)}),(t===void 0||e.length!==0)&&this._state.append.controller.append(e)}addTextPart(){let[e,t]=$i({strict:this._state.strict});return this._addPart(this._withParentIdOption({type:`text`}),e),t}addReasoningPart(e){let[t,n]=$i({strict:this._state.strict});return this._addPart(this._withParentIdOption({type:`reasoning`,...e}),t),n}addToolCallPart(e){let t=typeof e==`string`?{toolName:e}:e,n=t.toolName,r=t.toolCallId??Ui(),[i,a]=ia({strict:this._state.strict});return this._addPart({type:`tool-call`,toolName:n,toolCallId:r,...this._parentId&&{parentId:this._parentId}},i),t.argsText!==void 0&&(a.argsText.append(t.argsText),a.argsText.close()),t.args!==void 0&&(a.argsText.append(JSON.stringify(t.args)),a.argsText.close()),t.response!==void 0&&a.setResponse(t.response),a}_finishedPartStream(){return new ReadableStream({start(e){e.enqueue({type:`part-finish`,path:[]}),e.close()}})}_withParentIdOption(e){return this._parentId?{...e,parentId:this._parentId}:e}appendSource(e){this._addPart(this._withParentIdOption(e),this._finishedPartStream())}appendFile(e){this._addPart(this._withParentIdOption(e),this._finishedPartStream())}appendData(e){this._addPart(this._withParentIdOption(e),this._finishedPartStream())}enqueue(e){this._state.merger.enqueue(e),e.type===`part-start`&&e.path.length===0&&this._state.contentCounter.up()}withParentId(t){let n=new e(this._state);return n._parentId=t,n}close(){this._state.append?.controller?.close(),this._state.merger.seal(),this._state.closeSubscriber?.()}};function la(e,t={}){let n=new ca(void 0,t);return(async()=>{try{await e(n)}catch(e){n.__internal_isClosed?n.__internal_isCancelled||console.error(e):n.enqueue({type:`error`,path:[],error:String(e)})}finally{n.__internal_isClosed||n.close()}})(),n.__internal_getReadable()}function ua(e={}){let{resolve:t,promise:n}=Wi(),r;return[la(e=>(r=e,r.__internal_subscribeToClose(t),n),e),r]}var da=class extends TransformStream{constructor(e,t,n){let[r,i]=ua({strict:e.strict}),a=new AbortController,o;super({start(t){o=r.pipeTo(new WritableStream({write(e){t.enqueue(e)},abort(e){t.error(e)},close(){t.terminate()}}),{signal:a.signal}).catch(e=>{t.error(e)});try{return e.start?.(i)}catch(e){throw a.abort(e),e}},transform(t){return e.transform?.(t,i)},async flush(){await e.flush?.(i),i.close(),await o}},t,n);let s=super.readable.getReader(),c=!1;Object.defineProperty(this,"readable",{value:new ReadableStream({start(e){s.closed.catch(t=>{a.abort(t),e.error(t),s.releaseLock()})},async pull(e){let t=await s.read();c||(t.done?(e.close(),s.releaseLock()):e.enqueue(t.value))},async cancel(e){c=!0;let t=s.cancel(e);a.abort(e);try{await t}finally{await o,s.releaseLock()}}},{highWaterMark:0}),writable:!1})}},fa=(e,t,n)=>{if(e.startsWith(`data-`))return{type:`data`,name:e.substring(5),data:t,...typeof n==`string`&&{id:n}}},pa=(e,t,n)=>{let{role:r,id:i,createdAt:a,attachments:o,status:s,metadata:c}=e,l={id:i??t,createdAt:a??new Date},u=typeof e.content==`string`?[{type:`text`,text:e.content}]:e.content,d=({image:e,...t})=>typeof e==`string`?wi(e)?.mimeType.startsWith(`image/`)||/^(https:\/\/|blob:)/i.test(e)?{...t,image:e}:(console.warn(`Invalid image data format detected`),null):null;if(r!==`user`&&o?.length)throw Error(`attachments are only supported for user messages`);if(r!==`assistant`&&s)throw Error(`status is only supported for assistant messages`);if(r!==`assistant`&&c?.steps)throw Error(`metadata.steps is only supported for assistant messages`);switch(r){case`assistant`:return{...l,role:r,content:u.map(e=>{let t=e.type;switch(t){case`text`:return e.text?.trim()?e:null;case`reasoning`:return!e.text?.trim()&&!e.unstable_summary?.trim()?null:e;case`file`:case`source`:return e;case`image`:return d(e);case`data`:return e;case`generative-ui`:return e;case`tool-call`:{let{parentId:t,messages:n,unstable_interactions:r,...i}=e,a=Fi(r),o={...i,toolCallId:e.toolCallId||`tool-${W()}`,...t!==void 0&&{parentId:t},...n!==void 0&&{messages:n},...a!==void 0&&{unstable_interactions:a}};return e.args?{...o,args:e.args,argsText:e.argsText??JSON.stringify(e.args)}:{...o,args:Hi(e.argsText??``)??{},argsText:e.argsText??``}}case`audio`:throw Error(`Unsupported assistant message part type: ${t}`);default:{let n=t,r=fa(n,e.data,e.id);if(r)return r;throw Error(`Unsupported assistant message part type: ${n}`)}}}).filter(e=>!!e),status:s??n,metadata:{unstable_state:c?.unstable_state??null,unstable_annotations:c?.unstable_annotations??[],unstable_data:c?.unstable_data??[],custom:c?.custom??{},steps:c?.steps??[],...c?.timing&&{timing:c.timing},...c?.submittedFeedback&&{submittedFeedback:c.submittedFeedback},...c?.isOptimistic&&{isOptimistic:!0},...c?.modality&&{modality:c.modality}}};case`user`:return{...l,role:r,content:u.map(e=>{let t=e.type;switch(t){case`text`:case`image`:case`audio`:case`file`:case`data`:return e;case`reasoning`:case`source`:case`generative-ui`:case`tool-call`:throw Error(`Unsupported user message part type: ${t}`);default:{let n=t,r=fa(n,e.data,e.id);if(r)return r;throw Error(`Unsupported user message part type: ${n}`)}}}),attachments:(o??[]).map(e=>({...e,content:e.content.map(e=>fa(e.type,e.data,`id`in e?e.id:void 0)??e)})),metadata:{custom:c?.custom??{},...c?.isOptimistic&&{isOptimistic:!0},...c?.modality&&{modality:c.modality}}};case`system`:if(u.length!==1||u[0].type!==`text`)throw Error(`System messages must have exactly one text message part.`);return{...l,role:r,content:u,metadata:{custom:c?.custom??{}}};default:throw Error(`Unknown message role: ${r}`)}},ma=e=>{let t=x(4),n=gr(),r=j(e),i,a;t[0]!==n||t[1]!==e?(i=()=>{let t=r.current;t!==e&&(r.current=e,n(`threads.selectionChanged`,{threadId:e,previousThreadId:t}))},a=[e,n],t[0]=n,t[1]=e,t[2]=i,t[3]=a):(i=t[2],a=t[3]),N(i,a)},ha=(e,t,n)=>{let r=x(8),i=n===void 0?t:n,a=gr(),o=t&&i,s;r[0]!==o||r[1]!==e?(s={isMain:o,threadId:e},r[0]=o,r[1]=e,r[2]=s):s=r[2];let c=j(s),l,u;r[3]!==a||r[4]!==t||r[5]!==e?(l=()=>{let n=c.current;(n.isMain!==t||n.threadId!==e)&&(c.current={isMain:t,threadId:e},a(t?`threadListItem.switchedTo`:`threadListItem.switchedAway`,{threadId:e}))},u=[t,e,a],r[3]=a,r[4]=t,r[5]=e,r[6]=l,r[7]=u):(l=r[6],u=r[7]),N(l,u)},G=(e,t)=>gi(`thread list ${e}`,t),ga=nn(e=>{let t=x(27),{runtime:n,mainThreadIsRunning:r}=e,i=r!==void 0&&r,a=U(n),o;bb0:{let e=a.isRunning||a.isMain&&i;if(e===a.isRunning){o=a;break bb0}let n;t[0]!==e||t[1]!==a?(n={...a,isRunning:e},t[0]=e,t[1]=a,t[2]=n):n=t[2],o=n}let s=o;ha(a.id,a.isMain);let c;t[3]===s?c=t[4]:(c=()=>s,t[3]=s,t[4]=c);let l,u,d,f,p,m,h;t[5]===n?(l=t[6],u=t[7],d=t[8],f=t[9],p=t[10],m=t[11],h=t[12]):(u=e=>G(`switch`,()=>n.switchTo(e)),d=e=>G(`rename`,()=>n.rename(e)),f=e=>G(`update custom metadata`,()=>n.updateCustom(e)),p=()=>G(`archive`,()=>n.archive()),m=()=>G(`unarchive`,()=>n.unarchive()),h=()=>G(`delete`,()=>n.delete()),l=e=>G(`generate title`,()=>n.generateTitle(e)),t[5]=n,t[6]=l,t[7]=u,t[8]=d,t[9]=f,t[10]=p,t[11]=m,t[12]=h);let g;t[13]===n?g=t[14]:(g=()=>n,t[13]=n,t[14]=g);let _;return t[15]!==n.detach||t[16]!==n.initialize||t[17]!==l||t[18]!==g||t[19]!==c||t[20]!==u||t[21]!==d||t[22]!==f||t[23]!==p||t[24]!==m||t[25]!==h?(_={getState:c,switchTo:u,rename:d,updateCustom:f,archive:p,unarchive:m,delete:h,generateTitle:l,initialize:n.initialize,detach:n.detach,__internal_getRuntime:g},t[15]=n.detach,t[16]=n.initialize,t[17]=l,t[18]=g,t[19]=c,t[20]=u,t[21]=d,t[22]=f,t[23]=p,t[24]=m,t[25]=h,t[26]=_):_=t[26],_}),_a=mn({}),va=({effects:e})=>{"use no memo";return Ze(e),null},ya=rt(function(e,t){"use no memo";let{config:n,children:r}=e,i=`extends`in e,a=`value`in e,o=Bn();if(Ar){if(i&&a)throw Error("AuiProvider: pass either `extends` or `value`, not both.");if(i&&e.extends===void 0)throw Error("AuiProvider: `extends` must be a client or null, not undefined.");if(i&&!n)throw Error("AuiProvider: `extends` requires a `config`.");if(a&&n)throw Error("AuiProvider: pass either `value` or `config`, not both.");if(!a&&!n)throw Error("AuiProvider: a `config` is required.");if(!i&&!a&&o!==Nn)throw Error(`A parent AuiProvider exists — pass extends={aui} to inherit it or extends={null} to isolate.`)}let s=i?e.extends??Nn:a?e.value??Nn:o,c=Dr(),{client:l,effects:u}=Yr(s,n??_a,c);return nt(t,()=>l,[l]),(0,S.jsx)(_r.Provider,{value:c,children:(0,S.jsxs)(Fn.Provider,{value:l,children:[(0,S.jsx)(va,{effects:Rn(s)}),u&&(0,S.jsx)(va,{effects:u}),r]})})}),ba=lt(null),xa=(e,t)=>he(ba,e,t),Sa=()=>dt(ba),Ca={},wa=e=>{let t=Or(e??Ca);return e==null?null:t},Ta=e=>{let t=x(6),{adapters:n,children:r}=e,i=dt(ba),a;t[0]!==n||t[1]!==i?(a={...i,...n},t[0]=n,t[1]=i,t[2]=a):a=t[2];let o=a,s;return t[3]!==r||t[4]!==o?(s=(0,S.jsx)(ba.Provider,{value:o,children:r}),t[3]=r,t[4]=o,t[5]=s):s=t[5],s};function K(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ea(e,t=0){return t>100?!1:e===null||typeof e==`string`||typeof e==`boolean`?!0:typeof e==`number`?!Number.isNaN(e)&&Number.isFinite(e):Array.isArray(e)?e.every(e=>Ea(e,t+1)):K(e)?Object.entries(e).every(([e,n])=>typeof e==`string`&&Ea(n,t+1)):!1}var Da=e=>{if(e instanceof Date&&!Number.isNaN(e.getTime()))return e;if(typeof e!=`string`&&typeof e!=`number`)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t},Oa=e=>e===`system`||e===`user`||e===`assistant`,ka={running:()=>!0,"requires-action":e=>typeof e.reason==`string`,complete:e=>typeof e.reason==`string`,incomplete:e=>(e.reason===void 0||typeof e.reason==`string`)&&(e.error===void 0||Ea(e.error))},Aa=e=>K(e)&&typeof e.type==`string`&&Object.hasOwn(ka,e.type)&&ka[e.type](e)===!0,ja=e=>{if(K(e)){if(e.messageId!==void 0&&typeof e.messageId!=`string`){let{messageId:t,...n}=e;return ja(n)}if(e.usage!==void 0&&!K(e.usage)){let{usage:t,...n}=e;return n}return e}},Ma=e=>Array.isArray(e)?e.map(ja).filter(e=>e!==void 0):[],Na=(e,t)=>{let n={text:e=>typeof e.text==`string`,reasoning:e=>typeof e.text==`string`||typeof e.unstable_summary==`string`,image:e=>typeof e.image==`string`,file:e=>typeof e.data==`string`&&typeof e.mimeType==`string`,audio:e=>K(e.audio)&&typeof e.audio.data==`string`&&typeof e.audio.format==`string`,data:e=>typeof e.name==`string`,source:e=>typeof e.id==`string`&&(e.sourceType===`url`?typeof e.url==`string`:e.sourceType===`document`&&typeof e.title==`string`&&typeof e.mediaType==`string`),"generative-ui":e=>K(e.spec),"tool-call":e=>typeof e.toolCallId==`string`&&typeof e.toolName==`string`&&K(e.args)&&typeof e.argsText==`string`,...e};return e=>K(e)&&typeof e.type==`string`&&(Object.hasOwn(n,e.type)?n[e.type](e):t(e.type))};Na({},()=>!0);var Pa=Na({reasoning:e=>(e.text===void 0||typeof e.text==`string`)&&(e.unstable_summary===void 0||typeof e.unstable_summary==`string`)&&(typeof e.text==`string`||typeof e.unstable_summary==`string`),"tool-call":e=>typeof e.toolCallId==`string`&&typeof e.toolName==`string`&&(e.args===void 0||K(e.args))&&(e.argsText===void 0||typeof e.argsText==`string`)&&(e.args!==void 0||e.argsText!==void 0)},e=>e.startsWith(`data-`)),Fa={user:{text:!0,image:!0,file:!0,data:!0,audio:!0},assistant:{text:!0,reasoning:!0,"tool-call":!0,source:!0,file:!0,image:!0,data:!0,"generative-ui":!0}},Ia=(e,t)=>Pa(t)&&(e===`system`?t.type===`text`:Object.hasOwn(Fa.assistant,t.type)||Object.hasOwn(Fa.user,t.type)?Object.hasOwn(Fa[e],t.type):!0),La=(e,t)=>!K(e)||typeof e.id!=`string`||typeof e.type!=`string`||typeof e.name!=`string`||!K(e.status)||e.status.type!==`complete`||!Array.isArray(e.content)?null:{...e,content:e.content.filter(t)},Ra={toResponse(e,t){return new Response(Ra.toByteStream(e,t),{headers:t.headers??{}})},fromResponse(e,t){return Ra.fromByteStream(e.body,t)},toByteStream(e,t){return e.pipeThrough(t)},fromByteStream(e,t){return e.pipeThrough(t)}},za=new Set([`__proto__`,`constructor`,`prototype`]);function Ba(e){if(za.has(e))throw Error(`Unsafe gorp path segment: ${e}`)}var Va=class{_state;_strict;_logged=new Set;_warnedClamp=!1;constructor(e=null,t={}){this._state=e,this._strict=t.strict??!0}get state(){return this._state}logOnce(e,t){this._logged.has(e)||this._logged.size>=20||(this._logged.add(e),t())}append(e){this._state=e.reduce((e,t)=>{if(this._strict)return this.apply(e,t);try{return this.apply(e,t)}catch(n){return this.logOnce(`skip:${String(n)}`,()=>console.error(`Skipped unappliable gorp operation: ${String(n)}`,t)),e}},this._state)}apply(e,t){let n=t.type;switch(n){case`set`:return this.updatePath(e,t.path,()=>t.value);case`append-text`:return this.updatePath(e,t.path,e=>{if(typeof e!=`string`)throw Error(`Expected string at path [${t.path.join(`, `)}]`);return e+t.value});default:throw Error(`Invalid operation type: ${n}`)}}updatePath(e,t,n){if(t.length===0)return n(e);let r=[],i=e;for(let e=0;e<t.length;e++){if(i??={},typeof i!=`object`)throw Error(`Invalid path: [${t.slice(e).join(`, `)}]`);let n=t[e];if(Ba(n),Array.isArray(i)){let a=Number(n);if(!Number.isInteger(a)||String(a)!==String(n))throw Error(`Expected array index at [${t.slice(e).join(`, `)}]`);if(a<0)throw Error(`Insert array index out of bounds`);if(a>i.length){if(this._strict)throw Error(`Insert array index out of bounds`);this._warnedClamp||(this._warnedClamp=!0,console.warn(`Clamped out-of-bounds gorp array index ${a} to ${i.length}`)),a=i.length}r.push({kind:`array`,state:i,key:a}),i=Object.hasOwn(i,a)?i[a]:void 0}else{let e=i;r.push({kind:`object`,state:e,key:n}),i=Object.hasOwn(e,n)?e[n]:void 0}}let a=n(i);for(let e=r.length-1;e>=0;e--){let t=r[e];if(t.kind===`array`){let e=[...t.state];e[t.key]=a,a=e}else{let e={...t.state};e[t.key]=a,a=e}}return a}},Ha=class{_streamStartTime;_firstTokenTime;_totalChunks=0;_toolCallIds=new Set;constructor(){this._streamStartTime=Date.now()}recordChunk(){this._totalChunks++}recordFirstToken(){this._firstTokenTime===void 0&&(this._firstTokenTime=Date.now())}recordToolCallStart(e){this._toolCallIds.add(e)}getTiming(e,t){let n=Date.now()-this._streamStartTime,r=e&&e>0?e:t?Math.ceil(t.length/4):void 0,i=r&&n>0?r/n*1e3:void 0;return{streamStartTime:this._streamStartTime,...this._firstTokenTime===void 0?void 0:{firstTokenTime:this._firstTokenTime-this._streamStartTime},totalStreamTime:n,...r===void 0?void 0:{tokenCount:r},...i===void 0?void 0:{tokensPerSecond:i},totalChunks:this._totalChunks,toolCallCount:this._toolCallIds.size}}},Ua=(e,t)=>({...e,parts:t,get content(){return this.parts}}),Wa=(e,t)=>Ua(e,[...e.parts,t]),Ga=({unstable_state:e=null}={})=>({role:`assistant`,status:{type:`running`},parts:[],get content(){return this.parts},metadata:{unstable_state:e,unstable_data:[],unstable_annotations:[],steps:[],custom:{}}}),Ka=16,qa=(e,t,n,r)=>{let i=t.path.length===1?e.parts[t.path[0]]:void 0;if(i===void 0)return n(`no-part:${t.type}`,`Dropped ${t.type} chunk: no part at path [${t.path.join(`, `)}]`),e;let a=t.path[0],o=r(i);return o===i?e:Ua(e,[...e.parts.slice(0,a),o,...e.parts.slice(a+1)])},Ja=(e,t,n)=>{let r=t.part;if(r.type===`text`||r.type===`reasoning`)return Wa(e,{type:r.type,text:``,status:{type:`running`},...r.type===`reasoning`&&r.unstable_summary!==void 0?{unstable_summary:r.unstable_summary}:void 0,...r.type===`reasoning`?{timing:{startedAt:Date.now()}}:void 0,...r.parentId&&{parentId:r.parentId}});if(r.type===`tool-call`)return Wa(e,{type:`tool-call`,state:`partial-call`,status:{type:`running`,isArgsComplete:!1},toolCallId:r.toolCallId,toolName:r.toolName,argsText:``,args:{},timing:{startedAt:Date.now()},...r.parentId&&{parentId:r.parentId}});if(r.type===`source`)return Wa(e,{type:`source`,sourceType:r.sourceType,id:r.id,url:r.url,...r.title?{title:r.title}:void 0,...r.parentId&&{parentId:r.parentId}});if(r.type===`file`)return Wa(e,{type:`file`,mimeType:r.mimeType,data:r.data,...r.parentId&&{parentId:r.parentId}});if(r.type===`data`)return Wa(e,{type:`data`,name:r.name,data:r.data,...r.parentId&&{parentId:r.parentId}});{let t=String(r.type);return n(`unsupported-part-start:${t}`,`Unsupported part-start type ${t}: inserting an empty reasoning part to preserve part indices`),Wa(e,{type:`reasoning`,text:``,status:{type:`running`}})}},Ya=(e,t,n)=>qa(e,t,n,e=>e.type===`tool-call`?e.state===`partial-call`?{...e,state:`call`,status:e.status.type===`running`?{type:`running`,isArgsComplete:!0}:e.status}:e:(n(`wrong-part:tool-call-args-text-finish`,`Dropped tool-call-args-text-finish chunk: part is not a tool-call`),e)),Xa=(e,t,n)=>qa(e,t,n,e=>e.type===`tool-call`&&e.isPreliminary?e:e.type===`reasoning`&&e.timing!==void 0?{...e,status:{type:`complete`,reason:`unknown`},timing:{...e.timing,completedAt:e.timing.completedAt??Date.now()}}:{...e,status:{type:`complete`,reason:`unknown`}}),Za=(e,t,n)=>qa(e,t,n,e=>{if(e.type===`text`||e.type===`reasoning`)return{...e,text:e.text+t.textDelta};if(e.type===`tool-call`){let n=e.argsText+t.textDelta,r=Hi(n)??e.args;return{...e,argsText:n,args:r}}return n(`wrong-part:text-delta`,`Dropped text-delta chunk: part is neither text nor tool-call`),e}),Qa=(e,t,n)=>qa(e,t,n,e=>{if(e.type===`tool-call`){let n=t.isPreliminary===!0,r=e.status.type===`running`?e.status:{type:`running`,isArgsComplete:e.state!==`partial-call`};if(n)return e.state===`result`?e:{...e,state:e.state===`partial-call`?`partial-call`:`call`,...t.artifact===void 0?{}:{artifact:t.artifact},result:t.result,isError:t.isError??!1,isPreliminary:!0,...t.modelContent===void 0?{}:{modelContent:t.modelContent},...t.messages===void 0?{}:{messages:t.messages},status:r};let{isPreliminary:i,...a}=e;return{...a,state:`result`,...e.timing===void 0?{}:{timing:{...e.timing,completedAt:e.timing.completedAt??Date.now()}},...t.artifact===void 0?{}:{artifact:t.artifact},result:t.result,isError:t.isError??!1,...t.modelContent===void 0?{}:{modelContent:t.modelContent},...t.messages===void 0?{}:{messages:t.messages},status:{type:`complete`,reason:`stop`}}}return n(`wrong-part:result`,`Dropped result chunk: part is not a tool-call`),e}),$a=(e,t)=>{if(e.status?.type===`incomplete`&&e.status?.reason===`error`)return e;let n=eo(t);return{...e,status:n}},eo=e=>e.finishReason===`tool-calls`?{type:`requires-action`,reason:`tool-calls`}:e.finishReason===`stop`||e.finishReason===`unknown`?{type:`complete`,reason:e.finishReason}:{type:`incomplete`,reason:e.finishReason},to=(e,t)=>({...e,metadata:{...e.metadata,unstable_annotations:[...e.metadata.unstable_annotations,...t.annotations]}}),no=(e,t)=>({...e,metadata:{...e.metadata,unstable_data:[...e.metadata.unstable_data,...t.data]}}),ro=(e,t)=>({...e,metadata:{...e.metadata,steps:[...e.metadata.steps,{state:`started`,messageId:t.messageId}]}}),io=(e,t)=>{let n=e.metadata.steps.slice(),r=n.length-1;return n.length>0&&n[r]?.state===`started`?n[r]={...n[r],state:`finished`,finishReason:t.finishReason,usage:t.usage,isContinued:t.isContinued}:n.push({state:`finished`,messageId:Ui(),finishReason:t.finishReason,usage:t.usage,isContinued:t.isContinued}),{...e,metadata:{...e.metadata,steps:n}}},ao=(e,t)=>{let n=t.severity===`critical`||t.severity===`warning`||t.severity===`info`?t.severity:void 0;return{...e,status:{type:`incomplete`,reason:`error`,error:{code:t.code??`unknown`,message:t.error??`unknown error`,...n!==void 0&&{severity:n}}}}},oo=(e,t,n)=>(n.append(t.operations),{...e,metadata:{...e.metadata,unstable_state:n.state}}),so=e=>{let t=0;for(let n of e.metadata.steps)n.state===`finished`&&n.usage&&(t+=n.usage.outputTokens);return t},co=(e,t,n=0)=>{let r=n>0?n:so(t);if(r>0)return e.getTiming(r);let i=``;for(let e of t.parts)(e.type===`text`||e.type===`reasoning`)&&(i+=e.text);return e.getTiming(void 0,i||void 0)},lo=e=>{let t=!1;return()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}},uo=class extends TransformStream{constructor({initialMessage:e,throttle:t,onError:n,strict:r=!0}={}){let i=e??Ga(),a,o,s=new Ha,c=new Set,l=(e,t)=>{c.has(e)||c.size>=Ka||(c.add(e),console.warn(t))},u,d=t?lo(()=>{u?.enqueue(i)}):()=>{u?.enqueue(i)};super({start(e){u=e},transform(e){s.recordChunk();let t=e.type;switch(t){case`part-start`:i=Ja(i,e,l),e.part.type===`tool-call`&&s.recordToolCallStart(e.part.toolCallId);break;case`tool-call-args-text-finish`:i=Ya(i,e,l);break;case`part-finish`:i=Xa(i,e,l);break;case`text-delta`:{let t=Za(i,e,l);t!==i&&s.recordFirstToken(),i=t;break}case`result`:i=Qa(i,e,l);break;case`message-finish`:o=e.usage?.outputTokens,i=$a(i,e);break;case`annotations`:i=to(i,e);break;case`data`:i=no(i,e);break;case`step-start`:i=ro(i,e);break;case`step-finish`:i=io(i,e);break;case`error`:i=ao(i,e),n?.(e.error);break;case`update-state`:a??=new Va(i.metadata.unstable_state,{strict:r}),i=oo(i,e,a);break;default:throw Error(`Unsupported chunk type: ${t}`)}i.status.type!==`running`&&(i={...i,metadata:{...i.metadata,timing:co(s,i,o)}}),d()},flush(e){if(i.status?.type===`running`){let t=i.parts?.some(e=>e.type===`tool-call`&&(e.state===`call`||e.state===`partial-call`)&&(e.result===void 0||e.isPreliminary))??!1;i=$a(i,{type:`message-finish`,path:[],finishReason:t?`tool-calls`:`unknown`,usage:{inputTokens:0,outputTokens:0}}),i={...i,metadata:{...i.metadata,timing:co(s,i,o)}},e.enqueue(i)}}})}},fo=class e{readable;constructor(e){this.readable=e}static fromAssistantStream(t){return new e(t.pipeThrough(new uo))}async unstable_result(){let e;for await(let t of this)e=t;return e||{role:`assistant`,status:{type:`complete`,reason:`unknown`},parts:[],content:[],metadata:{unstable_state:null,unstable_data:[],unstable_annotations:[],steps:[],custom:{}}}}[Symbol.asyncIterator](){return Li(this.readable)[Symbol.asyncIterator]()}tee(){let[t,n]=this.readable.tee();return[new e(t),new e(n)]}},po=class extends TransformStream{constructor(e){super();let t=e(super.readable);Object.defineProperty(this,"readable",{value:t,writable:!1})}},mo=class extends po{constructor(){super(e=>{let t=new da({transform(e,t){t.appendText(e)}});return e.pipeThrough(new TextDecoderStream).pipeThrough(t)})}},ho=100,go=(e,t,n)=>{if(e===t)return!0;if(n>ho||e==null||t==null)return!1;if(Array.isArray(e))return!Array.isArray(t)||e.length!==t.length?!1:e.every((e,r)=>go(e,t[r],n+1));if(Array.isArray(t)||!K(e)||!K(t))return!1;let r=Object.keys(e),i=Object.keys(t);return r.length===i.length&&r.every(r=>Object.hasOwn(t,r)&&go(e[r],t[r],n+1))},_o=(e,t)=>!Ea(e)||!Ea(t)?!1:go(e,t,0);function vo(e){let t=e.metadata;if(!t||typeof t!=`object`)return;let n=t.custom;if(!n||typeof n!=`object`)return;let r=n.interactables;return Array.isArray(r)?r:void 0}function yo(e){return`update_${e.replace(/[^a-zA-Z0-9_-]/g,`_`)}`}var bo=e=>{if(!K(e))return;let t=e.id;return typeof t==`string`||typeof t==`number`?t:void 0};function xo(e,t,n=[]){if(!K(e)||!K(t))return t;let r={...e,...t},[i,...a]=n;return i!==void 0&&Object.hasOwn(t,i)&&(r[i]=xo(e[i],t[i],a)),r}function So(e,t,n,r){let i=Array.isArray(t.set)?[...t.set]:[...e];if(t.clear===!0&&(i=[]),Array.isArray(t.remove)&&t.remove.length>0){let e=new Set(t.remove);i=i.filter(t=>{let n=bo(t);return n===void 0?!e.has(t):!e.has(n)})}let a=t.update;if(Array.isArray(a)&&a.length>0){let e=new Map;for(let t of a){let n=bo(t);n!==void 0&&!Number.isNaN(n)&&!e.has(n)&&e.set(n,t)}let t=r?.[0]===`update`?{patch:a[Number(r[1])],rest:r.slice(2)}:void 0;i=i.map(n=>{let r=bo(n);if(r===void 0||!K(n))return n;let i=e.get(r);return i?t&&i===t.patch?xo(n,i,t.rest):{...n,...i}:n})}if(Array.isArray(t.add)&&t.add.length>0){let e=n?t.add.map(e=>{if(!K(e)||e.id!==void 0)return e;let t=n();return t===void 0?e:{...e,id:t}}):t.add;i=[...i,...e]}return i}function Co(e,t,n){if(!K(e)||!K(t))return t;let r=K(n?.arrayBaseline)?n.arrayBaseline:e,i=n?.partialPath,a=Object.entries(e);for(let[o,s]of Object.entries(t)){let t=r[o],c=i?.[0]===o?i.slice(1):void 0;if(Array.isArray(t)&&K(s)){let e=n?.idFactory&&(n.idKeyedFields===void 0||n.idKeyedFields.has(o))?()=>n.idFactory?.(o):void 0;a.push([o,So(t,s,e,c)])}else c?a.push([o,xo(e[o],s,c)]):a.push([o,s])}return Object.fromEntries(a)}function wo(e,t){if(!K(e)||!K(t))return;for(let n of Object.keys(e))if(!Object.hasOwn(t,n))return;let n=[];for(let[r,i]of Object.entries(t))(!Object.hasOwn(e,r)||!_o(e[r],i))&&n.push([r,i]);let r=n.length;if(r!==0&&r!==Object.keys(t).length)return Object.fromEntries(n)}var To=e=>{if(!e||typeof e!=`object`)return;let t=e;return t.type===`tool-call`?t:void 0},Eo=(e,t)=>{if(!e.args||typeof e.args!=`object`)return!1;let n=K(e.result)?e.result:void 0;if(n?.success===!1)return!1;if(typeof n?.id==`string`)return n.id===t;let r=e.args.id;return r===t||r===void 0},Do=e=>{let t=K(e)?e.addedItemIds:void 0;if(!K(t))return;let n=new Map;for(let[e,r]of Object.entries(t)){if(!Array.isArray(r))continue;let t=r.filter(e=>typeof e==`string`);t.length>0&&n.set(e,t)}if(n.size!==0)return e=>n.get(e)?.shift()},Oo=new WeakMap;function ko(e,t,n){let r=Oo.get(e);r||(r=new Map,Oo.set(e,r));let i=r.get(n);i||(i=new Map,r.set(n,i));let a=i.get(t);if(a)return a;let o=yo(n),s=[],c=()=>s[s.length-1];for(let r of e){if(r.role===`user`){let e=vo(r)?.find(e=>e.id===t);if(!e)continue;if(e.partial){let t=c();t&&s.push({state:Co(t.state,e.state),origin:`user-edit`})}else s.push({state:e.state,origin:`user-edit`});continue}if(r.role===`assistant`)for(let e of r.content??[]){let r=To(e);if(r){if(r.toolCallId===t&&r.toolName===n)r.args&&typeof r.args==`object`&&s.push({state:r.args,origin:`create`,toolCallId:t});else if(r.toolName===o&&Eo(r,t)){let e=c();if(e){let{id:t,...n}=r.args,i=Do(r.result);s.push({state:i?Co(e.state,n,{idFactory:i}):Co(e.state,n),origin:`update`,toolCallId:r.toolCallId})}}}}}return i.set(t,s),s}function Ao(e,t,n){let r=ko(e,t,n),i=r[r.length-1];return i?{state:i.state}:void 0}function jo(e,t){if(!e)return;let{interactables:n,...r}=e,i={...r};if(Array.isArray(n)){let e=[];for(let r of n){let n=Ao(t,r.id,r.name);if(!n){e.push({id:r.id,name:r.name,state:r.state});continue}if(_o(r.state,n.state))continue;let i=wo(n.state,r.state);e.push(i?{id:r.id,name:r.name,state:i,partial:!0}:{id:r.id,name:r.name,state:r.state})}e.length&&(i.interactables=e)}return Object.keys(i).length?i:void 0}var Mo=Symbol(`innerMessage`),No=e=>e.type===`tool-call`&&e.result===void 0,Po=e=>e.type===`tool-call`&&Si(e),Fo=Symbol(`autoStatus`),Io=Object.freeze(Object.assign({type:`running`},{[Fo]:!0})),Lo=Object.freeze(Object.assign({type:`complete`,reason:`unknown`},{[Fo]:!0})),Ro=Object.freeze(Object.assign({type:`incomplete`,reason:`cancelled`},{[Fo]:!0})),zo=Object.freeze(Object.assign({type:`requires-action`,reason:`tool-calls`},{[Fo]:!0})),Bo=Object.freeze(Object.assign({type:`requires-action`,reason:`interrupt`},{[Fo]:!0})),Vo=(e,t,n,r,i,a,o)=>e&&i!=null?Object.assign({type:`incomplete`,reason:`error`,error:i},{[Fo]:!0}):e&&t?Io:n?Bo:o&&!a?Io:r?zo:a?Ro:Lo,Ho=e=>Vo(!1,!1,typeof e!=`string`&&e.some(Po),typeof e!=`string`&&e.some(No)),Uo=e=>{let t=x(6),{runtime:n,children:r}=e,i=Xr(),a;t[0]===n?a=t[1]:(a=mn({threadListItem:ga({runtime:n})}),t[0]=n,t[1]=a);let o=a,s;return t[2]!==i||t[3]!==r||t[4]!==o?(s=(0,S.jsx)(ya,{extends:i,config:o,children:r}),t[2]=i,t[3]=r,t[4]=o,t[5]=s):s=t[5],s},Wo=[`critical`,`warning`,`info`],Go=[`inline`,`toast`,`silent`,`dev-only`],Ko=e=>{if(typeof e!=`object`||!e)return!1;let t=e;return!(typeof t.code!=`string`||typeof t.message!=`string`||`severity`in t&&t.severity!==void 0&&(typeof t.severity!=`string`||!Wo.includes(t.severity))||`display`in t&&t.display!==void 0&&(typeof t.display!=`string`||!Go.includes(t.display)))},qo=Symbol.for(`assistant-ui.message-not-sent`),Jo=class extends Error{[qo]=!0;constructor(e=`The message was not sent.`){super(e),this.name=`MessageNotSentError`}},Yo=e=>typeof e==`object`&&!!e&&qo in e,Xo=e=>{if(Ko(e))return e;if(e instanceof Error)return{code:`unknown`,message:e.message};if(typeof e==`string`)return{code:`unknown`,message:e};try{return{code:`unknown`,message:`[${typeof e}] ${String(e)}`}}catch{return{code:`unknown`,message:`[${typeof e}]`}}},Zo=(e,t)=>{Promise.resolve(t).catch(t=>{Yo(t)||console.error(`[assistant-ui] ${e} failed`,t)})},Qo=class{get path(){return this._core.path}_core;constructor(e){this._core=e,this.__internal_bindMethods()}__internal_bindMethods(){this.getState=this.getState.bind(this),this.remove=this.remove.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this._core.getState()}subscribe(e){return this._core.subscribe(e)}},$o=class extends Qo{_composerApi;constructor(e,t){super(e),this._composerApi=t}remove(){let e=this._composerApi.getState();if(!e)throw Error(`Composer is not available`);return e.removeAttachment(this.getState().id)}},es=class extends $o{get source(){return`thread-composer`}},ts=class extends $o{get source(){return`edit-composer`}},ns=class extends Qo{get source(){return`message`}remove(){throw Error(`Message attachments cannot be removed`)}},rs=Object.freeze([]),is=Object.freeze({}),as=e=>Object.freeze({type:`thread`,isEditing:e?.isEditing??!1,canCancel:e?.canCancel??!1,canSend:e?.canSend??!1,isEmpty:e?.isEmpty??!0,attachments:e?.attachments??rs,text:e?.text??``,role:e?.role??`user`,runConfig:e?.runConfig??is,attachmentAccept:e?.attachmentAccept??``,dictation:e?.dictation,quote:e?.quote,queue:e?.queue??rs,submission:e?.submission,inTransit:e?.inTransit??rs,value:e?.text??``}),os=e=>Object.freeze({type:`edit`,isEditing:e?.isEditing??!1,canCancel:e?.canCancel??!1,canSend:e?.canSend??!1,isEmpty:e?.isEmpty??!0,text:e?.text??``,role:e?.role??`user`,attachments:e?.attachments??rs,runConfig:e?.runConfig??is,attachmentAccept:e?.attachmentAccept??``,dictation:e?.dictation,quote:e?.quote,queue:e?.queue??rs,submission:e?.submission,inTransit:e?.inTransit??rs,parentId:e?.parentId??null,sourceId:e?.sourceId??null,value:e?.text??``}),ss=class{get path(){return this._core.path}_core;constructor(e){this._core=e}__internal_bindMethods(){this.setText=this.setText.bind(this),this.setRunConfig=this.setRunConfig.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.addAttachment=this.addAttachment.bind(this),this.reset=this.reset.bind(this),this.clearAttachments=this.clearAttachments.bind(this),this.send=this.send.bind(this),this.cancel=this.cancel.bind(this),this.steerQueueItem=this.steerQueueItem.bind(this),this.moveQueueItem=this.moveQueueItem.bind(this),this.removeQueueItem=this.removeQueueItem.bind(this),this.setRole=this.setRole.bind(this),this.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.startDictation=this.startDictation.bind(this),this.stopDictation=this.stopDictation.bind(this),this.setQuote=this.setQuote.bind(this),this.unstable_on=this.unstable_on.bind(this)}setText(e){let t=this._core.getState();if(!t)throw Error(`Composer is not available`);t.setText(e)}setRunConfig(e){let t=this._core.getState();if(!t)throw Error(`Composer is not available`);t.setRunConfig(e)}addAttachment(e){let t=this._core.getState();if(!t)throw Error(`Composer is not available`);return t.addAttachment(e)}reset(){let e=this._core.getState();if(!e)throw Error(`Composer is not available`);return e.reset()}clearAttachments(){let e=this._core.getState();if(!e)throw Error(`Composer is not available`);return e.clearAttachments()}send(e){let t=this._core.getState();if(!t)throw Error(`Composer is not available`);t.send(e)}cancel(){let e=this._core.getState();if(!e)throw Error(`Composer is not available`);e.cancel()}steerQueueItem(e){this.moveQueueItem(e,{lane:`steer`,insertAfter:null})}moveQueueItem(e,t){let n=this._core.getState();if(!n)throw Error(`Composer is not available`);n.moveQueueItem(e,t)}removeQueueItem(e){let t=this._core.getState();if(!t)throw Error(`Composer is not available`);t.removeQueueItem(e)}setRole(e){let t=this._core.getState();if(!t)throw Error(`Composer is not available`);t.setRole(e)}startDictation(){let e=this._core.getState();if(!e)throw Error(`Composer is not available`);e.startDictation()}stopDictation(){let e=this._core.getState();if(!e)throw Error(`Composer is not available`);e.stopDictation()}setQuote(e){let t=this._core.getState();if(!t)throw Error(`Composer is not available`);t.setQuote(e)}subscribe(e){return this._core.subscribe(e)}_eventSubscriptionSubjects=new Map;unstable_on(e,t){let n=this._eventSubscriptionSubjects.get(e);return n||(n=new ci({event:e,binding:this._core}),this._eventSubscriptionSubjects.set(e,n)),n.subscribe(t)}},cs=class extends ss{get path(){return this._core.path}get type(){return`thread`}_getState;constructor(e){let t=new oi({path:e.path,getState:()=>as(e.getState()),subscribe:t=>e.subscribe(t)});super({path:e.path,getState:()=>e.getState(),subscribe:e=>t.subscribe(e)}),this._getState=t.getState.bind(t),this.__internal_bindMethods()}getState(){return this._getState()}getAttachmentByIndex(e){return new es(new H({path:{...this.path,attachmentSource:`thread-composer`,attachmentSelector:{type:`index`,index:e},ref:`${this.path.ref}.attachments[${e}]`},getState:()=>{let t=this.getState().attachments[e];return t?{...t,source:`thread-composer`}:B},subscribe:e=>this._core.subscribe(e)}),this._core)}},ls=class extends ss{get path(){return this._core.path}get type(){return`edit`}_getState;_beginEdit;constructor(e,t){let n=new oi({path:e.path,getState:()=>os(e.getState()),subscribe:t=>e.subscribe(t)});super({path:e.path,getState:()=>e.getState(),subscribe:e=>n.subscribe(e)}),this._beginEdit=t,this._getState=n.getState.bind(n),this.__internal_bindMethods()}__internal_bindMethods(){super.__internal_bindMethods(),this.beginEdit=this.beginEdit.bind(this)}getState(){return this._getState()}beginEdit(){this._beginEdit()}getAttachmentByIndex(e){return new ts(new H({path:{...this.path,attachmentSource:`edit-composer`,attachmentSelector:{type:`index`,index:e},ref:`${this.path.ref}.attachments[${e}]`},getState:()=>{let t=this.getState().attachments[e];return t?{...t,source:`edit-composer`}:B},subscribe:e=>this._core.subscribe(e)}),this._core)}},us=`ui://`,ds=e=>!!e?.startsWith(us),fs=e=>e.display===`text`||e.display!==`questions`&&e.allowFreeform===!0,ps={"allow-once":!0,"allow-always":!0,"reject-once":!1,"reject-always":!1},ms=(e,t)=>{let n=e.questions??[];if(n.length===0)throw Error(`Tool approval "${e.id}" has display "questions" but declares no questions`);let r=new Set;for(let t of n){if(r.has(t.id))throw Error(`Tool approval "${e.id}" declares question "${t.id}" more than once`);r.add(t.id)}for(let n of Object.keys(t))if(!r.has(n))throw Error(`Tool approval "${e.id}" has no question with id "${n}"`);for(let r of n){let n=Object.hasOwn(t,r.id)?t[r.id]:void 0,i=n?.optionIds??[],a=n?.text;if(!Array.isArray(i)||a!==void 0&&typeof a!=`string`)throw Error(`Question "${r.id}" takes optionIds as an array and text as a string`);if(i.length===0&&(a===void 0||a.trim()===``))throw Error(`Tool approval "${e.id}" is missing an answer to question "${r.id}"`);if(i.length>1&&!r.multiple)throw Error(`Question "${r.id}" takes one option, not ${i.length}`);if(new Set(i).size!==i.length)throw Error(`Question "${r.id}" lists an option more than once`);for(let e of i)if(!r.options?.some(t=>t.id===e))throw Error(`Question "${r.id}" has no option with id "${e}"`);if(a!==void 0&&(r.options?.length??0)>0&&!r.allowFreeform)throw Error(`Question "${r.id}" does not accept a typed answer; it must declare allowFreeform`)}},hs=(e,t)=>{let n=t.reason;if(`answers`in t){if(`approved`in t||`optionId`in t||`text`in t)throw Error(`Tool approval "${e.id}" takes its answers alone, without approved, optionId or text`);return ms(e,t.answers),{approvalId:e.id,approved:!0,answers:t.answers,...n!=null&&{reason:n}}}if(`approved`in t&&t.approved===!1&&!(`optionId`in t)&&t.text===void 0)return{approvalId:e.id,approved:!1,...n!=null&&{reason:n}};throw Error(`Tool approval "${e.id}" asks questions; respond with answers, or with approved: false to dismiss it`)},gs=(e,t)=>{if(e.display===`questions`)return hs(e,t);if(`answers`in t)throw Error(`Tool approval "${e.id}" asks no questions; answers only resolve a display "questions" request`);let n=t.text;if(n!==void 0&&!fs(e))throw Error(`Tool approval "${e.id}" does not accept a free-form answer; the request must declare display "text" or allowFreeform`);let r,i;if(`optionId`in t){let n=e.options?.find(e=>e.id===t.optionId);if(!n)throw Error(`Tool approval has no option with id "${t.optionId}"`);if(`approved`in t)r=t.approved;else{if(!Object.hasOwn(ps,n.kind))throw Error(`Tool approval option "${n.id}" has a custom kind "${n.kind}"; respond with an explicit approved value instead`);r=ps[n.kind]}i=n.id}else if(`approved`in t)r=t.approved;else{if(e.display!==`text`&&e.display!==`select`)throw Error(`Tool approval "${e.id}" is a decision, not a question; respond with an explicit approved value, optionally alongside the answer`);r=!0}return{approvalId:e.id,approved:r,...i!==void 0&&{optionId:i},...n!==void 0&&{text:n},...t.reason!=null&&{reason:t.reason}}},_s=class{get path(){return this.contentBinding.path}contentBinding;messageApi;threadApi;constructor(e,t,n){this.contentBinding=e,this.messageApi=t,this.threadApi=n,this.__internal_bindMethods()}__internal_bindMethods(){this.addToolResult=this.addToolResult.bind(this),this.resumeToolCall=this.resumeToolCall.bind(this),this.respondToToolApproval=this.respondToToolApproval.bind(this),this.unstable_recordInteraction=this.unstable_recordInteraction.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this.contentBinding.getState()}addToolResult(e){let t=this.contentBinding.getState();if(!t)throw Error(`Message part is not available`);if(t.type!==`tool-call`)throw Error(`Tried to add tool result to non-tool message part`);if(!this.messageApi)throw Error(`Message API is not available. This is likely a bug in assistant-ui.`);if(!this.threadApi)throw Error(`Thread API is not available`);let n=this.messageApi.getState();if(!n)throw Error(`Message is not available`);let r=t.toolName,i=t.toolCallId,a=na.toResponse(e);this.threadApi.getState().addToolResult({messageId:n.id,toolName:r,toolCallId:i,result:a.result,isError:a.isError,...a.artifact!==void 0&&{artifact:a.artifact},...a.modelContent!==void 0&&{modelContent:a.modelContent}})}resumeToolCall(e){let t=this.contentBinding.getState();if(!t)throw Error(`Message part is not available`);if(t.type!==`tool-call`)throw Error(`Tried to resume tool call on non-tool message part`);if(!this.threadApi)throw Error(`Thread API is not available`);let n=t.toolCallId;this.threadApi.getState().resumeToolCall({toolCallId:n,payload:e}),this.unstable_recordInteraction({type:`human-response`,payload:e}).catch(()=>{})}respondToToolApproval(e){let t=this.contentBinding.getState();if(!t)throw Error(`Message part is not available`);if(t.type!==`tool-call`)throw Error(`Tried to respond to tool approval on non-tool message part`);if(!t.approval||t.approval.approved!==void 0||t.approval.resolution!==void 0)throw Error(`Tool call has no pending approval`);if(!this.threadApi)throw Error(`Thread API is not available`);return this.threadApi.getState().respondToToolApproval(gs(t.approval,e))}async unstable_recordInteraction(e){let t=this.contentBinding.getState();if(!t)throw Error(`Message part is not available`);if(t.type!==`tool-call`)throw Error(`Tried to record interaction on non-tool message part`);if(!this.messageApi)throw Error(`Message API is not available. This is likely a bug in assistant-ui.`);if(!this.threadApi)throw Error(`Thread API is not available`);let n=this.messageApi.getState();if(!n)throw Error(`Message is not available`);let r=this.threadApi.getState();if(!r.unstable_recordToolInteraction)throw Error(`Runtime does not support recording tool interactions.`);await r.unstable_recordToolInteraction({messageId:n.id,toolCallId:t.toolCallId,interaction:Mi(e)})}subscribe(e){return this.contentBinding.subscribe(e)}},vs=(e,t)=>{let n=e.content[t];if(!n)return B;let r=Ci(e,t,n);return Object.freeze({...n,[Mo]:n[Mo],status:r})},ys=class{get path(){return this._core.path}_core;_threadBinding;constructor(e,t){this._core=e,this._threadBinding=t,this.composer=new ls(new si({path:{...this.path,ref:`${this.path.ref}.composer`,composerSource:`edit`},getState:this._getEditComposerRuntimeCore,subscribe:e=>this._threadBinding.subscribe(e)}),()=>this._threadBinding.getState().beginEdit(this._core.getState().id)),this.__internal_bindMethods()}__internal_bindMethods(){this.reload=this.reload.bind(this),this.delete=this.delete.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.getMessagePartByIndex=this.getMessagePartByIndex.bind(this),this.getMessagePartByToolCallId=this.getMessagePartByToolCallId.bind(this),this.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.unstable_getCopyText=this.unstable_getCopyText.bind(this),this.speak=this.speak.bind(this),this.stopSpeaking=this.stopSpeaking.bind(this),this.submitFeedback=this.submitFeedback.bind(this),this.switchToBranch=this.switchToBranch.bind(this)}composer;_getEditComposerRuntimeCore=()=>this._threadBinding.getState().getEditComposer(this._core.getState().id);getState(){return this._core.getState()}delete(){let e=this._core.getState();return this._threadBinding.getState().deleteMessage(e.id)}reload(e={}){let t=this._getEditComposerRuntimeCore(),n=t??this._threadBinding.getState().composer,r=t??n,{runConfig:i=r.runConfig}=e,a=this._core.getState();if(a.role!==`assistant`)throw Error(`Can only reload assistant messages`);Zo(`Message reload`,this._threadBinding.getState().startRun({parentId:a.parentId,sourceId:a.id,runConfig:i}))}speak(){let e=this._core.getState();return this._threadBinding.getState().speak(e.id)}stopSpeaking(){let e=this._core.getState();if(this._threadBinding.getState().speech?.messageId===e.id)this._threadBinding.getState().stopSpeaking();else throw Error(`Message is not being spoken`)}submitFeedback({type:e,comment:t}){let n=this._core.getState();this._threadBinding.getState().submitFeedback({messageId:n.id,type:e,...t===void 0?void 0:{comment:t}})}switchToBranch({position:e,branchId:t}){let n=this._core.getState();if(t&&e)throw Error(`May not specify both branchId and position`);if(!t&&!e)throw Error(`Must specify either branchId or position`);let r=this._threadBinding.getState().getBranches(n.id),i=t;if(e===`previous`?i=r[n.branchNumber-2]:e===`next`&&(i=r[n.branchNumber]),!i)throw Error(`Branch not found`);this._threadBinding.getState().switchToBranch(i)}unstable_getCopyText(){return _i(this.getState())}subscribe(e){return this._core.subscribe(e)}getMessagePartByIndex(e){if(e<0)throw Error(`Message part index must be >= 0`);return new _s(new H({path:{...this.path,ref:`${this.path.ref}.content[${e}]`,messagePartSelector:{type:`index`,index:e}},getState:()=>vs(this.getState(),e),subscribe:e=>this._core.subscribe(e)}),this._core,this._threadBinding)}getMessagePartByToolCallId(e){return new _s(new H({path:{...this.path,ref:`${this.path.ref}.content[toolCallId=${JSON.stringify(e)}]`,messagePartSelector:{type:`toolCallId`,toolCallId:e}},getState:()=>{let t=this._core.getState(),n=t.content.findIndex(t=>t.type===`tool-call`&&t.toolCallId===e);return n===-1?B:vs(t,n)},subscribe:e=>this._core.subscribe(e)}),this._core,this._threadBinding)}getAttachmentByIndex(e){return new ns(new H({path:{...this.path,ref:`${this.path.ref}.attachments[${e}]`,attachmentSource:`message`,attachmentSelector:{type:`index`,index:e}},getState:()=>{let t=this.getState().attachments?.[e];return t?{...t,source:`message`}:B},subscribe:e=>this._core.subscribe(e)}))}},bs=e=>({parentId:e.parentId??null,sourceId:e.sourceId??null,runConfig:e.runConfig??{},...e.stream?{stream:e.stream}:{}}),xs=e=>({parentId:e.parentId??null,sourceId:e.sourceId??null,runConfig:e.runConfig??{}}),Ss=(e,t)=>typeof t==`string`?{createdAt:new Date,parentId:e.at(-1)?.id??null,sourceId:null,runConfig:{},role:`user`,content:[{type:`text`,text:t}],attachments:[],metadata:{custom:{}}}:{createdAt:t.createdAt??new Date,parentId:t.parentId===void 0?e.at(-1)?.id??null:t.parentId,sourceId:t.sourceId??null,role:t.role??`user`,content:t.content,attachments:t.attachments??[],metadata:t.metadata??{custom:{}},runConfig:t.runConfig??{},startRun:t.startRun},Cs=e=>{if(e.isRunning!==void 0)return e.isRunning;let t=e.messages.at(-1);return t?.role===`assistant`&&t.status.type===`running`},ws=(e,t)=>Object.freeze({threadId:t.id,metadata:t,capabilities:e.capabilities,isDisabled:e.isDisabled,isLoading:e.isLoading,hasEarlier:e.hasEarlier??!1,isLoadingEarlier:e.isLoadingEarlier??!1,isRunning:Cs(e),messages:e.messages,state:e.state,suggestions:e.suggestions,extras:e.extras,speech:e.speech,voice:e.voice}),Ts=class{get path(){return this._threadBinding.path}get __internal_threadBinding(){return this._threadBinding}_threadBinding;_stateBinding;constructor(e,t){let n=new H({path:e.path,getState:()=>ws(e.getState(),t.getState()),subscribe:n=>{let r=e.subscribe(n),i=t.subscribe(n);return()=>ei([r,i])}});this._stateBinding=n,this._threadBinding={path:e.path,getState:()=>e.getState(),getStateState:()=>n.getState(),outerSubscribe:t=>e.outerSubscribe(t),subscribe:t=>e.subscribe(t)},this.composer=new cs(new si({path:{...this.path,ref:`${this.path.ref}.composer`,composerSource:`thread`},getState:()=>this._threadBinding.getState().composer,subscribe:e=>this._threadBinding.subscribe(e)})),this.__internal_bindMethods()}__internal_bindMethods(){this.append=this.append.bind(this),this.deleteMessage=this.deleteMessage.bind(this),this.resumeRun=this.resumeRun.bind(this),this.loadEarlier=this.loadEarlier.bind(this),this.importExternalState=this.importExternalState.bind(this),this.exportExternalState=this.exportExternalState.bind(this),this.startRun=this.startRun.bind(this),this.cancelRun=this.cancelRun.bind(this),this.unstable_notifySessionReset=this.unstable_notifySessionReset.bind(this),this.stopSpeaking=this.stopSpeaking.bind(this),this.connectVoice=this.connectVoice.bind(this),this.disconnectVoice=this.disconnectVoice.bind(this),this.muteVoice=this.muteVoice.bind(this),this.unmuteVoice=this.unmuteVoice.bind(this),this.getVoiceVolume=this.getVoiceVolume.bind(this),this.subscribeVoiceVolume=this.subscribeVoiceVolume.bind(this),this.export=this.export.bind(this),this.import=this.import.bind(this),this.reset=this.reset.bind(this),this.getMessageByIndex=this.getMessageByIndex.bind(this),this.getMessageById=this.getMessageById.bind(this),this.subscribe=this.subscribe.bind(this),this.unstable_on=this.unstable_on.bind(this),this.getModelContext=this.getModelContext.bind(this),this.getState=this.getState.bind(this)}composer;getState(){return this._threadBinding.getStateState()}append(e){Zo(`Message append`,this._threadBinding.getState().append(Ss(this._threadBinding.getState().messages,e)))}deleteMessage(e){return this._threadBinding.getState().deleteMessage(e)}subscribe(e){return this._stateBinding.subscribe(e)}getModelContext(){return this._threadBinding.getState().getModelContext()}startRun(e){return this._threadBinding.getState().startRun(xs(e))}resumeRun(e){return this._threadBinding.getState().resumeRun(bs(e))}exportExternalState(){return this._threadBinding.getState().exportExternalState()}importExternalState(e){this._threadBinding.getState().importExternalState(e)}cancelRun(){this._threadBinding.getState().cancelRun()}loadEarlier(){return this._threadBinding.getState().loadEarlier?.()??Promise.resolve()}unstable_notifySessionReset(){this._threadBinding.getState().unstable_notifySessionReset()}stopSpeaking(){return this._threadBinding.getState().stopSpeaking()}connectVoice(){this._threadBinding.getState().connectVoice()}disconnectVoice(){this._threadBinding.getState().disconnectVoice()}getVoiceVolume(){return this._threadBinding.getState().getVoiceVolume()}subscribeVoiceVolume(e){return this._threadBinding.getState().subscribeVoiceVolume(e)}muteVoice(){this._threadBinding.getState().muteVoice()}unmuteVoice(){this._threadBinding.getState().unmuteVoice()}export(){return this._threadBinding.getState().export()}import(e){this._threadBinding.getState().import(e)}reset(e){this._threadBinding.getState().reset(e)}getMessageByIndex(e){if(e<0)throw Error(`Message index must be >= 0`);return this._getMessageRuntime({...this.path,ref:`${this.path.ref}.messages[${e}]`,messageSelector:{type:`index`,index:e}},()=>{let t=this._threadBinding.getState().messages,n=t[e];if(n)return{message:n,parentId:t[e-1]?.id??null,index:e}})}getMessageById(e){return this._getMessageRuntime({...this.path,ref:`${this.path.ref}.messages[messageId=${JSON.stringify(e)}]`,messageSelector:{type:`messageId`,messageId:e}},()=>this._threadBinding.getState().getMessageById(e))}_getMessageRuntime(e,t){return new ys(new H({path:e,getState:()=>{let{message:e,parentId:n,index:r}=t()??{},{messages:i,speech:a}=this._threadBinding.getState();if(!e||n===void 0||r===void 0)return B;let o=this._threadBinding.getState().getBranches(e.id);return{...e,[Mo]:e[Mo],index:r,isLast:i.at(-1)?.id===e.id,parentId:n,branchNumber:o.indexOf(e.id)+1,branchCount:o.length,speech:a?.messageId===e.id?a:void 0}},subscribe:e=>this._threadBinding.subscribe(e)}),this._threadBinding)}_eventSubscriptionSubjects=new Map;unstable_on(e,t){let n=this._eventSubscriptionSubjects.get(e);return n||(n=new ci({event:e,binding:this._threadBinding,notifyOnRebind:e===`modelContextUpdate`}),this._eventSubscriptionSubjects.set(e,n)),n.subscribe(t)}},Es=(e,t)=>({attachments:[],attachmentAccept:`*`,async addAttachment(){throw e},async removeAttachment(){throw e},isEditing:t,canCancel:!1,canSend:!1,isEmpty:!0,text:``,setText(){throw e},role:`user`,setRole(){throw e},runConfig:{},setRunConfig(){throw e},async reset(){},async clearAttachments(){},send(){throw e},cancel(){},queue:[],moveQueueItem(){},removeQueueItem(){},dictation:void 0,startDictation(){throw e},stopDictation(){},quote:void 0,setQuote(){throw e},subscribe(){return()=>{}},unstable_on(){return()=>{}}}),Ds=class extends ri{switchToBranch(){throw this.error}append(){throw this.error}deleteMessage(){throw this.error}startRun(){throw this.error}resumeRun(){throw this.error}cancelRun(){throw this.error}unstable_notifySessionReset(){throw this.error}addToolResult(){throw this.error}resumeToolCall(){throw this.error}respondToToolApproval(){throw this.error}async unstable_recordToolInteraction(e){throw this.error}speak(){throw this.error}stopSpeaking(){throw this.error}connectVoice(){throw this.error}disconnectVoice(){throw this.error}muteVoice(){throw this.error}unmuteVoice(){throw this.error}submitFeedback(){throw this.error}exportExternalState(){throw this.error}importExternalState(){throw this.error}beginEdit(){throw this.error}import(){throw this.error}reset(){throw this.error}getModelContext(){return{}}getEditComposer(){}getVoiceVolume=()=>0;subscribeVoiceVolume=()=>()=>{};speech=void 0;voice=void 0;capabilities={switchToBranch:!1,switchBranchDuringRun:!1,edit:!1,delete:!1,reload:!1,refetchThread:!1,cancel:!1,unstable_copy:!1,speech:!1,dictation:!1,voice:!1,attachments:!1,feedback:!1,queue:!1,answerToolCall:!1};isDisabled=!1;isSendDisabled=!1;state=null;suggestions=[];extras=void 0;unstable_on(){return()=>{}}},Os=new WeakMap,ks=e=>{let t=Os.get(e);return t||(t=new AbortController,Os.set(e,t)),t.signal},As=new WeakMap,js=e=>{let t=As.get(e);return t||(t=new AbortController,As.set(e,t)),t},Ms=e=>js(e).signal,Ns=e=>{let t=Os.get(e);t?.signal.aborted||(Os.delete(e),t?.abort())},Ps=e=>{if(e.voice)try{e.disconnectVoice()}catch(e){console.error(`[assistant-ui] Voice cleanup threw while discarding a thread runtime`,e)}},Fs=e=>{Ps(e),Ns(e)},Is=e=>{let t=Os.get(e)??new AbortController;Os.set(e,t),t.abort(),js(e).abort(),Ps(e)},Ls=class{get path(){return this._core.path}_core;_threadListBinding;constructor(e,t){this._core=e,this._threadListBinding=t,this.__internal_bindMethods()}__internal_bindMethods(){this.switchTo=this.switchTo.bind(this),this.rename=this.rename.bind(this),this.updateCustom=this.updateCustom.bind(this),this.archive=this.archive.bind(this),this.unarchive=this.unarchive.bind(this),this.delete=this.delete.bind(this),this.initialize=this.initialize.bind(this),this.generateTitle=this.generateTitle.bind(this),this.subscribe=this.subscribe.bind(this),this.unstable_on=this.unstable_on.bind(this),this.getState=this.getState.bind(this),this.detach=this.detach.bind(this)}getState(){return this._core.getState()}switchTo(e){let t=this._core.getState();return this._threadListBinding.switchToThread(t.id,e)}rename(e){let t=this._core.getState();return this._threadListBinding.rename(t.id,e)}updateCustom(e){let t=this._core.getState();if(!this._threadListBinding.updateCustom)throw Error(`Thread list runtime does not support updating custom metadata`);return this._threadListBinding.updateCustom(t.id,e)}archive(){let e=this._core.getState();return this._threadListBinding.archive(e.id)}unarchive(){let e=this._core.getState();return this._threadListBinding.unarchive(e.id)}delete(){let e=this._core.getState();return this._threadListBinding.delete(e.id)}initialize(){let e=this._core.getState();return this._threadListBinding.initialize(e.id)}generateTitle(e){let t=this._core.getState();return this._threadListBinding.generateTitle(t.id,e)}unstable_on(e,t){let n=this._core.getState().isMain,r=this._core.getState().id;return this.subscribe(()=>{let i=this._core.getState(),a=i.isMain,o=i.id;(n!==a||r!==o)&&(n=a,r=o,!(e===`switchedTo`&&!a)&&(e===`switchedAway`&&a||z([t],{},`Thread list item "${e}"`)))})}subscribe(e){return this._core.subscribe(e)}detach(){let e=this._core.getState();this._threadListBinding.detach(e.id)}__internal_getRuntime(){return this}},Rs=Promise.resolve(),zs=()=>{},Bs=e=>({mainThreadId:e.mainThreadId,newThreadId:e.newThreadId,threadIds:e.threadIds,archivedThreadIds:e.archivedThreadIds,isLoading:e.isLoading,loadError:e.loadError,isLoadingMore:e.isLoadingMore??!1,hasMore:e.hasMore??!1,threadItems:e.threadItems}),Vs=(e,t)=>{if(t===void 0)return B;let n=e.getItemById(t);return n?{id:n.id,remoteId:n.remoteId,externalId:n.externalId,title:n.title,status:n.status,lastMessageAt:n.lastMessageAt,custom:n.custom,isMain:n.id===e.mainThreadId,isRunning:e.unstable_isThreadRunning?.(n.id)??!1}:B},Hs=class{_getState;_stateBinding;_core;_runtimeFactory;constructor(e,t=Ts){this._core=e,this._runtimeFactory=t;let n=new oi({path:{},getState:()=>Bs(e),subscribe:t=>e.subscribe(t)});this._getState=n.getState.bind(n),this._stateBinding=n,this._mainThreadListItemRuntime=new Ls(new H({path:{ref:`threadItems[main]`,threadSelector:{type:`main`}},getState:()=>Vs(this._core,this._core.mainThreadId),subscribe:e=>this._core.subscribe(e)}),this._core),this.main=new t(new si({path:{ref:`threads.main`,threadSelector:{type:`main`}},getState:()=>e.getMainThreadRuntimeCore(),subscribe:t=>e.subscribe(t)}),this._mainThreadListItemRuntime),this.__internal_bindMethods()}__internal_bindMethods(){this.switchToThread=this.switchToThread.bind(this),this.switchToNewThread=this.switchToNewThread.bind(this),this.unstable_subscribeThreadEvents=this.unstable_subscribeThreadEvents.bind(this),this.getLoadThreadsPromise=this.getLoadThreadsPromise.bind(this),this.reload=this.reload.bind(this),this.reloadMainThread=this.reloadMainThread.bind(this),this.loadMore=this.loadMore.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.getById=this.getById.bind(this),this.getItemById=this.getItemById.bind(this),this.getItemByIndex=this.getItemByIndex.bind(this),this.getArchivedItemByIndex=this.getArchivedItemByIndex.bind(this)}switchToThread(e,t){return this._core.switchToThread(e,t)}switchToNewThread(){return this._core.switchToNewThread()}unstable_subscribeThreadEvents(e){return this._core.unstable_subscribeThreadEvents?.(e)??zs}getLoadThreadsPromise(){return this._core.getLoadThreadsPromise()}reload(){return this._core.reload?.()??Rs}reloadMainThread(){return this._core.reloadMainThread?.()??Rs}loadMore(){return this._core.loadMore?.()??Rs}getState(){return this._getState()}subscribe(e){return this._stateBinding.subscribe(e)}_mainThreadListItemRuntime;main;get mainItem(){return this._mainThreadListItemRuntime}_createItemStateBinding(e){return new H({path:{ref:`threadItems[threadId=${e}]`,threadSelector:{type:`threadId`,threadId:e}},getState:()=>Vs(this._core,e),subscribe:e=>this._core.subscribe(e)})}getById(e){return new this._runtimeFactory(new si({path:{ref:`threads[threadId=${JSON.stringify(e)}]`,threadSelector:{type:`threadId`,threadId:e}},getState:()=>this._core.getThreadRuntimeCore(e),subscribe:e=>this._core.subscribe(e)}),this._createItemStateBinding(e))}getItemByIndex(e){return new Ls(new H({path:{ref:`threadItems[${e}]`,threadSelector:{type:`index`,index:e}},getState:()=>Vs(this._core,this._core.threadIds[e]),subscribe:e=>this._core.subscribe(e)}),this._core)}getArchivedItemByIndex(e){return new Ls(new H({path:{ref:`archivedThreadItems[${e}]`,threadSelector:{type:`archiveIndex`,index:e}},getState:()=>Vs(this._core,this._core.archivedThreadIds[e]),subscribe:e=>this._core.subscribe(e)}),this._core)}getItemById(e){return new Ls(this._createItemStateBinding(e),this._core)}},Us=class{threads;_thread;_core;constructor(e){this._core=e,this.threads=new Hs(e.threads),this._thread=this.threads.main,this.__internal_bindMethods()}__internal_bindMethods(){this.registerModelContextProvider=this.registerModelContextProvider.bind(this)}get thread(){return this._thread}registerModelContextProvider(e){return this._core.registerModelContextProvider(e)}},Ws=class{_contextProvider=new di;registerModelContextProvider(e){return this._contextProvider.registerModelContextProvider(e)}getModelContextProvider(){return this._contextProvider}},Gs={fromArray:e=>{let t=e.map(e=>pa(e,e.id??W(),Ho(e.content)));return{messages:t.map((e,n)=>({parentId:n>0?t[n-1].id:null,message:e}))}},fromBranchableArray:(e,t)=>({...t?.headId===void 0?void 0:{headId:t.headId},messages:e.map(({message:e,parentId:t})=>{if(!e.id)throw Error(`ExportedMessageRepository.fromBranchableArray: Each message must have an 'id' field set.`);return{parentId:t,message:pa(e,e.id,Ho(e.content))}})})},Ks=e=>{let t=e;for(;t.next;)t=t.next;return`current`in t?t:null},qs=(e,t)=>{let n=new Set(e.map(e=>e.message.id)),r=new Set,i=new Map,a=[];for(let o of e){let{parentId:e}=o;if(e!==null&&n.has(e)&&!r.has(e)&&!t(e)){let t=i.get(e);t?t.push(o):i.set(e,[o]);continue}for(let e=a.push(o)-1;e<a.length;e++){let{id:t}=a[e].message;if(r.has(t))continue;r.add(t);let n=i.get(t);n&&(i.delete(t),a.push(...n))}}for(let e of i.values())a.push(...e);return a},Js=e=>{let t=new Set(e.messages.map(e=>e.message.id)),n=new Map,r=[];for(let{message:i,parentId:a}of e.messages){if(a===null)continue;let e=n.get(a);e?e.push(i.id):n.set(a,[i.id]),t.has(a)||r.push(i.id)}let i=new Set;for(let e=0;e<r.length;e++){let t=r[e];if(!i.has(t)){i.add(t);for(let e of n.get(t)??[])r.push(e)}}let a=e.headId!=null&&!t.has(e.headId);if(i.size===0&&!a)return{repository:e,droppedIds:[]};let o=[],s=new Set,c=e.messages.filter(({message:e,parentId:t})=>i.has(e.id)?(o.push(e.id),!1):(t!==null&&s.add(t),!0)),{headId:l}=e;if(l!=null&&(a||i.has(l))){l=null;for(let{message:e}of c)s.has(e.id)||(l=e.id)}return{repository:{...e,messages:c,...l!==void 0&&{headId:l}},droppedIds:o}},Ys=class{_value=null;func;constructor(e){this.func=e}get value(){return this._value===null&&(this._value=this.func()),this._value}dirty(){this._value=null}},Xs=class{messages=new Map;head=null;root={children:[],next:null};updateLevels(e,t){let n=[{message:e,level:t}];for(;n.length>0;){let e=n.pop();e.message.level=e.level;for(let t of e.message.children){let r=this.messages.get(t);r&&n.push({message:r,level:e.level+1})}}}selectPathTo(e){for(let t=e;t;t=t.prev)(t.prev??this.root).next=t}performOp(e,t,n){let r=t.prev??this.root,i=e??this.root;if(n!==`relink`||r!==i){if(n===`relink`){for(let n=e;n;n=n.prev)if(n.current.id===t.current.id)throw Error(`MessageRepository(performOp/relink): A message with the same id already exists in the parent tree. This error occurs if the same message id is found multiple times. This is likely an internal bug in assistant-ui.`)}if(n!==`link`&&(r.children=r.children.filter(e=>e!==t.current.id),r.next===t)){let e=r.children.at(-1),t=e?this.messages.get(e):null;if(t===void 0)throw Error(`MessageRepository(performOp/cut): Fallback sibling message not found. This is likely an internal bug in assistant-ui.`);r.next=t}if(n!==`cut`){i.children=[...i.children,t.current.id],t.prev=e,Ks(t)===this.head?this.selectPathTo(t):i.next===null&&(i.next=t,this.head===i&&(this.head=Ks(t)));let n=e?e.level+1:0;this.updateLevels(t,n)}}}_messages=new Ys(()=>{let e=Array((this.head?.level??-1)+1);for(let t=this.head;t;t=t.prev)e[t.level]=t.current;return e});get headId(){return this.head?.current.id??null}get canonicalHeadId(){let e=this.head;for(;e?.current.metadata?.isOptimistic;)e=e.prev;return e?.current.id??null}getMessages(e){if(e===void 0||e===this.head?.current.id)return this._messages.value;let t=this.messages.get(e);if(!t)throw Error(`MessageRepository(getMessages): Head message not found. This is likely an internal bug in assistant-ui.`);let n=Array(t.level+1);for(let e=t;e;e=e.prev)n[e.level]=e.current;return n}addOrUpdateMessage(e,t){let n=this.messages.get(t.id),r=e?this.messages.get(e):null;if(r===void 0)throw Error(`MessageRepository(addOrUpdateMessage): Parent message not found. This is likely an internal bug in assistant-ui.`);if(n){this.performOp(r,n,`relink`),n.current=t,this._messages.dirty();return}let i={prev:r,current:t,next:null,children:[],level:r?r.level+1:0};this.messages.set(t.id,i),this.performOp(r,i,`link`),this.head===r&&(this.head=i),this._messages.dirty()}getMessage(e){let t=this.messages.get(e);if(!t)throw Error(`MessageRepository(updateMessage): Message not found. This is likely an internal bug in assistant-ui.`);return{parentId:t.prev?.current.id??null,message:t.current,index:t.level}}deleteMessage(e,t){let n=this.messages.get(e);if(!n)throw Error(`MessageRepository(deleteMessage): Message not found. This is likely an internal bug in assistant-ui.`);let r=t===void 0?n.prev:t===null?null:this.messages.get(t);if(r===void 0)throw Error(`MessageRepository(deleteMessage): Replacement not found. This is likely an internal bug in assistant-ui.`);for(let e=r;e;e=e.prev)if(e===n)throw Error(`MessageRepository(deleteMessage): Replacement is the deleted message or one of its descendants. This is likely an internal bug in assistant-ui.`);for(let e of n.children){let t=this.messages.get(e);if(!t)throw Error(`MessageRepository(deleteMessage): Child message not found. This is likely an internal bug in assistant-ui.`);this.performOp(r,t,`relink`)}this.performOp(null,n,`cut`),this.messages.delete(e),this.head===n&&(this.head=Ks(r??this.root)),this._messages.dirty()}hasChildren(e){return(this.messages.get(e)?.children.length??0)>0}getBranches(e){let t=this.messages.get(e);if(!t)throw Error(`MessageRepository(getBranches): Message not found. This is likely an internal bug in assistant-ui.`);let{children:n}=t.prev??this.root;return n}evictOffBranchOptimisticMessages(e,t){if(!e)return;let n=new Set;for(let e=t;e;e=e.prev)n.add(e.current.id);let r=[];for(let t=e;t&&!n.has(t.current.id);t=t.prev)t.current.metadata?.isOptimistic&&r.push(t.current.id);for(let e of r)this.messages.has(e)&&this.deleteMessage(e)}switchToBranch(e){let t=this.messages.get(e);if(!t)throw Error(`MessageRepository(switchToBranch): Branch not found. This is likely an internal bug in assistant-ui.`);let n=this.head;this.selectPathTo(t),this.head=Ks(t),this.evictOffBranchOptimisticMessages(n,this.head),this._messages.dirty()}resetHead(e){if(e===null){this.clear();return}let t=this.messages.get(e);if(!t)throw Error(`MessageRepository(resetHead): Branch not found. This is likely an internal bug in assistant-ui.`);let n=this.head;if(t.children.length>0){let e=[...t.children];for(;e.length>0;){let t=e.pop(),n=this.messages.get(t);if(n){for(let t of n.children)e.push(t);this.messages.delete(t)}}t.children=[],t.next=null}this.head=t,this.selectPathTo(t),this.evictOffBranchOptimisticMessages(n,this.head),this._messages.dirty()}clear(){this.messages.clear(),this.head=null,this.root={children:[],next:null},this._messages.dirty()}export(){let e=[],t=[...this.root.children].reverse();for(;t.length>0;){let n=this.messages.get(t.pop());if(!n)continue;for(let e=n.children.length-1;e>=0;e--)t.push(n.children[e]);if(n.current.metadata?.isOptimistic)continue;let r=n.prev;for(;r&&r.current.metadata?.isOptimistic;)r=r.prev;e.push({message:n.current,parentId:r?.current.id??null})}return{headId:this.canonicalHeadId,messages:e}}import({headId:e,messages:t}){let n=qs(t,e=>this.messages.has(e));for(let{message:e,parentId:t}of n)this.addOrUpdateMessage(t,e);this.resetHead(e??n.at(-1)?.message.id??null)}},q=Object.freeze([]);function Zs(e,t){if(t===`*`)return!0;let n=t.split(`,`).map(e=>e.trim().toLowerCase()),r=e.name.toLowerCase(),i=e.type.split(`;`,1)[0].trim().toLowerCase();for(let e of n){if(e.startsWith(`.`)&&r.endsWith(e)||e.includes(`/`)&&e===i)return!0;if(e.endsWith(`/*`)){let t=e.split(`/`)[0];if(i.startsWith(`${t}/`))return!0}}return!1}function Qs(e){let t=W();return e.type===`image`?{id:t,type:`image`,name:e.filename??`image`,content:[e],status:{type:`complete`}}:e.type===`file`?{id:t,type:`document`,name:e.filename??`document`,contentType:e.mimeType,content:[e],status:{type:`complete`}}:e.type===`audio`?{id:t,type:`audio`,name:`audio.${e.audio.format}`,contentType:`audio/${e.audio.format}`,content:[e],status:{type:`complete`}}:{id:t,type:`data`,name:e.name,content:[e],status:{type:`complete`}}}function $s(e){let t=[];for(let n of e)n.type!==`text`&&t.push(Qs(n));return t}var ec=e=>`content`in e&&!(`lastModified`in e),J=e=>e.status.type===`complete`,tc=class{operations=new Set;uploading=new Map;start(){let e={cancelled:!1,attachmentIds:new Set};return this.operations.add(e),e}accept(e,t){if(e.cancelled)return!1;e.attachmentIds.add(t.id);let n=this.uploading.get(t.id);return n?.operation!==e&&(n||t.status.type===`running`)&&this.uploading.set(t.id,{operation:e,waiters:n?.waiters??new Set}),t.status.type!==`running`&&this.settle(t.id,e),!0}finish(e){this.operations.delete(e);for(let t of e.attachmentIds)this.settle(t,e)}isCancelled(e){return e.cancelled}cancel(e){for(let t of[...this.operations])t.attachmentIds.has(e)&&(t.cancelled=!0,this.operations.delete(t));this.settle(e)}cancelAll(){for(let e of this.operations)e.cancelled=!0;this.operations.clear();for(let e of[...this.uploading.keys()])this.settle(e)}whenSendable(e){let t=this.uploading.get(e);if(t)return new Promise(e=>t.waiters.add(e))}settle(e,t){let n=this.uploading.get(e);if(n&&!(t&&n.operation!==t)){this.uploading.delete(e);for(let e of n.waiters)e()}}},nc=async(e,t)=>{if(Symbol.asyncIterator in e){for await(let n of e)if(!t(n))break}else t(await e)},rc=class{entries=new WeakMap;removed=new WeakSet;markRemoved(e){this.removed.add(e)}unmarkRemoved(e){this.removed.delete(e)}isRemoved(e){return this.removed.has(e)}async send(e,t,n){if(J(e))return e;let r=this.entries.get(e)??{};if(r.result)return r.result;if(!t)throw Error(`Attachments are not supported`);this.entries.set(e,r);let i=await t.send(e,n?{signal:n}:void 0);return r.result=i,i}transfer(e,t){let n=this.entries.get(e);return n&&this.entries.set(t,n),t}},ic=class extends ri{isEditing=!0;enrichWithComposerMetadata(e,t){return t?{...e,metadata:{...e.metadata,custom:{...e.metadata?.custom,...t}}}:e}get attachmentAccept(){return this.getAttachmentAdapter()?.accept??`*`}_attachments=[];get attachments(){return this._attachments}setAttachments(e){this._attachments=e,this._notifySubscribers()}get isEmpty(){return!this.text.trim()&&!this.attachments.length}_text=``;get text(){return this._text}_role=`user`;get role(){return this._role}_runConfig={};get runConfig(){return this._runConfig}_quote=void 0;get quote(){return this._quote}setQuote(e){this._quote!==e&&(this._quote=e,this._notifySubscribers())}setText(e){this._text!==e&&(this._text=e,this._rebaseDictation(e),this._notifySubscribers())}_rebaseDictation(e){if(!this._dictation)return;this._dictationBaseText=e,this._currentInterimText=``;let{status:t,inputDisabled:n}=this._dictation;this._dictation=n?{status:t,inputDisabled:n}:{status:t}}setRole(e){this._role!==e&&(this._role=e,this._notifySubscribers())}setRunConfig(e){this._runConfig!==e&&(this._runConfig=e,this._notifySubscribers())}_submission;_submissionSend;_inTransit=[];_inTransitSubmissions=[];_sendGeneration=0;_attachmentAddOperations=new tc;_attachmentSends=new rc;get submission(){return this._submission}get inTransit(){return this._inTransitSubmissions}get isSubmitting(){return this._submission!==void 0}get detachesDraftOnSend(){return!0}threadMessageIds(e){}settleInTransit(){if(this._inTransit.length===0)return;let e=new Set,t=this._inTransit.filter(({submission:t,known:n})=>{let r=this.threadMessageIds(t.role)?.find(t=>!n.has(t)&&!e.has(t));return r===void 0||(e.add(r),!1)});t.length!==this._inTransit.length&&(this._setInTransit(t.map(t=>({...t,known:new Set([...t.known,...e])}))),this._notifySubscribers())}_setInTransit(e){this._inTransit=e,this._inTransitSubmissions=e.map(e=>e.submission)}_leaveTransit(e){let t=this._inTransit.filter(t=>t.submission!==e);return t.length!==this._inTransit.length&&(this._setInTransit(t),!0)}_cancelAttachmentAdd(e){this._attachmentAddOperations.cancel(e)}_cancelAllAttachmentAdds(){this._attachmentAddOperations.cancelAll()}_emptyTextAndAttachments(){this._attachments=[],this._text=``,this._rebaseDictation(``),this._notifySubscribers()}async _onClearAttachments(){let e=this.getAttachmentAdapter();if(e){let t=this._attachments.filter(e=>!J(e));await Promise.all(t.map(async t=>e.remove(t)))}}async reset(){this._cancelAllAttachmentAdds(),this._sendGeneration++;let e=this._discardSubmission();if(this._attachments.length===0&&this._text===``&&this._role===`user`&&Object.keys(this._runConfig).length===0&&this._quote===void 0){await e;return}this._role=`user`,this._runConfig={},this._quote=void 0;let t=this._onClearAttachments();this._emptyTextAndAttachments(),await Promise.all([t,e])}async clearAttachments(){if(this._cancelAllAttachmentAdds(),this.isSubmitting)for(let e of this._attachments)this._attachmentSends.markRemoved(e);let e=this._onClearAttachments();this.setAttachments([]),await e}async send(e){if(!this.canSend||this.isSubmitting)return;if(this._dictationSession){let e=this._activeDictationSessionId;try{this._dictationSession.cancel()}catch(e){console.error(`[assistant-ui] Dictation session cancel threw`,e)}finally{this._cleanupDictation({sessionId:e})}}let t=this.attachments.filter(e=>!this._attachmentSends.isRemoved(e));if(!this.text.trim()&&t.length===0)return;let n={id:W(),role:this.role,text:this.text,quote:this._quote,attachments:t},r={options:e,runConfig:this.runConfig},i=t.filter(J),a=i.length===t.length;if(a||(this._submission=n,this._submissionSend={...r,controller:new AbortController}),this.detachesDraftOnSend){let e=new Set(t);this._attachments=this._attachments.filter(t=>!e.has(t)),this._text=``,this._rebaseDictation(``),this._quote=void 0}let o=++this._sendGeneration;if(this._notifySubscribers(),a){this._dispatch(o,n,i,r,!1);return}await this._prepareSubmission(o)}async _prepareSubmission(e){let t=this.getAttachmentAdapter(),n=(this._submission?.attachments??[]).flatMap(e=>{let t=this._attachmentAddOperations.whenSendable(e.id);return t?[t]:[]});if(n.length>0){if(await Promise.all(n),e!==this._sendGeneration)return;this._refreshSubmissionAttachments()}let r=this._submission,i=this._submissionSend;if(!r||!i)return;let a=r.attachments.filter(e=>!this._attachmentSends.isRemoved(e));for(let e of a)this._cancelAttachmentAdd(e.id);let o=await Promise.allSettled(a.map(e=>this._attachmentSends.send(e,t,i.controller.signal)));if(e!==this._sendGeneration)return;let s=o.find(e=>e.status===`rejected`);if(s){this._returnSubmissionToDraft(a,o,s.reason);return}let c=o.flatMap((e,t)=>this._attachmentSends.isRemoved(a[t])||e.status===`rejected`?[]:[e.value]);this._dispatch(e,r,c,i,!0)}_dispatch(e,t,n,r,i){let a={createdAt:new Date,role:t.role,content:t.text?[{type:`text`,text:t.text}]:[],attachments:n,runConfig:r.runConfig,metadata:{custom:{...t.quote?{quote:t.quote}:{}}}},o={...t,attachments:n},s=this.queue.length;if(i){if(this._submission=void 0,this._submissionSend=void 0,!this.detachesDraftOnSend){let e=new Map(n.map(e=>[e.id,e]));this._attachments=this._attachments.map(t=>e.get(t.id)??t)}let e=this.threadMessageIds(t.role);e&&this._setInTransit([...this._inTransit,{submission:o,known:new Set(e)}])}let c;try{c=this.handleSend(a,r.options)}catch(t){console.error(`[assistant-ui] Failed to send the message`,t),this._leaveTransit(o),e===this._sendGeneration?this._returnToDraft(o):this._notifySubscribers();return}c&&c.catch(t=>{let n=this._leaveTransit(o);e===this._sendGeneration&&Yo(t)?this._returnToDraft(o):n&&this._notifySubscribers()}),this._notifyEventSubscribers(`send`,{chars:t.text.length,attachments:n.length}),i&&(this.queue.length>s&&this._leaveTransit(o),this._notifySubscribers(),this.settleInTransit())}_refreshSubmissionAttachments(){let e=this._submission;if(!e)return;let t=e.attachments.filter(e=>!this._attachmentSends.isRemoved(e));t.length!==e.attachments.length&&(this._submission={...e,attachments:t})}_returnSubmissionToDraft(e,t,n){let r=this._submission;if(!r)return;let i=new Map;t.forEach((t,n)=>{t.status===`rejected`&&i.set(e[n].id,t.reason)});let a=r.attachments.map(e=>{if(!i.has(e.id)||J(e))return e;let t=i.get(e.id);return this._attachmentSends.transfer(e,{...e,status:{type:`incomplete`,reason:`error`,message:t instanceof Error?t.message:String(t)}})});this._endSubmission(),this._returnToDraft({...r,attachments:a}),console.error(`[assistant-ui] Failed to send attachments`,n)}_endSubmission(){this._sendGeneration++,this._submission=void 0,this._submissionSend=void 0}__internal_dispose(){this._cancelAllAttachmentAdds(),this._submission&&(this._submissionSend?.controller.abort(),this._endSubmission(),this._notifySubscribers())}cancelSubmission(){let e=this._submission;e&&(this._submissionSend?.controller.abort(),this._endSubmission(),this._returnToDraft(e))}_returnToDraft(e){if(this.detachesDraftOnSend){let t=e.attachments.filter(e=>!this._attachmentSends.isRemoved(e));this._attachments=[...t,...this._attachments];let n=[e.text,this._text].filter(Boolean).join(`
6
- `);this._text=n,this._rebaseDictation(n),this._quote=this._quote??e.quote}else{let t=new Map(e.attachments.map(e=>[e.id,e]));this._attachments=this._attachments.map(e=>t.get(e.id)??e)}this._notifySubscribers()}async _discardSubmission(){let e=this._submission;if(!e)return;this._submissionSend?.controller.abort(),this._endSubmission(),this._notifySubscribers();let t=this.getAttachmentAdapter();if(!t)return;let n=new Set(this._attachments.map(e=>e.id));await Promise.all(e.attachments.filter(e=>!J(e)&&!n.has(e.id)).map(async e=>t.remove(e)))}restoreDraft(e){return this._text.trim()||this._quote!==void 0||this._attachments.length>0?!1:(this._text=e.text,this._rebaseDictation(e.text),this._quote=e.quote,this._attachments=e.attachments??[],this._notifySubscribers(),!0)}retractDraft(e){let t=e.attachments===void 0?this._attachments.length===0:this._attachments===e.attachments;this._text!==e.text||this._quote!==e.quote||!t||(this._text=``,this._rebaseDictation(``),this._quote=void 0,this._attachments=[],this._notifySubscribers())}cancel(){this.isSubmitting&&!this.detachesDraftOnSend&&(this._submissionSend?.controller.abort(),this._endSubmission(),this._notifySubscribers()),this.handleCancel()}get queue(){return q}moveQueueItem(e,t){}removeQueueItem(e){}async addAttachment(e){if(ec(e)){let t=this.getAttachmentAdapter();if(t&&!Zs({name:e.name,type:e.contentType??``},t.accept)){let n=`File type ${e.contentType||`unknown`} is not accepted. Accepted types: ${t.accept}`,r=Error(n);throw this._safeEmitAttachmentAddError(`not-accepted`,n,void 0,r,e.contentType),r}let n={id:e.id??W(),type:e.type??`document`,name:e.name,contentType:e.contentType,content:e.content,status:{type:`complete`}};this._attachments=[...this._attachments,n],this._notifySubscribers(),this._notifyEventSubscribers(`attachmentAdd`,{...n.contentType?{contentType:n.contentType}:void 0});return}let t=this.getAttachmentAdapter();if(!t){let t=`Attachments are not supported`,n=Error(t);throw this._safeEmitAttachmentAddError(`no-adapter`,t,void 0,n,e.type),n}if(!Zs({name:e.name,type:e.type},t.accept)){let n=`File type ${e.type||`unknown`} is not accepted. Accepted types: ${t.accept}`,r=Error(n);throw this._safeEmitAttachmentAddError(`not-accepted`,n,void 0,r,e.type),r}let n=this._attachmentAddOperations.start(),r=e=>{if(!this._attachmentAddOperations.accept(n,e))return!1;let t=this._submission,r=t?.attachments.some(t=>t.id===e.id)??!1;t&&r&&(this._submission={...t,attachments:t.attachments.map(t=>t.id===e.id?this._attachmentSends.transfer(t,e):t)});let i=this._attachments.findIndex(t=>t.id===e.id);return i===-1?r||(this._attachments=[...this._attachments,e]):this._attachments=[...this._attachments.slice(0,i),e,...this._attachments.slice(i+1)],this._notifySubscribers(),!0},i;try{await nc(t.add({file:e}),e=>(i=e,r(e)))}catch(t){if(this._attachmentAddOperations.isCancelled(n))return;throw i&&r({...i,status:{type:`incomplete`,reason:`error`,message:t instanceof Error?t.message:String(t)}}),this._safeEmitAttachmentAddError(`adapter-error`,t instanceof Error?t.message:String(t),i?.id,t instanceof Error?t:void 0,i?.contentType||e.type),t}finally{this._attachmentAddOperations.finish(n)}this._attachmentAddOperations.isCancelled(n)||(i?.status.type===`incomplete`&&i.status.reason===`error`?this._safeEmitAttachmentAddError(`adapter-error`,i.status.message??`Attachment upload did not complete successfully.`,i.id,void 0,i.contentType||e.type):this._notifyEventSubscribers(`attachmentAdd`,{...i?.contentType?{contentType:i.contentType}:e.type?{contentType:e.type}:void 0}))}_safeEmitAttachmentAddError(e,t,n,r,i){try{this._notifyEventSubscribers(`attachmentAddError`,{reason:e,message:t,...n!==void 0&&{attachmentId:n},...r!==void 0&&{error:r},...i?{contentType:i}:void 0})}catch(e){console.error(`[assistant-ui] attachmentAddError subscriber threw:`,e)}}async removeAttachment(e){let t=this._attachments.findIndex(t=>t.id===e);if(t===-1){await this._removeSubmittedAttachment(e);return}let n=this._attachments[t];if(this._cancelAttachmentAdd(e),this._attachmentSends.markRemoved(n),!J(n)){let t=this.getAttachmentAdapter();if(!t)throw Error(`Attachments are not supported`);try{await t.remove(n)}catch(t){let n=t instanceof Error?t.message:String(t);throw this._attachments=this._attachments.map(t=>t.id===e&&!J(t)?this._attachmentSends.transfer(t,{...t,status:{type:`incomplete`,reason:`error`,message:n}}):t),this._notifySubscribers(),t}}this._attachments=this._attachments.filter(t=>t.id!==e),this._notifySubscribers()}async _removeSubmittedAttachment(e){let t=this._submission?.attachments.find(t=>t.id===e);if(!t)throw Error(`Attachment not found`);if(this._cancelAttachmentAdd(e),this._attachmentSends.markRemoved(t),!J(t)){let n=this.getAttachmentAdapter();if(!n)throw Error(`Attachments are not supported`);try{await n.remove(t)}catch(t){throw this._failSubmittedRemoval(e,t),t}}let n=this._submission;n&&(this._submission={...n,attachments:n.attachments.filter(t=>t.id!==e)},this._notifySubscribers())}_failSubmittedRemoval(e,t){let n=this._submission;if(!n)return;let r=t instanceof Error?t.message:String(t);this._submission={...n,attachments:n.attachments.map(t=>{if(t.id!==e||J(t))return t;let n=this._attachmentSends.transfer(t,{...t,status:{type:`incomplete`,reason:`error`,message:r}});return this._attachmentSends.markRemoved(n),n})},this._notifySubscribers()}_dictation;_dictationSession;_dictationUnsubscribes=[];_dictationBaseText=``;_currentInterimText=``;_dictationSessionIdCounter=0;_activeDictationSessionId;_isCleaningDictation=!1;get dictation(){return this._dictation}_isActiveSession(e,t){return this._activeDictationSessionId===e&&this._dictationSession===t}startDictation(){let e=this.getDictationAdapter();if(!e)throw Error(`Dictation adapter not configured`);let t=this._dictationSession!==void 0;if(this._dictationSession){let e=this._dictationSession;this._cleanupDictation({notify:!1}),this._stopDictationSession(e)}let n=e.disableInputDuringDictation??!1;this._dictationBaseText=this._text,this._currentInterimText=``;let r;try{r=e.listen()}catch(e){if(t)try{this._notifySubscribers()}catch(e){console.error(`[assistant-ui] Dictation replacement rollback notification threw`,e)}throw e}this._dictationSession=r;let i=++this._dictationSessionIdCounter;this._activeDictationSessionId=i,this._dictation={status:r.status,inputDisabled:n};try{this._notifySubscribers()}catch(e){console.error(`[assistant-ui] Dictation start notification threw`,e)}if(!this._isActiveSession(i,r))return;let a=[],o=()=>{for(let e of a.splice(0))try{e()}catch(e){console.error(`[assistant-ui] Dictation cleanup threw`,e)}},s=e=>(a.push(e),this._isActiveSession(i,r)?!0:(o(),!1));try{if(!s(r.onSpeech(e=>{if(!this._isActiveSession(i,r))return;let t=e.isFinal!==!1,n=this._dictationBaseText&&!this._dictationBaseText.endsWith(` `)&&e.transcript?` `:``;if(t){if(this._dictationBaseText=this._dictationBaseText+n+e.transcript,this._currentInterimText=``,this._text=this._dictationBaseText,this._dictation){let{transcript:e,...t}=this._dictation;this._dictation=t}this._notifySubscribers()}else this._currentInterimText=n+e.transcript,this._text=this._dictationBaseText+this._currentInterimText,this._dictation&&={...this._dictation,transcript:e.transcript},this._notifySubscribers()}))||!s(r.onSpeechStart(()=>{this._isActiveSession(i,r)&&(this._dictation={status:{type:`running`},inputDisabled:n,...this._dictation?.transcript&&{transcript:this._dictation.transcript}},this._notifySubscribers())}))||!s(r.onSpeechEnd(()=>{this._cleanupDictation({sessionId:i})})))return;let e=setInterval(()=>{this._isActiveSession(i,r)&&r.status.type===`ended`&&this._cleanupDictation({sessionId:i})},100);if(!s(()=>clearInterval(e)))return;this._dictationUnsubscribes.push(...a.splice(0))}catch(e){if(o(),this._isActiveSession(i,r))try{r.cancel()}catch(e){console.error(`[assistant-ui] Dictation session cancel threw`,e)}finally{this._cleanupDictation({sessionId:i})}throw e}}stopDictation(){if(!this._dictationSession)return;let e=this._dictationSession,t=this._activeDictationSessionId;this._stopDictationSession(e,()=>this._cleanupDictation({sessionId:t}))}_stopDictationSession(e,t=()=>{}){let n;try{n=e.stop()}catch(e){console.error(`[assistant-ui] Dictation session stop threw`,e),t();return}n.then(t,e=>{console.error(`[assistant-ui] Dictation session stop rejected`,e),t()})}_cleanupDictation(e){if(e?.sessionId!==void 0&&e.sessionId!==this._activeDictationSessionId||this._isCleaningDictation)return;this._isCleaningDictation=!0;let t=e=>{try{e()}catch(e){console.error(`[assistant-ui] Dictation cleanup threw`,e)}};try{let n=this._dictationUnsubscribes;this._dictationUnsubscribes=[],this._dictationSession=void 0,this._activeDictationSessionId=void 0,this._dictation=void 0,this._dictationBaseText=``,this._currentInterimText=``;for(let e of n)t(e);e?.notify!==!1&&t(()=>this._notifySubscribers())}finally{this._isCleaningDictation=!1}}_eventSubscribers=new Map;_notifyEventSubscribers(e,t){let n=this._eventSubscribers.get(e);n&&z(n,t,`Composer runtime "${e}"`)}unstable_on(e,t){let n=t,r=this._eventSubscribers.get(e);return r||(r=new Set,this._eventSubscribers.set(e,r)),r.add(n),()=>{this._eventSubscribers.get(e)?.delete(n)}}},ac=e=>e.capabilities?.cancel?Cs(e):!1,oc=class extends ic{get canCancel(){return this.isSubmitting||ac(this.runtime)}get canSend(){if(this.isEmpty||this.runtime.isSendDisabled||this.isSubmitting)return!1;let e=this.runtime.voice;return!e||e.canSendText&&this.role===`user`&&this.attachments.length===0}cancel(){if(!this.isSubmitting){super.cancel();return}this.cancelSubmission(),ac(this.runtime)&&super.cancel()}threadMessageIds(e){return this.runtime.messages.filter(t=>t.role===e).map(e=>e.id)}_queueCache;get queue(){let e=this.runtime.getSteerQueueItems?.()??q,t=this.runtime.getQueueItems?.()??q,n=this._queueCache;if(n&&n.steer===e&&n.queue===t)return n.flat;let r=e.length===0?t:t.length===0?e:[...e,...t];return this._queueCache={steer:e,queue:t,flat:r},r}moveQueueItem(e,t){this.runtime.moveQueueItem?.(e,t)}removeQueueItem(e){this.runtime.removeQueueItem?.(e)}getAttachmentAdapter(){return this.runtime.adapters?.attachments}getDictationAdapter(){return this.runtime.adapters?.dictation}runtime;constructor(e){super(),this.runtime=e,this.connect()}connect(){let e=!1,t=this.runtime.isSendDisabled,n=this.runtime.voice?.canSendText,r=this.queue;return this.runtime.subscribe(()=>{this.settleInTransit();let i=!1,a=this.canCancel;e!==a&&(e=a,i=!0),t!==this.runtime.isSendDisabled&&(t=this.runtime.isSendDisabled,i=!0);let o=this.runtime.voice?.canSendText;n!==o&&(n=o,i=!0),r!==this.queue&&(r=this.queue,i=!0),i&&this._notifySubscribers()})}async handleSend(e,t){return this.runtime.append({...e,parentId:this.runtime.messages.at(-1)?.id??null,sourceId:null,startRun:t?.startRun,steer:t?.steer})}async handleCancel(){this.runtime.cancelRun()}},sc=class extends ic{get canCancel(){return!0}get detachesDraftOnSend(){return!1}get canSend(){return!this.isEmpty&&!this.runtime.voice&&!this.isSubmitting}getAttachmentAdapter(){return this.runtime.adapters?.attachments}getDictationAdapter(){return this.runtime.adapters?.dictation}_nonTextPassthrough;_parentId;_sourceId;runtime;endEditCallback;_ended=!1;constructor(e,t,{parentId:n,message:r}){super(),this.runtime=e;let i=e.voice!==void 0,a=e.subscribe(()=>{let t=e.voice!==void 0;t!==i&&(i=t,this._notifySubscribers())});this.endEditCallback=()=>{a(),t()},this._parentId=n,this._sourceId=r.id,this.setText(_i(r)),this.setRole(r.role);let o;r.role===`user`?(o=[...r.attachments??[],...$s(r.content)],this._nonTextPassthrough=[]):(o=r.attachments??[],this._nonTextPassthrough=r.content.filter(e=>e.type!==`text`)),this.setAttachments(o),this.setRunConfig({...e.composer.runConfig})}get parentId(){return this._parentId}get sourceId(){return this._sourceId}async handleSend(e,t){let n=this._nonTextPassthrough.length>0?[...e.content,...this._nonTextPassthrough]:e.content,r=this.runtime.append({...e,content:n,parentId:this._parentId,sourceId:this._sourceId,startRun:t?.startRun});return this.handleCancel(),r}handleCancel(){this._ended||(this._ended=!0,this.reset().catch(e=>{console.error(`[assistant-ui] Failed to clear cancelled edit`,e)}),this.endEditCallback(),this._notifySubscribers())}},cc=class extends ri{_isInitialized=!1;repository=new Xs;_voiceMessages=[];_voiceGeneration=0;_cachedMergedMessages=null;_cachedVoiceGeneration=-1;_cachedMergedBase=null;_markVoiceMessagesDirty(){this._voiceGeneration++,this._cachedMergedMessages=null}_getBaseMessages(){return this.repository.getMessages()}_commitVoiceMessage(e){}_onMessageMetadataChanged(e,t){}_dropVoiceMessage(e,t){let n=this._voiceMessages.findIndex(t=>t.id===e);n!==-1&&(this._voiceMessages.splice(n,1),this._markVoiceMessagesDirty(),t&&this._notifySubscribers())}get messages(){if(this._voiceMessages.length===0)return this._getBaseMessages();let e=this._getBaseMessages();if(this._cachedVoiceGeneration!==this._voiceGeneration||this._cachedMergedBase!==e){let t=new Set(e.map(e=>e.id));this._cachedMergedMessages=[...e,...this._voiceMessages.filter(e=>!t.has(e.id))],this._cachedVoiceGeneration=this._voiceGeneration,this._cachedMergedBase=e}return this._cachedMergedMessages}get state(){let e;for(let t of this.messages)t.role===`assistant`&&(e=t);return e?.metadata.unstable_state??null}composer=new oc(this);_contextProvider;constructor(e){super(),this._contextProvider=e,Ms(this).addEventListener(`abort`,()=>{this.composer.__internal_dispose();for(let e of this._editComposers.values())e.__internal_dispose()})}getModelContext(){return this._contextProvider.getModelContext()}enrichAppendMetadata(e,t=e.parentId){if(e.role!==`user`)return e;let n=this.messages,r=t===null?-1:n.findIndex(e=>e.id===t),i=jo(this.getModelContext().unstable_composerMetadata,n.slice(0,r+1));return i?{...e,metadata:{...e.metadata,custom:{...e.metadata?.custom,...i}}}:e}_editComposers=new Map;getEditComposer(e){return this._editComposers.get(e)}_isVoiceMessage(e){return e!==null&&this._voiceMessages.some(t=>t.id===e)}_resolveAppendParent(e){return this._isVoiceMessage(e)?this._getBaseMessages().at(-1)?.id??null:e}beginEdit(e){if(this.voice)throw Error(`Cannot edit a message while a voice session is connected`);if(this._isVoiceMessage(e))throw Error(`Voice transcript messages cannot be edited`);if(this._editComposers.has(e))throw Error(`Edit already in progress`);this._editComposers.set(e,new sc(this,()=>this._editComposers.delete(e),this.repository.getMessage(e))),this._notifySubscribers()}getMessageById(e){try{return this.repository.getMessage(e)}catch{let t=this.repository.getMessages(),n=this._voiceMessages.findIndex(t=>t.id===e);return n===-1?void 0:{parentId:n>0?this._voiceMessages[n-1].id:t.at(-1)?.id??null,message:this._voiceMessages[n],index:t.length+n}}}getBranches(e){return this._voiceMessages.some(t=>t.id===e)?[]:this.repository.getBranches(e)}switchToBranch(e){this.repository.switchToBranch(e),this._notifySubscribers()}_notifyEventSubscribers(e,t){let n=this._eventSubscribers.get(e);n&&z(n,t,`Thread runtime "${e}"`)}_notifyToolApprovalAnswered(e,t,n,r){this._notifyEventSubscribers(`toolApprovalAnswered`,{messageId:e,toolCallId:t,toolName:n,approved:r})}submitFeedback({messageId:e,type:t,comment:n}){let r=this.adapters?.feedback,i=this.getMessageById(e);if(!i)throw Error(`Message not found: ${e}`);let{message:a,parentId:o}=i,s=n?.trim(),c={type:t,...s?{comment:s}:void 0};if(r?.submit({message:a,...c}),a.role===`assistant`){let t={...a,metadata:{...a.metadata,submittedFeedback:c}},n=this._voiceMessages.findIndex(t=>t.id===e);n===-1?(this.repository.addOrUpdateMessage(o,t),this._onMessageMetadataChanged(a,t)):(this._voiceMessages[n]=t,this._currentAssistantMsg===a&&(this._currentAssistantMsg=t),this._markVoiceMessagesDirty())}this._notifySubscribers()}_stopSpeaking;speech;speak(e){let t=this.adapters?.speech;if(!t)throw Error(`Speech adapter not configured`);let n=this.getMessageById(e);if(!n)throw Error(`Message not found: ${e}`);let{message:r}=n,i=this._stopSpeaking,a;try{i?.(),a=t.speak(_i(r))}catch(e){if(i&&!this._stopSpeaking)try{this._notifySubscribers()}catch(e){console.error(`[assistant-ui] Speech rollback notification threw`,e)}throw e}let o,s=()=>{this._stopSpeaking=void 0,this.speech=void 0;let e=o;o=void 0,e?.()},c=()=>{if(this._stopSpeaking===c)try{s()}finally{a.cancel()}},l=()=>{this._stopSpeaking===c&&(a.status.type===`ended`?V([s,()=>this._notifySubscribers()]):(this.speech={messageId:e,status:a.status},this._notifySubscribers()))};this._stopSpeaking=c;try{if(o=a.subscribe(l),this._stopSpeaking!==c){o();return}l()}catch(e){if(this._stopSpeaking===c)try{V([c,()=>this._notifySubscribers()])}catch(e){console.error(`[assistant-ui] Speech rollback cleanup threw`,e)}throw e}}stopSpeaking(){if(!this._stopSpeaking)throw Error(`No message is being spoken`);V([this._stopSpeaking,()=>this._notifySubscribers()])}_voiceSession;_voiceUnsubs=[];voice;_voiceVolume=0;_voiceVolumeSubscribers=new Set;getVoiceVolume=()=>this._voiceVolume;subscribeVoiceVolume=e=>(this._voiceVolumeSubscribers.add(e),()=>this._voiceVolumeSubscribers.delete(e));_onVoiceConnected(){}_onVoiceDisconnected(){}_toVoiceSessionState(e,t,n){return{status:t,isMuted:e.isMuted,mode:n,canSendText:t.type===`running`&&e.sendText!==void 0}}_isRunActive(){if(this.isRunning)return!0;let e=this._getBaseMessages().at(-1);return e?.role===`assistant`&&(e.status.type===`running`||e.status.type===`requires-action`)}_getVoiceCommitBarrier(){if(!this.isLoading)return;let e=ks(this);return(async()=>{for(;this.isLoading&&!e.aborted;)await new Promise(t=>{let n=()=>{r(),e.removeEventListener(`abort`,n),t()},r=this.subscribe(n);e.addEventListener(`abort`,n)})})()}connectVoice(){let e=this.adapters?.voice;if(!e)throw Error(`Voice adapter not configured`);if(this._isRunActive())throw Error(`Cannot start a voice session while a run is in progress or paused on a pending tool action`);let t=this._voiceSession!==void 0;try{this._disconnectVoice(!1)}catch(e){console.error(`[assistant-ui] Voice cleanup threw before reconnect`,e)}let n;try{n=e.connect({})}catch(e){throw t&&this._voiceSession===void 0&&this._onVoiceDisconnected(),e}this._voiceSession=n;let r=[];this._voiceUnsubs=r;let i=()=>{if(this._voiceSession===n&&this._voiceUnsubs===r)return!1;try{V(r.splice(0))}catch(e){console.error(`[assistant-ui] Detached voice setup cleanup threw`,e)}return!0};try{let e=`listening`;if(this.voice=this._toVoiceSessionState(n,n.status,e),this._voiceVolume=0,this._notifySubscribers(),i()||(r.push(n.onStatusChange(t=>{if(this._voiceSession===n){if(t.type===`ended`){this._voiceSession=void 0,this.voice=void 0;try{this._finishVoiceAssistantMessage(!1),this._onVoiceDisconnected(),this._notifySubscribers()}finally{i()}}else this.voice=this._toVoiceSessionState(n,t,e),this._notifySubscribers()}})),i())||(r.push(n.onModeChange(t=>{this._voiceSession===n&&(e=t,this.voice&&(this.voice={...this.voice,mode:t},this._notifySubscribers()))})),i())||(r.push(n.onVolumeChange(e=>{this._voiceSession===n&&(this._voiceVolume=e,z(this._voiceVolumeSubscribers,void 0,`Voice volume`))})),i()))return;r.push(n.onTranscript(e=>{this._voiceSession===n&&this._handleVoiceTranscript(e)})),i()||this._onVoiceConnected()}catch(e){if(this._voiceSession===n&&this._voiceUnsubs===r){try{this._disconnectVoice(!1)}catch(e){console.error(`[assistant-ui] Voice rollback cleanup threw`,e)}t&&this._voiceSession===void 0&&this._onVoiceDisconnected()}else i();throw e}}_currentAssistantMsg=null;_observeVoiceCommit(e){new Promise(t=>t(e())).catch(e=>{console.error(`[assistant-ui] Voice message commit failed`,e)})}_handleVoiceTranscript(e){if(this.ensureInitialized(),e.role===`user`)this._finishVoiceAssistantMessage(),this._currentAssistantMsg=null,e.isFinal&&this._observeVoiceCommit(()=>this._commitVoiceUserMessage({id:W(),role:`user`,content:[{type:`text`,text:e.text}],metadata:{modality:`voice`,custom:{}},createdAt:new Date,attachments:[]}));else{let t=e.isFinal?{type:`complete`,reason:`stop`}:{type:`running`};if(!this._currentAssistantMsg)this._currentAssistantMsg={id:W(),role:`assistant`,content:[{type:`text`,text:e.text}],metadata:{unstable_state:this.state,unstable_annotations:[],unstable_data:[],steps:[],modality:`voice`,custom:{}},status:t,createdAt:new Date},this._voiceMessages.push(this._currentAssistantMsg);else{let n=this._voiceMessages.indexOf(this._currentAssistantMsg);if(n===-1)return;let r={...this._currentAssistantMsg,content:[{type:`text`,text:e.text}],status:t};this._voiceMessages[n]=r,this._currentAssistantMsg=r}if(e.isFinal){let e=this._currentAssistantMsg;this._observeVoiceCommit(()=>this._commitVoiceMessage(e)),this._currentAssistantMsg=null}this._markVoiceMessagesDirty(),this._notifySubscribers()}}_commitVoiceUserMessage(e){this._voiceMessages.push(e);try{return this._commitVoiceMessage(e)}finally{this._markVoiceMessagesDirty(),this._notifySubscribers()}}async _appendToVoiceSession(e){let t=this._voiceSession;if(!this.voice?.canSendText||!t?.sendText)throw Error(`Cannot send a text message while a voice session is connected`);let n=e.content.filter(e=>e.type===`text`);if(e.role!==`user`||e.sourceId!=null||e.parentId!==this._resolveAppendParent(this.messages.at(-1)?.id??null)||e.attachments?.length||n.length!==e.content.length||!n.some(e=>e.text.trim()))throw Error(`Only a plain text user message can be sent while a voice session is connected`);let r=this.enrichAppendMetadata(e);this.ensureInitialized();let i=ks(this);try{await t.sendText(_i(e))}catch(e){if(i.aborted)return;let t=new Jo;throw t.cause=e,t}if(!i.aborted){if(this._voiceSession!==t)throw new Jo(`The voice session ended before the typed message was recorded`);this._finishVoiceAssistantMessage(!1),this._currentAssistantMsg=null,await this._commitVoiceUserMessage({id:W(),role:`user`,content:n,metadata:{custom:{...r.metadata?.custom}},createdAt:e.createdAt,attachments:[]})}}_finishVoiceAssistantMessage(e=!0){let t=this._voiceMessages.at(-1);if(t?.role===`assistant`&&t.status.type===`running`){let n=this._voiceMessages.length-1;this._voiceMessages[n]={...t,status:{type:`complete`,reason:`stop`}},this._observeVoiceCommit(()=>this._commitVoiceMessage(this._voiceMessages[n])),this._currentAssistantMsg=null,this._markVoiceMessagesDirty(),e&&this._notifySubscribers()}}disconnectVoice(){this._disconnectVoice(!0)}_disconnectVoice(e){this._finishVoiceAssistantMessage(!1),this._currentAssistantMsg=null;let t=this._voiceUnsubs.splice(0);this._voiceUnsubs=[];let n=this._voiceSession;this._voiceSession=void 0,this.voice=void 0,this._voiceVolume=0;let r=this.speech&&this._isVoiceMessage(this.speech.messageId)?this._stopSpeaking:void 0;this._voiceMessages=[],this._markVoiceMessagesDirty();try{V([...t,...r?[r]:[],...n?[()=>n.disconnect()]:[],()=>z(this._voiceVolumeSubscribers,void 0,`Voice volume`),()=>this._notifySubscribers()])}finally{e&&n&&this._voiceSession===void 0&&this._onVoiceDisconnected()}}muteVoice(){if(!this._voiceSession)throw Error(`No active voice session`);this._voiceSession.mute(),this.voice={...this.voice,isMuted:!0},this._notifySubscribers()}unmuteVoice(){if(!this._voiceSession)throw Error(`No active voice session`);this._voiceSession.unmute(),this.voice={...this.voice,isMuted:!1},this._notifySubscribers()}ensureInitialized(){this._isInitialized||(this._isInitialized=!0,this._notifyEventSubscribers(`initialize`,{}))}export(){return this.repository.export()}import(e){this.ensureInitialized(),this.repository.clear(),this.repository.import(e),this._notifySubscribers()}reset(e){this.import(Gs.fromArray(e??[]))}_eventSubscribers=new Map;unstable_on(e,t){let n=t;if(e===`modelContextUpdate`)return this._contextProvider.subscribe?.(()=>z([n],{},`Thread runtime "${e}"`))??(()=>{});let r=this._eventSubscribers.get(e);return r||(r=new Set,this._eventSubscribers.set(e,r)),r.add(n),e===`initialize`&&this._isInitialized&&queueMicrotask(()=>{r.has(n)&&z([n],{},`Thread runtime "${e}"`)}),()=>{this._eventSubscribers.get(e)?.delete(n)}}},lc=lt(!1),uc=e=>he(lc,!0,e),dc=e=>e.status?.type!==`running`,fc=async(e,t)=>{let n=fo.fromAssistantStream(e);for await(let e of n){let n=e.parts.filter(e=>e.type===`text`)[0]?.text;n?.trim()&&await t(n)}},pc=(e,t)=>{let n=()=>void t.generateTitle({automatic:!0}).catch(e=>{hi(e)||console.error(`[assistant-ui] Thread title generation failed`,e)}),r=()=>e.getState().messages.some(dc);if(r())return n(),()=>{};let i=e.subscribe(()=>{r()&&(i(),n())});return i},mc=({threadId:e,generation:t,runtimeHook:n,publish:r,itemRuntime:i})=>{let a=uc(n),o=a?.thread?.__internal_threadBinding,s=Xe(()=>{o&&r(e,o.getState(),t)},[e,t,o,r]),c=j(!1);c.current||s(),N(()=>{if(o)return c.current=!0,s(),o.outerSubscribe(s)},[o,s]);let l=j(void 0),u=j(!1),d=j(i.getState().status===`new`),f=j(void 0),p=j(!1),m=Qe(()=>{if(u.current||i.getState().status!==`new`&&!d.current)return;u.current=!0,d.current=!1;let e=i.initialize();l.current=e,e.then(()=>{p.current&&(f.current?.(),f.current=pc(a.thread,i))},()=>{l.current===e&&(l.current=void 0,u.current=!1)})}),h=Qe(()=>(m(),l.current));return N(()=>{if(!o)return;let e=o.getState(),t=e.__internal_setGetInitializePromise;typeof t==`function`&&t.call(e,h)},[o]),N(()=>{if(!a?.threads?.main)return;u.current=!1,p.current=!0;let e=a.threads.main.unstable_on(`initialize`,m);return()=>{p.current=!1,e(),f.current?.(),f.current=void 0}},[a]),a},hc=nn(({threadId:e,generation:t,parentList:n,runtimeHook:r,parentClient:i,adapters:a,publish:o,destroySignal:s})=>{let c=M(()=>new Ls(new H({path:{ref:`threadItems[threadId=${e}]`,threadSelector:{type:`threadId`,threadId:e}},getState:()=>{let t=n.getItemById(e);return t?{id:t.id,remoteId:t.remoteId,externalId:t.externalId,title:t.title,lastMessageAt:t.lastMessageAt,custom:t.custom,status:t.status,isMain:t.id===n.mainThreadId,isRunning:n.unstable_isThreadRunning?.(t.id)??!1}:B},subscribe:e=>n.subscribe(e)}),n),[n,e]),{client:l}=Yr(i,{threadListItem:ga({runtime:c})});return vr(s,function(){return Vn(l,function(){return xa(a,function(){return mc({threadId:e,generation:t,runtimeHook:r,publish:o,itemRuntime:c})})})})}),gc=[`runStart`,`runEnd`,`initialize`,`modelContextUpdate`],_c=e=>{let t=x(3),{detectorRef:n}=e,r,i;return t[0]===n?(r=t[1],i=t[2]):(r=()=>{n.current=!0},i=[n],t[0]=n,t[1]=r,t[2]=i),Ze(r,i),null},vc=class extends ri{runtimeHook;adapterStore=new ii({defaultAdapters:null,threadAdapters:new Map});hostStore=new ii({threads:[],hookEpoch:0});pendingThreadAdapters=new Map;instances=new Map;nextGeneration=0;parent;constructor(e,t){super(),this.parent=t,this.runtimeHook=e}_whenRuntimeAttached(e){return new Promise((t,n)=>{let r=()=>{let r=this.instances.get(e);if(!r)i(),n(Error(`Thread was deleted before runtime was started`));else if(!r.runtime||r.publishedGeneration!==r.generation)return;else i(),t(r.runtime)},i=this.subscribe(r);r()})}startThreadRuntime(e){if(!this.instances.has(e)){let t=this.nextGeneration++;this.instances.set(e,{generation:t,isRunning:!1,destroy:new AbortController}),this._syncHostThreads()}return this._whenRuntimeAttached(e)}__internal_restartThreadRuntime(e){let t=this.instances.get(e);if(!t)return this.startThreadRuntime(e);try{t.unsubscribeRunning?.()}finally{t.unsubscribeRunning=void 0,t.runtime&&Fs(t.runtime),t.destroy.abort(),t.destroy=new AbortController,t.generation=this.nextGeneration++,this._syncHostThreads(),this._notifySubscribers()}return this._whenRuntimeAttached(e)}getThreadRuntimeCore(e){let t=this.instances.get(e);if(t)return t.runtime}__internal_isThreadRunning(e){return this.instances.get(e)?.isRunning??!1}runningSubscribers=new Set;__internal_subscribeRunningChanged(e){return this.runningSubscribers.add(e),()=>this.runningSubscribers.delete(e)}threadEventSubscribers=new Set;__internal_subscribeThreadEvents(e){return this.threadEventSubscribers.add(e),()=>this.threadEventSubscribers.delete(e)}_publish=(e,t,n)=>{this._publishThreadRuntime(e,t,n)};_publishThreadRuntime(e,t,n){let r=this.instances.get(e);if(!r||r.generation!==n)return;let i=r.runtime,a=r.publishedGeneration;r.runtime=t,r.publishedGeneration=n;try{i!==t&&this._trackRunning(e,r)}finally{try{this._notifySubscribers(),i!==void 0&&i!==t&&V(this.replacedSubscribers)}finally{a===n&&i!==void 0&&i!==t&&Is(i)}}}replacedSubscribers=new Set;__internal_subscribeRuntimeReplaced(e){return this.replacedSubscribers.add(e),()=>this.replacedSubscribers.delete(e)}_trackRunning(e,t){let n=t.unsubscribeRunning;t.unsubscribeRunning=void 0;try{n?.()}finally{let n=t.runtime;if(!n)this._setRunning(t,!1);else{let r=Cs(n);t.isRunning!==r&&(t.isRunning=r,queueMicrotask(()=>V(this.runningSubscribers)));let i=[n.subscribe(()=>{this._setRunning(t,Cs(n))}),...gc.map(t=>n.unstable_on(t,()=>{z(this.threadEventSubscribers,{threadId:e,type:t},`Thread event "${t}"`)}))];t.unsubscribeRunning=()=>ei(i)}}}_setRunning(e,t){e.isRunning!==t&&(e.isRunning=t,V(this.runningSubscribers))}stopThreadRuntime(e){let t=this.instances.get(e);try{t?.unsubscribeRunning?.()}finally{t?.runtime&&Is(t.runtime),t?.destroy.abort(),this.instances.delete(e),this.pendingThreadAdapters.delete(e),this._syncHostThreads(),this._notifySubscribers()}}setRuntimeHook(e){if(this.runtimeHook===e)return;this.runtimeHook=e;let t=this.hostStore.getState();this.hostStore.setState({...t,hookEpoch:t.hookEpoch+1})}__internal_setDefaultAdapters(e){let t=this.adapterStore.getState();t.defaultAdapters!==e&&this.adapterStore.setState({...t,defaultAdapters:e})}__internal_setThreadAdapters(e,t){let n=this.adapterStore.getState(),r=new Map(n.threadAdapters);t===null?r.delete(e):r.set(e,t),this.adapterStore.setState({...n,threadAdapters:r})}__internal_dispose(){for(let e of[...this.instances.keys()])try{this.stopThreadRuntime(e)}catch(e){console.error(`[assistant-ui] Thread runtime cleanup threw while stopping a thread`,e)}}_syncHostThreads(){let e=this.hostStore.getState();this.hostStore.setState({...e,threads:Array.from(this.instances.entries()).map(([e,{generation:t,destroy:n}])=>({id:e,generation:t,destroySignal:n.signal}))})}_threadElements(e,{threads:t,hookEpoch:n},r){let i=this.runtimeHook;return t.map(({id:t,generation:a,destroySignal:o})=>{let s=this.pendingThreadAdapters.has(t)?this.pendingThreadAdapters.get(t):r.threadAdapters.get(t)??r.defaultAdapters;return rn(`${t}:${a}:${n}`,hc({threadId:t,generation:a,parentList:this.parent,runtimeHook:i,parentClient:e,adapters:s,publish:this._publish,destroySignal:o}))})}__internal_useHost(e){let t=U(this.hostStore),n=U(this.adapterStore);return dn(this._threadElements(e,t,n))}__internal_RenderThreadRuntimes=({provider:e})=>(U(this.hostStore),Array.from(this.instances.entries()).map(([t,{generation:n}])=>(0,S.jsx)(this._OuterActiveThreadProvider,{threadId:t,provider:e},`${t}:${n}`)));__internal_Host=({parentClient:e})=>{let t=U(this.hostStore),n=U(this.adapterStore),r=this._threadElements(e,t,n),{effects:i}=pn(function(){return dn(r)});return Ze(i),null};_OuterActiveThreadProvider=it(({threadId:e,provider:t})=>{let n=M(()=>new Hs(this.parent).getItemById(e),[e]),r=j(!1);return N(()=>{},[t]),(0,S.jsx)(Uo,{runtime:n,children:(0,S.jsx)(t,{children:(0,S.jsx)(this._AdapterSink,{threadId:e,detectorRef:r})})})});_AdapterSink=({threadId:e,detectorRef:t})=>{let n=Sa();return this.pendingThreadAdapters.set(e,n),Ze(()=>(this.__internal_setThreadAdapters(e,n),()=>{this.pendingThreadAdapters.get(e)===n&&this.pendingThreadAdapters.delete(e),this.__internal_setThreadAdapters(e,null)}),[e,n]),(0,S.jsx)(_c,{detectorRef:t})}};function yc(e,t,n,...r){if(!n)return;let i=n=>{try{console.error(`[${e}] ${t} callback threw an error`,n)}catch{}};try{let e=n(...r);if(e!==null&&(typeof e==`object`||typeof e==`function`)&&`then`in e&&typeof e.then==`function`)return Promise.resolve(e).then(()=>void 0,e=>i(e))}catch(e){i(e)}}var bc=(e,t,n)=>n.reduce((e,n)=>n?.(e,t)??e,e),xc=class extends ri{_pendingTransforms=[];_completedOptimistics=[];_nextTransformOrder=0;_epoch=0;_baseValue;_cachedValue;constructor(e){super(),this._baseValue=e,this._cachedValue=e}_updateState(){let e=[...this._pendingTransforms.map(e=>({order:e.order,apply:t=>bc(t,e.task,[e.loading,e.optimistic])})),...this._completedOptimistics.map(({order:e,optimistic:t})=>({order:e,apply:t}))].sort((e,t)=>e.order-t.order);this._cachedValue=e.reduce((e,t)=>t.apply(e),this._baseValue),this._notifySubscribers()}get baseValue(){return this._baseValue}get value(){return this._cachedValue}update(e){this._baseValue=e,this._updateState()}reset(e){this._epoch++,this._pendingTransforms.length=0,this._completedOptimistics.length=0,this._baseValue=e,this._cachedValue=e,this._notifySubscribers()}async optimisticUpdate(e){let t=this._epoch,n=this._nextTransformOrder++,r=e.execute(),i={...e,order:n,task:r};try{this._pendingTransforms.push(i),this._updateState();let n=await r;if(t!==this._epoch)return n;this._baseValue=bc(this._baseValue,n,[e.optimistic,e.then]);for(let t of this._completedOptimistics)(e.then||t.order>i.order)&&(this._baseValue=t.optimistic(this._baseValue));return e.optimistic&&(this._completedOptimistics.push({order:i.order,optimistic:e.optimistic}),this._completedOptimistics.sort((e,t)=>e.order-t.order)),n}finally{let e=this._pendingTransforms.indexOf(i);e>-1&&this._pendingTransforms.splice(e,1),this._pendingTransforms.length===0&&(this._completedOptimistics.length=0),this._updateState()}}},Sc=Error("This is the empty thread, a placeholder for the main thread. You cannot perform any actions on this thread instance. This error is probably because you tried to call a thread method in your render function. Call the method inside a `useEffect` hook instead."),Cc=new class extends Ds{get error(){return Sc}messages=[];composer=Es(Sc,!0);isLoading=!0;getMessageById(){}getBranches(){return[]}export(){return{messages:[]}}subscribe(){return()=>{}}waitForUpdate(){return Promise.reject(Sc)}};function wc(e){return e}var Tc=`__LOCALID_`,Ec=e=>e||void 0,Dc=(e,t)=>{let n=[...t.threadIds],r=[...t.archivedThreadIds],i=C(t.threadIdMap),a=C(t.threadData),o=new Set([...n,...r]);for(let t of e){switch(t.status){case`regular`:case`archived`:break;default:{let e=t.status;throw Error(`Unsupported state: ${e}`)}}let e=i[t.remoteId],s=e===void 0?void 0:a[e],c=s?.id??t.remoteId,l=e??wc(c),u=s!==void 0&&s.status!==`new`?s.initializeTask:void 0;o.has(c)?s!==void 0&&s.status!==t.status&&(t.status===`regular`?(r=r.filter(e=>e!==c),n.push(c)):(n=n.filter(e=>e!==c),r.push(c))):(o.add(c),t.status===`regular`?n.push(c):r.push(c)),i[c]=l,i[t.remoteId]=l,a[l]={...s?.localOrigin===!0?{localOrigin:!0}:{},id:c,remoteId:t.remoteId,externalId:t.externalId,status:t.status,title:t.title,lastMessageAt:t.lastMessageAt,custom:t.custom,initializeTask:u??Promise.resolve({remoteId:t.remoteId,externalId:t.externalId})}}return{threadIds:n,archivedThreadIds:r,threadIdMap:i,threadData:a}},Oc=()=>({isLoading:!0,loadError:void 0,isLoadingMore:!1,cursor:void 0,newThreadId:void 0,threadIds:[],archivedThreadIds:[],threadIdMap:C(),threadData:C()}),kc=(e,t)=>{let n=`${Tc}${t??W()}`;for(;e.threadIdMap[n];)n=`${Tc}${W()}`;let r=wc(n);return{id:n,state:{...e,newThreadId:n,threadIdMap:C(e.threadIdMap,{[n]:r}),threadData:C(e.threadData,{[r]:{status:`new`,id:n,remoteId:void 0,externalId:void 0,title:void 0,custom:void 0,localOrigin:!0}})}}},Ac=(e,t,n)=>{let r=new Set(e.threadIds),i=new Set(e.archivedThreadIds),a=[],o=[],s=(e,t)=>e.has(t.id)||t.remoteId!==void 0&&e.has(t.remoteId);for(let t of Object.values(e.threadData)){let e=n.get(t.id);(e===void 0||e===`new`)&&(e!==void 0||t.localOrigin===!0)&&(t.status===`regular`&&!s(r,t)?(a.push(t),r.add(t.id)):t.status===`archived`&&!s(i,t)&&(o.push(t),i.add(t.id)))}if(a.length===0&&o.length===0)return e;let c=(e,t)=>{let n=e.indexOf(t.id);if(n!==-1)return n;let r=t.remoteId===void 0?-1:e.indexOf(t.remoteId);return r===-1?2**53-1:r};return a.sort((e,n)=>c(t.threadIds,e)-c(t.threadIds,n)),o.sort((e,n)=>c(t.archivedThreadIds,e)-c(t.archivedThreadIds,n)),{...e,threadIds:[...a.map(e=>e.id),...e.threadIds],archivedThreadIds:[...o.map(e=>e.id),...e.archivedThreadIds]}},jc=e=>new Map(Object.values(e.threadData).map(e=>[e.id,e.status])),Mc=(e,t)=>{let n=Object.hasOwn(e.threadIdMap,t)?e.threadIdMap[t]:void 0;if(n!==void 0)return Object.hasOwn(e.threadData,n)?e.threadData[n]:void 0},Nc=(e,t,n,r,i)=>{let a=wc(t),o=Object.hasOwn(e.threadData,a)?e.threadData[a]:void 0;if(!o)return{state:e,removedMappingId:void 0,survivorMappingId:a};let s=Object.hasOwn(e.threadIdMap,n)?e.threadIdMap[n]:void 0,c=s!==void 0&&s!==a&&Object.hasOwn(e.threadData,s)?e.threadData[s]:void 0,l=s!==void 0&&c!==void 0?{mappingId:s,data:c}:void 0,u=i!==void 0&&Object.hasOwn(e.threadIdMap,i)?e.threadIdMap[i]:void 0,d=l!==void 0&&u===l.mappingId?l.mappingId:a,f=l===void 0?void 0:d===a?l.mappingId:a,p=r??l?.data.externalId,m=C(e.threadData);f!==void 0&&delete m[f];let h={...o,id:d,initializeTask:Promise.resolve({remoteId:n,externalId:p}),remoteId:n,externalId:p};m[d]={...l?.data,...h,title:o.title??l?.data.title,lastMessageAt:(`lastMessageAt`in o?o.lastMessageAt:void 0)??(l&&`lastMessageAt`in l.data?l.data.lastMessageAt:void 0),custom:o.custom??l?.data.custom};let g=C(e.threadIdMap);if(f!==void 0)for(let[e,t]of Object.entries(g))t===f&&(g[e]=d);g[t]=d,g[n]=d;let _=e=>l===void 0?e:e.filter(e=>e!==l.data.id).map(e=>e===o.id?d:e);return{state:{...e,threadIds:_(e.threadIds),archivedThreadIds:_(e.archivedThreadIds),threadIdMap:g,threadData:m},removedMappingId:f,survivorMappingId:d}},Pc=(e,t,n,r)=>{let i=Mc(e,t);if(!i)return e;let{id:a,status:o}=i;if(o===n)return e;let s;if(n!==`deleted`){if(i.status===`new`){if(r===void 0)return e;s={...i,initializeTask:r,status:n}}else s={...i,status:n}}let c={...e};switch(o){case`new`:c.newThreadId=void 0;break;case`regular`:c.threadIds=c.threadIds.filter(e=>e!==a);break;case`archived`:c.archivedThreadIds=c.archivedThreadIds.filter(e=>e!==a);break;default:throw Error(`Unsupported state: ${o}`)}switch(n){case`regular`:c.threadIds=[a,...c.threadIds];break;case`archived`:c.archivedThreadIds=[a,...c.archivedThreadIds];break;case`deleted`:{let n=e.threadIdMap[t],r=C(c.threadData);delete r[n],c.threadData=r;let i=C(c.threadIdMap);for(let[e,t]of Object.entries(i))t===n&&delete i[e];c.threadIdMap=i;break}default:throw Error(`Unsupported state: ${n}`)}return s!==void 0&&(c.threadData={...c.threadData,[a]:s}),c},Fc=(e,t,n)=>Pc(e,t,n,void 0),Ic=(e,t,n)=>Pc(e,t,`regular`,n),Lc=class extends Error{[mi]=!0;constructor(){super(`Thread list adapter changed while an operation was pending.`),this.name=`ThreadListAdapterChangedError`}};function Rc(e,t){let n=e.get(t);return n===void 0&&(n={generations:new Set,pendingClaim:null,inFlightClaims:new Set,manualTitle:void 0,latestExplicit:null,nextOrder:0},e.set(t,n)),n}function zc(e,t,n){n.generations.size===0&&n.pendingClaim===null&&n.inFlightClaims.size===0&&n.manualTitle===void 0&&e.get(t)===n&&e.delete(t)}function Bc(e,t){return!t.superseded&&(e.latestExplicit?.order??0)<=t.order}function Vc(e,t){return(e.latestExplicit?.order??0)<t.order}function Hc(e,t,n){let r=Rc(e,t),i,a=new Promise(e=>{i=e}),o={title:n,order:++r.nextOrder,settled:a,settle:i};r.pendingClaim=o,r.inFlightClaims.add(o);for(let e of r.generations)e.order<o.order&&(e.claim=o);return o}function Uc(e,t,n,r){n.settle(r);let i=e.get(t);i!==void 0&&(i.inFlightClaims.delete(n),i.pendingClaim===n&&(i.pendingClaim=null,r&&(i.manualTitle=n.title)),zc(e,t,i))}function Wc(e,t,n){let r=n.manualTitle;if(r!==void 0)return n.manualTitle=void 0,zc(e,t,n),r}function Gc(e,t){e.delete(t)}function Kc(e,t,n){let r=Rc(e,t);if(n&&r.pendingClaim===null&&Wc(e,t,r)!==void 0)return null;let i,a=new Promise(e=>{i=e}),o={automatic:n,order:++r.nextOrder,claim:n?r.pendingClaim:null,beforeGenerationClaims:n?[]:[...r.inFlightClaims],superseded:!1,persisted:a,settlePersisted:i};if(!n){r.pendingClaim=null,r.manualTitle=void 0,r.latestExplicit=o;for(let e of r.generations)e.automatic&&(e.superseded=!0)}return r.generations.add(o),o}async function qc({states:e,threadId:t,automatic:n,generate:r,rename:i,applyTitle:a}){let o=Rc(e,t),s=Kc(e,t,n);if(s===null)return;let c,l=s.order,u=async e=>{let t=await e.settled;if(s.claim===e)return t||(s.claim=null,o.pendingClaim===e&&(o.pendingClaim=null)),t},d=()=>n&&Wc(e,t,o)!==void 0,f=async()=>{if(c!==void 0)for(;;){let e=s.claim;if(e!==null&&e.order>l&&Vc(o,e)){await u(e)===!0&&(c=e.title,l=e.order,await i(e.title));continue}let t=o.latestExplicit;if(t===null||t.order<=l)return;let n=await t.persisted;if(o.latestExplicit===t){if(l=t.order,n===void 0||n===c)return;c=n,await i(n)}}},p=async()=>{if(s.beforeGenerationClaims.length>0&&await Promise.all(s.beforeGenerationClaims.map(e=>e.settled)),s.claim!==null){let e=await u(s.claim);if(e===!0){s.superseded=!0;return}if(e===!1&&d())return}if(!Bc(o,s))return;let e=!1,t;for(await r(async n=>{e=!0,t=n,n!==void 0&&(c=n);let r=s.claim;if(r!==null){if(await u(r)!==!1)return;if(d()){s.superseded=!0;return}}Bc(o,s)&&await a(t)});;){let n=s.claim;if(n===null)return;let r=await u(n);if(r!==void 0){if(r===!1){if(d())return;e&&Bc(o,s)&&await a(t);return}if(!Vc(o,n))return;if(await i(n.title),c=n.title,l=n.order,s.claim===n){if(!Bc(o,s))return;await a(n.title),s.superseded=!0;return}}}};try{await p(),await f()}finally{s.settlePersisted(c),o.generations.delete(s),zc(e,t,o)}}var Y=(e,t)=>Error(`Thread "${e}" not found while ${t}.`),Jc=(e,t,n)=>Error(`Thread "${e}" has status "${t}", so it cannot ${n}.`),Yc=Oc(),Xc=class extends ri{_options;_hookManager;_runtimeAdapters;_loadThreadsPromise;_loadMorePromise;_loadGeneration=0;_adapterGeneration=0;_replaceListOnNextLoad=!1;_staleThreadIdsOnReplace;_switchGeneration=0;_switchTask;_titleStates=new Map;_mainThreadId;_state=new xc(Yc);_useAdaptersProvider=({children:e})=>{let t=this._options.adapter.unstable_useAdapters;return t===void 0?e:(0,S.jsx)(this._SynthesizedAdapters,{useAdapters:t,children:e})};_SynthesizedAdapters=({useAdapters:e,children:t})=>{let n=wa(e());return n==null?t:(0,S.jsx)(Ta,{adapters:n,children:t})};resolveProvider(e){return e.unstable_Provider===void 0?e.unstable_useAdapters===void 0?at:this._useAdaptersProvider:e.unstable_Provider}get threadItems(){return this._state.value.threadData}getLoadThreadsPromise(){if(!this._loadThreadsPromise){let e=this._loadGeneration,t=!1,n=jc(this._state.baseValue);this._loadThreadsPromise=this._state.optimisticUpdate({execute:()=>this._options.adapter.list(),loading:t=>e===this._loadGeneration?{...t,isLoading:!0,loadError:void 0}:t,then:(r,i)=>{if(e!==this._loadGeneration)return r;if(this._replaceListOnNextLoad)return this._replaceListOnNextLoad=!1,t=!0,this._replaceWithThreads({...r,loadError:void 0},i.threads,Ec(i.nextCursor));let a=Dc(i.threads,{threadIds:[],archivedThreadIds:[],threadIdMap:{...r.threadIdMap},threadData:{...r.threadData}});return Ac({...r,isLoading:!1,loadError:void 0,cursor:Ec(i.nextCursor),threadIds:a.threadIds,archivedThreadIds:a.archivedThreadIds,threadIdMap:a.threadIdMap,threadData:a.threadData},r,n)}}).catch(n=>{if(e===this._loadGeneration){if(console.error(`[assistant-ui] thread list load failed:`,n),this._loadThreadsPromise=void 0,!this._replaceListOnNextLoad){this._state.update({...this._state.baseValue,isLoading:!1,loadError:n});return}this._replaceListOnNextLoad=!1,t=!0,this._state.update(this._replaceWithThreads({...this._state.baseValue,loadError:n},[],void 0))}}).then(()=>{if(!t)return;let e=this._options.threadId;e!==void 0&&this.getItemById(e)?.id!==this._mainThreadId&&this._switchToThreadFromProp(e).catch(()=>{})})}return this._loadThreadsPromise}loadMore(){if(this._loadMorePromise)return this._loadMorePromise;let e=this._state.value;if(e.cursor===void 0||e.isLoading)return Promise.resolve();let t=this._loadGeneration,n=this._options.adapter,r=e.cursor,i=this._state.optimisticUpdate({execute:()=>n.list({after:r}),loading:e=>t===this._loadGeneration?{...e,isLoadingMore:!0}:e,then:(e,r)=>{if(t!==this._loadGeneration||n!==this._options.adapter)return e;let i=Dc(r.threads,{threadIds:[...e.threadIds],archivedThreadIds:[...e.archivedThreadIds],threadIdMap:{...e.threadIdMap},threadData:{...e.threadData}});return{...e,isLoadingMore:!1,cursor:Ec(r.nextCursor),threadIds:i.threadIds,archivedThreadIds:i.archivedThreadIds,threadIdMap:i.threadIdMap,threadData:i.threadData}}}).catch(e=>{t===this._loadGeneration&&console.error(`[assistant-ui] thread list loadMore failed:`,e)}).then(()=>{this._loadMorePromise===i&&(this._loadMorePromise=void 0)});return this._loadMorePromise=i,i}constructor(e,t,n){super(),this._state.subscribe(()=>{this._notifySubscribers(),this._notifyThreadIdChange()}),this._runtimeAdapters={modelContext:t},this._hookManager=new vc(e.runtimeHook,this),this._hookManager.__internal_setDefaultAdapters(this._runtimeAdapters),this._hookManager.__internal_subscribeRunningChanged(()=>this._notifySubscribers()),this._hookManager.__internal_subscribeRuntimeReplaced(()=>{queueMicrotask(()=>this._notifySubscribers())}),this.providerStore=new ii(this.resolveProvider(e.adapter)),this.__internal_setOptions(e),this._startSwitchToNewThread(!0,n)}_initialThreadLoaded=!1;providerStore;__internal_setOptions(e){if(this._options===e)return;let t=this._options!==void 0&&this._options.adapter!==e.adapter,n=this._initialThreadLoaded&&this._options!==void 0&&this._options.threadId!==e.threadId;this._options=e,this.providerStore.setState(this.resolveProvider(e.adapter)),this._hookManager.setRuntimeHook(e.runtimeHook),t&&(this._loadGeneration++,this._adapterGeneration++,this._switchGeneration++,this._switchTask=void 0,this._loadThreadsPromise=void 0,this._loadMorePromise=void 0,this._replaceListOnNextLoad=!0,this._staleThreadIdsOnReplace=new Set(Object.values(this._state.baseValue.threadData).filter(e=>e.status!==`new`).map(e=>e.id)),this._state.update({...this._state.baseValue,cursor:void 0,loadError:void 0}),this._titleStates.clear()),n&&this._switchToThreadFromProp(e.threadId).catch(()=>{})}_requireAdapterGeneration(e){if(e!==this._adapterGeneration)throw new Lc}_requireAdapterSettled(){if(this._replaceListOnNextLoad)throw new Lc}_replaceWithThreads(e,t,n){let r=[];if(e.newThreadId){let t=Object.hasOwn(e.threadIdMap,e.newThreadId)?e.threadIdMap[e.newThreadId]:void 0,n=t&&Object.hasOwn(e.threadData,t)?e.threadData[t]:void 0;n?.status===`new`&&r.push(n)}let i=this._staleThreadIdsOnReplace;if(i)for(let t of Object.values(e.threadData))i.has(t.id)||(t.status===`new`||t.remoteId!==void 0)&&r.push(t);this._staleThreadIdsOnReplace=void 0;let a={threadIds:[],archivedThreadIds:[],threadIdMap:C(),threadData:C()};for(let e of r){let t=wc(e.id);Object.hasOwn(a.threadData,t)||(a.threadIdMap[e.id]=t,e.remoteId!==void 0&&(a.threadIdMap[e.remoteId]=t),a.threadData[t]=e)}let{threadIds:o,archivedThreadIds:s,threadIdMap:c,threadData:l}=Dc(t,a);for(let e of r){if(e.remoteId===void 0)continue;let t=wc(e.id),n=Object.hasOwn(l,t)?l[t]:void 0;n!==void 0&&(n.status===`regular`&&!o.includes(n.id)?o.push(n.id):n.status===`archived`&&!s.includes(n.id)&&s.push(n.id))}let u={...e,isLoading:!1,cursor:n,threadIds:o,archivedThreadIds:s,threadIdMap:c,threadData:l,newThreadId:e.newThreadId!==void 0&&!Object.hasOwn(c,e.newThreadId)?void 0:e.newThreadId};if(Mc(u,this._mainThreadId)===void 0){let e=u.newThreadId;if(e!==void 0)this._mainThreadId=e;else{let e=kc(u);this._mainThreadId=e.id,u=e.state}this._options.threadId===void 0?this._notifyThreadIdChange():this._lastNotifiedThreadId=void 0}let d=new Set(Object.values(u.threadData).map(e=>e.id));for(let t of Object.values(e.threadData))if(!d.has(t.id))try{this._hookManager.stopThreadRuntime(t.id)}catch(e){console.error(`[assistant-ui] Thread runtime cleanup threw while stopping a thread`,e)}return this._hookManager.startThreadRuntime(this._mainThreadId).then(()=>this._notifySubscribers(),()=>void 0),u}__internal_load(){if(this.getLoadThreadsPromise(),this._initialThreadLoaded)return;this._initialThreadLoaded=!0;let e=this._options.threadId??this._options.initialThreadId;e!==void 0&&(this._options.threadId===void 0?this.switchToThread(e):this._switchToThreadFromProp(e)).catch(()=>{})}async reloadMainThread(){let e=this._mainThreadId;if(e===void 0||this.getItemById(e)?.status===`new`)return;let t=this._hookManager.getThreadRuntimeCore(e);try{t?.unstable_refetchThread?await t.unstable_refetchThread():await this._hookManager.__internal_restartThreadRuntime(e)}catch(t){if(e!==this._mainThreadId)return;throw t}e===this._mainThreadId&&this._notifySubscribers()}reload(){return this._loadGeneration++,this._loadThreadsPromise=void 0,this._loadMorePromise=void 0,this._state.update({...this._state.baseValue,cursor:void 0}),this.getLoadThreadsPromise()}get isLoading(){return this._state.value.isLoading}get loadError(){return this._state.value.loadError}get isLoadingMore(){return this._state.value.isLoadingMore}get hasMore(){return this._state.value.cursor!==void 0}get threadIds(){return this._state.value.threadIds}get archivedThreadIds(){return this._state.value.archivedThreadIds}get newThreadId(){return this._state.value.newThreadId}get mainThreadId(){return this._mainThreadId}get _mainThreadRemoteId(){if(this._mainThreadId!==void 0)return Mc(this._state.value,this._mainThreadId)?.remoteId}_lastNotifiedThreadId=void 0;_notifyThreadIdChange(e=!0){let t=this._mainThreadRemoteId;this._lastNotifiedThreadId!==t&&(this._lastNotifiedThreadId=t,e&&yc(`assistant-ui`,`onThreadIdChange`,this._options.onThreadIdChange,t))}getMainThreadRuntimeCore(){return this._hookManager.getThreadRuntimeCore(this._mainThreadId)||Cc}getThreadRuntimeCore(e){let t=this.getItemById(e);if(!t)throw Y(e,`getting its runtime`);let n=this._hookManager.getThreadRuntimeCore(t.id);if(!n)throw Error(`Runtime for thread "${e}" not found while getting its runtime.`);return n}unstable_isThreadRunning(e){let t=this.getItemById(e);return t?this._hookManager.__internal_isThreadRunning(t.id):!1}unstable_subscribeThreadEvents(e){return this._hookManager.__internal_subscribeThreadEvents(e)}getItemById(e){return Mc(this._state.value,e)}switchToThread(e,t){return this._startSwitchToThread(e,t,!0)}_startSwitchToThread(e,t,n){let r=++this._switchGeneration,i=this._switchToThread(e,t,r,n);return this._switchTask=i,i}async _switchToThread(e,t,n,r){if(this._replaceListOnNextLoad&&e!==this._state.value.newThreadId)throw new Lc;let i=this.getItemById(e);if(!i){let t=await this._options.adapter.fetch(e);if(n!==this._switchGeneration)return;let r=this._state.value,a=wc(t.remoteId),o={...r.threadData,[a]:{id:a,initializeTask:Promise.resolve({remoteId:t.remoteId,externalId:t.externalId}),remoteId:t.remoteId,externalId:t.externalId,status:t.status,title:t.title,lastMessageAt:t.lastMessageAt,custom:t.custom}},s={...r.threadIdMap,[t.remoteId]:a},c=t.remoteId,l=t.status===`regular`?r.threadIds.includes(c):r.archivedThreadIds.includes(c),u=r.threadIds.filter(e=>e!==c),d=r.archivedThreadIds.filter(e=>e!==c),f=t.status===`regular`?l?r.threadIds:[...u,c]:u,p=t.status===`archived`?l?r.archivedThreadIds:[...d,c]:d;this._state.update({...r,threadIds:f,archivedThreadIds:p,threadIdMap:s,threadData:o}),i=this.getItemById(e)}if(!i)throw Y(e,`switching to it`);if(this._mainThreadId===i.id)return;let a=this._hookManager.startThreadRuntime(i.id);if(this.mainThreadId===void 0?a.then(()=>this._notifySubscribers(),()=>void 0):await a,n!==this._switchGeneration)return;let o=this.getItemById(i.id);o?.id===i.id&&(o.status===`archived`&&t?.unarchive!==!1&&(await o.initializeTask,n!==this._switchGeneration||(o=this.getItemById(i.id),o?.id!==i.id)||o.status===`archived`&&(await this.unarchive(o.id),n!==this._switchGeneration||(o=this.getItemById(i.id),o?.id!==i.id)))||(this._mainThreadId=o.id,this._notifySubscribers(),this._notifyThreadIdChange(r)))}switchToNewThread(){return this._startSwitchToNewThread(!0)}_switchToThreadFromProp(e){return e===void 0?G(`create`,()=>this._startSwitchToNewThread(!1)):G(`switch`,()=>this._startSwitchToThread(e,void 0,!1))}_startSwitchToNewThread(e,t){let n=++this._switchGeneration,r=this._switchToNewThread(n,e,t);return this._switchTask=r,r}async _switchToNewThread(e,t,n){for(;this._state.baseValue.newThreadId!==void 0&&this._state.value.newThreadId===void 0;)if(await this._state.waitForUpdate(),e!==this._switchGeneration)return;let r=this._state.baseValue,i=this._state.value.newThreadId;if(i===void 0){let e=kc(r,n);i=e.id,this._state.update(e.state)}return this._switchToThread(i,void 0,e,t)}initialize=async e=>{let t=this._options.adapter,n=this._adapterGeneration;if(this._state.value.newThreadId!==e){this._requireAdapterSettled();let t=this.getItemById(e);if(!t)throw Y(e,`initializing it`);if(t.status===`new`)throw Jc(e,t.status,`be initialized here`);let{remoteId:r,externalId:i}=await t.initializeTask;return this._requireAdapterGeneration(n),{remoteId:r,externalId:i}}this._requireAdapterGeneration(n);let r=t.initialize(e),i,{remoteId:a,externalId:o}=await this._state.optimisticUpdate({execute:()=>r,optimistic:t=>Ic(t,e,r),then:(t,{remoteId:r,externalId:a})=>{if(n!==this._adapterGeneration)return t;let o=Nc(t,e,r,a,e);return i=o.removedMappingId,i===this._mainThreadId&&(this._mainThreadId=o.survivorMappingId),o.state}});return this._requireAdapterGeneration(n),i!==void 0&&this._hookManager.stopThreadRuntime(i),{remoteId:a,externalId:o}};generateTitle=async(e,t)=>{this._requireAdapterSettled();let n=this._options.adapter,r=this._adapterGeneration,i=this.getItemById(e);if(!i)throw Y(e,`generating its title`);if(i.status===`new`)throw Jc(e,i.status,`generate a title`);let{remoteId:a}=await i.initializeTask;this._requireAdapterGeneration(r);let o=this._hookManager.getThreadRuntimeCore(i.id);if(!o)return;let s=o.messages.filter(dc);await qc({states:this._titleStates,threadId:i.id,automatic:t?.automatic===!0,generate:async e=>{let t=await n.generateTitle(a,s);this._requireAdapterGeneration(r),await fc(t,e)},rename:async e=>{this._requireAdapterGeneration(r),await n.rename(a,e)},applyTitle:async e=>{await this._state.optimisticUpdate({execute:async()=>{},optimistic:t=>{if(r!==this._adapterGeneration)return t;let n=Mc(t,i.id);return n?{...t,threadData:{...t.threadData,[n.id]:{...n,title:e}}}:t}})}})};async rename(e,t){this._requireAdapterSettled();let n=this._options.adapter,r=this._adapterGeneration,i=this.getItemById(e);if(!i)throw Y(e,`renaming it`);if(i.status===`new`)throw Jc(e,i.status,`be renamed`);let a=Hc(this._titleStates,i.id,t);try{let o=await this._state.optimisticUpdate({execute:async()=>{let{remoteId:e}=await i.initializeTask;return this._requireAdapterGeneration(r),n.rename(e,t)},optimistic:n=>{let r=Mc(n,e);return r?{...n,threadData:{...n.threadData,[r.id]:{...r,title:t}}}:n}});return Uc(this._titleStates,i.id,a,!0),o}catch(e){throw Uc(this._titleStates,i.id,a,!1),e}}async updateCustom(e,t){this._requireAdapterSettled();let n=this._options.adapter,r=this._adapterGeneration,i=this.getItemById(e);if(!i)throw Y(e,`updating its custom metadata`);if(i.status===`new`)throw Jc(e,i.status,`update custom metadata`);if(!n.updateCustom)throw Error(`Remote thread list adapter does not support updating custom metadata`);return this._state.optimisticUpdate({execute:async()=>{let{remoteId:e}=await i.initializeTask;if(this._requireAdapterGeneration(r),!n.updateCustom)throw Error(`Remote thread list adapter does not support updating custom metadata`);return n.updateCustom(e,t)},optimistic:n=>{let r=Mc(n,e);return r?{...n,threadData:{...n.threadData,[r.id]:{...r,custom:t}}}:n}})}async _ensureThreadIsNotMain(e){if(e===this.newThreadId)throw Error(`Cannot ensure new thread is not main`);let t;for(;e===this._mainThreadId;){if(e===this.newThreadId)throw Error(`Cannot ensure new thread is not main`);let n=this._switchTask,r=!n||n===t;r&&(n=this.switchToNewThread()),t=n;try{await n}catch(e){if(r&&this._switchTask===n)throw e}}}async archive(e){this._requireAdapterSettled();let t=this._options.adapter,n=this._adapterGeneration,r=this.getItemById(e);if(!r)throw Y(e,`archiving it`);if(r.status!==`regular`)throw Jc(e,r.status,`be archived`);return await this._ensureThreadIsNotMain(r.id),this._requireAdapterGeneration(n),this._state.optimisticUpdate({execute:async()=>{let{remoteId:e}=await r.initializeTask;return this._requireAdapterGeneration(n),t.archive(e)},optimistic:e=>Fc(e,r.id,`archived`)})}async unarchive(e){this._requireAdapterSettled();let t=this._options.adapter,n=this._adapterGeneration,r=this.getItemById(e);if(!r)throw Y(e,`unarchiving it`);if(r.status!==`archived`)throw Jc(e,r.status,`be unarchived`);return this._state.optimisticUpdate({execute:async()=>{try{let{remoteId:e}=await r.initializeTask;return this._requireAdapterGeneration(n),await t.unarchive(e)}catch(e){throw n===this._adapterGeneration&&await this._ensureThreadIsNotMain(r.id),e}},optimistic:e=>Fc(e,r.id,`regular`)})}async delete(e){this._requireAdapterSettled();let t=this._options.adapter,n=this._adapterGeneration,r=this.getItemById(e);if(!r)throw Y(e,`deleting it`);if(r.status!==`regular`&&r.status!==`archived`)throw Jc(e,r.status,`be deleted`);await this._ensureThreadIsNotMain(r.id),this._requireAdapterGeneration(n);let i=await this._state.optimisticUpdate({execute:async()=>{let{remoteId:e}=await r.initializeTask;return this._requireAdapterGeneration(n),await t.delete(e)},optimistic:e=>Fc(e,r.id,`deleted`)});return this._hookManager.stopThreadRuntime(r.id),Gc(this._titleStates,r.id),i}__internal_dispose(){this._hookManager.__internal_dispose()}async detach(e){let t=this._adapterGeneration,n=this.getItemById(e);if(!n)throw Y(e,`detaching it`);if(n.status!==`regular`&&n.status!==`archived`)throw Jc(e,n.status,`be detached`);await this._ensureThreadIsNotMain(n.id),this._requireAdapterGeneration(t),this._hookManager.stopThreadRuntime(n.id)}boundIdsStore=new ii([]);__internal_RenderComponent=()=>{let e=tt();N(()=>(this.boundIdsStore.setState([...this.boundIdsStore.getState(),e]),()=>{this.boundIdsStore.setState(this.boundIdsStore.getState().filter(t=>t!==e))}),[e]);let t=U(this.boundIdsStore),n=U(this.providerStore),r=Xr();return(t.length===0||t[0]===e)&&(0,S.jsxs)(Ta,{adapters:this._runtimeAdapters,children:[(0,S.jsx)(this._hookManager.__internal_RenderThreadRuntimes,{provider:n}),(0,S.jsx)(this._hookManager.__internal_Host,{parentClient:r})]})}},Zc=()=>()=>{},Qc=()=>$e(Zc,$c,el);function $c(){return!1}function el(){return typeof document>`u`}var tl=class extends Ws{threads;constructor(e,t){super(),this.threads=new Xc(e,this._contextProvider,t)}get RenderComponent(){return this.threads.__internal_RenderComponent}},nl=e=>{let t=tt(),n=Qc(),[r]=A(()=>new tl(e,n?t:void 0)),[i]=A(()=>({generation:0}));P(()=>{let e=++i.generation;return()=>queueMicrotask(()=>{i.generation===e&&r.threads.__internal_dispose()})},[r,i]),N(()=>{r.threads.__internal_setOptions(e),r.threads.__internal_load()},[r,e]),N(()=>{if(typeof window>`u`||typeof document>`u`)return;let e=()=>{r.threads.loadError!==void 0&&r.threads.reload()},t=()=>{document.visibilityState===`visible`&&e()};return window.addEventListener(`online`,e),document.addEventListener(`visibilitychange`,t),()=>{window.removeEventListener(`online`,e),document.removeEventListener(`visibilitychange`,t)}},[r]);let[a]=A(()=>new Us(r));return a},rl=e=>{let[t]=A(()=>new ii(e.runtimeHook));Ze(()=>{t.setState(e.runtimeHook)},[t,e.runtimeHook]);let n=j(e.initialThreadId),[r]=A(()=>function(){return U({subscribe:t.subscribe,getState:t.getState,getServerSnapshot:t.getState})()}),i=Qe(t=>e.onThreadIdChange?.(t)),a=M(()=>({adapter:e.adapter,allowNesting:e.allowNesting,threadId:e.threadId,initialThreadId:n.current,runtimeHook:r,onThreadIdChange:i}),[e.adapter,e.allowNesting,e.threadId,r]);if(Xr().threadListItem.source!==null){if(!a.allowNesting)throw Error(`useRemoteThreadListRuntime cannot be nested inside another RemoteThreadListRuntime. Set allowNesting: true to allow nesting (the inner runtime will become a no-op).`);return e.runtimeHook()}return nl(a)},il=e=>{let t=e.type;switch(t){case`text`:return{type:`text`,...e.id===void 0?void 0:{id:e.id},text:e.text,...e.providerMetadata===void 0?void 0:{providerMetadata:e.providerMetadata},...e.parentId===void 0?void 0:{parentId:e.parentId}};case`image`:return{type:`image`,...e.id===void 0?void 0:{id:e.id},image:e.image,...e.filename==null?void 0:{filename:e.filename},...e.providerMetadata===void 0?void 0:{providerMetadata:e.providerMetadata}};case`file`:return{type:`file`,...e.id===void 0?void 0:{id:e.id},data:e.data,mimeType:e.mimeType,...e.filename==null?void 0:{filename:e.filename},...e.sourceType==null?void 0:{sourceType:e.sourceType},...e.providerMetadata==null?void 0:{providerMetadata:e.providerMetadata},...e.parentId===void 0?void 0:{parentId:e.parentId}};case`audio`:return{type:`audio`,audio:{data:e.audio.data,format:e.audio.format}};case`data`:return Ea(e.data)||console.warn(`attachment data is not JSON! ${JSON.stringify(e)}`),{type:`data`,...e.id===void 0?void 0:{id:e.id},name:e.name,data:e.data};default:throw Error(`Attachment part type not supported by aui/v0: ${t}`)}},al=e=>{if(e.role===`user`&&e.attachments.length!==0)return e.attachments.map(({id:e,type:t,name:n,contentType:r,status:i,content:a})=>({id:e,type:t,name:n,status:i,...r==null?void 0:{contentType:r},content:a.map(il)}))},ol=e=>{if(e!==void 0)try{let t=JSON.stringify(e);return t===void 0?void 0:JSON.parse(t)}catch{return}},sl=(e,t=0)=>{if(t>100||e===void 0||typeof e==`function`)return!1;if(typeof e==`number`)return Number.isFinite(e);if(typeof e!=`object`||!e||typeof e.toJSON==`function`)return!0;if((e instanceof Map||e instanceof Set)&&e.size>0)return!1;if(Array.isArray(e)){if(Reflect.ownKeys(e).length!==e.length+1)return!1;for(let n=0;n<e.length;n++)if(!Object.hasOwn(e,n)||!sl(e[n],t+1))return!1;return!0}return Reflect.ownKeys(e).every(n=>typeof n==`string`&&Object.getOwnPropertyDescriptor(e,n)?.enumerable===!0&&sl(e[n],t+1))},cl=e=>{try{return!sl(e)}catch{return!0}};function ll(e){let t=e.status?.type===`running`?{type:`incomplete`,reason:`cancelled`}:e.status,n=al(e);return{role:e.role,content:e.content.map(e=>{let t=e.type;switch(t){case`text`:return{type:`text`,...e.id===void 0?void 0:{id:e.id},text:e.text,...e.providerMetadata===void 0?void 0:{providerMetadata:e.providerMetadata},...e.parentId===void 0?void 0:{parentId:e.parentId}};case`reasoning`:return{type:`reasoning`,...e.id===void 0?void 0:{id:e.id},text:e.text,...e.unstable_summary===void 0?void 0:{unstable_summary:e.unstable_summary},...e.timing===void 0?void 0:{timing:e.timing},...e.providerMetadata===void 0?void 0:{providerMetadata:e.providerMetadata},...e.parentId===void 0?void 0:{parentId:e.parentId}};case`source`:return e.sourceType===`url`?{type:`source`,sourceType:`url`,id:e.id,url:e.url,...e.title==null?void 0:{title:e.title},...e.providerMetadata==null?void 0:{providerMetadata:e.providerMetadata},...e.parentId===void 0?void 0:{parentId:e.parentId}}:{type:`source`,sourceType:`document`,id:e.id,title:e.title,mediaType:e.mediaType,...e.filename==null?void 0:{filename:e.filename},...e.providerMetadata==null?void 0:{providerMetadata:e.providerMetadata},...e.parentId===void 0?void 0:{parentId:e.parentId}};case`tool-call`:{let t=ol(e.result);e.result!==void 0&&(t===void 0||cl(e.result))&&console.warn(t===void 0?`tool-call result for ${e.toolCallId} cannot be serialized as JSON; omitted`:`tool-call result for ${e.toolCallId} loses data in JSON; persisted as its JSON form`);let n=ol(e.artifact);e.artifact!==void 0&&n===void 0&&console.warn(`tool-call artifact is not JSON for ${e.toolCallId}`);let r=Fi(e.unstable_interactions);return{type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,...JSON.stringify(e.args)===e.argsText?{args:e.args}:{argsText:e.argsText},...t===void 0?void 0:{result:t},...n===void 0?void 0:{artifact:n},...e.modelContent===void 0?void 0:{modelContent:e.modelContent},...e.providerMetadata===void 0?void 0:{providerMetadata:e.providerMetadata},...e.isPreliminary?{isPreliminary:!0}:void 0,...e.isError?{isError:!0}:void 0,...e.interrupt===void 0?void 0:{interrupt:{type:e.interrupt.type,payload:e.interrupt.payload}},...e.timing===void 0?void 0:{timing:e.timing},...e.mcp===void 0?void 0:{mcp:e.mcp},...e.approval?{approval:e.approval}:void 0,...e.parentId===void 0?void 0:{parentId:e.parentId},...e.messages===void 0?void 0:{messages:e.messages.map(ml)},...r===void 0?void 0:{unstable_interactions:r}}}case`image`:return{type:`image`,...e.id===void 0?void 0:{id:e.id},image:e.image,...e.filename==null?void 0:{filename:e.filename},...e.providerMetadata==null?void 0:{providerMetadata:e.providerMetadata}};case`file`:return{type:`file`,...e.id===void 0?void 0:{id:e.id},data:e.data,mimeType:e.mimeType,...e.filename==null?void 0:{filename:e.filename},...e.sourceType?{sourceType:e.sourceType}:void 0,...e.providerMetadata==null?void 0:{providerMetadata:e.providerMetadata},...e.parentId===void 0?void 0:{parentId:e.parentId}};case`data`:return Ea(e.data)||console.warn(`data part is not JSON! ${JSON.stringify(e)}`),{type:`data`,...e.id===void 0?void 0:{id:e.id},name:e.name,data:e.data};case`audio`:return{type:`audio`,audio:{data:e.audio.data,format:e.audio.format}};case`generative-ui`:return{type:`generative-ui`,spec:e.spec,...e.id===void 0?void 0:{id:e.id},...e.parentId===void 0?void 0:{parentId:e.parentId}};default:throw Error(`Message part type not supported by aui/v0: ${t}`)}}),metadata:e.metadata,...t?{status:t}:void 0,...n?{attachments:n}:void 0}}var ul=(e,t,n)=>t.flatMap(t=>{if(!Ia(e,t))return[];if(t.type!==`tool-call`||t.messages===void 0)return[t];let{messages:r,...i}=t;return!Array.isArray(r)||n>=100?[i]:[{...i,messages:r.flatMap(e=>{let t=fl(e,n+1);return t?[t]:[]})}]}),dl=e=>e.flatMap(e=>{let t=La(e,e=>Ia(`user`,e));return t?[t]:[]}),fl=(e,t)=>{if(!K(e)||!Oa(e.role)||!Array.isArray(e.content))return null;let{role:n}=e,r=ul(n,e.content,t);if(n===`system`&&r.length!==1)return null;let{attachments:i,createdAt:a,status:o,metadata:s,...c}=e,l=Da(a),u=K(s)?n===`assistant`?{...s,steps:Ma(s.steps)}:{...s,steps:void 0}:s;return{...c,...l?{createdAt:a}:void 0,...n===`assistant`&&Aa(o)?{status:o}:void 0,...s===void 0?void 0:{metadata:u},content:r,...n===`user`&&Array.isArray(i)?{attachments:dl(i)}:void 0}};function pl(e){try{let t=fl(e.content,0);if(!t)throw Error(`stored row is not an aui/v0 message`);return{parentId:e.parent_id,message:hl({...t,id:e.id,createdAt:e.created_at},e.id)}}catch(t){return console.warn(`aui/v0: dropping unreadable message ${e.id}`,t),null}}var ml=e=>({...ll(e),id:e.id,createdAt:e.createdAt.toISOString()}),hl=(e,t)=>pa({...e,content:e.content.map((n,r)=>n.type!==`tool-call`||n.messages===void 0?n:{...n,messages:n.messages.map((i,a)=>hl({...i,createdAt:i.createdAt===void 0?e.createdAt:new Date(i.createdAt)},i.id??`${t}-${n.toolCallId}-${r}-${a}`))})},t,{type:`complete`,reason:`unknown`}),gl=class extends Error{constructor(e){super(e),this.name=`CloudResponseError`}},X=(e,t)=>new gl(`Invalid Assistant Cloud response for "${e}": expected ${t}`),Z=(e,t)=>{if(typeof e!=`object`||!e||Array.isArray(e))throw X(t,`an object`);return e},_l=(e,t)=>{if(!Array.isArray(e))throw X(t,`an array`);return e},Q=(e,t)=>{if(typeof e!=`string`)throw X(t,`a string`);return e},vl=(e,t)=>{if(typeof e!=`number`||!Number.isFinite(e))throw X(t,`a number`);return e},yl=(e,t)=>e===null?null:vl(e,t),bl=(e,t,n)=>{let r=Q(e,t);if(!n.includes(r))throw X(t,`one of ${n.map(e=>`"${e}"`).join(`, `)}`);return r},xl=(e,t)=>e===null?null:Q(e,t),Sl=(e,t)=>{if(typeof e!=`boolean`)throw X(t,`a boolean`);return e},Cl=(e,t)=>{if(!Number.isInteger(e))throw X(t,`an integer`);return e},wl=(e,t)=>{if(typeof e!=`string`)throw X(t,`a canonical ISO timestamp`);let n=new Date(e);if(Number.isNaN(n.getTime())||n.toISOString()!==e)throw X(t,`a canonical ISO timestamp`);return n},Tl=(e,t)=>Z(e,t),El=3e4,Dl=async(e,t)=>{let n=new AbortController,r=!1,i=setTimeout(()=>{r=!0,n.abort()},El);try{return await t(n.signal)}catch(t){throw r?Error(`Assistant Cloud ${e} timed out after ${El}ms`,{cause:t}):t}finally{clearTimeout(i)}},Ol=e=>{try{let t=e.split(`.`)[1];if(!t)throw Error(`Invalid JWT format`);let n=t.replace(/-/g,`+`).replace(/_/g,`/`);for(;n.length%4!=0;)n+=`=`;let r=atob(n),i=JSON.parse(r).exp;if(!i||typeof i!=`number`)throw Error(`JWT does not contain a valid "exp" field`);return i*1e3}catch(e){throw Error(`Unable to determine the token expiry: ${e}`)}},kl=(e,t)=>{let n=Q(e,t);if(n.length===0)throw new gl(`Invalid Assistant Cloud response for "${t}": expected a non-empty string`);return n},Al=(e,t)=>{let n=Z(e,t);return{token:kl(n.token,`${t}.token`),expires_at:kl(n.expires_at,`${t}.expires_at`)}},jl=async(e,t)=>{let n;try{n=await e.json()}catch{throw new gl(`Invalid Assistant Cloud response for "${t}": expected valid JSON`)}let r=Z(n,t);return{data:r,accessToken:kl(r.access_token,`${t}.access_token`)}},Ml=class{strategy=`jwt`;cachedToken=null;tokenExpiry=null;tokenRequest=null;#e;constructor(e){this.#e=e}async getAuthHeaders(){let e=Date.now();if(this.cachedToken&&this.tokenExpiry&&this.tokenExpiry-e>3e4)return{Authorization:`Bearer ${this.cachedToken}`};this.tokenRequest||=this.fetchAuthHeaders();let t=this.tokenRequest;try{return await t}finally{this.tokenRequest===t&&(this.tokenRequest=null)}}async fetchAuthHeaders(){let e=await this.#e();if(!e)return!1;let t=Ol(e);return this.cachedToken=e,this.tokenExpiry=t,{Authorization:`Bearer ${e}`}}readAuthHeaders(e){let t=e.get(`Authorization`);if(!t)return;let[n,r]=t.split(` `);if(n!==`Bearer`||!r)throw Error(`Invalid auth header received`);let i=Ol(r);this.cachedToken=r,this.tokenExpiry=i}},Nl=class{strategy=`api-key`;#e;#t;#n;constructor(e,t,n){this.#e=e,this.#t=t,this.#n=n}async getAuthHeaders(){return{Authorization:`Bearer ${this.#e}`,"Aui-User-Id":this.#t,"Aui-Workspace-Id":this.#n}}readAuthHeaders(){}},Pl=`aui:refresh_token`,Fl=e=>`${Pl}:${e}`,Il=e=>{try{e.removeItem(Pl)}catch{}},Ll=()=>{if(!(`localStorage`in globalThis))return null;try{return globalThis.localStorage}catch{return null}},Rl=e=>{let t=Ll();if(t)try{let n=Fl(e),r=t.getItem(n);if(r)return Il(t),JSON.parse(r);let i=t.getItem(Pl);if(!i)return;let a;try{a=JSON.parse(i)}catch{Il(t);return}return t.setItem(n,i),Il(t),a}catch{return}},zl=e=>!e||!e.endsWith(`/`)?e:e.slice(0,-1),Bl=(e,t)=>{let n=Ll();if(n)try{n.setItem(Fl(e),JSON.stringify(t))}catch{}},Vl=e=>{let t=Ll();if(t)try{t.removeItem(Fl(e))}catch{}},Hl=new WeakMap,Ul=()=>`navigator`in globalThis?globalThis.navigator?.locks??null:null,Wl=e=>`assistant-cloud:anonymous-auth:${e}`,Gl=(e,t)=>{let n=Ll();if(!n)return t();let r=Hl.get(n);r||(r=new Map,Hl.set(n,r));let i=r.get(e);if(i)return i;let a=Ul(),o=(a?a.request(Wl(e),t):t()).finally(()=>{r.get(e)===o&&r.delete(e)});return r.set(e,o),o},Kl=class{strategy=`anon`;baseUrl;jwtStrategy;constructor(e){this.baseUrl=e;let t=async()=>{let e=Date.now(),t=Rl(this.baseUrl);if(t){if(new Date(t.expires_at).getTime()-e>3e4){let e=await Dl(`refresh token request`,async e=>{let n=await fetch(`${this.baseUrl}/v1/auth/tokens/refresh`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({refresh_token:t.token}),signal:e});if(n.ok){let{data:e,accessToken:t}=await jl(n,`refresh auth token response`);return e.refresh_token!=null&&Bl(this.baseUrl,Al(e.refresh_token,`refresh auth token response.refresh_token`)),t}if(n.status===429||n.status>=500)throw Error(`Assistant Cloud token refresh failed with status ${n.status}`);return null});if(e!==null)return e}else Vl(this.baseUrl)}return Dl(`anonymous token request`,async e=>{let t=await fetch(`${this.baseUrl}/v1/auth/tokens/anonymous`,{method:`POST`,signal:e});if(!t.ok)return null;let{data:n,accessToken:r}=await jl(t,`anonymous auth token response`);return Bl(this.baseUrl,Al(n.refresh_token,`anonymous auth token response.refresh_token`)),r})};this.jwtStrategy=new Ml(()=>Gl(this.baseUrl,t))}async getAuthHeaders(){return this.jwtStrategy.getAuthHeaders()}readAuthHeaders(e){this.jwtStrategy.readAuthHeaders(e)}},ql=`0.2.5`,Jl=class extends Error{status;code;details;constructor(e,t,n,r){super(e),this.status=t,n!==void 0&&(this.code=n),r!==void 0&&(this.details=r),this.name=`CloudAPIError`}},Yl=/^[\x21-\x7e]+$/,Xl=class{_auth;_baseUrl;registerSdk;sdkHeader;constructor(e){let t=new Map;if(this.registerSdk=e=>{let n=e.name.trim(),r=e.version.trim();!Yl.test(n)||!Yl.test(r)||t.set(`${n}/${r}`,{name:n,version:r})},this.sdkHeader=()=>[`assistant-cloud/${ql}`,...Array.from(t.values(),({name:e,version:t})=>`${e}/${t}`)].join(` `),`authToken`in e)this._baseUrl=zl(e.baseUrl),this._auth=new Ml(e.authToken);else if(`apiKey`in e)this._baseUrl=zl(e.baseUrl??`https://backend.assistant-api.com`),this._auth=new Nl(e.apiKey,e.userId,e.workspaceId);else if(`anonymous`in e)this._baseUrl=zl(e.baseUrl),this._auth=new Kl(this._baseUrl);else throw Error(`Invalid configuration: Must provide authToken, apiKey, or anonymous configuration`)}async initializeAuth(){return!!await this._auth.getAuthHeaders()}async makeRawRequest(e,t={}){let n=await this._auth.getAuthHeaders();if(!n)throw Error(`Authorization failed`);let r={...n,...t.headers,"Content-Type":`application/json`,"Aui-Sdk":this.sdkHeader()},i=new URLSearchParams;if(t.query)for(let[e,n]of Object.entries(t.query))n!==!1&&(n===!0?i.set(e,`true`):i.set(e,n.toString()));let a=new URL(`${this._baseUrl}/v1${e}`);a.search=i.toString();let o=await fetch(a,{method:t.method??`GET`,headers:r,body:t.body?JSON.stringify(t.body):null,...t.keepalive?{keepalive:!0}:{}});if(this._auth.readAuthHeaders(o.headers),!o.ok){let e=await o.text(),t,n,r;try{let i=JSON.parse(e);if(typeof i==`object`&&i&&!Array.isArray(i)){let e=i;typeof e.message==`string`&&e.message.length>0&&(t=e.message),typeof e.error==`string`&&(n=e.error,r={...e},delete r.error)}}catch{}throw new Jl(t??`Request failed with status ${o.status}, ${e}`,o.status,n,r)}return o}async makeRequest(e,t={}){let n=await this.makeRawRequest(e,t);if(n.status===204||n.headers.get(`content-length`)===`0`)return;let r=await n.text();if(r.trim()!==``)return JSON.parse(r)}},Zl=20,Ql=50,$l=2e3,eu=[250,1e3],tu=new WeakMap,nu=e=>{tu.get(e)?.()},ru=class{buffer=[];timer;flushing;retryTimer;resolveRetryDelay;bestEffortRequested=!1;generation=0;cloud;isEnabled;listening=!1;constructor(e,t){this.cloud=e,this.isEnabled=t,tu.set(this,()=>this.clearPending())}track(e){if(this.isEnabled()){if(this.listen(),this.buffer.push(iu(e)),this.buffer.length>=Zl){this.flush(!0);return}this.scheduleFlush()}}listen(){this.listening||typeof window>`u`||typeof document>`u`||(this.listening=!0,window.addEventListener(`pagehide`,this.flushBestEffort),document.addEventListener(`visibilitychange`,this.onVisibilityChange))}unlisten(){this.listening&&(this.listening=!1,window.removeEventListener(`pagehide`,this.flushBestEffort),document.removeEventListener(`visibilitychange`,this.onVisibilityChange))}dispose(){this.unlisten(),this.clearFlushTimer(),this.flushBestEffort()}clearPending(){this.generation++,this.buffer=[],this.clearFlushTimer(),this.interruptRetryDelay(),this.unlisten()}onVisibilityChange=()=>{document.visibilityState===`hidden`&&this.flushBestEffort()};flushBestEffort=()=>(this.flushing&&(this.bestEffortRequested=!0,this.interruptRetryDelay()),this.flush(!1));flush=async e=>{if(!this.isEnabled()){this.clearPending();return}if(this.flushing)return this.flushing;this.clearFlushTimer();let t=this.flushPending(e);return this.flushing=t,t.then(()=>{this.flushing===t&&(this.flushing=void 0,this.bestEffortRequested=!1,this.buffer.length===0?(this.clearFlushTimer(),this.unlisten()):this.flush(!0))}),t};async flushPending(e){for(;this.buffer.length>0;){if(!this.isEnabled()){this.buffer=[];return}let t=this.buffer.splice(0,Ql),n=this.generation;for(let r=0;;r++)try{if(await this.cloud.makeRequest(`/events`,{method:`POST`,body:{events:t},keepalive:!0}),n!==this.generation)return;break}catch{if(n!==this.generation)return;let t=e&&!this.bestEffortRequested?eu[r]:void 0;if(t===void 0)break;if(await this.waitForRetry(t),n!==this.generation)return;if(!this.isEnabled())return this.clearPending();if(this.bestEffortRequested)break}}}waitForRetry(e){return new Promise(t=>{let n=()=>{this.retryTimer=void 0,this.resolveRetryDelay=void 0,t()};this.resolveRetryDelay=n,this.retryTimer=setTimeout(n,e)})}interruptRetryDelay(){this.retryTimer!==void 0&&clearTimeout(this.retryTimer),this.resolveRetryDelay?.()}scheduleFlush(){this.timer===void 0&&(this.timer=setTimeout(()=>{this.timer=void 0,this.flush(!0)},$l))}clearFlushTimer(){this.timer!==void 0&&(clearTimeout(this.timer),this.timer=void 0)}},iu=e=>{let t=su(e.props);return{kind:e.kind,...au(e.thread_id)?{thread_id:e.thread_id}:{},...au(e.message_id)?{message_id:e.message_id}:{},...au(e.run_id)?{run_id:e.run_id}:{},...ou(e.value)?{value:e.value}:{},...t?{props:t}:{}}},au=e=>e&&e.length<=48?e:void 0,ou=e=>e!==void 0&&Number.isInteger(e)&&e>=0,su=e=>{if(!e)return;let t=Object.entries(e);if(t.some(([,e])=>typeof e==`string`&&e.length>256||typeof e==`number`&&!Number.isFinite(e)||typeof e!=`string`&&typeof e!=`number`&&typeof e!=`boolean`))return;let n=Object.fromEntries(t);return new TextEncoder().encode(JSON.stringify(n)).byteLength<=1024?n:void 0},cu=[`numeric`,`categorical`,`boolean`],lu=class{cloud;constructor(e){this.cloud=e}async create(e){let t=Z(await this.cloud.makeRequest(`/scores`,{method:`POST`,body:e}),`score response`);return{score_id:Q(t.score_id,`score response.score_id`),name:Q(t.name,`score response.name`),data_type:bl(t.data_type,`score response.data_type`,cu),value:yl(t.value,`score response.value`),string_value:xl(t.string_value,`score response.string_value`)}}},uu=class{cloud;constructor(e){this.cloud=e}async create(){return{token:Q(Z(await this.cloud.makeRequest(`/auth/tokens`,{method:`POST`}),`auth token response`).token,`token`)}}},du=[`positive`,`negative`],fu=(e,t)=>{let n=Z(e,t);return{id:Q(n.id,`${t}.id`),parent_id:xl(n.parent_id,`${t}.parent_id`),height:Cl(n.height,`${t}.height`),created_at:wl(n.created_at,`${t}.created_at`),updated_at:wl(n.updated_at,`${t}.updated_at`),format:Q(n.format,`${t}.format`),content:Tl(n.content,`${t}.content`),external_id:xl(n.external_id??null,`${t}.external_id`)}},pu=class{cloud;constructor(e){this.cloud=e}async list(e,t){return{messages:_l(Z(await this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}/messages`,{query:t}),`thread message list response`).messages,`messages`).map((e,t)=>fu(e,`messages[${t}]`))}}async create(e,t){return{message_id:Q(Z(await this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}/messages`,{method:`POST`,body:{parent_id:t.parent_id,format:t.format,content:t.content,...t.external_id===void 0?void 0:{external_id:t.external_id},...t.parent_external_id===void 0?void 0:{parent_external_id:t.parent_external_id}}}),`thread message create response`).message_id,`message_id`)}}async update(e,t,n){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}`,{method:`PUT`,body:n})}async feedback(e,t,n){let r=n.comment?.trim(),i=Z(await this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/feedback`,{method:`POST`,body:{type:n.type,...r?{comment:r}:void 0}}),`thread message feedback response`);return{feedback_id:Q(i.feedback_id,`feedback_id`),type:bl(i.type,`type`,du),...`comment`in i?{comment:xl(i.comment,`comment`)}:void 0}}},mu=(e,t)=>{let n=Z(e,t);return{title:xl(n.title,`${t}.title`)??``,last_message_at:wl(n.last_message_at,`${t}.last_message_at`),metadata:n.metadata,external_id:xl(n.external_id,`${t}.external_id`),id:Q(n.id,`${t}.id`),project_id:Q(n.project_id,`${t}.project_id`),created_at:wl(n.created_at,`${t}.created_at`),updated_at:wl(n.updated_at,`${t}.updated_at`),workspace_id:Q(n.workspace_id,`${t}.workspace_id`),is_archived:Sl(n.is_archived,`${t}.is_archived`)}},hu=class{messages;cloud;constructor(e){this.cloud=e,this.messages=new pu(e)}async list(e){let t=e?.is_archived===void 0?e:{...e,is_archived:String(e.is_archived)};return{threads:_l(Z(await this.cloud.makeRequest(`/threads`,{query:t}),`thread list response`).threads,`threads`).map((e,t)=>mu(e,`threads[${t}]`))}}async get(e){return mu(Z(await this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`),`thread response`).thread,`thread`)}async create(e){return{thread_id:Q(Z(await this.cloud.makeRequest(`/threads`,{method:`POST`,body:e}),`thread create response`).thread_id,`thread_id`)}}async update(e,t){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`,{method:`PUT`,body:t})}async claim(e){return{moved:Cl(Z(await this.cloud.makeRequest(`/threads/claim`,{method:`POST`,body:e}),`thread claim response`).moved,`moved`)}}async delete(e){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`,{method:`DELETE`})}},gu=class{cloud;constructor(e){this.cloud=e}async list(e,t){return{messages:_l(Z(await this.cloud.makeRequest(`/projects/threads/${encodeURIComponent(e)}/messages`,{query:t}),`project thread message list response`).messages,`messages`).map((e,t)=>fu(e,`messages[${t}]`))}}},_u=class{messages;cloud;constructor(e){this.cloud=e,this.messages=new gu(e)}async list(e){return{threads:_l(Z(await this.cloud.makeRequest(`/projects/threads`,{query:{...e,...e?.is_archived===void 0?{}:{is_archived:String(e.is_archived)}}}),`project thread list response`).threads,`threads`).map((e,t)=>mu(e,`threads[${t}]`))}}},vu=class{threads;constructor(e){this.threads=new _u(e)}},yu=class{cloud;constructor(e){this.cloud=e}__internal_getAssistantOptions(e){return{api:`${this.cloud._baseUrl}/v1/runs/stream`,protocol:`ui-message-stream`,headers:async()=>{let e=await this.cloud._auth.getAuthHeaders();if(!e)throw Error(`Authorization failed`);return{...e,Accept:`text/plain`,"Aui-Sdk":this.cloud.sdkHeader()}},body:async t=>{let n=t?.threadId;if(n===void 0)throw Error(`Assistant Cloud runs need a thread; the thread list adapter has not assigned a remote id to this thread yet.`);return{assistant_id:e,response_format:`vercel-ai-data-stream/v1`,thread_id:n}}}}async stream(e){let t=await this.cloud.makeRawRequest(`/runs/stream`,{method:`POST`,headers:{Accept:`text/plain`},body:e});if(!t.body)throw new gl(`Invalid Assistant Cloud response for "run stream": expected a response body`);let n=t.headers.get(`content-type`);if(n?.split(`;`,1)[0]?.trim().toLowerCase()!==`text/plain`)throw await t.body.cancel().catch(()=>void 0),new gl(`Invalid Assistant Cloud response for "run stream": expected a "text/plain" content type, received ${n?`"${n}"`:`no Content-Type header`}`);return Ra.fromResponse(t,new mo)}async report(e){return{run_id:Q(Z(await this.cloud.makeRequest(`/runs`,{method:`POST`,body:e}),`run report response`).run_id,`run_id`)}}},bu=class{cloud;constructor(e){this.cloud=e}async pdfToImages(e){let t=Z(await this.cloud.makeRequest(`/files/pdf-to-images`,{method:`POST`,body:e}),`PDF conversion response`);return{success:Sl(t.success,`PDF conversion response.success`),urls:_l(t.urls,`PDF conversion response.urls`).map((e,t)=>Q(e,`PDF conversion response.urls[${t}]`)),message:Q(t.message,`PDF conversion response.message`)}}async generatePresignedUploadUrl(e){let t=Z(await this.cloud.makeRequest(`/files/attachments/generate-presigned-upload-url`,{method:`POST`,body:e}),`presigned upload response`);return{success:Sl(t.success,`presigned upload response.success`),signedUrl:Q(t.signedUrl,`presigned upload response.signedUrl`),expiresAt:Q(t.expiresAt,`presigned upload response.expiresAt`),publicUrl:Q(t.publicUrl,`presigned upload response.publicUrl`),...`key`in t?{key:Q(t.key,`presigned upload response.key`)}:{}}}async generatePresignedDownloadUrl(e){let t=Z(await this.cloud.makeRequest(`/files/attachments/generate-presigned-download-url`,{method:`POST`,body:e}),`presigned download response`);return{signedUrl:Q(t.signedUrl,`presigned download response.signedUrl`),expiresAt:Q(t.expiresAt,`presigned download response.expiresAt`),key:Q(t.key,`presigned download response.key`)}}},xu=class{threads;projects;auth;runs;files;events;scores;telemetry;registerSdk;constructor(e){let t=new Xl(e);this.registerSdk=t.registerSdk;let n=e.telemetry,r=n===!1?{enabled:!1}:n===!0||n===void 0?{enabled:!0}:{...n,enabled:n.enabled!==!1};this.telemetry=new Proxy(r,{set:(e,t,n)=>{let r=Reflect.set(e,t,n);return(t===`enabled`||t===`events`)&&(e.enabled===!1||e.events===!1)&&nu(this.events),r}}),this.threads=new hu(t),this.projects=new vu(t),this.auth={tokens:new uu(t)},this.runs=new yu(t),this.files=new bu(t),this.events=new ru(t,()=>this.telemetry.enabled!==!1&&this.telemetry.events!==!1),this.scores=new lu(t)}},Su=256;function Cu(e,t,n){e.delete(t),e.set(t,n),e.size>Su&&e.delete(e.keys().next().value)}function wu(e,t){e.delete(t),e.add(t),e.size>Su&&e.delete(e.values().next().value)}var Tu=(e,t)=>({thread_id:e,...t===void 0?void 0:{message_id:t}}),Eu=class{runStartedAt=new Map;runEndedAt=new Map;shownErrors=new Set;shownSuggestions=new Set;getCloud;resolveIds;constructor(e,t=Tu){this.getCloud=typeof e==`function`?e:()=>e,this.resolveIds=t}runStarted(e){this.runStartedAt.set(e,Date.now()),this.shownErrors.delete(e)}runEnded(e){this.runStartedAt.delete(e),Cu(this.runEndedAt,e,Date.now())}runStopped(e){let t=this.runStartedAt.get(e);if(t===void 0)return;let n=Date.now();this.runStartedAt.delete(e),Cu(this.runEndedAt,e,n),this.track(`run_stopped`,e,void 0,{value:Math.max(0,n-t)})}messageSent(e,t){let n=this.runEndedAt.get(e);this.track(`message_sent`,e,t.messageId,{props:{chars:t.chars,attachments:t.attachments},...n===void 0?void 0:{value:Math.max(0,Date.now()-n)}},{awaitThread:!0})}messageEdited(e,t){this.track(`message_edited`,e,t.messageId,{props:{chars:t.chars}})}messageRegenerated(e,t){this.track(`message_regenerated`,e,t)}errorShown(e,t){this.shownErrors.has(e)||(wu(this.shownErrors,e),this.track(`error_shown`,e,t.messageId,{props:{reason:t.reason}}))}suggestionsShown(e,t){this.shownSuggestions.has(e)||(wu(this.shownSuggestions,e),this.track(`suggestions_shown`,e,void 0,{value:t}))}suggestionClicked(e){this.track(`suggestion_clicked`,e)}attachmentAdded(e,t){this.track(`attachment_added`,e,t.messageId,{...t.contentType?{props:{type:t.contentType}}:void 0})}attachmentFailed(e,t){this.track(`attachment_failed`,e,t.messageId,{...t.contentType?{props:{type:t.contentType}}:void 0})}voiceStarted(e){this.track(`voice_started`,e)}speechStarted(e,t){this.track(`speech_started`,e,t)}branchSwitched(e,t){this.track(`branch_switched`,e,t)}messageCopied(e,t){this.track(`message_copied`,e,t)}toolApproved(e,t,n,r){this.track(`tool_approved`,e,t,{props:{toolCallId:n,toolName:r}})}toolRejected(e,t,n,r){this.track(`tool_rejected`,e,t,{props:{toolCallId:n,toolName:r}})}threadSwitched(e){this.track(`thread_switched`,e)}track(e,t,n,r={},i={awaitThread:!1}){Promise.resolve().then(()=>this.resolveIds(t,n,i)).then(t=>{t&&(e===`thread_switched`&&!t.thread_id||this.getCloud().events.track({kind:e,...r,...t}))}).catch(()=>{})}},Du=200,Ou=class{idMapping=new Map;getCloud;constructor(e){this.getCloud=typeof e==`function`?e:()=>e}async append(e,t,n,r,i){let a=this.getCloud(),o=this.idMapping.get(t);if(o instanceof Promise){await o;return}let s=(async()=>{let t=n?this.idMapping.get(n):void 0,o=n?await t??n:null,{message_id:s}=await a.threads.messages.create(e,{parent_id:o,format:r,content:i});return s})();this.idMapping.set(t,s);try{let e=await s;this.idMapping.get(t)===s&&this.idMapping.set(t,e)}catch(e){throw this.idMapping.get(t)===s&&this.idMapping.delete(t),e}}async update(e,t,n,r){let i=this.getCloud(),a=await this.getRemoteId(t);if(!a){console.warn(`Skipping update for message ${t}: no remote id is mapped.`);return}await i.threads.messages.update(e,a,{content:r})}isPersisted(e){return this.idMapping.has(e)}async getRemoteId(e){let t=this.idMapping.get(e);if(t)return t}getResolvedRemoteId(e){let t=this.idMapping.get(e);return typeof t==`string`?t:void 0}record(e,t){this.idMapping.set(e,t)}async load(e,t){let n=this.idMapping,r=this.getCloud(),i=[],a=new Set,o;for(;;){let n=await r.threads.messages.list(e,{...t?{format:t}:void 0,limit:Du,...o?{after:o}:void 0}),s=n.messages.at(-1);if(!s)break;let c=n.messages.filter(e=>!a.has(e.id));if(c.length===0)break;for(let e of c)a.add(e.id);if(i.push(...c),n.messages.length<Du)break;o=s.id}if(this.idMapping===n)for(let e of i){let t=n.get(e.id);t===void 0?n.set(e.id,e.id):t instanceof Promise&&t.catch(()=>{let r=n.get(e.id);(r===void 0||r===t)&&n.set(e.id,e.id)})}return i}reset(){this.idMapping=new Map}},ku=5e4,Au=/^[A-Za-z0-9+/]+={0,2}$/;function ju(e,t=`completed`){if(e.isError)return{status:`error`};if(e.isAbort)return{status:`incomplete`,outcome:`aborted`};if(e.isDisconnect)return{status:`incomplete`,outcome:`disconnected`};switch(e.finishReason){case`length`:return{status:`incomplete`,outcome:`length`};case`content-filter`:case`content_filter`:return{status:`incomplete`,outcome:`content_filter`};case`cancelled`:return{status:`incomplete`,outcome:`aborted`};case`error`:return{status:`error`};default:return{status:e.finishReason===void 0?t:`completed`}}}var Mu=64,Nu=2048;function Pu(e){if(e==null)return{};let t=typeof e==`object`?e:void 0,n=typeof e==`string`?e:typeof t?.message==`string`?t.message:void 0,r=typeof t?.code==`string`?t.code:typeof t?.name==`string`&&t.name!==`Error`?t.name:void 0;return{...n?{error:n.slice(0,Nu)}:void 0,...r?{errorCode:r.slice(0,Mu)}:void 0}}function Fu(e){return e.length<=ku?e:e.slice(0,ku)}function Iu(e){if(e!=null)try{return Fu(JSON.stringify(e))}catch{return}}var Lu=e=>(e.length*3/4/1024).toFixed(1),Ru=e=>{if(typeof e!=`string`)return!1;let t=e.slice(0,200);return t.length>0&&t.length%4==0&&Au.test(t)};function zu(e){if(!e||typeof e!=`object`)return e;let t=e;if((t.type===`image`||t.type===`audio`)&&Ru(t.data))return{...t,data:`[${String(t.type)}: ${Lu(t.data)}KB]`};if(t.type===`resource`&&t.resource&&typeof t.resource==`object`){let e=t.resource;if(Ru(e.blob))return{...t,resource:{...e,blob:`[resource: ${Lu(e.blob)}KB]`}}}return e}function Bu(e){if(e!=null){try{let t=typeof e==`string`?JSON.parse(e):e;if(Array.isArray(t))return Fu(JSON.stringify(t.map(zu)));if(typeof t==`object`){let e=t.content;if(Array.isArray(e))return Fu(JSON.stringify({...t,content:e.map(zu)}))}}catch{}return Iu(e)}}function Vu(e){let{toolName:t,toolCallId:n,args:r,argsText:i,result:a,toolSource:o}=e,s={tool_name:t,tool_call_id:n},c=i==null?Iu(r):Fu(i);c!==void 0&&(s.tool_args=c);let l=o===`mcp`?Bu(a):Iu(a);return l!==void 0&&(s.tool_result=l),o&&(s.tool_source=o),s}function Hu(e){if(!e)return;if(typeof e.modelId==`string`)return e.modelId;let t=e.custom;if(typeof t?.modelId==`string`)return t.modelId;let n=e.steps;if(Array.isArray(n))for(let e of n){if(!e||typeof e!=`object`)continue;let t=e.response;if(!t||typeof t!=`object`)continue;let n=t.modelId;if(typeof n==`string`)return n}}function Uu(e,t){if(!t)return;let n=Xu(t);n&&(n.inputTokens!==void 0&&(e.input_tokens=n.inputTokens),n.outputTokens!==void 0&&(e.output_tokens=n.outputTokens),n.reasoningTokens!==void 0&&(e.reasoning_tokens=n.reasoningTokens),n.cachedInputTokens!==void 0&&(e.cached_input_tokens=n.cachedInputTokens))}function Wu(e){let t={},n=e.usage?Xu(e.usage):void 0;return n?.inputTokens!==void 0&&(t.input_tokens=n.inputTokens),n?.outputTokens!==void 0&&(t.output_tokens=n.outputTokens),n?.reasoningTokens!==void 0&&(t.reasoning_tokens=n.reasoningTokens),n?.cachedInputTokens!==void 0&&(t.cached_input_tokens=n.cachedInputTokens),e.toolCalls!==void 0&&(t.tool_calls=e.toolCalls),e.startMs!==void 0&&(t.start_ms=e.startMs),e.endMs!==void 0&&(t.end_ms=e.endMs),e.finishReason!==void 0&&(t.finish_reason=e.finishReason.slice(0,32)),e.input!==void 0&&(t.input=Fu(e.input)),t}function Gu(e){if(!e)return;let t=[],n=new Set;for(let r of e){let e=r.trim().slice(0,64).trim();if(!(!e||n.has(e))&&(n.add(e),t.push(e),t.length===20))break}return t.length>0?t:void 0}function Ku(e){if(!(e===void 0||!Number.isFinite(e)))return Math.max(0,Math.round(e))}function qu(e){if(!(e===void 0||!Number.isFinite(e)||e<0))return e}function Ju(e,t){if(!t)return;let n={},r=qu(t.input);r!==void 0&&(n.input=r);let i=qu(t.inputCachedTokens);i!==void 0&&(n.input_cached_tokens=i);let a=qu(t.output);a!==void 0&&(n.output=a);let o=qu(t.total);o!==void 0&&(n.total=o),Object.keys(n).length>0&&(e.cost_details=n)}function Yu(e){let t={thread_id:e.threadId,status:e.status},n=e.traceId?.toLowerCase();n&&/^[0-9a-f]{32}$/.test(n)&&(t.trace_id=n);let r=e.rootSpanId?.toLowerCase();r&&/^[0-9a-f]{16}$/.test(r)&&(t.root_span_id=r),e.outcome!==void 0&&(t.outcome_type=e.outcome),e.errorCode!==void 0&&(t.error_code=e.errorCode),e.error!==void 0&&(t.error=e.error),e.messageId!==void 0&&(t.message_id=e.messageId),e.modelId!==void 0&&(t.model_id=e.modelId),e.provider!==void 0&&(t.provider=e.provider,t.provider_type=e.provider),Uu(t,e.usage),e.steps===void 0?e.totalSteps!==void 0&&(t.total_steps=e.totalSteps):(t.steps=e.steps.map(Wu),t.total_steps=e.steps.length),e.toolCalls!==void 0&&(t.tool_calls=e.toolCalls);let i=Ku(e.durationMs);i!==void 0&&(t.duration_ms=i);let a=Ku(e.firstTokenMs);a!==void 0&&(t.first_token_ms=a);let o=qu(e.costUsd);o!==void 0&&(t.cost_usd=o),Ju(t,e.costDetails),e.outputText!==void 0&&(t.output_text=Fu(e.outputText)),e.attributes!==void 0&&(t.attributes=e.attributes),e.metadata!==void 0&&(t.metadata=e.metadata),e.telemetry?.environment!==void 0&&(t.environment=e.telemetry.environment),e.telemetry?.release!==void 0&&(t.release=e.telemetry.release);let s=Gu(e.telemetry?.tags);return s!==void 0&&(t.tags=s),t}function Xu(e){let t=e.inputTokens??e.promptTokens,n=e.outputTokens??e.completionTokens,r=e.reasoningTokens??e.outputTokenDetails?.reasoningTokens,i=e.cachedInputTokens??e.inputTokenDetails?.cacheReadTokens;if(t!=null||n!=null||r!=null||i!=null)return{...t==null?void 0:{inputTokens:t},...n==null?void 0:{outputTokens:n},...r==null?void 0:{reasoningTokens:r},...i==null?void 0:{cachedInputTokens:i}}}var Zu=class{reported=new Set;getCloud;constructor(e){this.getCloud=typeof e==`function`?e:()=>e}async report(e,t){let n;try{let r=this.getCloud();if(!r.telemetry.enabled||t!==void 0&&this.reported.has(t))return;let i=Yu({...e,telemetry:r.telemetry}),{beforeReport:a}=r.telemetry,o=a?a(i):i;if(!o)return;t!==void 0&&(this.reported.add(t),n=t),await r.runs.report(o)}catch(e){n!==void 0&&Qu(e)&&this.reported.delete(n);return}}},Qu=e=>e instanceof Jl&&e.status===429,$u=(e,t)=>({append:async(n,r)=>{let i=t.getId(r.message),a=t.encode(r);return e.append(n,i,r.parentId,t.format,a)},update:e.update?async(n,r,i)=>{let a=t.encode(r);return e.update(n,i,t.format,a)}:void 0,load:async n=>({messages:(await e.load(n,t.format)).filter(e=>e.format===t.format).map(e=>t.decode({id:e.id,parent_id:e.parent_id,format:e.format,content:e.content})).reverse()}),isPersisted:t=>e.isPersisted(t)});function ed(e){return typeof e==`object`&&!!e}function td(e){return ed(e)&&typeof e.type==`string`}function nd(e){if(typeof e.toolCallId!=`string`)return;let t=e.type.startsWith(`tool-`);if(!t&&e.type!==`dynamic-tool`)return;let n=t?e.type.slice(5):typeof e.toolName==`string`?e.toolName:void 0;if(n)return Vu({toolName:n,toolCallId:e.toolCallId,args:e.input??e.args,result:e.output??e.result,toolSource:t?`frontend`:`mcp`})}function rd(e,t){let n=ed(t?.samplingCalls)?t.samplingCalls:void 0;if(n)for(let t of e){let e=n[t.tool_call_id];Array.isArray(e)&&e.length>0&&(t.sampling_calls=e)}}function id(e){let t=e?.steps;return Array.isArray(t)?t.map(e=>ed(e)&&ed(e.usage)?e.usage:void 0):[]}function ad(e){let t={};for(let n of e)n.inputTokens!=null&&(t.inputTokens=(t.inputTokens??0)+n.inputTokens),n.outputTokens!=null&&(t.outputTokens=(t.outputTokens??0)+n.outputTokens),n.reasoningTokens!=null&&(t.reasoningTokens=(t.reasoningTokens??0)+n.reasoningTokens),n.cachedInputTokens!=null&&(t.cachedInputTokens=(t.cachedInputTokens??0)+n.cachedInputTokens);return t}function od(e){let t=ed(e?.usage)?Xu(e.usage):void 0;if(t)return t;let n=id(e).flatMap(e=>{let t=e?Xu(e):void 0;return t?[t]:[]});return n.length>0?ad(n):void 0}function sd(e){let t=[],n=[],r=[],i=[],a;for(let o of e){if(o.role!==`assistant`)continue;a=o;let e=ed(o.metadata)?o.metadata:void 0,s=id(e),c=[],l,u=-1;for(let e of o.parts){if(!td(e))continue;if(e.type===`step-start`){u+=1;let e=s[u];l=e?{usage:e}:{},r.push(l);continue}if(e.type===`text`&&typeof e.text==`string`&&e.text){t.push(e.text);continue}let i=nd(e);i&&(n.push(i),c.push(i),l&&(l.toolCalls=[...l.toolCalls??[],i],l.finishReason=`tool-calls`))}rd(c,e);let d=od(e);d&&i.push(d)}if(!a)return null;let o=ed(a.metadata)?a.metadata:void 0,s=i.length>0?ad(i):void 0,c=Hu(o),l=t.length>0||n.length>0;return{...a.id===void 0?void 0:{assistantMessageId:a.id},status:l?`completed`:`incomplete`,...n.length>0?{toolCalls:n}:void 0,...r.length>0?{steps:r,totalSteps:r.length}:void 0,...t.length>0?{outputText:Fu(t.join(``))}:void 0,...s?{usage:s}:void 0,...c?{modelId:c}:void 0,...o?{metadata:o}:void 0}}var cd=new WeakMap,ld=new WeakMap,ud=e=>{let t=ld.get(e);return t||(t={settled:new Set,reported:new Set},ld.set(e,t)),t},dd=e=>e.role===`assistant`&&(e.status.type===`complete`||e.status.type===`incomplete`),fd=(e,t)=>{let n=Fi(t);if(!e)return n;if(!n)return e;let r=Math.max(e.omitted??0,n.omitted??0),i={entries:e.entries,...r?{omitted:r}:void 0};for(let e of n.entries)i.entries.some(t=>t.type===e.type&&t.occurredAt===e.occurredAt&&_o(t.payload,e.payload))||(i=Ni(i,e));return i},pd=new Set([401,403,408,429]),md=new Set([402,404]),hd=e=>e instanceof Jl&&e.status>=400&&e.status<500&&!pd.has(e.status),gd=class{cloudRef;getAui;runReporter;copiedThreads=new Map;copyQueues=new Map;constructor(e,t){this.cloudRef=e,this.getAui=t,this.runReporter=new Zu(()=>this.cloudRef.current)}get aui(){return this.getAui()}getCloud(){return this.cloudRef.current}ownsThread(e){let t=this.aui.threadListItem;if(!t.source)return!1;let{id:n,remoteId:r}=t.getState();return n===e||r===e}getPersistence(e=this.aui.threadListItem){let t=wn(e);return cd.has(t)||cd.set(t,new Ou(()=>this.cloudRef.current)),cd.get(t)}get _persistence(){return this.getPersistence()}async resolveEngagementEventIds(e,t,n){let r=this.getThreadListItem(e);if(!r)return;let i=r.getState().remoteId;!i&&n?.awaitThread&&(i=await r.initialize().then(e=>e.remoteId).catch(()=>void 0));let a=t?this.getPersistence(r).getResolvedRemoteId(t):void 0;return{...i?{thread_id:i}:void 0,...a?{message_id:a}:void 0}}feedback={submit:({message:e,type:t,comment:n})=>{(async()=>{let r=this.tryGetKeyedThreadListItem(),i=r?.getState().remoteId;if(!r||!i){console.warn(`[assistant-ui] Skipping feedback for message ${e.id}: the thread has no remote id.`);return}let a=await this.getPersistence(r).getRemoteId(e.id);if(!a){console.warn(`[assistant-ui] Skipping feedback for message ${e.id}: no cloud message id is mapped.`);return}await this.cloudRef.current.threads.messages.feedback(i,a,{type:t,...n?{comment:n}:void 0})})().catch(e=>{console.error(`[assistant-ui] Cloud feedback submission failed:`,e)})}};tryGetKeyedThreadListItem(){let e=this.aui.threadListItem;if(!e.source)return;let t=e.getState().id;if(t!==void 0)return this.aui.threads.getState().threadItems.some(e=>e.id===t||e.remoteId===t)?this.aui.threads.item({id:t}):e}getThreadListItem(e){let t=this.aui.threadListItem;if(t.source){let n=t.getState();if(n.id===e||n.remoteId===e)return t}let n=this.aui.threads.getState().threadItems.find(t=>t.id===e||t.remoteId===e);return n?this.aui.threads.item({id:n.id}):void 0}withFormat(e){let t=this,n,r=()=>{let e=t.tryGetKeyedThreadListItem();return e&&(n=e),n},i=()=>n??r(),a=n=>$u(t.getPersistence(n),e);return{pin(){r()},async append(e){let t=i();if(!t)throw Error(`Cannot persist cloud history without a thread list item.`);let n=t.getState().remoteId??(await t.initialize()).remoteId;await a(t).append(n,e)},async update(e,t){let n=i(),r=n?.getState().remoteId;!r||!n||await a(n).update?.(r,e,t)},async delete(){throw Error(`Assistant Cloud does not support deleting thread messages yet.`)},reportTelemetry(n,r){let a=n.map(t=>e.encode(t));t._reportRunTelemetry(e.format,a,r,i(),yd(vd(n,e),r?.message?bd(r.message,`aui/v0`):void 0))},async load(){let e=r(),n=t.aui.threadListItem,i=n.source?n.getState().remoteId:void 0;return i?a(e??n).load(i):{messages:[]}}}}async append({parentId:e,message:t}){let{remoteId:n}=await this.aui.threadListItem.initialize(),r=this._persistence;await this._writeMessage(r,n,t,i=>r.append(n,t.id,e,`aui/v0`,i))}async update(e){let t=this._persistence;if(!t.isPersisted(e.message.id))return this.append(e);let{message:n}=e,r=this.aui.threadListItem.getState().remoteId;r&&await this._writeMessage(t,r,n,e=>t.update(r,n.id,`aui/v0`,e))}get unstable_copy(){let e=this.cloudRef.current?.telemetry;return e?.enabled===!1||e?.messages===!1?void 0:this.copy}copy=async(e,t)=>{let n=this.cloudRef.current;if(t.length===0)return;let r=this.tryGetKeyedThreadListItem();if(!r)throw Error(`Cannot copy cloud history without a thread list item.`);let i=(await r.initialize()).remoteId,a=this.getPersistence(r),o=(this.copyQueues.get(i)??Promise.resolve()).catch(()=>void 0).then(()=>this.copyBranch(n,i,a,e,t));this.copyQueues.set(i,o);try{await o}finally{this.copyQueues.get(i)===o&&this.copyQueues.delete(i)}};async copyBranch(e,t,n,r,i){let a=this.copiedThreads.get(t);a||(a=(async()=>{let r={stored:new Set,refused:new Set,closed:!1,interactions:new Map},i=new Set,a;for(;;){let o=await e.threads.messages.list(t,{limit:200,...a?{after:a}:void 0}),s=o.messages.filter(e=>!i.has(e.id));for(let e of s){if(i.add(e.id),!e.external_id||e.format!==`aui/v0`)continue;r.stored.add(e.external_id),n.record(e.external_id,e.id);let t=pl(e);for(let e of t?.message.content??[]){if(e.type!==`tool-call`)continue;let t=fd(r.interactions.get(e.toolCallId),e.unstable_interactions);t&&r.interactions.set(e.toolCallId,t)}}let c=o.messages.at(-1);if(s.length===0||o.messages.length<200||!c)break;a=c.id}return r})(),this.copiedThreads.set(t,a));let o;try{o=await a}catch(e){throw this.copiedThreads.get(t)===a&&this.copiedThreads.delete(t),e}if(o.closed)return;let s=r.filter(e=>e.id.length>0&&e.id.length<=255),c=new Set(i),l=0,u;for(let r=0;r<s.length;r++)if(c.has(s[r].id))for(;l<=r;l++){let i=s[l];if(l!==r&&(o.stored.has(i.id)||o.refused.has(i.id))){o.stored.has(i.id)&&(u=i.id);continue}let a=ll(i),c={...a,content:a.content.map(e=>{if(e.type!==`tool-call`)return e;let t=fd(o.interactions.get(e.toolCallId),e.unstable_interactions);return{...e,...t?{unstable_interactions:t}:void 0}})},d;try{({message_id:d}=await e.threads.messages.create(t,{parent_id:null,format:`aui/v0`,content:c,external_id:i.id,...u?{parent_external_id:u}:void 0}))}catch(e){if(!hd(e))throw e;if(md.has(e.status)||o.stored.size===0&&o.refused.size>0){o.closed=!0,console.warn(`[assistant-ui] The cloud refused copies to thread ${t}; the dashboard shows the conversation as far as it was copied.`,e);return}o.refused.add(i.id),console.warn(`[assistant-ui] The cloud refused the copy of message ${i.id}; the dashboard shows the conversation without it.`,e);continue}o.stored.add(i.id),o.refused.delete(i.id),u=i.id,n.record(i.id,d);for(let e of c.content)e.type===`tool-call`&&e.unstable_interactions&&o.interactions.set(e.toolCallId,e.unstable_interactions)}}async _writeMessage(e,t,n,r){let i=ll(n),a=ud(e),o=dd(n)&&!a.settled.has(n.id);if(await r(i),!o||(a.settled.add(n.id),a.reported.has(n.id))||!this.cloudRef.current.telemetry.enabled)return;let s=Td(`aui/v0`,i);s&&(a.reported.add(n.id),this._sendReport(t,s,void 0,void 0,bd(n,`aui/v0`),e))}async delete(){throw Error(`Assistant Cloud does not support deleting thread messages yet.`)}async load(){let e=this.aui.threadListItem.getState().remoteId;if(!e)return{messages:[]};let t=this._persistence,n=(await t.load(e,`aui/v0`)).filter(e=>e.format===`aui/v0`).reverse(),r=[],i=new Set,{settled:a}=ud(t);for(let e of n){let t=pl(e);t&&(t.parentId&&!i.has(t.parentId)||(i.add(t.message.id),dd(t.message)&&a.add(t.message.id),r.push(t)))}return{messages:r}}_reportRunTelemetry(e,t,n,r,i){let a=r??this.aui.threadListItem,o=a.getState().remoteId;if(!o)return;let s=Ed(e,t)??(i?.status===void 0?void 0:{status:`incomplete`});s&&this._sendReport(o,s,n?.durationMs,n?.stepTimestamps,i,this.getPersistence(a))}_sendReport(e,t,n,r,i,a=this._persistence){let o=_d(t.steps,r),s=i?.localMessageId?a.getResolvedRemoteId(i.localMessageId):void 0;this.runReporter.report({threadId:e,status:i?.status??t.status,outcome:i?.outcomeType,error:i?.error,errorCode:i?.errorCode,messageId:s,traceId:i?.traceId,modelId:t.modelId,provider:i?.provider,usage:t.usage,steps:o,totalSteps:t.totalSteps,toolCalls:t.toolCalls,durationMs:n,firstTokenMs:i?.firstTokenMs,outputText:t.outputText,metadata:t.metadata})}};function _d(e,t){if(!t)return e;if(!e)return t.map(({start_ms:e,end_ms:t})=>({startMs:e,endMs:t}));let n=Math.min(e.length,t.length);return e.map((e,r)=>({...e,...r<n?{startMs:t[r].start_ms,endMs:t[r].end_ms}:void 0}))}function vd(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n],i=bd(r.message,t.format,t.getId(r.message));if(i)return i}}function yd(e,t){if(!t)return e;let{localMessageId:n,...r}=t;return{...e,...r}}function bd(e,t,n){if(!$(e)||e.role!==`assistant`)return;let r=$(e.status)?e.status:void 0,i=$(e.metadata)?e.metadata:void 0,a=$(i?.custom)?i.custom:void 0,o=($(i?.timing)?i.timing:void 0)?.firstTokenTime,s=typeof o==`number`&&Number.isFinite(o)?Math.round(o):void 0,c=r?.type===`incomplete`?typeof r.reason==`string`?r.reason:void 0:typeof i?.finishReason==`string`?i.finishReason:void 0,l=r?.type===`incomplete`&&r.reason===`error`,u=ju({finishReason:c,isError:l}),d=u.outcome,f=u.status===`error`?`error`:r?.type===`incomplete`?`incomplete`:c===void 0?void 0:u.status,p=l?Pu(r.error):{},m=n??(typeof e.id==`string`?e.id:void 0),h=t===`aui/v0`?a?.traceId:t===`ai-sdk/v6`?i?.traceId:void 0,g=typeof a?.provider==`string`?a.provider:typeof i?.provider==`string`?i.provider:void 0;return{...m?{localMessageId:m}:void 0,...f===void 0?void 0:{status:f},...d?{outcomeType:d}:void 0,...p,...s!=null&&s>=0?{firstTokenMs:s}:void 0,...typeof h==`string`?{traceId:h}:void 0,...g===void 0?void 0:{provider:g}}}function $(e){return typeof e==`object`&&!!e}var xd=[`inputTokens`,`outputTokens`,`reasoningTokens`,`cachedInputTokens`,`promptTokens`,`completionTokens`],Sd=e=>typeof e==`number`&&Number.isFinite(e)&&e>=0?e:void 0,Cd=e=>{if(!$(e)||Array.isArray(e))return;let t={};for(let n of xd){let r=Sd(e[n]);r!==void 0&&(t[n]=r)}let n=$(e.inputTokenDetails)&&!Array.isArray(e.inputTokenDetails)?Sd(e.inputTokenDetails.cacheReadTokens):void 0;n!==void 0&&(t.inputTokenDetails={cacheReadTokens:n});let r=$(e.outputTokenDetails)&&!Array.isArray(e.outputTokenDetails)?Sd(e.outputTokenDetails.reasoningTokens):void 0;return r!==void 0&&(t.outputTokenDetails={reasoningTokens:r}),Object.keys(t).length>0?t:void 0},wd=e=>Ma(e).map(e=>{let t=Cd(e.usage);return t?{usage:t}:{}});function Td(e,t){switch(e){case`aui/v0`:return Dd(t);case`ai-sdk/v6`:return sd([t]);default:return null}}function Ed(e,t){if(e===`ai-sdk/v6`)return sd(t);for(let n=t.length-1;n>=0;n--){let r=Td(e,t[n]);if(r)return r}return null}function Dd(e){let t=e;if(t.role!==`assistant`||t.status!==void 0&&!Aa(t.status))return null;let n=$(t.status)&&typeof t.status.type==`string`?t.status.type:void 0;if(n===`running`||n===`requires-action`)return null;let r=t.content?.filter(e=>e.type===`tool-call`&&e.toolName&&e.toolCallId).map(e=>Vu({toolName:e.toolName,toolCallId:e.toolCallId,args:e.args,result:e.result,argsText:e.argsText})),i=t.content?.filter(e=>e.type===`text`&&e.text),a=i&&i.length>0?Fu(i.map(e=>e.text).join(``)):void 0,o=wd(t.metadata?.steps),s,c,l,u;if(o&&o.length>0){let e=0,t=0,n=0,r=0,i=!1,a=!1,d=!1,f=!1;for(let s of o){if(!s.usage)continue;let o=Xu(s.usage);o&&(o.inputTokens!=null&&(e+=o.inputTokens,i=!0),o.outputTokens!=null&&(t+=o.outputTokens,a=!0),o.reasoningTokens!=null&&(n+=o.reasoningTokens,d=!0),o.cachedInputTokens!=null&&(r+=o.cachedInputTokens,f=!0))}s=i?e:void 0,c=a?t:void 0,l=d?n:void 0,u=f?r:void 0}let d=n===`incomplete`?`incomplete`:`completed`,f=t.metadata?.custom,p=Hu(t.metadata),m=o.length>0?o:void 0;return{status:d,...r&&r.length>0?{toolCalls:r}:void 0,...o?.length?{totalSteps:o.length}:void 0,...s!=null||c!=null||l!=null||u!=null?{usage:{...s==null?void 0:{inputTokens:s},...c==null?void 0:{outputTokens:c},...l==null?void 0:{reasoningTokens:l},...u==null?void 0:{cachedInputTokens:u}}}:void 0,...a==null?void 0:{outputText:a},...f?{metadata:f}:void 0,...m?{steps:m}:void 0,...p?{modelId:p}:void 0}}function Od(e){let t=Xr(),n=j(t);N(()=>{n.current=t});let[r]=A(()=>new gd(e,()=>n.current));return Fd(r,t),r}var kd=new WeakMap,Ad=(e,t)=>{let n;for(let r of e.mounted.keys()){if(t!==void 0&&r.ownsThread(t))return r;n??=r}return n??e.lastMounted},jd=e=>{let t={mounted:new Map,lastMounted:e,reporter:new Eu(()=>Ad(t).getCloud(),(e,n,r)=>Ad(t,e).resolveEngagementEventIds(e,n,r)),host:void 0,dispose:void 0};return t},Md=(e,t)=>{let n=()=>{let{mainThreadId:n}=e.threads.getState(),{isEmpty:r,suggestions:i}=e.thread.getState();!r||i.length===0||t.suggestionsShown(n,i.length)},r=[e.on({scope:`*`,event:`threads.selectionChanged`},e=>{t.threadSwitched(e.threadId)}),e.on({scope:`*`,event:`composer.send`},e=>{e.messageId?t.messageEdited(e.threadId,{messageId:e.messageId,chars:e.chars}):t.messageSent(e.threadId,{chars:e.chars,attachments:e.attachments}),e.suggestion&&t.suggestionClicked(e.threadId)}),e.on({scope:`*`,event:`composer.attachmentAdd`},e=>{t.attachmentAdded(e.threadId,{messageId:e.messageId,contentType:e.contentType})}),e.on({scope:`*`,event:`composer.attachmentAddError`},e=>{t.attachmentFailed(e.threadId,{messageId:e.messageId,contentType:e.contentType})}),e.on({scope:`*`,event:`composer.cancel`},e=>{t.runStopped(e.threadId)}),e.on({scope:`*`,event:`thread.runStart`},e=>{t.runStarted(e.threadId)}),e.on({scope:`*`,event:`thread.runEnd`},e=>{t.runEnded(e.threadId)}),e.on({scope:`*`,event:`thread.cancelRun`},e=>{t.runStopped(e.threadId)}),e.on({scope:`*`,event:`thread.voiceStarted`},e=>{t.voiceStarted(e.threadId)}),e.on({scope:`*`,event:`message.reload`},e=>{t.messageRegenerated(e.threadId,e.messageId)}),e.on({scope:`*`,event:`message.branchSwitched`},e=>{t.branchSwitched(e.threadId,e.messageId)}),e.on({scope:`*`,event:`message.copied`},e=>{t.messageCopied(e.threadId,e.messageId)}),e.on({scope:`*`,event:`thread.toolApprovalAnswered`},e=>{e.approved?t.toolApproved(e.threadId,e.messageId,e.toolCallId,e.toolName):t.toolRejected(e.threadId,e.messageId,e.toolCallId,e.toolName)}),e.on({scope:`*`,event:`message.speak`},e=>{t.speechStarted(e.threadId,e.messageId)}),e.on({scope:`*`,event:`message.error`},e=>{t.errorShown(e.threadId,{messageId:e.messageId,reason:e.reason})}),e.subscribe(n)];return n(),()=>ei(r)},Nd=(e,t)=>{e.host=t,e.dispose=Md(t,e.reporter)},Pd=e=>{let t=e.dispose;e.host=void 0,e.dispose=void 0,t?.()},Fd=(e,t)=>{let n=x(4),r,i;n[0]!==e||n[1]!==t?(r=()=>{let n=wn(t.threads),r=kd.get(n);r||(r=jd(e),kd.set(n,r));let i=r;return i.mounted.set(e,t),i.lastMounted=e,i.host===void 0&&Nd(i,t),()=>{if(i.mounted.delete(e),i.host!==t)return;Pd(i);let n=i.mounted.values().next();n.done||Nd(i,n.value)}},i=[e,t],n[0]=e,n[1]=t,n[2]=r,n[3]=i):(r=n[2],i=n[3]),N(r,i)};function Id(e,t){return t||Ti(e)||`application/octet-stream`}var Ld=`application/octet-stream`,Rd=e=>e.startsWith(`image/`)?`image`:e.startsWith(`text/`)?`document`:`file`,zd=class{accept=`*`;getCloud;constructor(e){this.getCloud=typeof e==`function`?e:()=>e}uploadedUrls=new Map;activeUploads=new Map;async*add({file:e}){let t=W(),n=Rd(e.type),r=e.type||Ld,i={id:t,type:n,name:e.name,contentType:r,file:e,status:{type:`running`,reason:`uploading`,progress:0}},a=new AbortController,o={cancelled:!1,controller:a};this.activeUploads.set(t,o);try{if(yield i,o.cancelled)return;let{signedUrl:n,publicUrl:s}=await this.getCloud().files.generatePresignedUploadUrl({filename:e.name});if(o.cancelled)return;let c=await fetch(n,{method:`PUT`,body:e,headers:{"Content-Type":r},mode:`cors`,signal:a.signal});if(o.cancelled)return;if(!c.ok)throw Error(`Failed to upload file: ${c.status} ${c.statusText}`);this.uploadedUrls.set(t,s),i={...i,status:{type:`requires-action`,reason:`composer-send`}},yield i}catch(e){if(o.cancelled)return;console.error(`[assistant-ui] Failed to upload attachment:`,e),i={...i,status:{type:`incomplete`,reason:`error`,message:e instanceof Error?e.message:String(e)}},yield i}finally{this.activeUploads.get(t)===o&&this.activeUploads.delete(t)}}async remove(e){let t=this.activeUploads.get(e.id);t&&(t.cancelled=!0,t.controller.abort(),this.activeUploads.delete(e.id)),this.uploadedUrls.delete(e.id)}async send(e){let t=this.uploadedUrls.get(e.id);if(!t)throw Error(`Attachment not uploaded`);this.uploadedUrls.delete(e.id);let n;return n=e.type===`image`?[{type:`image`,image:t,filename:e.name}]:[{type:`file`,data:t,mimeType:Id(t,e.contentType),filename:e.name}],{...e,status:{type:`complete`},content:n}}},Bd=class{list(){return Promise.resolve({threads:[]})}rename(){return Promise.resolve()}updateCustom(){return Promise.resolve()}archive(){return Promise.resolve()}unarchive(){return Promise.resolve()}delete(){return Promise.resolve()}initialize(e){return Promise.resolve({remoteId:e,externalId:void 0})}generateTitle(){return Promise.resolve(new ReadableStream({start(e){e.close()}}))}fetch(e){return Promise.reject(Error(`Thread "${e}" not found in in-memory thread list.`))}},Vd={name:`@assistant-ui/core`,version:`0.3.24`},Hd=e=>K(e)?e:void 0,Ud=typeof process<`u`?{}.NEXT_PUBLIC_ASSISTANT_BASE_URL:void 0,Wd=Ud?new xu({baseUrl:Ud,anonymous:!0}):void 0,Gd=e=>{let t=Od(e),[n]=A(()=>new zd(()=>e.current));return M(()=>({history:t,attachments:n,feedback:t.feedback}),[t,n])},Kd=20,qd=e=>{let t={activeCursor:e,archivedCursor:void 0,activeExhausted:!1,archivedExhausted:!1};if(!e||!e.startsWith(`{`))return t;try{let n=JSON.parse(e);return K(n)?{activeCursor:typeof n.a==`string`?n.a:void 0,archivedCursor:typeof n.r==`string`?n.r:void 0,activeExhausted:n.ae===!0,archivedExhausted:n.re===!0}:t}catch{return t}},Jd=e=>{let t=typeof e==`function`?e:()=>e,n=function(){return Gd({get current(){return t().cloud??Wd}})},r=t().cloud??Wd;if(!r){let e=new Bd;return e.initialize=async e=>({remoteId:e,externalId:(await t().create?.(e))?.externalId}),e}r.registerSdk?.(Vd);let i=t().sdk;return i&&r.registerSdk?.(i),{list:async({after:e}={})=>{let{activeCursor:t,archivedCursor:n,activeExhausted:i,archivedExhausted:a}=qd(e),[{threads:o},{threads:s}]=await Promise.all([i?Promise.resolve({threads:[]}):r.threads.list({limit:Kd,...t?{after:t}:{}}),a?Promise.resolve({threads:[]}):r.threads.list({is_archived:!0,limit:Kd,...n?{after:n}:{}})]),c=!i&&o.length===Kd?o.at(-1)?.id:void 0,l=!a&&s.length===Kd?s.at(-1)?.id:void 0;return{threads:[...o,...s].map(e=>({status:e.is_archived?`archived`:`regular`,remoteId:e.id,title:e.title,lastMessageAt:e.last_message_at?new Date(e.last_message_at):void 0,externalId:e.external_id??void 0,custom:Hd(e.metadata)})),nextCursor:c||l?JSON.stringify({a:c,r:l,...c===void 0?{ae:!0}:{},...l===void 0?{re:!0}:{}}):void 0}},initialize:async e=>{let n=await(t().create?.(e)??Promise.resolve()),i=n?n.externalId:void 0,{thread_id:a}=await r.threads.create({last_message_at:new Date,external_id:i,...i!==void 0&&t().upsert?{upsert:!0}:{}});return{externalId:i,remoteId:a}},rename:async(e,t)=>r.threads.update(e,{title:t}),updateCustom:async(e,t)=>r.threads.update(e,{metadata:t??null}),archive:async e=>r.threads.update(e,{is_archived:!0}),unarchive:async e=>r.threads.update(e,{is_archived:!1}),delete:async e=>(await t().delete?.(e),r.threads.delete(e)),generateTitle:async(e,t)=>{let n=t.map(e=>({...e,content:e.content.filter(e=>e.type===`text`||e.type===`tool-call`)}));return r.runs.stream({thread_id:e,assistant_id:`system/thread_title`,messages:n})},fetch:async e=>{let t=await r.threads.get(e);return{status:t.is_archived?`archived`:`regular`,remoteId:t.id,title:t.title,lastMessageAt:t.last_message_at?new Date(t.last_message_at):void 0,externalId:t.external_id??void 0,custom:Hd(t.metadata)}},unstable_useAdapters:n}},Yd=e=>{let t=j(e);P(()=>{t.current=e},[e]);let[n]=A(()=>({get current(){return t.current.cloud??Wd}})),[r]=A(()=>function(){return Gd(n)}),i=e.cloud??Wd,a=()=>{let n=()=>e,a=Jd(()=>({...n(),cloud:i}));return n=()=>t.current,a.unstable_useAdapters===void 0?a:{...a,unstable_useAdapters:r}},[o,s]=A(()=>({cloud:i,adapter:a()}));if(o.cloud!==i){let e={cloud:i,adapter:a()};return s(e),e.adapter}return o.adapter},Xd=async(e,t)=>{let{signal:n,onUpdate:r}=t;if(Symbol.asyncIterator in e)for await(let t of e){if(n.aborted)break;r(t)}else{let t=await e;if(n.aborted)return;r(t)}},Zd=e=>{let t=[...e.content,...(e.attachments??[]).flatMap(e=>(e.content??[]).filter(e=>e.type!==`text`))],n=[];for(let e of t)e.type===`file`||e.type===`text`?n.push(e):e.type===`image`&&n.push({type:`file`,data:e.image,mimeType:`image/*`,...e.filename!==void 0&&{filename:e.filename}});return n},Qd=e=>{let t={queue:q,steer:q},n=new Map,r=new Set,i=!1,a=!1,o=!1,s=!1,c=e=>e,l=0,u=0,d=!1,f=0,p=()=>{z(r,void 0,`Message queue`)},m=e=>{t=e,T.items=e.queue,T.steerItems=e.steer,p()},h=(e,t)=>({id:e,prompt:_i(t),parts:Zd(t)}),g=(e,r,i=0)=>{o=!0,n.set(r.id,r.message),m({...t,[e]:[...t[e].slice(0,i),r.item,...t[e].slice(i)]})},_=e=>{if(t.steer.some(t=>t.id===e))return`steer`;if(t.queue.some(t=>t.id===e))return`queue`},v=()=>{if(i||o||s)return;let r=t.steer.length>0?`steer`:`queue`,l=t[r][0];if(!l)return;let u=n.get(l.id);if(!u)return;i=!0,n.delete(l.id),a=!0,m({...t,[r]:t[r].slice(1)}),a=!1;let d={id:l.id,item:l,message:u},p=f;try{e.run(c(u),{steer:!1})}catch(e){throw f===p&&(i=!1,g(r,d)),e}},y=(t,n=`steer`,r=0)=>{o=!1,l+=Math.max(u,1),u=0;let a=(e=!1)=>{if(e)return;let a=l;l=Math.max(a-1,0),u=+(a>0),i=a>0,g(n,t,r)};d=!0;try{e.cancel()}catch(e){throw a(),e}finally{d=!1}i=!0;let s=f;try{e.run(c(t.message),{steer:!0})}catch(e){throw a(f!==s),e}},b=(e,r)=>{o=!1;let i=W();n.set(i,r),m({...t,[e]:[...t[e],h(i,r)]}),v()},ee=e=>{b(`queue`,e)},te=t=>{if(i&&!a&&e.cancel){let e=W();y({id:e,item:h(e,t),message:t});return}b(`steer`,t)},x=(r,o)=>{let s=_(r);if(!s)throw Error(`Unknown queue item "${r}".`);let c=o.lane??s,l=t[s].findIndex(e=>e.id===r),u=t[s][l],d=(c===s?t[s]:t[c]).filter(e=>e.id!==r),f=e=>{if(e===r)throw Error(`Queue item "${r}" cannot anchor itself.`);let t=d.findIndex(t=>t.id===e);if(t===-1)throw Error(`Unknown anchor "${e}" in lane "${c}".`);return t},{insertAfter:p,insertBefore:h}=o,g;if(p===void 0&&h===void 0)g=c===s?t[s].findIndex(e=>e.id===r):d.length;else if(p!==void 0&&h!==void 0){let e=p===null?-1:f(p);if((h===null?d.length:f(h))!==e+1)throw Error(`insertAfter "${p}" and insertBefore "${h}" are not adjacent in lane "${c}".`);g=e+1}else g=p===void 0?h===null?d.length:f(h):p===null?0:f(p)+1;if(p===void 0&&h===void 0&&c===`steer`&&s!==`steer`&&i&&!a&&e.cancel){let e=n.get(r);n.delete(r),m({queue:t.queue.filter(e=>e.id!==r),steer:t.steer}),y({id:r,item:u,message:e},s,l);return}let b=[...d.slice(0,g),u,...d.slice(g)],ee={...t,[c]:b};c!==s&&(ee[s]=t[s].filter(e=>e.id!==r)),m(ee),v()},S=(e,r)=>{let i=_(e);if(!i)throw Error(`Unknown queue item "${e}".`);n.set(e,r),m({...t,[i]:t[i].map(t=>t.id===e?h(e,r):t)})},C=e=>{n.delete(e)&&m({queue:t.queue.filter(t=>t.id!==e),steer:t.steer.filter(t=>t.id!==e)})},w=()=>{d||a||i&&u===0&&(o=!0,u=1)},T={items:t.queue,steerItems:t.steer,enqueue:ee,steer:te,move:x,edit:S,remove:C,__internal_setDispatchTransform:e=>{c=e},__internal_notifyCancelled:w};return{adapter:T,hold:()=>{s=!0},release:()=>{s=!1,v()},notifyBusy:()=>{o=!1,l+=u,u=0,i=!0,f++},notifyIdle:()=>{if(l>0){l--;return}u>0&&u--,i=!1,v()},notifyCancelled:w,clear:()=>{n.clear(),m({queue:q,steer:q})},subscribe:e=>(r.add(e),()=>{r.delete(e)})}},$d=(e,t)=>e.status?.type!==`requires-action`||e.status.reason!==`tool-calls`||e.content.some(e=>e.type===`tool-call`&&e.result===void 0&&e.approval!==void 0&&e.approval.approved===void 0&&e.approval.resolution===void 0)?!1:t===void 0?e.content.every(e=>e.type!==`tool-call`||e.result!==void 0||e.approval!==void 0):e.content.every(e=>e.type!==`tool-call`||e.result!==void 0||e.approval!==void 0||!t.includes(e.toolName)),ef=class extends Error{name=`AbortError`;detach;constructor(e,t){super(t),this.detach=e}},tf=e=>e.role!==`assistant`||e.status.type!==`requires-action`||e.status.reason!==`interrupt`||e.content.some(e=>e.type===`tool-call`&&e.result===void 0&&e.interrupt!=null)?e:{...e,status:Vo(!1,!1,!1,e.content.some(e=>e.type===`tool-call`&&e.result===void 0))},nf=e=>{let t=!1,n=e.content.map(e=>e.type!==`tool-call`||e.approval===void 0||e.approval.approved!==void 0||e.approval.resolution!==void 0?e:(t=!0,{...e,approval:{...e.approval,resolution:`cancelled`}})),r=e.status.type===`running`||e.status.type===`requires-action`;return!t&&!r?e:{...e,content:n,status:r?{type:`incomplete`,reason:`cancelled`}:e.status}},rf=e=>{let t=new Set(e.messages.map(e=>e.parentId));return{...e,messages:e.messages.map(e=>({...e,message:e.message.role===`assistant`&&t.has(e.message.id)?nf(e.message):tf(e.message)}))}},af=e=>{if(e.role!==`assistant`)return e;let t=!1,n=e.content.map(e=>{if(e.type!==`tool-call`)return e;let n=e.messages?.map(af),r=n?.some((t,n)=>t!==e.messages?.[n]);if(e.unstable_interactions===void 0&&r!==!0)return e;t=!0;let{unstable_interactions:i,...a}=e;return r?{...a,messages:n}:a});return t?{...e,content:n}:e},of=class extends cc{capabilities={switchToBranch:!0,switchBranchDuringRun:!0,edit:!0,delete:!1,reload:!0,refetchThread:!1,cancel:!0,unstable_copy:!0,speech:!1,dictation:!1,voice:!1,attachments:!1,feedback:!1,queue:!1,answerToolCall:!0};abortController=null;_queue=null;_queueRunInFlight=null;_activeRun=null;_runGeneration=0;_messageReplacements=new WeakMap;_historyWrites=new Map;async _writeHistory(e,t,n){try{await n()}catch(n){throw console.error(`[assistant-ui] local thread history write failed:`,n),this._notifyEventSubscribers(`historyWriteError`,{operation:e,messageIds:t,message:n instanceof Error?n.message:String(n),error:n}),n}}_deletedMessages=new Map;_chainHistoryWrite(e,t){let n=this._deletedMessages.get(e);if(n)return n.suppressed?.push(t),Promise.resolve();let r=this._historyWrites.get(e),i;if(r)i=r.then(t,t);else try{i=Promise.resolve(t())}catch(e){i=Promise.reject(e)}let a=i.then(()=>{},()=>{});return this._historyWrites.set(e,a),a.then(()=>{this._historyWrites.get(e)===a&&this._historyWrites.delete(e)}),i}_persistMessageUpdate(e){let t=this._options.adapters.history;if(!t)return;let n;try{n=this.repository.getMessage(e)}catch{return}let{parentId:r,message:i}=n;i.role===`assistant`&&i.status.type!==`running`&&(this._unwrittenMessages.has(i.id)&&!t.update&&i.status.type===`requires-action`||this._persistSettled(r,i)?.catch(()=>{}))}_roundtripsInFlight=new Map;_followedDuringRun=new Set;_unwrittenMessages=new Set;_persistSettled(e,t){let n=this._options.adapters.history;if(!n)return;let r=this._unwrittenMessages.delete(t.id)?`append`:`update`,i=r===`append`?n.append:n.update;if(!i)return;let a={parentId:e,message:t,runConfig:this._lastRunConfig};return this._chainHistoryWrite(t.id,()=>this._writeHistory(r,[t.id],()=>i.call(n,a)))}_cancelPause(e){if(e===null)return;let t;try{t=this.repository.getMessage(e)}catch{return}if(t.message.role!==`assistant`)return;if(this._roundtripsInFlight.has(e)){this._followedDuringRun.add(e);let n=nf(t.message),r=this._options.adapters.history;if(r&&!r.update&&this._roundtripsInFlight.get(e)?.resumedFromPause&&!this._unwrittenMessages.has(e)){let i={parentId:t.parentId,message:n,runConfig:this._lastRunConfig};return this._chainHistoryWrite(e,()=>this._writeHistory(`append`,[e],()=>r.append(i)))}return this._persistSettled(t.parentId,n)}let n=nf(t.message);if(n!==t.message)return this.repository.addOrUpdateMessage(t.parentId,n),this._persistSettled(t.parentId,n)}_resumeIfReady(e){let t=this.getMessageById(e);return t?.message.role!==`assistant`||this.repository.hasChildren(e)||this._followedDuringRun.has(e)||!$d(t.message,this._options.unstable_humanToolNames)?!1:(this._runLoop(t.parentId,t.message,this._lastRunConfig).catch(()=>{}),!0)}isDisabled=!1;isSendDisabled=!1;_isLoading=!1;get isLoading(){return this._isLoading}_suggestions=[];_suggestionsController=null;get suggestions(){return this._suggestions}get adapters(){return this._options.adapters}constructor(e,t){super(e),this.__internal_setOptions(t)}_options;_lastRunConfig={};_getThreadId;__internal_setGetThreadId(e){this._getThreadId=e}_getInitializePromise;__internal_setGetInitializePromise(e){this._getInitializePromise=e}get extras(){}__internal_setOptions(e){if(this._options===e)return;let t=this._options?.adapters.history;if(this._options=e,!e.adapters.voice&&this.voice)try{this.disconnectVoice()}catch(e){console.error(`[assistant-ui] Voice cleanup threw after the adapter changed`,e)}let n=!1;e.adapters.suggestion||(this._suggestionsController?.abort(),this._suggestionsController=null,this._suggestions.length>0&&(this._suggestions=[],n=!0));let r=e.adapters?.speech!==void 0;this.capabilities.speech!==r&&(this.capabilities.speech=r,n=!0);let i=e.adapters?.dictation!==void 0;this.capabilities.dictation!==i&&(this.capabilities.dictation=i,n=!0);let a=e.adapters?.voice!==void 0;this.capabilities.voice!==a&&(this.capabilities.voice=a,n=!0);let o=e.adapters?.attachments!==void 0;this.capabilities.attachments!==o&&(this.capabilities.attachments=o,n=!0);let s=e.adapters?.feedback!==void 0;this.capabilities.feedback!==s&&(this.capabilities.feedback=s,n=!0);let c=e.adapters?.history?.delete!==void 0;this.capabilities.delete!==c&&(this.capabilities.delete=c,n=!0);let l=e.unstable_enableMessageQueue===!0;l&&!this._queue?(this._queue=Qd({run:e=>{let t={};this._queueRunInFlight=t;let n=this._runGeneration;this._runAppend({...e,parentId:this._resolveAppendParent(this.messages.at(-1)?.id??null)}).finally(()=>{this._queueRunInFlight===t&&(this._queueRunInFlight=null,this._runGeneration===n&&this._queue?.notifyIdle())}).catch(()=>{})}}),this.voice&&this._queue.hold(),this._queue.subscribe(()=>this._notifySubscribers())):!l&&this._queue&&(this._queue=null),this.capabilities.queue!==l&&(this.capabilities.queue=l,n=!0),n&&this._notifySubscribers(),this._loadRequested&&!this._loadPromise&&!t&&e.adapters.history&&this.messages.length===0&&this.__internal_load().catch(e=>{console.error(`[assistant-ui] local thread history load failed:`,e)})}_loadPromise;_loadRequested=!1;__internal_load(){if(this._loadRequested=!0,this._loadPromise)return this._loadPromise;if(!this.adapters.history)return Promise.resolve();let e=this.adapters.history.load();return this._isLoading=!0,this._loadPromise=e.then(e=>{if(!e)return;let{repository:t,droppedIds:n}=Js(e);n.length>0&&console.warn(`[assistant-ui] Skipped history messages with missing parents:`,n),e.headId!=null&&!e.messages.some(t=>t.message.id===e.headId)&&console.warn(`[assistant-ui] History head is not among the loaded messages:`,e.headId),this.repository.import(rf(t)),t.messages.length>0&&this.ensureInitialized(),this._notifySubscribers();let r=this.adapters.history?.resume?.bind(this.adapters.history);e.unstable_resume&&r&&this.startRun({parentId:this.repository.headId,sourceId:this.repository.headId,runConfig:this._lastRunConfig},r).catch(()=>{})}).finally(()=>{this._isLoading=!1,this._notifySubscribers()}),this._notifySubscribers(),this._loadPromise}_getHistoryLoadBarrier(){if(!(!this._isLoading||!this._loadPromise))return this._loadPromise.catch(()=>{})}async append(e){if(e={...e,parentId:this._resolveAppendParent(e.parentId)},this.voice)return this._appendToVoiceSession(e);if(this._isVoiceMessage(e.sourceId))throw Error(`Voice transcript messages cannot be edited`);let t=e.parentId===(this.messages.at(-1)?.id??null),n=e.startRun??e.role===`user`;if(this._queue&&n&&t){e.steer??this._queueRunInFlight!==null?this._queue.adapter.steer(e):this._queue.adapter.enqueue(e);return}return this._queue&&!t&&(this._options.unstable_queueClearOnRewind??!0)&&this._queue.clear(),this._runAppend(e)}_commitVoiceMessage(e){let t=ks(this),n=n=>{if(t.aborted){this._dropVoiceMessage(e.id,n);return}let r=this.repository.headId;this.repository.addOrUpdateMessage(r,e);let i=this._cancelPause(r);this.repository.resetHead(e.id);let a=this._options.adapters.history,o=a?this._chainHistoryWrite(e.id,()=>this._writeHistory(`append`,[e.id],()=>a.append({parentId:r,message:e}))):void 0;return o?.catch(()=>{}),this._dropVoiceMessage(e.id,!1),n&&this._notifySubscribers(),i?Promise.all([i,o]).then(()=>{}):o},r=this._getVoiceCommitBarrier();return r?r.then(()=>n(!0)):n(!1)}_onVoiceConnected(){this._queue?.hold()}_onVoiceDisconnected(){this._queue?.release()}getQueueItems(){return this._queue?.adapter.items??q}getSteerQueueItems(){return this._queue?.adapter.steerItems??q}moveQueueItem(e,t){this._queue?.adapter.move(e,t)}removeQueueItem(e){this._queue?.adapter.remove(e)}_rollbackAppend(e){try{this.repository.deleteMessage(e)}catch{return}this._notifySubscribers()}_pendingAppends=0;_isRunActive(){return this._pendingAppends>0||super._isRunActive()}async _runAppend(e){this._pendingAppends+=1;try{await this._runAppendInner(e)}finally{--this._pendingAppends}}async _runAppendInner(e){let t=ks(this),n=this._getHistoryLoadBarrier();if(n){let r=e.parentId===(this.messages.at(-1)?.id??null);if(await n,t.aborted)return;r&&(e={...e,parentId:this._resolveAppendParent(this.messages.at(-1)?.id??null)})}let r=this.enrichAppendMetadata(e);this.ensureInitialized();let i=pa(r,W(),{type:`complete`,reason:`unknown`});this.repository.addOrUpdateMessage(r.parentId,i),this._notifySubscribers();try{let e=this._getInitializePromise?.();e&&await e}catch(e){if(this._rollbackAppend(i.id),t.aborted)return;r.parentId!==null&&this._resumeIfReady(r.parentId);let n=new Jo;throw n.cause=e,n}if(t.aborted){this._rollbackAppend(i.id);return}let a=this._cancelPause(r.parentId),o=this._options.adapters.history,s=o?this._chainHistoryWrite(i.id,()=>this._writeHistory(`append`,[i.id],()=>o.append({parentId:r.parentId,message:i,...r.runConfig!==void 0&&{runConfig:r.runConfig}}))):void 0,c=a?Promise.all([a,s]).then(()=>{}):s;if(c?.catch(()=>{}),r.startRun??r.role===`user`){let[e,t]=await Promise.allSettled([this.startRun({parentId:i.id,sourceId:r.sourceId,runConfig:r.runConfig??{}}),c]);if(e.status===`rejected`)throw e.reason;if(t.status===`rejected`)throw t.reason}else this.repository.switchToBranch(i.id),this._notifySubscribers(),await c}async deleteMessage(e){let t=this._options.adapters.history;if(!t?.delete)throw Error(`Runtime does not support deleting messages.`);let n=this.repository.getMessages(),r=n.findIndex(t=>t.id===e);if(r===-1)throw Error(`Message not found.`);let i=this._deletedMessages.get(e);if(i?.suppressed&&i.deletion)return i.deletion;let a=t.delete.bind(t),o=e=>this._writeHistory(`delete`,e.map(e=>e.message.id),()=>a(e)),s=n[r],c=[{parentId:n[r-1]?.id??null,message:s}],l=this._historyWrites.get(e),u={suppressed:[]};return this._deletedMessages.set(e,u),u.deletion=(async()=>{try{await o(c)}catch(t){let n=u.suppressed??[];if(u.suppressed=null,this._deletedMessages.get(e)===u){this._deletedMessages.delete(e);for(let t of n)this._chainHistoryWrite(e,t).catch(()=>{})}throw t}u.suppressed=null,l?.then(()=>this._deletedMessages.get(e)===u?o(c):void 0).catch(()=>{}),this.repository.deleteMessage(e),this._notifySubscribers()})(),u.deletion}resumeRun({stream:e,...t}){if(!e)throw Error(`You must pass a stream parameter to resume runs.`);return this.startRun(t,e)}exportExternalState(){throw Error(`Runtime does not support exporting external states.`)}import(e){this._roundtripsInFlight.clear(),this._followedDuringRun.clear(),this._unwrittenMessages.clear(),this._deletedMessages.clear(),super.import(rf(e))}importExternalState(){throw Error(`Runtime does not support importing external states.`)}unstable_notifySessionReset(){throw Error(`Runtime does not support resetting sessions.`)}async startRun({parentId:e,sourceId:t,runConfig:n},r){if(this.ensureInitialized(),this.voice)throw Error(`Cannot start a run while a voice session is connected`);if(this._isVoiceMessage(t))throw Error(`Voice transcript messages cannot be reloaded`);let i=this._cancelPause(e),a=W(),o={id:a,role:`assistant`,status:{type:`running`},content:[],metadata:{unstable_state:this.state,unstable_annotations:[],unstable_data:[],steps:[],custom:{}},createdAt:new Date};this._unwrittenMessages.add(a);let s=this._runLoop(e,o,n,r);if(!i)return s;let[c,l]=await Promise.allSettled([s,i]);if(c.status===`rejected`)throw c.reason;if(l.status===`rejected`)throw l.reason}async _runLoop(e,t,n,r){if(this.voice)throw Error(`Cannot start a run while a voice session is connected`);this._notifyEventSubscribers(`runStart`,{});let i={cancelled:!1,resumedFromPause:t.status.type===`requires-action`};this._activeRun=i,this._runGeneration++;let a=!1;try{this._queue?.notifyBusy(),this._suggestions=[],this._suggestionsController?.abort(),this._suggestionsController=null,this._notifySubscribers();do{if(t=await this.performRoundtrip(e,t,n,i,r),r=void 0,this._activeRun!==i)break;let a=this._messageReplacements.get(t);for(;a;)t=a.message,a=this._messageReplacements.get(t);if(this.getMessageById(t.id)?.message!==t)break}while($d(t,this._options.unstable_humanToolNames)&&!this.repository.hasChildren(t.id))}finally{this._notifyEventSubscribers(`runEnd`,{}),a=this._activeRun===i,a&&(this._activeRun=null),(a||i.cancelled)&&queueMicrotask(()=>this._queue?.notifyIdle())}if(a&&this.adapters.suggestion&&t.status?.type!==`requires-action`){this._suggestionsController=new AbortController;let e=this._suggestionsController.signal,t=this.adapters.suggestion;(async()=>{try{await Xd(t.generate({messages:this.messages,signal:e}),{signal:e,onUpdate:e=>{this._suggestions=e,this._notifySubscribers()}})}catch{}})()}}async performRoundtrip(e,t,n,r,i){let a=(e?this.repository.getMessages(e):[]).map(e=>af(e.role===`assistant`&&(e.status.type===`running`||this._roundtripsInFlight.has(e.id))?nf(e):e));this.abortController?.abort();let o=new AbortController;this.abortController=o;let s=t.content,c=t.metadata?.unstable_annotations,l=t.metadata?.unstable_data,u=t.metadata?.steps,d=t.metadata?.custom,f=new Set,p=!0;try{this.repository.getMessage(t.id)}catch{p=!1}let m=()=>{if(!p)return this._activeRun===r;try{let e=t,n=this._messageReplacements.get(e);for(;n;)n.toolCallId!==void 0&&f.add(n.toolCallId),e=n.message,n=this._messageReplacements.get(e);return this.repository.getMessage(t.id).message===e&&(t=e,!0)}catch{return!1}},h=e=>{let n=new Map;for(let e of t.content)e.type===`tool-call`&&e.unstable_interactions!==void 0&&n.set(e.toolCallId,e.unstable_interactions);let r=e.map(e=>{if(e.type!==`tool-call`||e.unstable_interactions!==void 0)return e;let t=n.get(e.toolCallId);return t===void 0?e:{...e,unstable_interactions:t}});if(f.size===0)return r;let i=new Map;for(let e of t.content){if(e.type!==`tool-call`||!f.has(e.toolCallId))continue;let t=i.get(e.toolCallId)??[];t.push(e),i.set(e.toolCallId,t)}let a=new Map;return r.map(e=>{if(e.type!==`tool-call`)return e;let t=a.get(e.toolCallId)??0;if(a.set(e.toolCallId,t+1),e.result!==void 0&&e.isPreliminary!==!0)return e;let n=i.get(e.toolCallId)?.[t];if(!n||n.result===void 0||n.isPreliminary===!0)return e;let{isPreliminary:r,artifact:o,modelContent:s,...c}=e;return{...c,result:n.result,isError:n.isError,...n.artifact!==void 0&&{artifact:n.artifact},...n.modelContent!==void 0&&{modelContent:n.modelContent}}})},g=n=>{if(!m())return;let r=n.metadata?.steps,i=r?[...u??[],...r]:void 0,a=n.metadata?.unstable_annotations,o=n.metadata?.unstable_data,f=a?[...c??[],...a]:void 0,g=o?[...l??[],...o]:void 0,_=n.content?h([...s,...n.content]):void 0;t={...t,..._?{content:_}:void 0,status:n.status??t.status,...n.metadata?{metadata:{...t.metadata,...n.metadata.unstable_state===void 0?void 0:{unstable_state:n.metadata.unstable_state},...f?{unstable_annotations:f}:void 0,...g?{unstable_data:g}:void 0,...i?{steps:i}:void 0,...n.metadata?.timing?{timing:n.metadata.timing}:void 0,...n.metadata?.custom?{custom:{...d??{},...n.metadata.custom}}:void 0}}:void 0},this.repository.addOrUpdateMessage(e,t),p=!0,this._notifySubscribers()},_=this._options.maxSteps??2;this._roundtripsInFlight.set(t.id,{controller:o,resumedFromPause:r.resumedFromPause});try{if((t.metadata?.steps?.length??0)>=_)return g({status:{type:`incomplete`,reason:`tool-calls`}}),t;let s=!p;g({status:{type:`running`}}),s&&(this.repository.switchToBranch(t.id),this._notifySubscribers()),this._lastRunConfig=n??{};let{unstable_composerMetadata:c,...l}=this.getModelContext();i??=this.adapters.chatModel.run.bind(this.adapters.chatModel);let u=o.signal,d=()=>u.aborted&&(t.status.type===`running`||t.status.type===`requires-action`&&(this._activeRun!==r||$d(t,this._options.unstable_humanToolNames))),f=this._getThreadId?.(),h=i({messages:a,runConfig:this._lastRunConfig,abortSignal:u,context:l,unstable_assistantMessageId:t.id,unstable_threadId:f,unstable_parentId:e,unstable_getMessage(){return m(),af(t)}});if(Symbol.asyncIterator in h)for await(let e of h){if(u.aborted){d()&&g({status:{type:`incomplete`,reason:`cancelled`}});break}g(e)}else g(await h);d()?g({status:{type:`incomplete`,reason:`cancelled`}}):t.status.type===`running`&&g({status:{type:`complete`,reason:`unknown`}})}catch(e){if(e instanceof ef)g({status:{type:`incomplete`,reason:`cancelled`}});else if(e instanceof Error&&e.name===`AbortError`)g({status:{type:`incomplete`,reason:`cancelled`}});else throw g({status:{type:`incomplete`,reason:`error`,error:Xo(e)}}),e}finally{this.abortController===o&&(this.abortController=null);let n=this._roundtripsInFlight.get(t.id)?.controller===o;n&&this._roundtripsInFlight.delete(t.id);let i=this._options.adapters.history,a=m(),s=!1,c,l=n&&this._followedDuringRun.delete(t.id);if(l){let e=this.getMessageById(t.id);if(e?.message.role===`assistant`){let n=nf(e.message);n!==e.message&&(this.repository.addOrUpdateMessage(e.parentId,n),s=!0,a?t=n:c=this._persistSettled(e.parentId,n))}}if(n&&!a&&!c){let e=this.getMessageById(t.id);e?.message.role===`assistant`&&(e.message.status.type===`complete`||e.message.status.type===`incomplete`)&&this._unwrittenMessages.has(t.id)&&(c=this._persistSettled(e.parentId,e.message))}let u=t.status.type===`complete`||t.status.type===`incomplete`,d=t.status.type===`requires-action`&&!$d(t,this._options.unstable_humanToolNames);if(a&&(u||d&&i?.update)){if(u&&r.resumedFromPause&&!l&&!this._unwrittenMessages.has(t.id)&&i&&!i.update){let n={parentId:e,message:t,runConfig:this._lastRunConfig};c=this._chainHistoryWrite(t.id,()=>this._writeHistory(`append`,[t.id],()=>i.append(n)))}else c=this._persistSettled(e,t)}s&&this._notifySubscribers(),c&&await c}return t}detach(){Ns(this),this._queue=null;let e=new ef(!0);this.abortController?.abort(e),this.abortController=null,this._suggestionsController?.abort(),this._suggestionsController=null}cancelRun(){this._queue&&(this._options.unstable_queueClearOnCancel??!0?this._queue.clear():(this._queue.notifyCancelled(),this._activeRun&&(this._activeRun.cancelled=!0)));let e=new ef(!1);this.abortController?.abort(e),this.abortController=null,this._suggestionsController?.abort(),this._suggestionsController=null}_onMessageMetadataChanged(e,t){this._messageReplacements.set(e,{message:t}),this._persistMessageUpdate(t.id)}addToolResult({messageId:e,toolCallId:t,result:n,isError:r,artifact:i,modelContent:a}){if(this.voice)throw Error(`Cannot add a tool result while a voice session is connected`);let o=this.repository.getMessage(e),{parentId:s}=o,{message:c}=o;if(c.role!==`assistant`)throw Error(`Tried to add tool result to non-assistant message`);let l=!1,u=!1,d=c.content.map(e=>{if(e.type!==`tool-call`||e.toolCallId!==t)return e;u=!0,(e.result===void 0||e.isPreliminary===!0)&&(l=!0);let{isPreliminary:o,...s}=e;return{...s,result:n,isError:r,...i!==void 0&&{artifact:i},...a!==void 0&&{modelContent:a}}});if(!u)throw Error(`Tried to add tool result to non-existing tool call`);let f=c;c={...c,content:d},f.status.type===`running`&&this._messageReplacements.set(f,{message:c,toolCallId:t}),this.repository.addOrUpdateMessage(s,c),this._notifySubscribers(),l&&(this._resumeIfReady(e)||this._persistMessageUpdate(e))}resumeToolCall(e){throw Error(`Local runtime does not support resuming tool calls. For human-in-the-loop tools, list the tool in unstable_humanToolNames and complete the call with addToolResult.`)}async unstable_recordToolInteraction({messageId:e,toolCallId:t,interaction:n}){let r;try{r=this.repository.getMessage(e)}catch{throw Error(`Tried to record a tool interaction on a non-existing message`)}let{parentId:i,message:a}=r;if(a.role!==`assistant`)throw Error(`Tried to record a tool interaction on a non-assistant message`);let o=a.content.findIndex(e=>e.type===`tool-call`&&e.toolCallId===t);if(o===-1)throw Error(`Tried to record a tool interaction on a non-existing tool call`);let s=a.content[o];if(s.type!==`tool-call`)throw Error(`Tried to record a tool interaction on a non-existing tool call`);let c={...a,content:a.content.map((e,t)=>t===o?{...e,unstable_interactions:Ni(s.unstable_interactions,n)}:e)};a.status.type===`running`&&this._messageReplacements.set(a,{message:c}),this.repository.addOrUpdateMessage(i,c),this._notifySubscribers(),this._persistMessageUpdate(c.id)}respondToToolApproval({approvalId:e,approved:t,optionId:n,text:r,answers:i,reason:a}){if(this.voice)throw Error(`Cannot respond to a tool approval while a voice session is connected`);let o=this.repository.getMessages().findLast(t=>t.role===`assistant`&&t.content.some(t=>t.type===`tool-call`&&t.approval?.id===e));if(!o)throw Error(`Tried to respond to a non-existing tool approval`);if(this.abortController!==null)throw Error(`Tried to respond to a tool approval while a run is in progress`);if(o.status?.type!==`requires-action`)throw Error(`Tried to respond to a tool approval on a message whose status is not requires-action`);if(this.repository.hasChildren(o.id))throw Error(`Tried to respond to a tool approval on a message that later messages follow`);if(this._followedDuringRun.has(o.id))throw Error(`Tried to respond to a tool approval that was cancelled or expired`);let s=o.content.find(t=>t.type===`tool-call`&&t.approval?.id===e);if(s?.type!==`tool-call`||!s.approval)throw Error(`Tried to respond to a non-existing tool approval`);if(s.approval.resolution!==void 0)throw Error(`Tried to respond to a tool approval that was cancelled or expired`);if(s.approval.approved!==void 0)throw Error(`Tried to respond to an already decided tool approval`);let c=s.approval,l=o.content.map(e=>{if(e!==s)return e;let o={...c,approved:t,...n!=null&&{optionId:n},...r!=null&&{text:r},...i!=null&&{answers:i},...a!=null&&{reason:a}};return t?{...e,approval:o}:{...e,approval:o,result:{error:a||`Tool approval denied`},isError:!0}});o={...o,content:l};let{parentId:u}=this.repository.getMessage(o.id);this.repository.addOrUpdateMessage(u,o),this._notifySubscribers(),this._notifyToolApprovalAnswered(o.id,s.toolCallId,s.toolName,t);let d=this.getMessageById(o.id);return this.repository.headId===o.id&&d?.message.role===`assistant`&&$d(d.message,this._options.unstable_humanToolNames)?this._runLoop(d.parentId,d.message,this._lastRunConfig).catch(()=>{}):this._persistMessageUpdate(o.id),Promise.resolve()}},sf=Object.freeze([]),cf=`__DEFAULT_ID__`,lf=Object.freeze({[cf]:{id:cf,remoteId:void 0,externalId:void 0,status:`regular`,title:void 0}}),uf=class extends ri{_mainThread;constructor(e){super(),this._mainThread=e()}get isLoading(){return!1}getMainThreadRuntimeCore(){return this._mainThread}get newThreadId(){}get threadIds(){return sf}get archivedThreadIds(){return sf}get mainThreadId(){return cf}get threadItems(){return lf}getThreadRuntimeCore(){throw Error(`Method not implemented.`)}getLoadThreadsPromise(){return Promise.resolve()}getItemById(e){if(e===this.mainThreadId)return{status:`regular`,id:this.mainThreadId,remoteId:this.mainThreadId,externalId:void 0,title:void 0,isMain:!0};throw Error(`Method not implemented`)}async switchToThread(){throw Error(`Method not implemented.`)}switchToNewThread(){throw Error(`Method not implemented.`)}rename(){throw Error(`Method not implemented.`)}archive(){throw Error(`Method not implemented.`)}detach(){throw Error(`Method not implemented.`)}unarchive(){throw Error(`Method not implemented.`)}delete(){throw Error(`Method not implemented.`)}initialize(e){return Promise.resolve({remoteId:e,externalId:void 0})}generateTitle(){throw Error(`Method not implemented.`)}},df=class extends Ws{threads;Provider=void 0;_options;constructor(e,t){super(),this._options=e,this.threads=new uf(()=>new of(this._contextProvider,this._options)),t&&this.threads.getMainThreadRuntimeCore().import(Gs.fromArray(t))}},ff=()=>()=>{},pf=(e,t,n)=>{let r=x(40),i,a;r[0]===t?(i=r[1],a=r[2]):({initialMessages:i,...a}=t,r[0]=t,r[1]=i,r[2]=a);let o=Sa()??{},s,c;r[3]===o?(s=r[4],c=r[5]):({modelContext:s,...c}=o,r[3]=o,r[4]=s,r[5]=c);let l;r[6]!==e||r[7]!==a.adapters||r[8]!==c?(l={...c,...a.adapters,chatModel:e},r[6]=e,r[7]=a.adapters,r[8]=c,r[9]=l):l=r[9];let u;r[10]!==a||r[11]!==l?(u={...a,adapters:l},r[10]=a,r[11]=l,r[12]=u):u=r[12];let d=u,f;r[13]!==i||r[14]!==n||r[15]!==d?(f=()=>{let e=n===void 0?i:i?.map((e,t)=>({...e,id:e.id??`${n}-message-${t}`,content:typeof e.content==`string`?e.content:e.content.map((e,r)=>e.type===`tool-call`&&!e.toolCallId?{...e,toolCallId:`${n}-tool-${t}-${r}`}:e)}));return new df(d,e)},r[13]=i,r[14]=n,r[15]=d,r[16]=f):f=r[16];let[p]=A(f),m=Xr(),h=j(void 0),g;r[17]!==m||r[18]!==p.threads?(g=()=>{p.threads.getMainThreadRuntimeCore().__internal_setGetThreadId(()=>m.threadListItem.__internal_getRuntime?.().getState().remoteId)},r[17]=m,r[18]=p.threads,r[19]=g):g=r[19];let _;r[20]!==m||r[21]!==p?(_=[m,p],r[20]=m,r[21]=p,r[22]=_):_=r[22],N(g,_);let v;r[23]===p.threads?v=r[24]:(v=()=>()=>{p.threads.getMainThreadRuntimeCore().detach()},r[23]=p.threads,r[24]=v);let y;r[25]===p?y=r[26]:(y=[p],r[25]=p,r[26]=y),pi(v,y);let b;r[27]!==d||r[28]!==p.threads?(b=()=>{p.threads.getMainThreadRuntimeCore().__internal_setOptions(d)},r[27]=d,r[28]=p.threads,r[29]=b):b=r[29],N(b);let ee;r[30]===p.threads?ee=r[31]:(ee=()=>{let e=p.threads.getMainThreadRuntimeCore().__internal_load();h.current!==e&&(h.current=e,e.catch(gf))},r[30]=p.threads,r[31]=ee);let te;r[32]===p?te=r[33]:(te=[p],r[32]=p,r[33]=te),N(ee,te);let S,C;r[34]!==s||r[35]!==p?(S=()=>{if(s)return p.registerModelContextProvider(s)},C=[s,p],r[34]=s,r[35]=p,r[36]=S,r[37]=C):(S=r[36],C=r[37]),N(S,C);let w;r[38]===p?w=r[39]:(w=()=>new Us(p),r[38]=p,r[39]=w);let[T]=A(w);return T},mf=e=>{let{cloud:t,initialMessages:n,maxSteps:r,adapters:i,unstable_humanToolNames:a,unstable_enableMessageQueue:o,unstable_queueClearOnRewind:s,unstable_queueClearOnCancel:c,...l}=e;return{localRuntimeOptions:{cloud:t,initialMessages:n,maxSteps:r,adapters:i,unstable_humanToolNames:a,unstable_enableMessageQueue:o,unstable_queueClearOnRewind:s,unstable_queueClearOnCancel:c},otherOptions:l}},hf=(e,{cloud:t,...n}={})=>{let r=tt(),i=n.initialMessages?.some(e=>e.id===void 0||typeof e.content!=`string`&&e.content.some(e=>e.type===`tool-call`&&!e.toolCallId))??!1,a=$e(ff,()=>!1,()=>i);return rl({runtimeHook:function(){return pf(e,n,a?r:void 0)},adapter:Yd({cloud:t}),allowNesting:!0})};function gf(e){console.error(`[assistant-ui] local thread history load failed:`,e)}function _f(e,t){function n(n){let r=e(n);return r?r[t]:null}function r(e){let t=!1,r;typeof e==`function`?r=e:e&&typeof e==`object`&&(t=!!e.optional,r=e.selector);let i=n({optional:t});return i?r?i(r):i():null}return{[t]:r,[`${t}Store`]:n}}var vf=e=>{let t,n=new Set,r=(e,r)=>{let i=typeof e==`function`?e(t):e;if(!Object.is(i,t)){let e=t;t=r??(typeof i!=`object`||!i)?i:Object.assign({},t,i),n.forEach(n=>n(t,e))}},i=()=>t,a={setState:r,getState:i,getInitialState:()=>o,subscribe:e=>(n.add(e),()=>n.delete(e))},o=t=e(r,i,a);return a},yf=(e=>e?vf(e):vf),bf=e=>e;function xf(e,t=bf){let n=b.useSyncExternalStore(e.subscribe,b.useCallback(()=>t(e.getState()),[e,t]),b.useCallback(()=>t(e.getInitialState()),[e,t]));return b.useDebugValue(n),n}var Sf=e=>{let t=yf(e),n=e=>xf(t,e);return Object.assign(n,t),n},Cf=(e=>e?Sf(e):Sf),wf=e=>e;export{rt as $,$r as A,Gn as B,xi as C,U as D,gi as E,mr as F,on as G,mn as H,gr as I,bt as J,rn as K,hr as L,kr as M,xr as N,di as O,yr as P,ot as Q,rr as R,yi as S,_i as T,z as U,Un as V,dn as W,st as X,at as Y,lt as Z,G as _,hf as a,Qe as at,la as b,Gs as c,Ze as ct,Us as d,A as dt,ct as et,Ts as f,$e as ft,ga as g,ya as h,mf as i,N as it,Xr as j,ei as k,Xs as l,M as lt,Vo as m,x as mt,Cf as n,Xe as nt,rl as o,tt as ot,ds as p,C as pt,nn as q,_f as r,dt as rt,oc as s,P as st,wf as t,it as tt,Ws as u,j as ut,ma as v,Ci as w,vi as x,pa as y,nr as z};