@readmagic/workmate 0.0.15 → 0.0.17

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 (274) hide show
  1. package/dist/chunks/{AddWorkspaceDirectory-DcVnvL_u.js → AddWorkspaceDirectory-YAhnVwyN.js} +1 -1
  2. package/dist/chunks/AgentsMdExternalIncludesDialog--D4BeNAN.js +1 -0
  3. package/dist/chunks/{AgentsMdExternalIncludesDialog-D6DopTxc.js → AgentsMdExternalIncludesDialog-Ba4GYFl3.js} +1 -1
  4. package/dist/chunks/{App-BoI5EJry.js → App-mri25OrC.js} +1 -1
  5. package/dist/chunks/{ApproveApiKey-BjlQDcMx.js → ApproveApiKey-DCw6d7dm.js} +1 -1
  6. package/dist/chunks/ApproveApiKey-lv4Sg0RR.js +1 -0
  7. package/dist/chunks/{BackgroundTasksDialog-ClSMkcGp.js → BackgroundTasksDialog-CZND8e_Z.js} +1 -1
  8. package/dist/chunks/{BypassPermissionsModeDialog-KCZv-PXl.js → BypassPermissionsModeDialog-B5QBJTB4.js} +1 -1
  9. package/dist/chunks/{DiffDialog-BGBkuVIn.js → DiffDialog-Bd-DcTsK.js} +1 -1
  10. package/dist/chunks/{Doctor-CI04juFO.js → Doctor-C9t7udHN.js} +2 -2
  11. package/dist/chunks/Doctor-V-JLC4e3.js +1 -0
  12. package/dist/chunks/ExitFlow-CShdrKmr.js +2 -0
  13. package/dist/chunks/{Grove-B-M3DWD3.js → Grove-CClEZT2e.js} +1 -1
  14. package/dist/chunks/{HybridTransport-n5jji6SI.js → HybridTransport-DyEuslQB.js} +1 -1
  15. package/dist/chunks/{InvalidConfigDialog-By-j6fHE.js → InvalidConfigDialog-Wyrk_cXR.js} +1 -1
  16. package/dist/chunks/{InvalidSettingsDialog-C_reeMzL.js → InvalidSettingsDialog-Cr9fmSyh.js} +1 -1
  17. package/dist/chunks/MCPConnectionManager-BnUw0nYN.js +1 -0
  18. package/dist/chunks/{MCPToolListView-jw0tITfc.js → MCPToolListView-CY2EezWF.js} +1 -1
  19. package/dist/chunks/{McpParsingWarnings-BeZ3Bn8N.js → McpParsingWarnings-BF4np2Y3.js} +1 -1
  20. package/dist/chunks/{MessageSelector-Ci6N-gCw.js → MessageSelector-Dtt2Sf65.js} +1 -1
  21. package/dist/chunks/Messages-D5Uuapmf.js +10 -0
  22. package/dist/chunks/{Onboarding-DDkVEq-G.js → Onboarding-BAJXV7Ay.js} +1 -1
  23. package/dist/chunks/{PromptInputFooterSuggestions-BlhZuQ5F.js → PromptInputFooterSuggestions-Cm4WN3qd.js} +1 -1
  24. package/dist/chunks/PromptInputHelpMenu-ESj8sOpK.js +1 -0
  25. package/dist/chunks/QueryEngine-B79JLwG4.js +1 -0
  26. package/dist/chunks/REPL-B7evbhvN.js +1 -0
  27. package/dist/chunks/REPL-cAXdORs2.js +128 -0
  28. package/dist/chunks/{RemoteSessionManager-mWVrdNfS.js → RemoteSessionManager-C5pAD0Lh.js} +2 -2
  29. package/dist/chunks/{ResumeConversation-BzTn_1jS.js → ResumeConversation-NSVT3gn7.js} +1 -1
  30. package/dist/chunks/{SSETransport-D86IVNn1.js → SSETransport-CDGMGrxN.js} +1 -1
  31. package/dist/chunks/SearchExtraToolsTool-CddjJcAH.js +1 -0
  32. package/dist/chunks/Settings-_b5Yxt_9.js +2 -0
  33. package/dist/chunks/{TeleportProgress-CW8mLRy2.js → TeleportProgress-8cS6aHVO.js} +1 -1
  34. package/dist/chunks/{TeleportRepoMismatchDialog-DZD32R-l.js → TeleportRepoMismatchDialog-B0epkMgp.js} +1 -1
  35. package/dist/chunks/{TeleportResumeWrapper-BhuUE1aq.js → TeleportResumeWrapper-Bb14JeEk.js} +1 -1
  36. package/dist/chunks/{ThemePicker-ByQZgIbH.js → ThemePicker-CnX8faYA.js} +1 -1
  37. package/dist/chunks/{TrustDialog-BzwibD_8.js → TrustDialog-6wJF3W6K.js} +1 -1
  38. package/dist/chunks/{add-dir-BQ-ljgk6.js → add-dir-LLAv-rGS.js} +1 -1
  39. package/dist/chunks/{agentDisplay-tRprY4gB.js → agentDisplay-QqGqcHGz.js} +1 -1
  40. package/dist/chunks/{agents-DMyQUXwl.js → agents-C8wRUTNV.js} +6 -6
  41. package/dist/chunks/{agents-Dq4BCf0H.js → agents-DFPEienW.js} +1 -1
  42. package/dist/chunks/{allErrors-CQWZ6BPw.js → allErrors-DUYYPpdH.js} +1 -1
  43. package/dist/chunks/{api-ClAyS7cQ.js → api-B3Wnozaf.js} +1 -1
  44. package/dist/chunks/api-BAT--5sp.js +1 -0
  45. package/dist/chunks/auth-CQGJitIV.js +10 -0
  46. package/dist/chunks/auth-DaJXqwN5.js +1 -0
  47. package/dist/chunks/auth-DkhPycBL.js +1 -0
  48. package/dist/chunks/{backgroundHousekeeping-rzQFJiND.js → backgroundHousekeeping-Bjb_Jc7L.js} +2 -2
  49. package/dist/chunks/backgroundHousekeeping-V-dg2j2E.js +1 -0
  50. package/dist/chunks/{branch-BWbCrXBJ.js → branch-BWq5ynjm.js} +1 -1
  51. package/dist/chunks/{bridgeConfig-CPHAyzdg.js → bridgeConfig-B3mR0kJ0.js} +1 -1
  52. package/dist/chunks/bridgeConfig-D31i4BRi.js +1 -0
  53. package/dist/chunks/{bridgeMessaging-vR7uQXB9.js → bridgeMessaging-wZ5EKxW_.js} +1 -1
  54. package/dist/chunks/{bridgeStatusUtil-CHTx7XwJ.js → bridgeStatusUtil-mvVQSVN-.js} +1 -1
  55. package/dist/chunks/{btw-IGcgP-Qq.js → btw-XNgXHnNr.js} +1 -1
  56. package/dist/chunks/{caches-FP8mGB4k.js → caches-ByLjTvdy.js} +1 -1
  57. package/dist/chunks/caches-ckqJ4Qso.js +1 -0
  58. package/dist/chunks/{ccrClient--8aPutWE.js → ccrClient-EisctZbc.js} +1 -1
  59. package/dist/chunks/{clear-CF-FZwpe.js → clear-BjtPf2Jb.js} +1 -1
  60. package/dist/chunks/client-Bb2eZnuq.js +1 -0
  61. package/dist/chunks/client-Bl43xcRk.js +1 -0
  62. package/dist/chunks/client-DNEVh6Wu.js +1 -0
  63. package/dist/chunks/client-Pap_HyZZ.js +1 -0
  64. package/dist/chunks/client-zhozU2ws.js +1 -0
  65. package/dist/chunks/commands-BDhn7EPO.js +1 -0
  66. package/dist/chunks/{compact-BrJGpEFZ.js → compact-w8AhLkr6.js} +1 -1
  67. package/dist/chunks/config-CbAvTdZ7.js +1 -0
  68. package/dist/chunks/{context-DADnwl4t.js → context-Btn2JU2y.js} +1 -1
  69. package/dist/chunks/{context-noninteractive-kACWzgS1.js → context-noninteractive-044464Vs.js} +1 -1
  70. package/dist/chunks/context-noninteractive-ulRLlYg5.js +1 -0
  71. package/dist/chunks/conversation-D08lU377.js +1 -0
  72. package/dist/chunks/{conversation-C8w1DtXk.js → conversation-a82khZ_n.js} +1 -1
  73. package/dist/chunks/{createSSHSession-B71Plec6.js → createSSHSession-C0KSI0fJ.js} +1 -1
  74. package/dist/chunks/{createSession-BJeDECzt.js → createSession-8ScCWTKb.js} +1 -1
  75. package/dist/chunks/createSession-CnlPXXkA.js +1 -0
  76. package/dist/chunks/{crossProjectResume-B1I6YzXr.js → crossProjectResume-BCN462Wa.js} +1 -1
  77. package/dist/chunks/{datadog-C9uqPA6N.js → datadog-BqINRWAW.js} +1 -1
  78. package/dist/chunks/{diff-CzChvQyK.js → diff-CcrSQNvQ.js} +1 -1
  79. package/dist/chunks/doctor-DRFDBrH1.js +1 -0
  80. package/dist/chunks/{entry-BoL8sy1Y.js → entry-oVZ7Z59B.js} +2 -2
  81. package/dist/chunks/{esm-DtcV71xh.js → esm-BZciQG9N.js} +1 -1
  82. package/dist/chunks/exit-jikLI2Zh.js +1 -0
  83. package/dist/chunks/extraUsage-BT3in1Aj.js +1 -0
  84. package/dist/chunks/extractMemories-BsQU2bVO.js +1 -0
  85. package/dist/chunks/fast-B9vVL3sY.js +1 -0
  86. package/dist/chunks/fast-CKhtBOx7.js +1 -0
  87. package/dist/chunks/fetchModelList-BeL40TyR.js +1 -0
  88. package/dist/chunks/fetchModelList-DmaMgpa2.js +1 -0
  89. package/dist/chunks/{fileSuggestions-DU7gmksK.js → fileSuggestions-BfG3sbET.js} +1 -1
  90. package/dist/chunks/firstPartyEventLogger-6GwZ6VLr.js +1 -0
  91. package/dist/chunks/{firstPartyEventLogger-7pAyUdbp.js → firstPartyEventLogger-Q3fMF0BR.js} +2 -2
  92. package/dist/chunks/{flushGate-4DfYr-Ru.js → flushGate-COa_KO98.js} +1 -1
  93. package/dist/chunks/{gemini-Cll4fVQn.js → gemini-L8Gj2B4H.js} +1 -1
  94. package/dist/chunks/{generateSessionName-BgGMwpps.js → generateSessionName-cAL5T7pG.js} +1 -1
  95. package/dist/chunks/{goal-D4E2WQVn.js → goal-D-x2WXm7.js} +1 -1
  96. package/dist/chunks/grok-DtypRM4d.js +1 -0
  97. package/dist/chunks/{grove-Bck1zFaD.js → grove-CSivzrhe.js} +1 -1
  98. package/dist/chunks/{help-DJp61Job.js → help-DKZhC0lL.js} +1 -1
  99. package/dist/chunks/{hooks-CJ17byYD.js → hooks-D_afUDcs.js} +1 -1
  100. package/dist/chunks/hooks-DvVuNKRx.js +1 -0
  101. package/dist/chunks/initReplBridge-sTaq4a0K.js +1 -0
  102. package/dist/chunks/{install-Dd5fw0cA.js → install-BWe3Jz4M.js} +1 -1
  103. package/dist/chunks/{instrumentation-jsPu6qqs.js → instrumentation-IljwxX0V.js} +4 -4
  104. package/dist/chunks/{job-BHhkQbvu.js → job-N25KhSUu.js} +1 -1
  105. package/dist/chunks/keybindings-DLEorhlY.js +1 -0
  106. package/dist/chunks/{launchLocalMemory-DsaijVcO.js → launchLocalMemory-DJsuNLIf.js} +1 -1
  107. package/dist/chunks/{launchOnboarding-DHOylaqn.js → launchOnboarding-CVvuxeH-.js} +1 -1
  108. package/dist/chunks/{loadAgentsDir-CwEfQDOw.js → loadAgentsDir-CbtNPJV3.js} +569 -569
  109. package/dist/chunks/loadAgentsDir-D0gl_H2S.js +1 -0
  110. package/dist/chunks/{loadPluginHooks-C-Yk5KlI.js → loadPluginHooks-BxkDBFd6.js} +1 -1
  111. package/dist/chunks/{localSearch-BEnlgSB7.js → localSearch-B5mTHBwK.js} +1 -1
  112. package/dist/chunks/localSearch-D3UrYUre.js +1 -0
  113. package/dist/chunks/{logoV2Utils-DG9GwFjl.js → logoV2Utils-D5nRpirL.js} +1 -1
  114. package/dist/chunks/{magicDocs-qGHR3Cqh.js → magicDocs-C9aIo4Oe.js} +2 -2
  115. package/dist/chunks/{main-CBVQ8bRm.js → main-DeUt_aE2.js} +26 -26
  116. package/dist/chunks/managedEnv-ADMKY7-G.js +1 -0
  117. package/dist/chunks/{managedEnv-3MbOWrVs.js → managedEnv-CDxyrUw1.js} +1 -1
  118. package/dist/chunks/{mappers-CdY45PDA.js → mappers-Del1KoA7.js} +1 -1
  119. package/dist/chunks/{mcp-DvY_FibT.js → mcp-Bh3MNBIj.js} +3 -3
  120. package/dist/chunks/{mcp-DI8pGrqi.js → mcp-D7vMhEOV.js} +1 -1
  121. package/dist/chunks/{mcp-BA8XQ6h1.js → mcp-nnBVM5Lt.js} +1 -1
  122. package/dist/chunks/{memory-C2U7CCmM.js → memory-DtqQhHu8.js} +1 -1
  123. package/dist/chunks/{mode-ByV6NqmB.js → mode-DPbrxU32.js} +1 -1
  124. package/dist/chunks/model-B50j-O5v.js +1 -0
  125. package/dist/chunks/model-DLG1nrnf.js +1 -0
  126. package/dist/chunks/{model-CeG-iOKF.js → model-DlLO7TSx.js} +1 -1
  127. package/dist/chunks/modelOptions-SMq3one0.js +1 -0
  128. package/dist/chunks/{nativeInstaller-CXFD8LDV.js → nativeInstaller-DTJ4clp-.js} +1 -1
  129. package/dist/chunks/{omit-B65XeX8r.js → omit-CMldTqqy.js} +1 -1
  130. package/dist/chunks/{onChangeAppState-EtUxsgYz.js → onChangeAppState-EAnsmOuo.js} +1 -1
  131. package/dist/chunks/openai-CR3CcjCE.js +17 -0
  132. package/dist/chunks/{openai-Dx5mvMjY.js → openai-D9KvLMrj.js} +2 -2
  133. package/dist/chunks/{partition-8vZDG3rY.js → partition-B8Y4jvjW.js} +1 -1
  134. package/dist/chunks/{permissions-CJUBfBTr.js → permissions-cDtIZRM1.js} +2 -2
  135. package/dist/chunks/{pidLock-tjm2n1Nd.js → pidLock-Br3_YNi_.js} +2 -2
  136. package/dist/chunks/{plan-eFur8bdH.js → plan-dG2H4eQl.js} +1 -1
  137. package/dist/chunks/{plugin-fYLRLdOY.js → plugin-CzQHuIlP.js} +1 -1
  138. package/dist/chunks/{pluginAutoupdate-B4w7SSYc.js → pluginAutoupdate-B9W_vxOG.js} +1 -1
  139. package/dist/chunks/{pluginBlocklist-CMwb7gmY.js → pluginBlocklist-BvdBsnJG.js} +1 -1
  140. package/dist/chunks/{pluginCliCommands-3YCj7Y3Q.js → pluginCliCommands-NKIgFTUF.js} +1 -1
  141. package/dist/chunks/{pluginFlagging-srvq9H7p.js → pluginFlagging-C0PtAJEg.js} +1 -1
  142. package/dist/chunks/{pluginOperations-C7BCR7pw.js → pluginOperations-wUUdFpu9.js} +1 -1
  143. package/dist/chunks/pluginStartupCheck-hDT6pEAd.js +1 -0
  144. package/dist/chunks/{pluginStartupCheck-BLc0U7W7.js → pluginStartupCheck-p0njap1l.js} +1 -1
  145. package/dist/chunks/{plugins-CPtmmDDi.js → plugins-B9WBqOAW.js} +1 -1
  146. package/dist/chunks/print-G3DgPTxy.js +14 -0
  147. package/dist/chunks/{processBashCommand-C9-FonuX.js → processBashCommand-zLWgCRws.js} +1 -1
  148. package/dist/chunks/{processSlashCommand-Bi8_1MRC.js → processSlashCommand-BHBnHBjj.js} +2 -2
  149. package/dist/chunks/{prompt-Bm2EEG4F.js → prompt-BRGC5U9Y.js} +1 -1
  150. package/dist/chunks/prompt-Ct3Ryb3C.js +1 -0
  151. package/dist/chunks/prompt-TZJKyomz.js +1 -0
  152. package/dist/chunks/{promptEditor-DQ9fpdQD.js → promptEditor-CRIw6vJS.js} +1 -1
  153. package/dist/chunks/{reconciler-DgQ4y1Vn.js → reconciler-DiU1RvGD.js} +1 -1
  154. package/dist/chunks/{refresh-CayVRWUY.js → refresh-DEXe3Lmx.js} +1 -1
  155. package/dist/chunks/{reload-plugins-6xcH3dLg.js → reload-plugins-Cl6wvT6V.js} +1 -1
  156. package/dist/chunks/{remoteBridgeCore-BnZYGaMH.js → remoteBridgeCore-DnFZoXaw.js} +1 -1
  157. package/dist/chunks/{remoteManagedSettings-CfFmrRze.js → remoteManagedSettings-BboLJ46D.js} +1 -1
  158. package/dist/chunks/{rename-mDtCTbnD.js → rename-CdzxOzN5.js} +1 -1
  159. package/dist/chunks/{resume-DRvz4QFs.js → resume-DgFXYWTN.js} +1 -1
  160. package/dist/chunks/{runtimeObserver-Ba6SM-sI.js → runtimeObserver-CwtRE2cj.js} +1 -1
  161. package/dist/chunks/{runtimeObserver-Dt5sGJVb.js → runtimeObserver-Dov-m2dl.js} +2 -2
  162. package/dist/chunks/sandbox-adapter-CtEngx-6.js +1 -0
  163. package/dist/chunks/{sandbox-toggle-DKcw3SbO.js → sandbox-toggle-DWCrG9zV.js} +1 -1
  164. package/dist/chunks/searchExtraTools-zFMN5MqY.js +1 -0
  165. package/dist/chunks/{session-COVyD8UU.js → session-L5191BSn.js} +1 -1
  166. package/dist/chunks/sessionFileAccessHooks-C2VjT-PU.js +1 -0
  167. package/dist/chunks/sessionObserver-BuhXr3FP.js +1 -0
  168. package/dist/chunks/{sessionObserver-iAgSetlC.js → sessionObserver-DpY0DOjI.js} +1 -1
  169. package/dist/chunks/{sessionState-zhvcDpb2.js → sessionState-BlbRQ3Y6.js} +2 -2
  170. package/dist/chunks/sessionStorage-CiYSwyY3.js +1 -0
  171. package/dist/chunks/sessionTitle-k4wpUS5l.js +2 -0
  172. package/dist/chunks/{sessionTracing-C4uqAdud.js → sessionTracing-DqVx8aFD.js} +1 -1
  173. package/dist/chunks/{settingsSync-BGo6dHJo.js → settingsSync-BhlegQAU.js} +1 -1
  174. package/dist/chunks/setup-DvnKMqDy.js +3 -0
  175. package/dist/chunks/{shadowedRuleDetection-CzRAzcC1.js → shadowedRuleDetection-Gerk3t93.js} +1 -1
  176. package/dist/chunks/{sideQuestion-oIYrx5ar.js → sideQuestion-RndkXExy.js} +1 -1
  177. package/dist/chunks/sinks-Cf4vx9UX.js +1 -0
  178. package/dist/chunks/{sinks-Bje3hCkR.js → sinks-CfzgqLH5.js} +1 -1
  179. package/dist/chunks/skillChangeDetector-BQx4xe_b.js +1 -0
  180. package/dist/chunks/{skillGapStore-CJjt3IW7.js → skillGapStore-CLxhWLyq.js} +2 -2
  181. package/dist/chunks/{skillLifecycle-BsgH84vl.js → skillLifecycle-CSNX2qOH.js} +2 -2
  182. package/dist/chunks/{skillSearchPanel-CneXymsb.js → skillSearchPanel-CsQDjy_E.js} +4 -4
  183. package/dist/chunks/{skills-DZRBy7vT.js → skills-DM9ACPW-.js} +1 -1
  184. package/dist/chunks/status-C3z0CSBw.js +1 -0
  185. package/dist/chunks/{status-BP_R8051.js → status-C5v7KsX4.js} +2 -2
  186. package/dist/chunks/{statusNoticeHelpers-ODrnrLAZ.js → statusNoticeHelpers-BY_8pK19.js} +1 -1
  187. package/dist/chunks/switcher-C9VsM-ip.js +1 -0
  188. package/dist/chunks/{switcher-BkGOeIzI.js → switcher-CnBKuiNp.js} +1 -1
  189. package/dist/chunks/syncCache-Dff4hbz4.js +1 -0
  190. package/dist/chunks/{tasks-CIUuwrX4.js → tasks-qVyXOLBf.js} +1 -1
  191. package/dist/chunks/{teleport-IzyDplC7.js → teleport-Deq_ecN9.js} +1 -1
  192. package/dist/chunks/{templateJobs-De57J461.js → templateJobs-CntPyct-.js} +1 -1
  193. package/dist/chunks/{theme-Nwii7354.js → theme-DVWYzSct.js} +1 -1
  194. package/dist/chunks/{toolEventObserver-Cq-uBb0-.js → toolEventObserver-BZn8ZJB5.js} +1 -1
  195. package/dist/chunks/toolPool-Dzp1ob3I.js +1 -0
  196. package/dist/chunks/trustedDevice-1Q4FTNyX.js +1 -0
  197. package/dist/chunks/{trustedDevice-DWZxDUxS.js → trustedDevice-CdLAZK6m.js} +1 -1
  198. package/dist/chunks/{useExitOnCtrlCDWithKeybindings-D48aDPG9.js → useExitOnCtrlCDWithKeybindings-YSWYVWk6.js} +1 -1
  199. package/dist/chunks/useMainLoopModel-C1JRp4zE.js +1 -0
  200. package/dist/chunks/{useManagePlugins-EqoQELMT.js → useManagePlugins-DfuI4Nhd.js} +1 -1
  201. package/dist/chunks/{useMergedTools-BJ4L9QSK.js → useMergedTools-B4qRVJ8b.js} +1 -1
  202. package/dist/chunks/{useSearchInput-DkVER3cm.js → useSearchInput-DfUNYhqC.js} +1 -1
  203. package/dist/chunks/{useSettingsErrors-D3MlQ1GF.js → useSettingsErrors-Bls74ocI.js} +1 -1
  204. package/dist/chunks/{userAgent-aoe_xVAb.js → userAgent-CNPTS7ix.js} +1 -1
  205. package/dist/chunks/{util-g-5UX5gH.js → util-6aJHnBQ_.js} +1 -1
  206. package/dist/chunks/{validatePlugin-CSE8zjZn.js → validatePlugin-BajM6yNf.js} +1 -1
  207. package/dist/chunks/{workerRegistry-DGwy0YHB.js → workerRegistry-BwJ54Lzk.js} +2 -2
  208. package/dist/chunks/worktree-BFP10vim.js +1 -0
  209. package/dist/cli.js +1 -1
  210. package/package.json +1 -1
  211. package/dist/chunks/AgentsMdExternalIncludesDialog-0Qdg3Rh7.js +0 -1
  212. package/dist/chunks/ApproveApiKey-PWFcscjY.js +0 -1
  213. package/dist/chunks/Doctor-DCrqcW68.js +0 -1
  214. package/dist/chunks/ExitFlow-qrCDVA9i.js +0 -2
  215. package/dist/chunks/MCPConnectionManager-BNG7iSlw.js +0 -1
  216. package/dist/chunks/Messages-D6CRTH2m.js +0 -10
  217. package/dist/chunks/PromptInputHelpMenu-kKyPIMau.js +0 -1
  218. package/dist/chunks/QueryEngine-DXpS0Ytq.js +0 -1
  219. package/dist/chunks/REPL-D1BCm7cR.js +0 -128
  220. package/dist/chunks/REPL-JQgCrSEv.js +0 -1
  221. package/dist/chunks/SearchExtraToolsTool-BXIja1MR.js +0 -1
  222. package/dist/chunks/Settings-D_i8HzEW.js +0 -2
  223. package/dist/chunks/api-CpD5jeKe.js +0 -1
  224. package/dist/chunks/auth-CWAvPfX7.js +0 -10
  225. package/dist/chunks/auth-DG5bkWDc.js +0 -1
  226. package/dist/chunks/auth-DuHfQBuH.js +0 -1
  227. package/dist/chunks/backgroundHousekeeping-kf_v7Vfr.js +0 -1
  228. package/dist/chunks/bridgeConfig-CABsoOum.js +0 -1
  229. package/dist/chunks/caches-Dj1YhqrG.js +0 -1
  230. package/dist/chunks/client-B7WkO81L.js +0 -17
  231. package/dist/chunks/client-BCzhAEd0.js +0 -1
  232. package/dist/chunks/client-BU7upHOb.js +0 -1
  233. package/dist/chunks/commands-Cr1p7OPH.js +0 -1
  234. package/dist/chunks/config-BohF3_IV.js +0 -1
  235. package/dist/chunks/context-noninteractive-BAbzwNxu.js +0 -1
  236. package/dist/chunks/conversation-Ds7zRD0x.js +0 -1
  237. package/dist/chunks/createSession-Bozo4Bu8.js +0 -1
  238. package/dist/chunks/doctor-DdvdGkNX.js +0 -1
  239. package/dist/chunks/exit-Af27f74w.js +0 -1
  240. package/dist/chunks/extraUsage-DsFwXMAj.js +0 -1
  241. package/dist/chunks/extractMemories-B1KbTMY0.js +0 -1
  242. package/dist/chunks/fast-BGU8p2uY.js +0 -1
  243. package/dist/chunks/fast-CuUjONVV.js +0 -1
  244. package/dist/chunks/firstPartyEventLogger-sMeCTEUW.js +0 -1
  245. package/dist/chunks/grok-HF1PHxXb.js +0 -1
  246. package/dist/chunks/hooks-CjR3Eq0Z.js +0 -1
  247. package/dist/chunks/initReplBridge-D09JEKHt.js +0 -1
  248. package/dist/chunks/keybindings-Ch5lzNB8.js +0 -1
  249. package/dist/chunks/loadAgentsDir-8FioUEwX.js +0 -1
  250. package/dist/chunks/localSearch-LcgRjjl3.js +0 -1
  251. package/dist/chunks/managedEnv-B4YV3A_y.js +0 -1
  252. package/dist/chunks/model-C73ETGu9.js +0 -1
  253. package/dist/chunks/model-CVG_RRTy.js +0 -1
  254. package/dist/chunks/modelOptions-A5jrCUBp.js +0 -1
  255. package/dist/chunks/pluginStartupCheck-nzVDPI1k.js +0 -1
  256. package/dist/chunks/print-BCud0ukQ.js +0 -14
  257. package/dist/chunks/prompt-CX_v9F3s.js +0 -1
  258. package/dist/chunks/prompt-V0WQJrkO2.js +0 -1
  259. package/dist/chunks/sandbox-adapter-Cmrd6tBj.js +0 -1
  260. package/dist/chunks/searchExtraTools-DIgC0CFB.js +0 -1
  261. package/dist/chunks/sessionFileAccessHooks-yAPDTrbm.js +0 -1
  262. package/dist/chunks/sessionObserver-BizdPx8P.js +0 -1
  263. package/dist/chunks/sessionStorage-LMY409Ji.js +0 -1
  264. package/dist/chunks/sessionTitle-QPRly1tZ.js +0 -14
  265. package/dist/chunks/setup-Bjw5VS6x.js +0 -3
  266. package/dist/chunks/sinks-FaljTZ-c.js +0 -1
  267. package/dist/chunks/skillChangeDetector-v6mAYzXX.js +0 -1
  268. package/dist/chunks/status-CZYD3NGb.js +0 -1
  269. package/dist/chunks/switcher-DwKN9daN.js +0 -1
  270. package/dist/chunks/syncCache-CpmpvjfC.js +0 -1
  271. package/dist/chunks/toolPool-BBU4ll_p.js +0 -1
  272. package/dist/chunks/trustedDevice-BKzkA7fq.js +0 -1
  273. package/dist/chunks/useMainLoopModel-89eUU13X.js +0 -1
  274. package/dist/chunks/worktree-jjuORs7p.js +0 -1
@@ -1 +0,0 @@
1
- import{t as e}from"./REPL-D1BCm7cR.js";export{e as REPL};
@@ -1 +0,0 @@
1
- import{E_ as e,T_ as t}from"./loadAgentsDir-CwEfQDOw.js";e();export{t as clearSearchExtraToolsDescriptionCache};
@@ -1,2 +0,0 @@
1
- import{n as e,o as t}from"./rolldown-runtime-DaDcL9Zw.js";import{d as n,l as r,o as i}from"./envUtils-DcaKZlRU.js";import{n as a,t as o}from"./figures-5ThXQEtq.js";import{$h as ee,$u as te,Dp as s,Gy as ne,Hy as re,Ky as c,Op as ie,Qh as ae,Qu as oe,Uh as se,Wh as ce,Wy as le,Xh as l,Zh as u,Zu as d,b as f,br as p,cb as ue,cd as m,eo as h,hC as g,j as de,lb as fe,ld as _,no as pe,pb as me,rr as he,to as v,xC as ge}from"./loadAgentsDir-CwEfQDOw.js";import{D as y,Gt as _e,H as ve,I as b,P as x,T as S,U as ye,Wt as be,Xn as xe,a as Se,ai as C,di as w,fi as T,k as Ce,n as we,ot as Te,r as E,t as D,x as O,y as Ee}from"./src-DL3w8VPk2.js";import{t as k}from"./jsx-runtime-Bb4Xn-E0.js";import{Wt as De,pt as Oe}from"./state-BPFYBqm1.js";import{n as ke,t as A}from"./cwd-Besi3Os3.js";import{Bt as Ae,Ft as je,It as Me,Mt as j,Pt as Ne,c as Pe,g as Fe,n as Ie,x as M,zt as Le}from"./settings-CvhsRFaT.js";import{a as Re,c as N,h as ze,i as Be,o as Ve,y as P}from"./config-BSkuQZNf.js";import{o as He,s as Ue}from"./log-BlJ7CcKG.js";import{n as We,r as F}from"./analytics-DJobLaWP.js";import{G as Ge,K as Ke,_ as I,b as qe,br as Je,et as L,it as Ye,q as Xe,rt as Ze,tt as Qe,x as $e,xr as et}from"./model-CeG-iOKF.js";import{a as tt,c as nt,d as rt,i as it,l as at,n as ot,o as R,r as st,s as ct,t as z,u as B}from"./status-BP_R8051.js";import{n as V,t as lt}from"./useExitOnCtrlCDWithKeybindings-D48aDPG9.js";import{i as ut,n as dt,r as ft}from"./modalContext-wY9CeN4G.js";import{n as pt,t as mt}from"./ThemePicker-ByQZgIbH.js";import{i as ht,n as gt,r as _t,t as vt}from"./extraUsage-DsFwXMAj.js";import{n as yt,t as bt}from"./AgentsMdExternalIncludesDialog-D6DopTxc.js";import{t as H}from"./SearchBox-CwwV0W-w.js";import{n as xt,t as St}from"./useSearchInput-DkVER3cm.js";function Ct(){let e=Oe();return[{label:`Version`,value:`0.0.15`},{label:`Session name`,value:he(e)??(0,K.jsx)(x,{dimColor:!0,children:`/rename to add a name`})},{label:`Session ID`,value:e},{label:`cwd`,value:A()},...ot(),...z()]}function wt({mainLoopModel:e,mcp:t,theme:n,context:r}){return[{label:`Model`,value:B(e)},...st(t.clients,r.options.ideInstallationStatus,n),...R(t.clients,n),...nt(),...at()]}async function U(){return[...await it(),...await tt(),...await ct()]}function Tt({value:e}){return Array.isArray(e)?(0,K.jsx)(b,{flexWrap:`wrap`,columnGap:1,flexShrink:99,children:e.map((t,n)=>(0,K.jsxs)(x,{children:[t,n<e.length-1?`,`:``]},n))}):typeof e==`string`?(0,K.jsx)(x,{children:e}):e}function Et({context:e,diagnosticsPromise:t}){let n=u(e=>e.mainLoopModel),r=u(e=>e.mcp),[i]=ve(),a=W.useMemo(()=>[Ct(),wt({mainLoopModel:n,mcp:r,theme:i,context:e})],[n,r,i,e]),o=ft()?1:void 0;return(0,K.jsxs)(b,{flexDirection:`column`,flexGrow:o,children:[(0,K.jsxs)(b,{flexDirection:`column`,gap:1,flexGrow:o,children:[a.map((e,t)=>e.length>0&&(0,K.jsx)(b,{flexDirection:`column`,children:e.map(({label:e,value:t},n)=>(0,K.jsxs)(b,{flexDirection:`row`,gap:1,flexShrink:0,children:[e!==void 0&&(0,K.jsxs)(x,{bold:!0,children:[e,`:`]}),(0,K.jsx)(Tt,{value:t})]},n))},t)),(0,K.jsx)(G.Suspense,{fallback:null,children:(0,K.jsx)(Dt,{promise:t})})]}),(0,K.jsx)(x,{dimColor:!0,children:(0,K.jsx)(s,{action:`confirm:no`,context:`Settings`,fallback:`Esc`,description:`cancel`})})]})}function Dt({promise:e}){let t=(0,G.use)(e);return t.length===0?null:(0,K.jsxs)(b,{flexDirection:`column`,paddingBottom:1,children:[(0,K.jsx)(x,{bold:!0,children:`System Diagnostics`}),t.map((e,t)=>(0,K.jsxs)(b,{flexDirection:`row`,gap:1,paddingX:1,children:[(0,K.jsx)(x,{color:`error`,children:o.warning}),typeof e==`string`?(0,K.jsx)(x,{wrap:`wrap`,children:e}):e]},t))]})}var W,G,K,Ot=e((()=>{a(),W=t(C(),1),G=t(C(),1),De(),dt(),D(),l(),ke(),p(),rt(),ie(),K=k()}));function kt({currentVersion:e,onChoice:t}){function n(e){t(e)}function r(){t(`cancel`)}return(0,At.jsxs)(Ee,{title:`Switch to Stable Channel`,onCancel:r,color:`permission`,hideBorder:!0,hideInputGuide:!0,children:[(0,At.jsxs)(x,{children:[`The stable channel may have an older version than what you're currently running (`,e,`).`]}),(0,At.jsx)(x,{dimColor:!0,children:`How would you like to handle this?`}),(0,At.jsx)(oe,{options:[{label:`Allow possible downgrade to stable version`,value:`downgrade`},{label:`Stay on current version (${e}) until stable catches up`,value:`stay`}],onChange:n})]})}var At,jt=e((()=>{D(),d(),At=k()}));function Mt(e){return Object.entries(e).map(([e,t])=>({label:t?.name??Ft,value:e,description:t?.description??It}))}function Nt({initialStyle:e,onComplete:t,onCancel:n,isStandaloneCommand:r}){let[i,a]=(0,Pt.useState)([]),[o,ee]=(0,Pt.useState)(!0);(0,Pt.useEffect)(()=>{v(A()).then(e=>{let t=Mt(e);a(t),ee(!1)}).catch(()=>{let e=Mt(h);a(e),ee(!1)})},[]);let te=(0,Pt.useCallback)(e=>{t(e)},[t]);return(0,q.jsx)(Ee,{title:`Preferred output style`,onCancel:n,hideInputGuide:!r,hideBorder:!r,children:(0,q.jsxs)(b,{flexDirection:`column`,gap:1,children:[(0,q.jsx)(b,{marginTop:1,children:(0,q.jsx)(x,{dimColor:!0,children:`This changes how Work Mate communicates with you`})}),o?(0,q.jsx)(x,{dimColor:!0,children:`Loading output styles…`}):(0,q.jsx)(oe,{options:i,onChange:te,visibleOptionCount:10,defaultValue:e})]})})}var Pt,q,Ft,It,Lt=e((()=>{Pt=t(C(),1),pe(),D(),ke(),te(),q=k(),Ft=`Default`,It=`Work Mate completes coding tasks efficiently and provides concise responses`}));function Rt({initialLanguage:e,onComplete:t,onCancel:n}){let[r,i]=(0,zt.useState)(e),[a,ee]=(0,zt.useState)((e??``).length);be(`confirm:no`,n,{context:`Settings`});function te(){let e=r?.trim();t(e||void 0)}return(0,J.jsxs)(b,{flexDirection:`column`,gap:1,children:[(0,J.jsx)(x,{children:`Enter your preferred response and voice language:`}),(0,J.jsxs)(b,{flexDirection:`row`,gap:1,children:[(0,J.jsx)(x,{children:o.pointer}),(0,J.jsx)(m,{value:r??``,onChange:i,onSubmit:te,focus:!0,showCursor:!0,placeholder:`e.g., Japanese, 日本語, Español${o.ellipsis}`,columns:60,cursorOffset:a,onChangeCursorOffset:ee})]}),(0,J.jsx)(x,{dimColor:!0,children:`Leave empty for default (English)`})]})}var zt,J,Bt=e((()=>{a(),zt=t(C(),1),D(),g(),_(),J=k()}));function Vt({onClose:e,context:t,setTabsHidden:i,onIsSearchModeChange:a,contentHeight:te}){let{headerFocused:c,focusHeader:ie}=Se(),se=ft(),[,l]=ve(),d=ye(),[f,p]=(0,X.useState)(N()),m=Y.useRef(N()),[h,g]=(0,X.useState)(Ie()),fe=Y.useRef(Ie()),[_,pe]=(0,X.useState)(h?.outputStyle||`default`),he=Y.useRef(_),[v,ge]=(0,X.useState)(h?.language),C=Y.useRef(v),[T,we]=(0,X.useState)(0),[E,D]=(0,X.useState)(0),[O,k]=(0,X.useState)(!1),De=xe(),{rows:Oe}=Te(),ke=te??Math.min(Math.floor(Oe*.8),30),A=Math.max(5,ke-10),j=u(e=>e.mainLoopModel),Fe=u(e=>e.verbose),ze=u(e=>e.thinkingEnabled),He=u(e=>Ze()?e.fastMode:!1);u(e=>e.promptSuggestionEnabled);let We=je(h?.permissions?.defaultMode??`default`),I=ee(),[Je,L]=(0,X.useState)({}),tt=Y.useRef(ze),[nt]=(0,X.useState)(()=>Pe(`localSettings`)),[rt]=(0,X.useState)(()=>Pe(`userSettings`)),it=Y.useRef(d),at=ae(),[ot]=(0,X.useState)(()=>{let e=at.getState();return{mainLoopModel:e.mainLoopModel,mainLoopModelForSession:e.mainLoopModelForSession,verbose:e.verbose,thinkingEnabled:e.thinkingEnabled,fastMode:e.fastMode,promptSuggestionEnabled:e.promptSuggestionEnabled,replBridgeEnabled:e.replBridgeEnabled,replBridgeOutboundOnly:e.replBridgeOutboundOnly,settings:e.settings}}),R=Y.useRef(!1),[st,ct]=(0,X.useState)(!1),[z,B]=(0,X.useState)(null),{query:V,setQuery:lt,cursorOffset:ut}=xt({isActive:O&&z===null&&!c,onExit:()=>k(!1),onExitUp:ie,passthroughCtrlKeys:[`c`,`d`]}),dt=O&&!c;Y.useEffect(()=>{a?.(dt)},[dt,a]);let pt=ue(t.options.mcpClients),ht=!r(process.env.CLAUDE_CODE_DISABLE_FILE_CHECKPOINTING),vt=Y.use(le(!0)),yt=ne(vt),H=Re();function St(e){F(`tengu_config_model_changed`,{from_model:j,to_model:e}),I(t=>({...t,mainLoopModel:e,mainLoopModelForSession:null})),L(t=>{let n=$e(e)+(gt(e,!1,qe())?` · Billed as extra usage`:``);if(`model`in t){let{model:e,...r}=t;return{...r,model:n}}return{...t,model:n}})}function Ct(e){P(t=>({...t,verbose:e})),p({...N(),verbose:e}),I(t=>({...t,verbose:e})),L(t=>{if(`verbose`in t){let{verbose:e,...n}=t;return n}return{...t,verbose:e}})}let wt=[{id:`autoCompactEnabled`,label:`Auto-compact`,value:f.autoCompactEnabled,type:`boolean`,onChange(e){P(t=>({...t,autoCompactEnabled:e})),p({...N(),autoCompactEnabled:e}),F(`tengu_auto_compact_setting_changed`,{enabled:e})}},{id:`spinnerTipsEnabled`,label:`Show tips`,value:h?.spinnerTipsEnabled??!0,type:`boolean`,onChange(e){M(`localSettings`,{spinnerTipsEnabled:e}),g(t=>({...t,spinnerTipsEnabled:e})),F(`tengu_tips_setting_changed`,{enabled:e})}},{id:`cacheWarningEnabled`,label:`Cache warnings`,value:h?.cacheWarningEnabled??!0,type:`boolean`,onChange(e){M(`localSettings`,{cacheWarningEnabled:e}),g(t=>({...t,cacheWarningEnabled:e})),F(`tengu_cache_warning_setting_changed`,{enabled:e})}},{id:`prefersReducedMotion`,label:`Reduce motion`,value:h?.prefersReducedMotion??!1,type:`boolean`,onChange(e){M(`localSettings`,{prefersReducedMotion:e}),g(t=>({...t,prefersReducedMotion:e})),I(t=>({...t,settings:{...t.settings,prefersReducedMotion:e}})),F(`tengu_reduce_motion_setting_changed`,{enabled:e})}},{id:`thinkingEnabled`,label:`Thinking mode`,value:ze??!0,type:`boolean`,onChange(e){I(t=>({...t,thinkingEnabled:e})),M(`userSettings`,{alwaysThinkingEnabled:e?void 0:!1}),F(`tengu_thinking_toggled`,{enabled:e})}},...Ze()&&Qe()?[{id:`fastMode`,label:`Fast mode (${Ge} only)`,value:!!He,type:`boolean`,onChange(e){Ke(),M(`userSettings`,{fastMode:e?!0:void 0}),e?(I(e=>({...e,mainLoopModel:Xe(),mainLoopModelForSession:null,fastMode:!0})),L(e=>({...e,model:Xe(),"Fast mode":`ON`}))):(I(e=>({...e,fastMode:!1})),L(e=>({...e,"Fast mode":`OFF`})))}}]:[],...ht?[{id:`fileCheckpointingEnabled`,label:`Rewind code (checkpoints)`,value:f.fileCheckpointingEnabled,type:`boolean`,onChange(e){P(t=>({...t,fileCheckpointingEnabled:e})),p({...N(),fileCheckpointingEnabled:e}),F(`tengu_file_history_snapshots_setting_changed`,{enabled:e})}}]:[],{id:`verbose`,label:`Verbose output`,value:Fe,type:`boolean`,onChange:Ct},{id:`terminalProgressBarEnabled`,label:`Terminal progress bar`,value:f.terminalProgressBarEnabled,type:`boolean`,onChange(e){P(t=>({...t,terminalProgressBarEnabled:e})),p({...N(),terminalProgressBarEnabled:e}),F(`tengu_terminal_progress_bar_setting_changed`,{enabled:e})}},{id:`showTurnDuration`,label:`Show turn duration`,value:f.showTurnDuration,type:`boolean`,onChange(e){P(t=>({...t,showTurnDuration:e})),p({...N(),showTurnDuration:e}),F(`tengu_show_turn_duration_setting_changed`,{enabled:e})}},{id:`defaultPermissionMode`,label:`Default permission mode`,value:We,options:(()=>{let e=[`default`,`plan`];return[...e,...Ae.filter(t=>!e.includes(t))]})(),type:`enum`,onChange(e){let t=je(e),n=t===`auto`?t:Ne(t)?Le(t):t,r=M(`userSettings`,{permissions:{...h?.permissions,defaultMode:n}});if(r.error){Ue(r.error);return}g(e=>({...e,permissions:{...e?.permissions,defaultMode:n}})),L(t=>({...t,defaultPermissionMode:e})),F(`tengu_config_changed`,{setting:`defaultPermissionMode`,value:e})}},{id:`respectGitignore`,label:`Respect .gitignore in file picker`,value:f.respectGitignore,type:`boolean`,onChange(e){P(t=>({...t,respectGitignore:e})),p({...N(),respectGitignore:e}),F(`tengu_respect_gitignore_setting_changed`,{enabled:e})}},...ce()?[{id:`copyOnSelect`,label:`Copy on select`,value:f.copyOnSelect??!0,type:`boolean`,onChange(e){P(t=>({...t,copyOnSelect:e})),p({...N(),copyOnSelect:e}),F(`tengu_config_changed`,{setting:`copyOnSelect`,value:String(e)})}}]:[],H?{id:`autoUpdatesChannel`,label:`Auto-update channel`,value:`disabled`,type:`managedEnum`,onChange(){}}:{id:`autoUpdatesChannel`,label:`Auto-update channel`,value:h?.autoUpdatesChannel??`latest`,type:`managedEnum`,onChange(){}},{id:`theme`,label:`Theme`,value:d,type:`managedEnum`,onChange:l},{id:`notifChannel`,label:`Notifications`,value:f.preferredNotifChannel,options:[`auto`,`iterm2`,`terminal_bell`,`iterm2_with_bell`,`kitty`,`ghostty`,`notifications_disabled`],type:`enum`,onChange(e){P(t=>({...t,preferredNotifChannel:e})),p({...N(),preferredNotifChannel:e})}},{id:`outputStyle`,label:`Output style`,value:_,type:`managedEnum`,onChange:()=>{}},{id:`language`,label:`Language`,value:v??`Default (English)`,type:`managedEnum`,onChange:()=>{}},{id:`editorMode`,label:`Editor mode`,value:f.editorMode===`emacs`?`normal`:f.editorMode||`normal`,options:[`normal`,`vim`],type:`enum`,onChange(e){P(t=>({...t,editorMode:e})),p({...N(),editorMode:e}),F(`tengu_editor_mode_changed`,{mode:e,source:`config_panel`})}},{id:`prStatusFooterEnabled`,label:`Show PR status footer`,value:f.prStatusFooterEnabled??!0,type:`boolean`,onChange(e){P(t=>t.prStatusFooterEnabled===e?t:{...t,prStatusFooterEnabled:e}),p({...N(),prStatusFooterEnabled:e}),F(`tengu_pr_status_footer_setting_changed`,{enabled:e})}},{id:`model`,label:`Model`,value:j===null?`Default (recommended)`:j,type:`managedEnum`,onChange:St},...pt?[{id:`diffTool`,label:`Diff tool`,value:f.diffTool??`auto`,options:[`terminal`,`auto`],type:`enum`,onChange(e){P(t=>({...t,diffTool:e})),p({...N(),diffTool:e}),F(`tengu_diff_tool_changed`,{tool:e,source:`config_panel`})}}]:[],...me()?[]:[{id:`autoConnectIde`,label:`Auto-connect to IDE (external terminal)`,value:f.autoConnectIde??!1,type:`boolean`,onChange(e){P(t=>({...t,autoConnectIde:e})),p({...N(),autoConnectIde:e}),F(`tengu_auto_connect_ide_changed`,{enabled:e,source:`config_panel`})}}],...me()?[{id:`autoInstallIdeExtension`,label:`Auto-install IDE extension`,value:f.autoInstallIdeExtension??!0,type:`boolean`,onChange(e){P(t=>({...t,autoInstallIdeExtension:e})),p({...N(),autoInstallIdeExtension:e}),F(`tengu_auto_install_ide_extension_changed`,{enabled:e,source:`config_panel`})}}]:[],...yt?[{id:`showExternalIncludesDialog`,label:`External AGENTS.md includes`,value:Ve().hasAgentsMdExternalIncludesApproved?`true`:`false`,type:`managedEnum`,onChange(){}}]:[],...process.env.ANTHROPIC_API_KEY&&!n()?[{id:`apiKey`,label:(0,Z.jsxs)(x,{children:[`Use custom API key: `,(0,Z.jsx)(x,{bold:!0,children:et(process.env.ANTHROPIC_API_KEY)})]}),searchText:`Use custom API key`,value:!!(process.env.ANTHROPIC_API_KEY&&f.customApiKeyResponses?.approved?.includes(et(process.env.ANTHROPIC_API_KEY))),type:`boolean`,onChange(e){P(t=>{let n={...t};if(n.customApiKeyResponses||(n.customApiKeyResponses={approved:[],rejected:[]}),n.customApiKeyResponses.approved||(n.customApiKeyResponses={...n.customApiKeyResponses,approved:[]}),n.customApiKeyResponses.rejected||(n.customApiKeyResponses={...n.customApiKeyResponses,rejected:[]}),process.env.ANTHROPIC_API_KEY){let t=et(process.env.ANTHROPIC_API_KEY);e?n.customApiKeyResponses={...n.customApiKeyResponses,approved:[...(n.customApiKeyResponses.approved??[]).filter(e=>e!==t),t],rejected:(n.customApiKeyResponses.rejected??[]).filter(e=>e!==t)}:n.customApiKeyResponses={...n.customApiKeyResponses,approved:(n.customApiKeyResponses.approved??[]).filter(e=>e!==t),rejected:[...(n.customApiKeyResponses.rejected??[]).filter(e=>e!==t),t]}}return n}),p(N())}}]:[]],U=Y.useMemo(()=>{if(!V)return wt;let e=V.toLowerCase();return wt.filter(t=>t.id.toLowerCase().includes(e)?!0:(`searchText`in t?t.searchText:t.label).toLowerCase().includes(e))},[wt,V]);Y.useEffect(()=>{if(T>=U.length){let e=Math.max(0,U.length-1);we(e),D(Math.max(0,e-A+1));return}D(e=>T<e?T:T>=e+A?T-A+1:e)},[U.length,T,A]);let Tt=(0,X.useCallback)(e=>{D(t=>e<t?e:e>=t+A?e-A+1:t)},[A]),Et=(0,X.useCallback)(()=>{if(z!==null)return;let t=Object.entries(Je).map(([e,t])=>(F(`tengu_config_changed`,{key:e,value:t}),`Set ${e} to ${w.bold(t)}`)),r=n()?void 0:process.env.ANTHROPIC_API_KEY,i=!!(r&&m.current.customApiKeyResponses?.approved?.includes(et(r))),a=!!(r&&f.customApiKeyResponses?.approved?.includes(et(r)));if(i!==a&&(t.push(`${a?`Enabled`:`Disabled`} custom API key`),F(`tengu_config_changed`,{key:`env.ANTHROPIC_API_KEY`,value:a})),f.theme!==m.current.theme&&t.push(`Set theme to ${w.bold(f.theme)}`),f.preferredNotifChannel!==m.current.preferredNotifChannel&&t.push(`Set notifications to ${w.bold(f.preferredNotifChannel)}`),_!==he.current&&t.push(`Set output style to ${w.bold(_)}`),v!==C.current&&t.push(`Set response language to ${w.bold(v??`Default (English)`)}`),f.editorMode!==m.current.editorMode&&t.push(`Set editor mode to ${w.bold(f.editorMode||`emacs`)}`),f.diffTool!==m.current.diffTool&&t.push(`Set diff tool to ${w.bold(f.diffTool)}`),f.autoConnectIde!==m.current.autoConnectIde&&t.push(`${f.autoConnectIde?`Enabled`:`Disabled`} auto-connect to IDE`),f.autoInstallIdeExtension!==m.current.autoInstallIdeExtension&&t.push(`${f.autoInstallIdeExtension?`Enabled`:`Disabled`} auto-install IDE extension`),f.autoCompactEnabled!==m.current.autoCompactEnabled&&t.push(`${f.autoCompactEnabled?`Enabled`:`Disabled`} auto-compact`),f.respectGitignore!==m.current.respectGitignore&&t.push(`${f.respectGitignore?`Enabled`:`Disabled`} respect .gitignore in file picker`),f.copyOnSelect!==m.current.copyOnSelect&&t.push(`${f.copyOnSelect?`Enabled`:`Disabled`} copy on select`),f.terminalProgressBarEnabled!==m.current.terminalProgressBarEnabled&&t.push(`${f.terminalProgressBarEnabled?`Enabled`:`Disabled`} terminal progress bar`),f.showStatusInTerminalTab!==m.current.showStatusInTerminalTab&&t.push(`${f.showStatusInTerminalTab?`Enabled`:`Disabled`} terminal tab status`),f.showTurnDuration!==m.current.showTurnDuration&&t.push(`${f.showTurnDuration?`Enabled`:`Disabled`} turn duration`),f.remoteControlAtStartup!==m.current.remoteControlAtStartup){let e=f.remoteControlAtStartup===void 0?`Reset Remote Control to default`:`${f.remoteControlAtStartup?`Enabled`:`Disabled`} Remote Control for all sessions`;t.push(e)}h?.autoUpdatesChannel!==fe.current?.autoUpdatesChannel&&t.push(`Set auto-update channel to ${w.bold(h?.autoUpdatesChannel??`latest`)}`),t.length>0?e(t.join(`
2
- `)):e(`Config dialog dismissed`,{display:`system`})},[z,Je,f,j,_,v,h?.autoUpdatesChannel,Ze()?h?.fastMode:void 0,e]),Dt=(0,X.useCallback)(()=>{d!==it.current&&l(it.current),P(()=>m.current);let e=nt;M(`localSettings`,{spinnerTipsEnabled:e?.spinnerTipsEnabled,prefersReducedMotion:e?.prefersReducedMotion,defaultView:e?.defaultView,outputStyle:e?.outputStyle});let t=rt;M(`userSettings`,{alwaysThinkingEnabled:t?.alwaysThinkingEnabled,fastMode:t?.fastMode,promptSuggestionEnabled:t?.promptSuggestionEnabled,autoUpdatesChannel:t?.autoUpdatesChannel,minimumVersion:t?.minimumVersion,language:t?.language,syntaxHighlightingDisabled:t?.syntaxHighlightingDisabled,permissions:t?.permissions===void 0?void 0:{...t.permissions,defaultMode:t.permissions.defaultMode}});let n=ot;I(e=>({...e,mainLoopModel:n.mainLoopModel,mainLoopModelForSession:n.mainLoopModelForSession,verbose:n.verbose,thinkingEnabled:n.thinkingEnabled,fastMode:n.fastMode,promptSuggestionEnabled:n.promptSuggestionEnabled,replBridgeEnabled:n.replBridgeEnabled,replBridgeOutboundOnly:n.replBridgeOutboundOnly,settings:n.settings,toolPermissionContext:de(e.toolPermissionContext)}))},[d,l,nt,rt,ot,I]);be(`confirm:no`,(0,X.useCallback)(()=>{z===null&&(R.current&&Dt(),e(`Config dialog dismissed`,{display:`system`}))},[z,Dt,e]),{context:`Settings`,isActive:z===null&&!O&&!c}),be(`settings:close`,Et,{context:`Settings`,isActive:z===null&&!O&&!c});let W=(0,X.useCallback)(()=>{let e=U[T];if(e?.onChange){if(e.type===`boolean`){R.current=!0,e.onChange(!e.value),e.id===`thinkingEnabled`&&(!e.value===tt.current?ct(!1):t.messages.some(e=>e.type===`assistant`)&&ct(!0));return}if(e.id===`theme`||e.id===`model`||e.id===`showExternalIncludesDialog`||e.id===`outputStyle`||e.id===`language`)switch(e.id){case`theme`:B(`Theme`),i(!0);return;case`model`:B(`Model`),i(!0);return;case`showExternalIncludesDialog`:B(`ExternalIncludes`),i(!0);return;case`outputStyle`:B(`OutputStyle`),i(!0);return;case`language`:B(`Language`),i(!0);return}if(e.id===`autoUpdatesChannel`){if(H){B(`EnableAutoUpdates`),i(!0);return}(h?.autoUpdatesChannel??`latest`)===`latest`?(B(`ChannelDowngrade`),i(!0)):(R.current=!0,M(`userSettings`,{autoUpdatesChannel:`latest`,minimumVersion:void 0}),g(e=>({...e,autoUpdatesChannel:`latest`,minimumVersion:void 0})),F(`tengu_autoupdate_channel_changed`,{channel:`latest`}));return}if(e.type===`enum`){R.current=!0;let t=(e.options.indexOf(e.value)+1)%e.options.length;e.onChange(e.options[t]);return}}},[H,U,T,h?.autoUpdatesChannel,i]),G=e=>{ct(!1);let t=Math.max(0,Math.min(U.length-1,T+e));we(t),Tt(t)};return _e({"select:previous":()=>{T===0?(ct(!1),k(!0),D(0)):G(-1)},"select:next":()=>G(1),"scroll:lineUp":()=>G(-1),"scroll:lineDown":()=>G(1),"select:accept":W,"select:previousValue":()=>W(),"select:nextValue":()=>W(),"settings:search":()=>{k(!0),lt(``)}},{context:`Settings`,isActive:z===null&&!O&&!c}),(0,Z.jsx)(b,{flexDirection:`column`,width:`100%`,tabIndex:0,autoFocus:!0,onKeyDown:(0,X.useCallback)(e=>{if(z===null&&!c){if(O){if(e.key===`escape`){e.preventDefault(),V.length>0?lt(``):k(!1);return}(e.key===`return`||e.key===`down`||e.key===`wheeldown`)&&(e.preventDefault(),k(!1),we(0),D(0));return}if(e.key===`left`||e.key===`right`||e.key===`tab`){e.preventDefault(),W();return}e.ctrl||e.meta||e.key===`j`||e.key===`k`||e.key===`/`||e.key.length===1&&e.key!==` `&&(e.preventDefault(),k(!0),lt(e.key))}},[z,c,O,V,lt,W]),children:z===`Theme`?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(mt,{onThemeSelect:e=>{R.current=!0,l(e),B(null),i(!1)},onCancel:()=>{B(null),i(!1)},hideEscToCancel:!0,skipExitHandling:!0}),(0,Z.jsx)(b,{children:(0,Z.jsx)(x,{dimColor:!0,italic:!0,children:(0,Z.jsxs)(S,{children:[(0,Z.jsx)(y,{shortcut:`Enter`,action:`select`}),(0,Z.jsx)(s,{action:`confirm:no`,context:`Confirmation`,fallback:`Esc`,description:`cancel`})]})})})]}):z===`Model`?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(_t,{initial:j,onSelect:e=>{R.current=!0,St(e),B(null),i(!1)},onCancel:()=>{B(null),i(!1)},showFastModeNotice:Ze()?He&&Ye(j)&&Qe():!1}),(0,Z.jsx)(x,{dimColor:!0,children:(0,Z.jsxs)(S,{children:[(0,Z.jsx)(y,{shortcut:`Enter`,action:`confirm`}),(0,Z.jsx)(s,{action:`confirm:no`,context:`Confirmation`,fallback:`Esc`,description:`cancel`})]})})]}):z===`ExternalIncludes`?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(bt,{onDone:()=>{B(null),i(!1)},externalIncludes:re(vt)}),(0,Z.jsx)(x,{dimColor:!0,children:(0,Z.jsxs)(S,{children:[(0,Z.jsx)(y,{shortcut:`Enter`,action:`confirm`}),(0,Z.jsx)(s,{action:`confirm:no`,context:`Confirmation`,fallback:`Esc`,description:`disable external includes`})]})})]}):z===`OutputStyle`?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Nt,{initialStyle:_,onComplete:e=>{R.current=!0,pe(e??`default`),B(null),i(!1),M(`localSettings`,{outputStyle:e}),F(`tengu_output_style_changed`,{style:e??`default`,source:`config_panel`,settings_source:`localSettings`})},onCancel:()=>{B(null),i(!1)}}),(0,Z.jsx)(x,{dimColor:!0,children:(0,Z.jsxs)(S,{children:[(0,Z.jsx)(y,{shortcut:`Enter`,action:`confirm`}),(0,Z.jsx)(s,{action:`confirm:no`,context:`Confirmation`,fallback:`Esc`,description:`cancel`})]})})]}):z===`Language`?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Rt,{initialLanguage:v,onComplete:e=>{R.current=!0,ge(e),B(null),i(!1),M(`userSettings`,{language:e}),F(`tengu_language_changed`,{language:e??`default`,source:`config_panel`})},onCancel:()=>{B(null),i(!1)}}),(0,Z.jsx)(x,{dimColor:!0,children:(0,Z.jsxs)(S,{children:[(0,Z.jsx)(y,{shortcut:`Enter`,action:`confirm`}),(0,Z.jsx)(s,{action:`confirm:no`,context:`Settings`,fallback:`Esc`,description:`cancel`})]})})]}):z===`EnableAutoUpdates`?(0,Z.jsx)(Ee,{title:`Enable Auto-Updates`,onCancel:()=>{B(null),i(!1)},hideBorder:!0,hideInputGuide:!0,children:H?.type===`config`?(0,Z.jsx)(oe,{options:[{label:`Enable with latest channel`,value:`latest`},{label:`Enable with stable channel`,value:`stable`}],onChange:e=>{R.current=!0,B(null),i(!1),P(e=>({...e,autoUpdates:!0})),p({...N(),autoUpdates:!0}),M(`userSettings`,{autoUpdatesChannel:e,minimumVersion:void 0}),g(t=>({...t,autoUpdatesChannel:e,minimumVersion:void 0})),F(`tengu_autoupdate_enabled`,{channel:e})}}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(x,{children:H?.type===`env`?`Auto-updates are controlled by an environment variable and cannot be changed here.`:`Auto-updates are disabled in development builds.`}),H?.type===`env`&&(0,Z.jsxs)(x,{dimColor:!0,children:[`Unset `,H.envVar,` to re-enable auto-updates.`]})]})}):z===`ChannelDowngrade`?(0,Z.jsx)(kt,{currentVersion:`0.0.15`,onChoice:e=>{if(B(null),i(!1),e===`cancel`)return;R.current=!0;let t={autoUpdatesChannel:`stable`};e===`stay`&&(t.minimumVersion=`0.0.15`),M(`userSettings`,t),g(e=>({...e,...t})),F(`tengu_autoupdate_channel_changed`,{channel:`stable`,minimum_version_set:e===`stay`})}}):(0,Z.jsxs)(b,{flexDirection:`column`,gap:1,marginY:se?void 0:1,children:[(0,Z.jsx)(Ce,{query:V,isFocused:O&&!c,isTerminalFocused:De,cursorOffset:ut,placeholder:`Search settings…`}),(0,Z.jsx)(b,{flexDirection:`column`,children:U.length===0?(0,Z.jsxs)(x,{dimColor:!0,italic:!0,children:[`No settings match "`,V,`"`]}):(0,Z.jsxs)(Z.Fragment,{children:[E>0&&(0,Z.jsxs)(x,{dimColor:!0,children:[o.arrowUp,` `,E,` more above`]}),U.slice(E,E+A).map((e,t)=>{let n=E+t===T&&!c&&!O;return(0,Z.jsx)(Y.Fragment,{children:(0,Z.jsxs)(b,{width:`100%`,children:[(0,Z.jsx)(b,{width:44,children:(0,Z.jsxs)(x,{color:n?`suggestion`:void 0,children:[n?o.pointer:` `,` `,e.label]})}),(0,Z.jsx)(b,{flexGrow:1,children:e.type===`boolean`?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(x,{color:n?`suggestion`:void 0,children:e.value.toString()}),st&&e.id===`thinkingEnabled`&&(0,Z.jsxs)(x,{color:`warning`,children:[` `,`Changing thinking mode mid-conversation will increase latency and may reduce quality.`]})]}):e.id===`theme`?(0,Z.jsx)(x,{color:n?`suggestion`:void 0,children:Ut[e.value.toString()]??e.value.toString()}):e.id===`notifChannel`?(0,Z.jsx)(x,{color:n?`suggestion`:void 0,children:(0,Z.jsx)(Ht,{value:e.value.toString()})}):e.id===`defaultPermissionMode`?(0,Z.jsx)(x,{color:n?`suggestion`:void 0,children:Me(e.value)}):e.id===`autoUpdatesChannel`&&H?(0,Z.jsxs)(b,{flexDirection:`column`,children:[(0,Z.jsx)(x,{color:n?`suggestion`:void 0,children:`disabled`}),(0,Z.jsxs)(x,{dimColor:!0,children:[`(`,Be(H),`)`]})]}):(0,Z.jsx)(x,{color:n?`suggestion`:void 0,children:e.value.toString()})})]})},e.id)}),E+A<U.length&&(0,Z.jsxs)(x,{dimColor:!0,children:[o.arrowDown,` `,U.length-E-A,` more below`]})]})}),c?(0,Z.jsx)(x,{dimColor:!0,children:(0,Z.jsxs)(S,{children:[(0,Z.jsx)(y,{shortcut:`←/→ tab`,action:`switch`}),(0,Z.jsx)(y,{shortcut:`↓`,action:`return`}),(0,Z.jsx)(s,{action:`confirm:no`,context:`Settings`,fallback:`Esc`,description:`close`})]})}):O?(0,Z.jsx)(x,{dimColor:!0,children:(0,Z.jsxs)(S,{children:[(0,Z.jsx)(x,{children:`Type to filter`}),(0,Z.jsx)(y,{shortcut:`Enter/↓`,action:`select`}),(0,Z.jsx)(y,{shortcut:`↑`,action:`tabs`}),(0,Z.jsx)(s,{action:`confirm:no`,context:`Settings`,fallback:`Esc`,description:`clear`})]})}):(0,Z.jsx)(x,{dimColor:!0,children:(0,Z.jsxs)(S,{children:[(0,Z.jsx)(s,{action:`select:accept`,context:`Settings`,fallback:`Space`,description:`change`}),(0,Z.jsx)(s,{action:`settings:close`,context:`Settings`,fallback:`Enter`,description:`save`}),(0,Z.jsx)(s,{action:`settings:search`,context:`Settings`,fallback:`/`,description:`search`}),(0,Z.jsx)(s,{action:`confirm:no`,context:`Settings`,fallback:`Esc`,description:`cancel`})]})})]})})}function Ht({value:e}){switch(e){case`auto`:return`Auto`;case`iterm2`:return(0,Z.jsxs)(x,{children:[`iTerm2 `,(0,Z.jsx)(x,{dimColor:!0,children:`(OSC 9)`})]});case`terminal_bell`:return(0,Z.jsxs)(x,{children:[`Terminal Bell `,(0,Z.jsx)(x,{dimColor:!0,children:`(\\a)`})]});case`kitty`:return(0,Z.jsxs)(x,{children:[`Kitty `,(0,Z.jsx)(x,{dimColor:!0,children:`(OSC 99)`})]});case`ghostty`:return(0,Z.jsxs)(x,{children:[`Ghostty `,(0,Z.jsx)(x,{dimColor:!0,children:`(OSC 777)`})]});case`iterm2_with_bell`:return`iTerm2 w/ Bell`;case`notifications_disabled`:return`Disabled`;default:return e}}var Y,X,Z,Ut,Wt=e((()=>{D(),Y=t(C(),1),X=t(C(),1),g(),a(),ze(),Je(),T(),j(),f(),He(),We(),pt(),l(),ht(),I(),vt(),yt(),jt(),d(),Lt(),Bt(),c(),ie(),dt(),H(),fe(),Fe(),pe(),i(),St(),ge(),L(),se(),Z=k(),Ut={auto:`Auto (match terminal)`,dark:`Dark mode`,light:`Light mode`,"dark-daltonized":`Dark mode (colorblind-friendly)`,"light-daltonized":`Light mode (colorblind-friendly)`,"dark-ansi":`Dark mode (ANSI colors only)`,"light-ansi":`Light mode (ANSI colors only)`}}));function Gt({onClose:e,context:t,defaultTab:n}){let[r,i]=(0,Q.useState)(n),[a,o]=(0,Q.useState)(!1),[ee,te]=(0,Q.useState)(!1),s=ft(),{rows:ne}=ut(Te()),re=s?ne+1:Math.max(15,Math.min(Math.floor(ne*.8),30)),[c]=(0,Q.useState)(()=>U().catch(()=>[]));return V(),be(`confirm:no`,()=>{a||e(`Status dialog dismissed`,{display:`system`})},{context:`Settings`,isActive:!a&&!(r===`Config`&&ee)}),(0,$.jsx)(O,{color:`permission`,children:(0,$.jsx)(E,{color:`permission`,selectedTab:r,onTabChange:i,hidden:a,initialHeaderFocused:n!==`Config`,contentHeight:a||s?void 0:re,children:[(0,$.jsx)(we,{title:`Status`,children:(0,$.jsx)(Et,{context:t,diagnosticsPromise:c})},`status`),(0,$.jsx)(we,{title:`Config`,children:(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(Vt,{context:t,onClose:e,setTabsHidden:o,onIsSearchModeChange:te,contentHeight:re})})},`config`)]})})}var Q,$,Kt=e((()=>{Q=t(C(),1),g(),lt(),ge(),dt(),D(),Ot(),Wt(),$=k()}));export{Kt as n,Gt as t};
@@ -1 +0,0 @@
1
- import{a as e,o as t}from"./api-ClAyS7cQ.js";t();export{e as getOAuthHeaders};
@@ -1,10 +0,0 @@
1
- import{d as e,o as t}from"./envUtils-DcaKZlRU.js";import{n,t as r}from"./defineProperty-C-QyHrDq.js";import{n as i,t as a}from"./axios-DaWTGg7G.js";import{aS as o,nf as s,oS as c,rf as l}from"./loadAgentsDir-CwEfQDOw.js";import{C as ee,P as u,R as te,c as d,i as ne,x as f}from"./debug-BQj6h99Q.js";import{g as p,n as m}from"./settings-CvhsRFaT.js";import{c as re,h,y as g}from"./config-BSkuQZNf.js";import{o as _,s as v}from"./log-BlJ7CcKG.js";import{n as y,r as b}from"./analytics-DJobLaWP.js";import{l as x,u as S}from"./oauth-D38aRTUb.js";import{$n as ie,Ar as ae,Br as C,Bt as w,Cn as oe,Dt as se,En as ce,Ft as le,Hr as T,Ir as E,Mr as D,Or as O,Ot as k,Pr as A,Rr as j,Sn as M,St as N,Ur as P,fn as F,gn as I,ii as L,jn as R,jr as z,jt as B,kr as V,mn as H,nn as U,nr as W,oi as ue,pn as G,un as de,yt as fe,zr as K}from"./model-CeG-iOKF.js";import{n as pe,t as me}from"./userAgent-aoe_xVAb.js";import{F as q,T as he}from"./sessionState-zhvcDpb2.js";import{d as ge,u as _e}from"./firstPartyEventLogger-7pAyUdbp.js";import{n as ve}from"./trustedDevice-DWZxDUxS.js";import{i as ye,r as be}from"./grove-Bck1zFaD.js";import{t as xe}from"./remoteManagedSettings-CfFmrRze.js";import{d as Se,n as Ce,t as we}from"./status-BP_R8051.js";import{createHash as Te,randomBytes as J}from"crypto";import{createServer as Ee}from"http";l(),w(),R(),h(),oe(),I(),_e();async function Y(){k.cache?.clear?.(),ve(),ce(),H(),ge(),be.cache?.clear?.(),ye.cache?.clear?.(),await xe(),await s()}async function De({clearOnboarding:e=!1}){let{flushTelemetry:t}=await import(`./instrumentation-jsPu6qqs.js`);await t(),await de(),M().delete(),await Y(),g(t=>{let n={...t};return e&&(n.hasCompletedOnboarding=!1,n.subscriptionNoticeCount=0,n.hasAvailableSubscription=!1,n.customApiKeyResponses?.approved&&(n.customApiKeyResponses={...n.customApiKeyResponses,approved:[]})),n.oauthAccount=void 0,n})}t(),n(),te(),f(),ne(),y(),p(),ue(),P(),A(),he(),a(),S(),h(),W(),_(),pe();async function Oe(){try{if(re().claudeCodeFirstTokenDate!==void 0)return;let e=ie();if(e.error){v(Error(`Failed to get auth headers: ${e.error}`));return}let t=`${x().BASE_API_URL}/api/organization/claude_code_first_token_date`,n=(await i.get(t,{headers:{...e.headers,"User-Agent":me()},timeout:1e4})).data?.first_token_date??null;if(n!==null){let e=new Date(n).getTime();if(isNaN(e)){v(Error(`Received invalid first_token_date from API: ${n}`));return}}g(e=>({...e,claudeCodeFirstTokenDate:n}))}catch(e){v(e)}}o(),S(),_();var ke=class{constructor(e=`/callback`){r(this,`localServer`,void 0),r(this,`port`,0),r(this,`promiseResolver`,null),r(this,`promiseRejecter`,null),r(this,`expectedState`,null),r(this,`pendingResponse`,null),r(this,`callbackPath`,void 0),this.localServer=Ee(),this.callbackPath=e}async start(e){return new Promise((t,n)=>{this.localServer.once(`error`,e=>{n(Error(`Failed to start OAuth callback server: ${e.message}`))}),this.localServer.listen(e??0,`localhost`,()=>{let e=this.localServer.address();this.port=e.port,t(this.port)})})}getPort(){return this.port}hasPendingResponse(){return this.pendingResponse!==null}async waitForAuthorization(e,t){return new Promise((n,r)=>{this.promiseResolver=n,this.promiseRejecter=r,this.expectedState=e,this.startLocalListener(t)})}handleSuccessRedirect(e,t){if(!this.pendingResponse)return;if(t){t(this.pendingResponse,e),this.pendingResponse=null,b(`tengu_oauth_automatic_redirect`,{custom_handler:!0});return}let n=K(e)?x().CLAUDEAI_SUCCESS_URL:x().CONSOLE_SUCCESS_URL;this.pendingResponse.writeHead(302,{Location:n}),this.pendingResponse.end(),this.pendingResponse=null,b(`tengu_oauth_automatic_redirect`,{})}handleErrorRedirect(){if(!this.pendingResponse)return;let e=x().CLAUDEAI_SUCCESS_URL;this.pendingResponse.writeHead(302,{Location:e}),this.pendingResponse.end(),this.pendingResponse=null,b(`tengu_oauth_automatic_redirect_error`,{})}startLocalListener(e){this.localServer.on(`request`,this.handleRedirect.bind(this)),this.localServer.on(`error`,this.handleError.bind(this)),e()}handleRedirect(e,t){let n=new URL(e.url||``,`http://${e.headers.host||`localhost`}`);if(n.pathname!==this.callbackPath){t.writeHead(404),t.end();return}let r=n.searchParams.get(`code`)??void 0,i=n.searchParams.get(`state`)??void 0;this.validateAndRespond(r,i,t)}validateAndRespond(e,t,n){if(!e){n.writeHead(400),n.end(`Authorization code not found`),this.reject(Error(`No authorization code received`));return}if(t!==this.expectedState){n.writeHead(400),n.end(`Invalid state parameter`),this.reject(Error(`Invalid state parameter`));return}this.pendingResponse=n,this.resolve(e)}handleError(e){v(e),this.close(),this.reject(e)}resolve(e){this.promiseResolver&&(this.promiseResolver(e),this.promiseResolver=null,this.promiseRejecter=null)}reject(e){this.promiseRejecter&&(this.promiseRejecter(e),this.promiseResolver=null,this.promiseRejecter=null)}close(){this.pendingResponse&&this.handleErrorRedirect(),this.localServer&&(this.localServer.removeAllListeners(),this.localServer.close())}};function X(e){return e.toString(`base64`).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=/g,``)}function Z(){return X(J(32))}function Ae(e){let t=Te(`sha256`);return t.update(e),X(t.digest())}function je(){return X(J(32))}y(),A(),n();var Q=class{constructor(){r(this,`codeVerifier`,void 0),r(this,`authCodeListener`,null),r(this,`port`,null),r(this,`manualAuthCodeResolver`,null),this.codeVerifier=Z()}async startOAuthFlow(e,t){this.authCodeListener=new ke,this.port=await this.authCodeListener.start();let n=Ae(this.codeVerifier),r=je(),i={codeChallenge:n,state:r,port:this.port,loginWithClaudeAi:t?.loginWithClaudeAi,inferenceOnly:t?.inferenceOnly,orgUUID:t?.orgUUID,loginHint:t?.loginHint,loginMethod:t?.loginMethod},a=O({...i,isManual:!0}),o=O({...i,isManual:!1}),s=await this.waitForAuthorizationCode(r,async()=>{t?.skipBrowserOpen?await e(a,o):(await e(a),await c(o))}),l=this.authCodeListener?.hasPendingResponse()??!1;b(`tengu_oauth_auth_code_received`,{automatic:l});try{let e=await ae(s,r,this.codeVerifier,this.port,!l,t?.expiresIn),n=await D(e.access_token);if(l){let t=E(e.scope);this.authCodeListener?.handleSuccessRedirect(t)}return this.formatTokens(e,n.subscriptionType,n.rateLimitTier,n.rawProfile)}catch(e){throw l&&this.authCodeListener?.handleErrorRedirect(),e}finally{this.authCodeListener?.close()}}async waitForAuthorizationCode(e,t){return new Promise((n,r)=>{this.manualAuthCodeResolver=n,this.authCodeListener?.waitForAuthorization(e,t).then(e=>{this.manualAuthCodeResolver=null,n(e)}).catch(e=>{this.manualAuthCodeResolver=null,r(e)})})}handleManualAuthCodeInput(e){this.manualAuthCodeResolver&&(this.manualAuthCodeResolver(e.authorizationCode),this.manualAuthCodeResolver=null,this.authCodeListener?.close())}formatTokens(e,t,n,r){return{accessToken:e.access_token,refreshToken:e.refresh_token,expiresAt:Date.now()+e.expires_in*1e3,scopes:E(e.scope),subscriptionType:t,rateLimitTier:n,profile:r,tokenAccount:e.account?{uuid:e.account.uuid,emailAddress:e.account.email_address,organizationUuid:e.organization?.uuid}:void 0}}cleanup(){this.authCodeListener?.close(),this.manualAuthCodeResolver=null}};y(),A(),w(),h(),_(),Se();async function $(e){await De({clearOnboarding:!1});let t=e.profile??await T(e.accessToken);t?C({accountUuid:t.account.uuid,emailAddress:t.account.email,organizationUuid:t.organization.uuid,displayName:t.account.display_name||void 0,hasExtraUsageEnabled:t.organization.has_extra_usage_enabled??void 0,billingType:t.organization.billing_type??void 0,subscriptionCreatedAt:t.organization.subscription_created_at??void 0,accountCreatedAt:t.account.created_at}):e.tokenAccount&&C({accountUuid:e.tokenAccount.uuid,emailAddress:e.tokenAccount.emailAddress,organizationUuid:e.tokenAccount.organizationUuid});let n=F(e);if(fe(),n.warning&&b(`tengu_oauth_storage_warning`,{warning:n.warning}),await z(e.accessToken).catch(e=>d(String(e),{level:`error`})),K(e.scopes))await Oe().catch(e=>d(String(e),{level:`error`}));else if(!await V(e.accessToken))throw Error(`Unable to create API key. The server accepted the request but did not return a key.`);await Y()}async function Me({email:e,sso:t,console:n,claudeai:r}){n&&r&&(process.stderr.write(`Error: --console and --claudeai cannot be used together.
2
- `),process.exit(1));let i=m(),a=i.forceLoginMethod?i.forceLoginMethod===`claudeai`:!n,o=i.forceLoginOrgUUID,s=process.env.CLAUDE_CODE_OAUTH_REFRESH_TOKEN;if(s){let e=process.env.CLAUDE_CODE_OAUTH_SCOPES;e||(process.stderr.write(`CLAUDE_CODE_OAUTH_SCOPES is required when using CLAUDE_CODE_OAUTH_REFRESH_TOKEN.
3
- Set it to the space-separated scopes the refresh token was issued with
4
- (e.g. "user:inference" or "user:profile user:inference user:sessions:claude_code user:mcp_servers").
5
- `),process.exit(1));let t=e.split(/\s+/).filter(Boolean);try{b(`tengu_login_from_refresh_token`,{});let e=await j(s,{scopes:t});await $(e);let n=await G();n.valid||(process.stderr.write(`${n.message}\n`),process.exit(1)),g(e=>e.hasCompletedOnboarding?e:{...e,hasCompletedOnboarding:!0}),b(`tengu_oauth_success`,{loginWithClaudeAi:K(e.scopes)}),process.stdout.write(`Login successful.
6
- `),process.exit(0)}catch(e){v(e);let t=q(e);process.stderr.write(`Login failed: ${u(e)}\n${t?`${t}\n`:``}`),process.exit(1)}}let c=t?`sso`:void 0,l=new Q;try{b(`tengu_oauth_flow_start`,{loginWithClaudeAi:a}),await $(await l.startOAuthFlow(async e=>{process.stdout.write(`Opening browser to sign in…
7
- `),process.stdout.write(`If the browser didn't open, visit: ${e}\n`)},{loginWithClaudeAi:a,loginHint:e,loginMethod:c,orgUUID:o}));let t=await G();t.valid||(process.stderr.write(`${t.message}\n`),process.exit(1)),b(`tengu_oauth_success`,{loginWithClaudeAi:a}),process.stdout.write(`Login successful.
8
- `),process.exit(0)}catch(e){v(e);let t=q(e);process.stderr.write(`Login failed: ${u(e)}\n${t?`${t}\n`:``}`),process.exit(1)}finally{l.cleanup()}}async function Ne(t){let{source:n,hasToken:r}=se(),{source:i}=N(),a=!!process.env.ANTHROPIC_API_KEY&&!e(),o=B(),s=le(),c=U(),l=r||i!==`none`||a||c,u=`none`;if(c?u=`third_party`:n===`claude.ai`?u=`claude.ai`:n===`apiKeyHelper`?u=`api_key_helper`:n===`none`?i===`ANTHROPIC_API_KEY`||a?u=`api_key`:i===`/login managed key`&&(u=`claude.ai`):u=`oauth_token`,t.text){let e=[...Ce(),...we()],t=!1;for(let n of e){let e=typeof n.value==`string`?n.value:Array.isArray(n.value)?n.value.join(`, `):null;e===null||e===`none`||(t=!0,n.label?process.stdout.write(`${n.label}: ${e}\n`):process.stdout.write(`${e}\n`))}!t&&a&&process.stdout.write(`API key: ANTHROPIC_API_KEY
9
- `),l||process.stdout.write(`Not logged in.
10
- `)}else{let e=L(),t=i===`none`?a?`ANTHROPIC_API_KEY`:null:i,n={loggedIn:l,authMethod:u,apiProvider:e};t&&(n.apiKeySource=t),u===`claude.ai`&&(n.email=o?.emailAddress??null,n.orgId=o?.organizationUuid??null,n.orgName=o?.organizationName??null,n.subscriptionType=s??null),process.stdout.write(`${ee(n,null,2)}\n`)}process.exit(+!l)}export{Q as i,Ne as n,$ as r,Me as t};
@@ -1 +0,0 @@
1
- import{Bt as e,It as t,Ot as n,mt as r,yt as i}from"./model-CeG-iOKF.js";e();export{r as checkAndRefreshOAuthTokenIfNeeded,i as clearOAuthTokenCache,n as getClaudeAIOAuthTokens,t as handleOAuth401Error};
@@ -1 +0,0 @@
1
- import{n as e,t}from"./auth-CWAvPfX7.js";export{t as authLogin,e as authStatus};
@@ -1 +0,0 @@
1
- import{t as e}from"./backgroundHousekeeping-rzQFJiND.js";export{e as startBackgroundHousekeeping};
@@ -1 +0,0 @@
1
- import{a as e,n as t,o as n,t as r}from"./bridgeConfig-CPHAyzdg.js";e();export{r as getBridgeAccessToken,t as getBridgeBaseUrl,n as isSelfHostedBridge};
@@ -1 +0,0 @@
1
- import{n as e,t}from"./caches-FP8mGB4k.js";e();export{t as clearSessionCaches};
@@ -1,17 +0,0 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{a as t,l as n}from"./proxy-C0j74LqT.js";import{r,t as i}from"./store-Z8rTjDHe.js";function a(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function o(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}var s=e((()=>{})),c,l=e((()=>{c=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return c=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^n()&15>>e/4).toString(16))}}));function u(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}var d,f=e((()=>{d=e=>{if(e instanceof Error)return e;if(typeof e==`object`&&e){try{if(Object.prototype.toString.call(e)===`[object Error]`){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)}})),p,m,h,g,ee,_,v,y,te,ne,re,ie,ae,oe,se,ce,le,ue,de=e((()=>{f(),p=class extends Error{},m=class e extends p{constructor(t,n,r,i){super(`${e.makeMessage(t,n,r)}`),this.status=t,this.headers=i,this.requestID=i?.get(`x-request-id`),this.error=n;let a=n;this.code=a?.code,this.param=a?.param,this.type=a?.type}static makeMessage(e,t,n){let r=t?.message?typeof t.message==`string`?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||`(no status code or body)`}static generate(t,n,r,i){if(!t||!i)return new g({message:r,cause:d(n)});let a=n?.error;return t===400?new _(t,a,r,i):t===401?new v(t,a,r,i):t===403?new y(t,a,r,i):t===404?new te(t,a,r,i):t===409?new ne(t,a,r,i):t===422?new re(t,a,r,i):t===429?new ie(t,a,r,i):t>=500?new ae(t,a,r,i):new e(t,a,r,i)}},h=class extends m{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},g=class extends m{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},ee=class extends g{constructor({message:e}={}){super({message:e??`Request timed out.`})}},_=class extends m{},v=class extends m{},y=class extends m{},te=class extends m{},ne=class extends m{},re=class extends m{},ie=class extends m{},ae=class extends m{},oe=class extends p{constructor(){super(`Could not parse response content as the length limit was reached`)}},se=class extends p{constructor(){super(`Could not parse response content as the request was rejected by the content filter`)}},ce=class extends Error{constructor(e){super(e)}},le=class extends m{constructor(e,t,n){let r=`OAuth2 authentication error`,i;if(t&&typeof t==`object`){let e=t;i=e.error;let n=e.error_description;n&&typeof n==`string`?r=n:i&&(r=i)}super(e,t,r,n),this.error_code=i}},ue=class extends p{constructor(e,t,n){super(e),this.provider=t,this.cause=n}}}));function fe(e){return typeof e==`object`?e??{}:{}}function pe(e){if(!e)return!0;for(let t in e)return!1;return!0}function me(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function he(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var ge,_e,b,ve,ye,be,xe=e((()=>{de(),ge=/^[a-z][a-z0-9+.-]*:/i,_e=e=>ge.test(e),b=e=>(b=Array.isArray,b(e)),ve=b,ye=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new p(`${e} must be an integer`);if(t<0)throw new p(`${e} must be a positive integer`);return t},be=e=>{try{return JSON.parse(e)}catch{return}}})),Se,Ce=e((()=>{Se=e=>new Promise(t=>setTimeout(t,e))})),we,Te=e((()=>{we=`6.46.0`}));function Ee(){return typeof Deno<`u`&&Deno.build!=null?`deno`:typeof EdgeRuntime<`u`?`edge`:Object.prototype.toString.call(globalThis.process===void 0?0:globalThis.process)===`[object process]`?`node`:`unknown`}function De(){if(typeof navigator>`u`||!navigator)return null;for(let{key:e,pattern:t}of[{key:`edge`,pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`chrome`,pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`firefox`,pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`safari`,pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}]){let n=t.exec(navigator.userAgent);if(n)return{browser:e,version:`${n[1]||0}.${n[2]||0}.${n[3]||0}`}}return null}var Oe,ke,Ae,je,Me,Ne,Pe=e((()=>{Te(),Oe=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`,ke=()=>{let e=Ee();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":we,"X-Stainless-OS":je(Deno.build.os),"X-Stainless-Arch":Ae(Deno.build.arch),"X-Stainless-Runtime":`deno`,"X-Stainless-Runtime-Version":typeof Deno.version==`string`?Deno.version:Deno.version?.deno??`unknown`};if(typeof EdgeRuntime<`u`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":we,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":`edge`,"X-Stainless-Runtime-Version":globalThis.process.version};if(e===`node`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":we,"X-Stainless-OS":je(globalThis.process.platform??`unknown`),"X-Stainless-Arch":Ae(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=De();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":we,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":we,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}},Ae=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,je=e=>(e=e.toLowerCase(),e.includes(`ios`)?`iOS`:e===`android`?`Android`:e===`darwin`?`MacOS`:e===`win32`?`Windows`:e===`freebsd`?`FreeBSD`:e===`openbsd`?`OpenBSD`:e===`linux`?`Linux`:e?`Other:${e}`:`Unknown`),Ne=()=>Me??(Me=ke())}));function Fe(){if(typeof fetch<`u`)return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Ie(...e){let t=globalThis.ReadableStream;if(t===void 0)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function Le(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return Ie({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function Re(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function ze(e){if(typeof e!=`object`||!e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}var Be=e((()=>{})),Ve,He=e((()=>{Ve=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)})})),Ue,We,Ge,Ke=e((()=>{Ue=`RFC3986`,We=e=>String(e),Ge={RFC1738:e=>String(e).replace(/%20/g,`+`),RFC3986:We}}));function qe(e){return!e||typeof e!=`object`?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function Je(e,t){if(b(e)){let n=[];for(let r=0;r<e.length;r+=1)n.push(t(e[r]));return n}return t(e)}var Ye,x,Xe,Ze,Qe=e((()=>{Ke(),xe(),Ye=(e,t)=>(Ye=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Ye(e,t)),x=(()=>{let e=[];for(let t=0;t<256;++t)e.push(`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase());return e})(),Xe=1024,Ze=(e,t,n,r,i)=>{if(e.length===0)return e;let a=e;if(typeof e==`symbol`?a=Symbol.prototype.toString.call(e):typeof e!=`string`&&(a=String(e)),n===`iso-8859-1`)return escape(a).replace(/%u[0-9a-f]{4}/gi,function(e){return`%26%23`+parseInt(e.slice(2),16)+`%3B`});let o=``;for(let e=0;e<a.length;e+=Xe){let t=a.length>=Xe?a.slice(e,e+Xe):a,n=[];for(let e=0;e<t.length;++e){let r=t.charCodeAt(e);if(r===45||r===46||r===95||r===126||r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122||i===`RFC1738`&&(r===40||r===41)){n[n.length]=t.charAt(e);continue}if(r<128){n[n.length]=x[r];continue}if(r<2048){n[n.length]=x[192|r>>6]+x[128|r&63];continue}if(r<55296||r>=57344){n[n.length]=x[224|r>>12]+x[128|r>>6&63]+x[128|r&63];continue}e+=1,r=65536+((r&1023)<<10|t.charCodeAt(e)&1023),n[n.length]=x[240|r>>18]+x[128|r>>12&63]+x[128|r>>6&63]+x[128|r&63]}o+=n.join(``)}return o}}));function $e(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`symbol`||typeof e==`bigint`}function et(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,ee){let _=e,v=ee,y=0,te=!1;for(;(v=v.get(ot))!==void 0&&!te;){let t=v.get(e);if(y+=1,t!==void 0){if(t===y)throw RangeError(`Cyclic object value`);te=!0}v.get(ot)===void 0&&(y=0)}if(typeof l==`function`?_=l(t,_):_ instanceof Date?_=f?.(_):n===`comma`&&b(_)&&(_=Je(_,function(e){return e instanceof Date?f?.(e):e})),_===null){if(a)return c&&!h?c(t,S.encoder,g,`key`,p):t;_=``}if($e(_)||qe(_)){if(c){let e=h?t:c(t,S.encoder,g,`key`,p);return[m?.(e)+`=`+m?.(c(_,S.encoder,g,`value`,p))]}return[m?.(t)+`=`+m?.(String(_))]}let ne=[];if(_===void 0)return ne;let re;if(n===`comma`&&b(_))h&&c&&(_=Je(_,c)),re=[{value:_.length>0?_.join(`,`)||null:void 0}];else if(b(l))re=l;else{let e=Object.keys(_);re=u?e.sort(u):e}let ie=s?String(t).replace(/\./g,`%2E`):String(t),ae=r&&b(_)&&_.length===1?ie+`[]`:ie;if(i&&b(_)&&_.length===0)return ae+`[]`;for(let t=0;t<re.length;++t){let v=re[t],te=typeof v==`object`&&v.value!==void 0?v.value:_[v];if(o&&te===null)continue;let ie=d&&s?v.replace(/\./g,`%2E`):v,oe=b(_)?typeof n==`function`?n(ae,ie):ae:ae+(d?`.`+ie:`[`+ie+`]`);ee.set(e,y);let se=new WeakMap;se.set(ot,ee),it(ne,et(te,oe,n,r,i,a,o,s,n===`comma`&&h&&b(_)?null:c,l,u,d,f,p,m,h,g,se))}return ne}function tt(e=S){if(e.allowEmptyArrays!==void 0&&typeof e.allowEmptyArrays!=`boolean`)throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(e.encodeDotInKeys!==void 0&&typeof e.encodeDotInKeys!=`boolean`)throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&e.encoder!==void 0&&typeof e.encoder!=`function`)throw TypeError(`Encoder has to be a function.`);let t=e.charset||S.charset;if(e.charset!==void 0&&e.charset!==`utf-8`&&e.charset!==`iso-8859-1`)throw TypeError(`The charset option must be either utf-8, iso-8859-1, or undefined`);let n=Ue;if(e.format!==void 0){if(!Ye(Ge,e.format))throw TypeError(`Unknown format option provided.`);n=e.format}let r=Ge[n],i=S.filter;(typeof e.filter==`function`||b(e.filter))&&(i=e.filter);let a;if(a=e.arrayFormat&&e.arrayFormat in rt?e.arrayFormat:`indices`in e?e.indices?`indices`:`repeat`:S.arrayFormat,`commaRoundTrip`in e&&typeof e.commaRoundTrip!=`boolean`)throw TypeError("`commaRoundTrip` must be a boolean, or absent");let o=e.allowDots===void 0?e.encodeDotInKeys?!0:S.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix==`boolean`?e.addQueryPrefix:S.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays==`boolean`?!!e.allowEmptyArrays:S.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel==`boolean`?e.charsetSentinel:S.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:e.delimiter===void 0?S.delimiter:e.delimiter,encode:typeof e.encode==`boolean`?e.encode:S.encode,encodeDotInKeys:typeof e.encodeDotInKeys==`boolean`?e.encodeDotInKeys:S.encodeDotInKeys,encoder:typeof e.encoder==`function`?e.encoder:S.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==`boolean`?e.encodeValuesOnly:S.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:typeof e.serializeDate==`function`?e.serializeDate:S.serializeDate,skipNulls:typeof e.skipNulls==`boolean`?e.skipNulls:S.skipNulls,sort:typeof e.sort==`function`?e.sort:null,strictNullHandling:typeof e.strictNullHandling==`boolean`?e.strictNullHandling:S.strictNullHandling}}function nt(e,t={}){let n=e,r=tt(t),i,a;typeof r.filter==`function`?(a=r.filter,n=a(``,n)):b(r.filter)&&(a=r.filter,i=a);let o=[];if(typeof n!=`object`||!n)return``;let s=rt[r.arrayFormat],c=s===`comma`&&r.commaRoundTrip;i||(i=Object.keys(n)),r.sort&&i.sort(r.sort);let l=new WeakMap;for(let e=0;e<i.length;++e){let t=i[e];r.skipNulls&&n[t]===null||it(o,et(n[t],t,s,c,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,l))}let u=o.join(r.delimiter),d=r.addQueryPrefix===!0?`?`:``;return r.charsetSentinel&&(r.charset===`iso-8859-1`?d+=`utf8=%26%2310003%3B&`:d+=`utf8=%E2%9C%93&`),u.length>0?d+u:``}var rt,it,at,S,ot,st=e((()=>{Qe(),Ke(),xe(),rt={brackets(e){return String(e)+`[]`},comma:`comma`,indices(e,t){return String(e)+`[`+t+`]`},repeat(e){return String(e)}},it=function(e,t){Array.prototype.push.apply(e,b(t)?t:[t])},S={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:`indices`,charset:`utf-8`,charsetSentinel:!1,delimiter:`&`,encode:!0,encodeDotInKeys:!1,encoder:Ze,encodeValuesOnly:!1,format:Ue,formatter:We,indices:!1,serializeDate(e){return(at??(at=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1},ot={}}));function ct(e){return nt(e,{arrayFormat:`brackets`})}var lt=e((()=>{st()}));function ut(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function dt(e){let t;return(pt??(t=new globalThis.TextEncoder,pt=t.encode.bind(t)))(e)}function ft(e){let t;return(mt??(t=new globalThis.TextDecoder,mt=t.decode.bind(t)))(e)}var pt,mt,ht=e((()=>{}));function gt(e,t){for(let n=t??0;n<e.length;n++){if(e[n]===10)return{preceding:n,index:n+1,carriage:!1};if(e[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function _t(e){for(let t=0;t<e.length-1;t++){if(e[t]===10&&e[t+1]===10||e[t]===13&&e[t+1]===13)return t+2;if(e[t]===13&&e[t+1]===10&&t+3<e.length&&e[t+2]===13&&e[t+3]===10)return t+4}return-1}var C,w,vt,yt=e((()=>{s(),ht(),vt=class{constructor(){C.set(this,void 0),w.set(this,void 0),a(this,C,new Uint8Array,`f`),a(this,w,null,`f`)}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==`string`?dt(e):e;a(this,C,ut([o(this,C,`f`),t]),`f`);let n=[],r;for(;(r=gt(o(this,C,`f`),o(this,w,`f`)))!=null;){if(r.carriage&&o(this,w,`f`)==null){a(this,w,r.index,`f`);continue}if(o(this,w,`f`)!=null&&(r.index!==o(this,w,`f`)+1||r.carriage)){n.push(ft(o(this,C,`f`).subarray(0,o(this,w,`f`)-1))),a(this,C,o(this,C,`f`).subarray(o(this,w,`f`)),`f`),a(this,w,null,`f`);continue}let e=o(this,w,`f`)===null?r.preceding:r.preceding-1,t=ft(o(this,C,`f`).subarray(0,e));n.push(t),a(this,C,o(this,C,`f`).subarray(r.index),`f`),a(this,w,null,`f`)}return n}flush(){return o(this,C,`f`).length?this.decode(`
2
- `):[]}},C=new WeakMap,w=new WeakMap,vt.NEWLINE_CHARS=new Set([`
3
- `,`\r`]),vt.NEWLINE_REGEXP=/\r\n|[\n\r]/g}));function bt(){}function xt(e,t,n){return!t||St[e]>St[n]?bt:t[e].bind(t)}function T(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return wt;let r=Tt.get(t);if(r&&r[0]===n)return r[1];let i={error:xt(`error`,t,n),warn:xt(`warn`,t,n),info:xt(`info`,t,n),debug:xt(`debug`,t,n)};return Tt.set(t,[n,i]),i}var St,Ct,wt,Tt,Et,Dt=e((()=>{xe(),St={off:0,error:200,warn:300,info:400,debug:500},Ct=(e,t,n)=>{if(e){if(me(St,e))return e;T(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(St))}`)}},wt={error:bt,warn:bt,info:bt,debug:bt},Tt=new WeakMap,Et=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,e.toLowerCase()===`authorization`||e.toLowerCase()===`api-key`||e.toLowerCase()===`x-api-key`||e.toLowerCase()===`x-amz-security-token`||e.toLowerCase()===`cookie`||e.toLowerCase()===`set-cookie`?`***`:t]))),`retryOfRequestLogID`in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e)}));async function*Ot(e,t){if(!e.body)throw t.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new p(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`):new p(`Attempted to iterate over a response with no body`);let n=new Nt,r=new vt,i=Re(e.body);for await(let e of kt(i))for(let t of r.decode(e)){let e=n.decode(t);e&&(yield e)}for(let e of r.flush()){let t=n.decode(e);t&&(yield t)}}async function*kt(e){let t=new Uint8Array;for await(let n of e){if(n==null)continue;let e=n instanceof ArrayBuffer?new Uint8Array(n):typeof n==`string`?dt(n):n,r=new Uint8Array(t.length+e.length);r.set(t),r.set(e,t.length),t=r;let i;for(;(i=_t(t))!==-1;)yield t.slice(0,i),t=t.slice(i)}t.length>0&&(yield t)}function At(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.substring(0,n),t,e.substring(n+t.length)]}var jt,Mt,Nt,Pt=e((()=>{s(),de(),Be(),yt(),f(),ht(),Dt(),Mt=class e{constructor(e,t,n){this.iterator=e,jt.set(this,void 0),this.controller=t,a(this,jt,n,`f`)}static fromSSEResponse(t,n,r,i){let a=!1,o=r?T(r):console;async function*s(){if(a)throw new p("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");a=!0;let e=!1;try{for await(let r of Ot(t,n))if(!e){if(r.data.startsWith(`[DONE]`)){e=!0;continue}if(r.event===null||!r.event.startsWith(`thread.`)){let e;try{e=JSON.parse(r.data)}catch(e){throw o.error(`Could not parse message into JSON:`,r.data),o.error(`From chunk:`,r.raw),e}if(e&&e.error)throw new m(void 0,e.error,void 0,t.headers);yield i?{event:r.event,data:e}:e}else{let e;try{e=JSON.parse(r.data)}catch(e){throw console.error(`Could not parse message into JSON:`,r.data),console.error(`From chunk:`,r.raw),e}if(r.event==`error`)throw new m(void 0,e.error,e.message,void 0);yield{event:r.event,data:e}}}e=!0}catch(e){if(u(e))return;throw e}finally{e||n.abort()}}return new e(s,n,r)}static fromReadableStream(t,n,r){let i=!1;async function*a(){let e=new vt,n=Re(t);for await(let t of n)for(let n of e.decode(t))yield n;for(let t of e.flush())yield t}async function*o(){if(i)throw new p("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let e=!1;try{for await(let t of a())e||t&&(yield JSON.parse(t));e=!0}catch(e){if(u(e))return;throw e}finally{e||n.abort()}}return new e(o,n,r)}[(jt=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let t=[],n=[],r=this.iterator(),i=e=>({next:()=>{if(e.length===0){let e=r.next();t.push(e),n.push(e)}return e.shift()}});return[new e(()=>i(t),this.controller,o(this,jt,`f`)),new e(()=>i(n),this.controller,o(this,jt,`f`))]}toReadableStream(){let e=this,t;return Ie({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{let{value:n,done:r}=await t.next();if(r)return e.close();let i=dt(JSON.stringify(n)+`
4
- `);e.enqueue(i)}catch(t){e.error(t)}},async cancel(){await t.return?.()}})}},Nt=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith(`\r`)&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let e={event:this.event,data:this.data.join(`
5
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(`:`))return null;let[t,n,r]=At(e,`:`);return r.startsWith(` `)&&(r=r.substring(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}}}));async function Ft(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(t.options.stream)return T(e).debug(`response`,n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller,e,t.options.__synthesizeEventData):Mt.fromSSEResponse(n,t.controller,e,t.options.__synthesizeEventData);if(n.status===204)return null;if(t.options.__binaryResponse)return n;let r=n.headers.get(`content-type`)?.split(`;`)[0]?.trim();return r?.includes(`application/json`)||r?.endsWith(`+json`)?n.headers.get(`content-length`)===`0`?void 0:It(await n.json(),n):await n.text()})();return T(e).debug(`[${r}] response parsed`,Et({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}function It(e,t){return!e||typeof e!=`object`||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get(`x-request-id`),enumerable:!1})}var Lt=e((()=>{Pt(),Dt()})),Rt,zt,Bt=e((()=>{s(),Lt(),zt=class e extends Promise{constructor(e,t,n=Ft){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=n,Rt.set(this,void 0),a(this,Rt,e,`f`)}_thenUnwrap(t){return new e(o(this,Rt,`f`),this.responsePromise,async(e,n)=>It(t(await this.parseResponse(e,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get(`x-request-id`)}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(o(this,Rt,`f`),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}},Rt=new WeakMap})),Vt,Ht,Ut,E,D,O,k,A=e((()=>{s(),de(),Lt(),Bt(),xe(),Ht=class{constructor(e,t,n,r){Vt.set(this,void 0),a(this,Vt,e,`f`),this.options=r,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new p("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await o(this,Vt,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Vt=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Ut=class extends zt{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await Ft(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},E=class extends Ht{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},D=class extends Ht{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more!==!1&&super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...fe(this.options.query),after:t}}:null}},O=class extends Ht{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.last_id=n.last_id||``}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more!==!1&&super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...fe(this.options.query),after:e}}:null}},k=class extends Ht{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.next=n.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more!==!1&&super.hasNextPage()}nextPageRequestOptions(){let e=this.next;return e?{...this.options,query:{...fe(this.options.query),after:e}}:null}}})),Wt,Gt,Kt,qt=e((()=>{Be(),de(),Wt={jwt:`urn:ietf:params:oauth:token-type:jwt`,id:`urn:ietf:params:oauth:token-type:id_token`},Gt=`urn:ietf:params:oauth:grant-type:token-exchange`,Kt=class{constructor(e,t){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl=`https://auth.openai.com/oauth/token`,this.config=e,this.fetch=t??Fe()}async getToken(){if(!this.cachedToken||this.isTokenExpired(this.cachedToken)){if(this.refreshPromise)return await this.refreshPromise;this.refreshPromise=this.refreshToken();try{return await this.refreshPromise}finally{this.refreshPromise=null}}return this.needsRefresh(this.cachedToken)&&!this.refreshPromise&&(this.refreshPromise=this.refreshToken().finally(()=>{this.refreshPromise=null})),this.cachedToken.token}async refreshToken(){let e=await this.config.provider.getToken(),t={grant_type:Gt,subject_token:e,subject_token_type:Wt[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};this.config.clientId&&(t.client_id=this.config.clientId);let n=await this.fetch(this.tokenExchangeUrl,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.text(),t;try{t=JSON.parse(e)}catch{}throw n.status===400||n.status===401||n.status===403?new le(n.status,t,n.headers):m.generate(n.status,t,`Token exchange failed with status ${n.status}`,n.headers)}let r=await n.json();if(typeof r!=`object`||!r||!(`access_token`in r)||typeof r.access_token!=`string`||r.access_token.trim().length===0)throw new p(`Token exchange response missing 'access_token' field`);let i=r.access_token,a=r.expires_in??3600,o=Date.now()+a*1e3;return this.cachedToken={token:i,expiresAt:o},i}isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){let t=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-t}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}}}));function Jt(e,t,n){return Zt(),new File(e,t??`unknown_file`,n)}function Yt(e){return(typeof e==`object`&&!!e&&(`name`in e&&e.name&&String(e.name)||`url`in e&&e.url&&String(e.url)||`filename`in e&&e.filename&&String(e.filename)||`path`in e&&e.path&&String(e.path))||``).split(/[\\/]/).pop()||void 0}function Xt(e){let t=typeof e==`function`?e:e.fetch,n=en.get(t);if(n)return n;let r=(async()=>{try{let e=`Response`in t?t.Response:(await t(`data:,`)).constructor,n=new FormData;return n.toString()!==await new e(n).text()}catch{return!0}})();return en.set(t,r),r}var Zt,Qt,$t,j,en,tn,nn,rn,an,on,M=e((()=>{Be(),Zt=()=>{if(typeof File>`u`){let{process:e}=globalThis,t=typeof e?.versions?.node==`string`&&parseInt(e.versions.node.split(`.`))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":``))}},Qt=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,$t=async(e,t)=>an(e.body)?{...e,body:await tn(e.body,t)}:e,j=async(e,t)=>({...e,body:await tn(e.body,t)}),en=new WeakMap,tn=async(e,t)=>{if(!await Xt(t))throw TypeError(`The provided fetch function does not support file uploads with the current global FormData class.`);let n=new FormData;return await Promise.all(Object.entries(e||{}).map(([e,t])=>on(n,e,t))),n},nn=e=>e instanceof Blob&&`name`in e,rn=e=>typeof e==`object`&&!!e&&(e instanceof Response||Qt(e)||nn(e)),an=e=>{if(rn(e))return!0;if(Array.isArray(e))return e.some(an);if(e&&typeof e==`object`){for(let t in e)if(an(e[t]))return!0}return!1},on=async(e,t,n)=>{if(n!==void 0){if(n==null)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)e.append(t,String(n));else if(n instanceof Response)e.append(t,Jt([await n.blob()],Yt(n)));else if(Qt(n))e.append(t,Jt([await new Response(Le(n)).blob()],Yt(n)));else if(nn(n))e.append(t,n,Yt(n));else if(Array.isArray(n))await Promise.all(n.map(n=>on(e,t+`[]`,n)));else if(typeof n==`object`)await Promise.all(Object.entries(n).map(([n,r])=>on(e,`${t}[${n}]`,r)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}}}));async function sn(e,t,n){if(Zt(),e=await e,dn(e))return e instanceof File?e:Jt([await e.arrayBuffer()],e.name);if(fn(e)){let r=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),Jt(await cn(r),t,n)}let r=await cn(e);if(t||(t=Yt(e)),!n?.type){let e=r.find(e=>typeof e==`object`&&`type`in e&&e.type);typeof e==`string`&&(n={...n,type:e})}return Jt(r,t,n)}async function cn(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(un(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(Qt(e))for await(let n of e)t.push(...await cn(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${ln(e)}`)}return t}function ln(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var un,dn,fn,pn=e((()=>{M(),un=e=>typeof e==`object`&&!!e&&typeof e.size==`number`&&typeof e.type==`string`&&typeof e.text==`function`&&typeof e.slice==`function`&&typeof e.arrayBuffer==`function`,dn=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&un(e),fn=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`})),mn=e((()=>{pn()})),N,P=e((()=>{N=class{constructor(e){this._client=e}}}));function hn(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var gn,_n,F,I=e((()=>{de(),gn=Object.freeze(Object.create(null)),_n=(e=hn)=>function(t,...n){if(t.length===1)return t[0];let r=!1,i=[],a=t.reduce((t,a,o)=>{/[?#]/.test(a)&&(r=!0);let s=n[o],c=(r?encodeURIComponent:e)(``+s);return o!==n.length&&(s==null||typeof s==`object`&&s.toString===Object.getPrototypeOf(Object.getPrototypeOf(s.hasOwnProperty??gn)??gn)?.toString)&&(c=s+``,i.push({start:t.length+a.length,length:c.length,error:`Value of type ${Object.prototype.toString.call(s).slice(8,-1)} is not a valid path parameter`})),t+a+(o===n.length?``:c)},``),o=a.split(/[?#]/,1)[0],s=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,c;for(;(c=s.exec(o))!==null;)i.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can\'t be safely passed as a path parameter`});if(i.sort((e,t)=>e.start-t.start),i.length>0){let e=0,t=i.reduce((t,n)=>{let r=` `.repeat(n.start-e),i=`^`.repeat(n.length);return e=n.start+n.length,t+r+i},``);throw new p(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
6
- `)}\n${a}\n${t}`)}return a},F=_n(hn)})),vn,yn=e((()=>{P(),A(),I(),vn=class extends N{list(e,t={},n){return this._client.getAPIList(F`/chat/completions/${e}/messages`,D,{query:t,...n,__security:{bearerAuth:!0}})}}})),L=e((()=>{de()}));function bn(e){return e!==void 0&&`function`in e&&e.function!==void 0}function xn(e){return e?.$brand===`auto-parseable-response-format`}function Sn(e){return e?.$brand===`auto-parseable-tool`}function Cn(e,t){return!t||!On(t)?{...e,choices:e.choices.map(e=>(kn(e.message.tool_calls),{...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}}))}:wn(e,t)}function wn(e,t){let n=e.choices.map(e=>{if(e.finish_reason===`length`)throw new oe;if(e.finish_reason===`content_filter`)throw new se;return kn(e.message.tool_calls),{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map(e=>En(t,e))??void 0}:void 0,parsed:e.message.content&&!e.message.refusal?Tn(t,e.message.content):null}}});return{...e,choices:n}}function Tn(e,t){return e.response_format?.type===`json_schema`&&e.response_format?.type===`json_schema`?`$parseRaw`in e.response_format?e.response_format.$parseRaw(t):JSON.parse(t):null}function En(e,t){let n=e.tools?.find(e=>bn(e)&&e.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:Sn(n)?n.$parseRaw(t.function.arguments):n?.function.strict?JSON.parse(t.function.arguments):null}}}function Dn(e,t){if(!e||!(`tools`in e)||!e.tools)return!1;let n=e.tools?.find(e=>bn(e)&&e.function?.name===t.function.name);return bn(n)&&(Sn(n)||n?.function.strict||!1)}function On(e){return xn(e.response_format)?!0:e.tools?.some(e=>Sn(e)||e.type===`function`&&e.function.strict===!0)??!1}function kn(e){for(let t of e||[])if(t.type!==`function`)throw new p(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}function An(e){for(let t of e??[]){if(t.type!==`function`)throw new p(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(t.function.strict!==!0)throw new p(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var jn=e((()=>{L()})),Mn,Nn,Pn=e((()=>{Mn=e=>e?.role===`assistant`,Nn=e=>e?.role===`tool`})),Fn,In,Ln,Rn,zn,Bn,Vn,R,Hn,Un,Wn,Gn,Kn,qn,Jn,Yn,Xn=e((()=>{s(),L(),Yn=class{constructor(){Fn.add(this),this.controller=new AbortController,In.set(this,void 0),Ln.set(this,()=>{}),Rn.set(this,()=>{}),zn.set(this,void 0),Bn.set(this,()=>{}),Vn.set(this,()=>{}),R.set(this,{}),Hn.set(this,[]),Un.set(this,!1),Wn.set(this,!1),Gn.set(this,!1),Kn.set(this,!1),a(this,In,new Promise((e,t)=>{a(this,Ln,e,`f`),a(this,Rn,t,`f`)}),`f`),a(this,zn,new Promise((e,t)=>{a(this,Bn,e,`f`),a(this,Vn,t,`f`)}),`f`),o(this,In,`f`).catch(()=>{}),o(this,zn,`f`).catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit(`end`)},o(this,Fn,`m`,Jn).bind(this))},0)}_connected(){this.ended||(o(this,Ln,`f`).call(this),this._emit(`connect`))}get ended(){return o(this,Un,`f`)}get errored(){return o(this,Wn,`f`)}get aborted(){return o(this,Gn,`f`)}abort(){this.controller.abort()}_listenForAbort(e){if(!e||this.ended)return;if(e.aborted){this.controller.abort();return}let t=()=>this.controller.abort();e.addEventListener(`abort`,t,{once:!0}),o(this,Hn,`f`).push({signal:e,listener:t})}on(e,t){return(o(this,R,`f`)[e]||(o(this,R,`f`)[e]=[])).push({listener:t}),this}off(e,t){let n=o(this,R,`f`)[e];if(!n)return this;let r=n.findIndex(e=>e.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(o(this,R,`f`)[e]||(o(this,R,`f`)[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{a(this,Kn,!0,`f`),e!==`error`&&this.once(`error`,n),this.once(e,t)})}async done(){a(this,Kn,!0,`f`),await o(this,zn,`f`)}_emit(e,...t){if(o(this,Un,`f`))return;e===`end`&&(o(this,Fn,`m`,qn).call(this),a(this,Un,!0,`f`),o(this,Bn,`f`).call(this));let n=o(this,R,`f`)[e];if(n&&(o(this,R,`f`)[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),e===`abort`){let e=t[0];!o(this,Kn,`f`)&&!n?.length&&Promise.reject(e),o(this,Rn,`f`).call(this,e),o(this,Vn,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=t[0];!o(this,Kn,`f`)&&!n?.length&&Promise.reject(e),o(this,Rn,`f`).call(this,e),o(this,Vn,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){}},In=new WeakMap,Ln=new WeakMap,Rn=new WeakMap,zn=new WeakMap,Bn=new WeakMap,Vn=new WeakMap,R=new WeakMap,Hn=new WeakMap,Un=new WeakMap,Wn=new WeakMap,Gn=new WeakMap,Kn=new WeakMap,Fn=new WeakSet,qn=function(){for(let{signal:e,listener:t}of o(this,Hn,`f`).splice(0))e.removeEventListener(`abort`,t)},Jn=function(e){if(a(this,Wn,!0,`f`),e instanceof Error&&e.name===`AbortError`&&(e=new h),e instanceof h)return a(this,Gn,!0,`f`),this._emit(`abort`,e);if(e instanceof p)return this._emit(`error`,e);if(e instanceof Error){let t=new p(e.message);return t.cause=e,this._emit(`error`,t)}return this._emit(`error`,new p(String(e)))}}));function Zn(e){return typeof e.parse==`function`}var Qn=e((()=>{}));function $n(e){for(let t of e.choices)for(let e of t.message.tool_calls??[])e.id||(e.id=`call_${c()}`)}var z,er,tr,nr,rr,ir,ar,or,sr,cr,lr=e((()=>{s(),L(),l(),jn(),Pn(),Xn(),Qn(),sr=10,cr=class extends Yn{constructor(){super(...arguments),z.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){$n(e),this._chatCompletions.push(e),this._emit(`chatCompletion`,e);let t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if(`content`in e||(e.content=null),this.messages.push(e),t){if(this._emit(`message`,e),Nn(e)&&e.content)this._emit(`functionToolCallResult`,e.content);else if(Mn(e)&&e.tool_calls)for(let t of e.tool_calls)t.type===`function`&&this._emit(`functionToolCall`,t.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new p(`stream ended without producing a ChatCompletion`);return e}async finalContent(){return await this.done(),o(this,z,`m`,er).call(this)}async finalMessage(){return await this.done(),o(this,z,`m`,tr).call(this)}async finalFunctionToolCall(){return await this.done(),o(this,z,`m`,nr).call(this)}async finalFunctionToolCallResult(){return await this.done(),o(this,z,`m`,rr).call(this)}async totalUsage(){return await this.done(),o(this,z,`m`,ir).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit(`finalChatCompletion`,e);let t=o(this,z,`m`,tr).call(this);t&&this._emit(`finalMessage`,t);let n=o(this,z,`m`,er).call(this);n&&this._emit(`finalContent`,n);let r=o(this,z,`m`,nr).call(this);r&&this._emit(`finalFunctionToolCall`,r);let i=o(this,z,`m`,rr).call(this);i!=null&&this._emit(`finalFunctionToolCallResult`,i),this._chatCompletions.some(e=>e.usage)&&this._emit(`totalUsage`,o(this,z,`m`,ir).call(this))}async _createChatCompletion(e,t,n){this._listenForAbort(n?.signal),o(this,z,`m`,ar).call(this,t);let r=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(wn(r,t))}async _runChatCompletion(e,t,n){for(let e of t.messages)this._addMessage(e,!1);return await this._createChatCompletion(e,t,n)}async _runTools(e,t,n,r){let i=`tool`,{tool_choice:a=`auto`,stream:s,...c}=t,l=typeof a!=`string`&&a.type===`function`&&a?.function?.name,{maxChatCompletions:u=sr,afterCompletion:d}=r||{},f=t.tools.map(e=>{if(Sn(e)){if(!e.$callback)throw new p("Tool given to `.runTools()` that does not have an associated function");return{type:`function`,function:{function:e.$callback,name:e.function.name,description:e.function.description||``,parameters:e.function.parameters,parse:e.$parseRaw,strict:!0}}}return e}),m={};for(let e of f)e.type===`function`&&(m[e.function.name||e.function.function.name]=e.function);let h=`tools`in t?f.map(e=>e.type===`function`?{type:`function`,function:{name:e.function.name||e.function.function.name,parameters:e.function.parameters,description:e.function.description,strict:e.function.strict}}:e):void 0;for(let e of t.messages)this._addMessage(e,!1);let g=async e=>{if(e.type!==`function`)return{message:void 0,functionCalled:!1};let t=e.id,{name:r,arguments:a}=e.function,s=m[r];if(!s){let e=`Invalid tool_call: ${JSON.stringify(r)}. Available options are: ${Object.keys(m).map(e=>JSON.stringify(e)).join(`, `)}. Please try again`;return{message:{role:i,tool_call_id:t,content:e},functionCalled:!1}}if(l&&l!==r){let e=`Invalid tool_call: ${JSON.stringify(r)}. ${JSON.stringify(l)} requested. Please try again`;return{message:{role:i,tool_call_id:t,content:e},functionCalled:!1}}let c;if(Zn(s)){let e;try{e=await s.parse(a)}catch(e){let n=e instanceof Error?e.message:String(e);return{message:{role:i,tool_call_id:t,content:n},functionCalled:!1}}c=await s.function(e,n)}else c=await s.function(a,n);let u=o(this,z,`m`,or).call(this,c);return{message:{role:i,tool_call_id:t,content:u},functionCalled:!0}};for(let i=0;i<u;++i){let i=await this._createChatCompletion(e,{...c,tool_choice:a,tools:h,messages:[...this.messages]},r),o=i.choices[0]?.message;if(!o)throw new p(`missing message in ChatCompletion response`);if(!o.tool_calls?.length){await d?.(i,n);return}if(l||t.parallel_tool_calls===!1)for(let e of o.tool_calls){let t=await g(e);if(t.message&&this._addMessage(t.message),l&&t.functionCalled){await d?.(i,n);return}}else{let e=await Promise.allSettled(o.tool_calls.map(g));for(let t of e)if(t.status===`rejected`)throw t.reason;for(let t of e)t.status===`fulfilled`&&t.value.message&&this._addMessage(t.value.message)}await d?.(i,n)}}},z=new WeakSet,er=function(){return o(this,z,`m`,tr).call(this).content??null},tr=function(){let e=this.messages.length;for(;e-->0;){let t=this.messages[e];if(Mn(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new p(`stream ended without producing a ChatCompletionMessage with role=assistant`)},nr=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Mn(t)&&t?.tool_calls?.length)for(let e=t.tool_calls.length-1;e>=0;e--){let n=t.tool_calls[e];if(n?.type===`function`)return n.function}}},rr=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Nn(t)&&t.content!=null&&typeof t.content==`string`&&this.messages.some(e=>e.role===`assistant`&&e.tool_calls?.some(e=>e.type===`function`&&e.id===t.tool_call_id)))return t.content}},ir=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},ar=function(e){if(e.n!=null&&e.n>1)throw new p(`ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.`)},or=function(e){return typeof e==`string`?e:e===void 0?`undefined`:JSON.stringify(e)}})),ur,dr=e((()=>{lr(),Pn(),ur=class e extends cr{static runTools(t,n,r){let i=new e,a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`runTools`}};return i._run(()=>i._runTools(t,n,i,a)),i}_addMessage(e,t=!0){super._addMessage(e,t),Mn(e)&&e.content&&this._emit(`content`,e.content)}}}));function fr(e,t=B.ALL){if(typeof e!=`string`)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return hr(e.trim(),t)}var B,pr,mr,hr,gr,_r=e((()=>{B={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},pr=class extends Error{},mr=class extends Error{},hr=(e,t)=>{let n=e.length,r=0,i=e=>{throw new pr(`${e} at position ${r}`)},a=e=>{throw new mr(`${e} at position ${r}`)},o=()=>(d(),r>=n&&i(`Unexpected end of input`),e[r]===`"`?s():e[r]===`{`?c():e[r]===`[`?l():e.substring(r,r+4)===`null`||B.NULL&t&&n-r<4&&`null`.startsWith(e.substring(r))?(r+=4,null):e.substring(r,r+4)===`true`||B.BOOL&t&&n-r<4&&`true`.startsWith(e.substring(r))?(r+=4,!0):e.substring(r,r+5)===`false`||B.BOOL&t&&n-r<5&&`false`.startsWith(e.substring(r))?(r+=5,!1):e.substring(r,r+8)===`Infinity`||B.INFINITY&t&&n-r<8&&`Infinity`.startsWith(e.substring(r))?(r+=8,1/0):e.substring(r,r+9)===`-Infinity`||B.MINUS_INFINITY&t&&1<n-r&&n-r<9&&`-Infinity`.startsWith(e.substring(r))?(r+=9,-1/0):e.substring(r,r+3)===`NaN`||B.NAN&t&&n-r<3&&`NaN`.startsWith(e.substring(r))?(r+=3,NaN):u()),s=()=>{let o=r,s=!1;for(r++;r<n&&(e[r]!==`"`||s&&e[r-1]===`\\`);)s=e[r]===`\\`&&!s,r++;if(e.charAt(r)==`"`)try{return JSON.parse(e.substring(o,++r-Number(s)))}catch(e){a(String(e))}else if(B.STR&t)try{return JSON.parse(e.substring(o,r-Number(s))+`"`)}catch{return JSON.parse(e.substring(o,e.lastIndexOf(`\\`))+`"`)}i(`Unterminated string literal`)},c=()=>{r++,d();let a={};try{for(;e[r]!==`}`;){if(d(),r>=n&&B.OBJ&t)return a;let i=s();d(),r++;try{let e=o();Object.defineProperty(a,i,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){if(B.OBJ&t)return a;throw e}d(),e[r]===`,`&&r++}}catch{if(B.OBJ&t)return a;i(`Expected '}' at end of object`)}return r++,a},l=()=>{r++;let n=[];try{for(;e[r]!==`]`;)n.push(o()),d(),e[r]===`,`&&r++}catch{if(B.ARR&t)return n;i(`Expected ']' at end of array`)}return r++,n},u=()=>{if(r===0){e===`-`&&B.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e)}catch(n){if(B.NUM&t)try{return e[e.length-1]===`.`?JSON.parse(e.substring(0,e.lastIndexOf(`.`))):JSON.parse(e.substring(0,e.lastIndexOf(`e`)))}catch{}a(String(n))}}let o=r;for(e[r]===`-`&&r++;e[r]&&!`,]}`.includes(e[r]);)r++;r==n&&!(B.NUM&t)&&i(`Unterminated number literal`);try{return JSON.parse(e.substring(o,r))}catch{e.substring(o,r)===`-`&&B.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e.substring(o,e.lastIndexOf(`e`)))}catch(e){a(String(e))}}},d=()=>{for(;r<n&&`
7
- \r `.includes(e[r]);)r++};return o()},gr=e=>fr(e,B.ALL^B.NUM)})),vr=e((()=>{Pt()}));function yr(e,t){let{id:n,choices:r,created:i,model:a,system_fingerprint:o,...s}=e;return Cn({...s,id:n,choices:r.map(({message:t,finish_reason:n,index:r,logprobs:i,...a})=>{if(!n)throw new p(`missing finish_reason for choice ${r}`);let{content:o=null,function_call:s,tool_calls:l,...u}=t,d=t.role;if(!d)throw new p(`missing role for choice ${r}`);if(s){let{arguments:e,name:c}=s;if(e==null)throw new p(`missing function_call.arguments for choice ${r}`);if(!c)throw new p(`missing function_call.name for choice ${r}`);return{...a,message:{content:o,function_call:{arguments:e,name:c},role:d,refusal:t.refusal??null},finish_reason:n,index:r,logprobs:i}}return l?{...a,index:r,finish_reason:n,logprobs:i,message:{...u,role:d,content:o,refusal:t.refusal??null,tool_calls:l.map((t,n)=>{let{function:i,type:a,id:o,...s}=t,{arguments:l,name:u,...d}=i||{};if(a==null)throw new p(`missing choices[${r}].tool_calls[${n}].type\n${br(e)}`);if(u==null)throw new p(`missing choices[${r}].tool_calls[${n}].function.name\n${br(e)}`);if(l==null)throw new p(`missing choices[${r}].tool_calls[${n}].function.arguments\n${br(e)}`);return{...s,id:o||`call_${c()}`,type:a,function:{...d,name:u,arguments:l}}})}}:{...a,message:{...u,content:o,role:d,refusal:t.refusal??null},finish_reason:n,index:r,logprobs:i}}),created:i,model:a,object:`chat.completion`,...o?{system_fingerprint:o}:{}},t)}function br(e){return JSON.stringify(e)}var V,xr,Sr,Cr,wr,Tr,Er,Dr,Or,kr,Ar,jr,Mr,Nr=e((()=>{s(),_r(),L(),l(),jn(),vr(),lr(),Mr=class e extends cr{constructor(e){super(),V.add(this),xr.set(this,void 0),Sr.set(this,void 0),Cr.set(this,void 0),a(this,xr,e,`f`),a(this,Sr,[],`f`)}get currentChatCompletionSnapshot(){return o(this,Cr,`f`)}static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static createChatCompletion(t,n,r){let i=new e(n);return i._run(()=>i._runChatCompletion(t,{...n,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createChatCompletion(e,t,n){super._createChatCompletion,this._listenForAbort(n?.signal),o(this,V,`m`,wr).call(this);let r=await e.chat.completions.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let e of r)o(this,V,`m`,Er).call(this,e);if(r.controller.signal?.aborted)throw new h;return this._addChatCompletion(o(this,V,`m`,kr).call(this))}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),o(this,V,`m`,wr).call(this),this._connected();let n=Mt.fromReadableStream(e,this.controller),r;for await(let e of n)r&&r!==e.id&&this._addChatCompletion(o(this,V,`m`,kr).call(this)),o(this,V,`m`,Er).call(this,e),r=e.id;if(n.controller.signal?.aborted)throw new h;return this._addChatCompletion(o(this,V,`m`,kr).call(this))}[(xr=new WeakMap,Sr=new WeakMap,Cr=new WeakMap,V=new WeakSet,wr=function(){this.ended||a(this,Cr,void 0,`f`)},Tr=function(e){let t=o(this,Sr,`f`)[e.index];return t||(t={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},o(this,Sr,`f`)[e.index]=t,t)},Er=function(e){if(this.ended)return;let t=o(this,V,`m`,jr).call(this,e);this._emit(`chunk`,e,t);for(let n of e.choices){let e=t.choices[n.index];n.delta.content!=null&&e.message?.role===`assistant`&&e.message?.content&&(this._emit(`content`,n.delta.content,e.message.content),this._emit(`content.delta`,{delta:n.delta.content,snapshot:e.message.content,parsed:e.message.parsed})),n.delta.refusal!=null&&e.message?.role===`assistant`&&e.message?.refusal&&this._emit(`refusal.delta`,{delta:n.delta.refusal,snapshot:e.message.refusal}),n.logprobs?.content!=null&&e.message?.role===`assistant`&&this._emit(`logprobs.content.delta`,{content:n.logprobs?.content,snapshot:e.logprobs?.content??[]}),n.logprobs?.refusal!=null&&e.message?.role===`assistant`&&this._emit(`logprobs.refusal.delta`,{refusal:n.logprobs?.refusal,snapshot:e.logprobs?.refusal??[]});let r=o(this,V,`m`,Tr).call(this,e);e.finish_reason&&(o(this,V,`m`,Or).call(this,e),r.current_tool_call_index!=null&&o(this,V,`m`,Dr).call(this,e,r.current_tool_call_index));for(let t of n.delta.tool_calls??[])r.current_tool_call_index!==t.index&&(o(this,V,`m`,Or).call(this,e),r.current_tool_call_index!=null&&o(this,V,`m`,Dr).call(this,e,r.current_tool_call_index)),r.current_tool_call_index=t.index;for(let t of n.delta.tool_calls??[]){let n=e.message.tool_calls?.[t.index];n?.type&&(n?.type===`function`?this._emit(`tool_calls.function.arguments.delta`,{name:n.function?.name,index:t.index,arguments:n.function.arguments,parsed_arguments:n.function.parsed_arguments,arguments_delta:t.function?.arguments??``}):n?.type)}}},Dr=function(e,t){if(o(this,V,`m`,Tr).call(this,e).done_tool_calls.has(t))return;let n=e.message.tool_calls?.[t];if(!n)throw Error(`no tool call snapshot`);if(!n.type)throw Error("tool call snapshot missing `type`");if(n.type===`function`){let e=o(this,xr,`f`)?.tools?.find(e=>bn(e)&&e.function.name===n.function.name);this._emit(`tool_calls.function.arguments.done`,{name:n.function.name,index:t,arguments:n.function.arguments,parsed_arguments:Sn(e)?e.$parseRaw(n.function.arguments):e?.function.strict?JSON.parse(n.function.arguments):null})}else n.type},Or=function(e){let t=o(this,V,`m`,Tr).call(this,e);if(e.message.content&&!t.content_done){t.content_done=!0;let n=o(this,V,`m`,Ar).call(this);this._emit(`content.done`,{content:e.message.content,parsed:n?n.$parseRaw(e.message.content):null})}e.message.refusal&&!t.refusal_done&&(t.refusal_done=!0,this._emit(`refusal.done`,{refusal:e.message.refusal})),e.logprobs?.content&&!t.logprobs_content_done&&(t.logprobs_content_done=!0,this._emit(`logprobs.content.done`,{content:e.logprobs.content})),e.logprobs?.refusal&&!t.logprobs_refusal_done&&(t.logprobs_refusal_done=!0,this._emit(`logprobs.refusal.done`,{refusal:e.logprobs.refusal}))},kr=function(){if(this.ended)throw new p(`stream has ended, this shouldn't happen`);let e=o(this,Cr,`f`);if(!e)throw new p(`request ended without sending any chunks`);return a(this,Cr,void 0,`f`),a(this,Sr,[],`f`),yr(e,o(this,xr,`f`))},Ar=function(){let e=o(this,xr,`f`)?.response_format;return xn(e)?e:null},jr=function(e){var t,n,r,i;let s=o(this,Cr,`f`),{choices:c,...l}=e;s?Object.assign(s,l):s=a(this,Cr,{...l,choices:[]},`f`);for(let{delta:a,finish_reason:c,index:l,logprobs:u=null,...d}of e.choices){let e=s.choices[l];if(e||(e=s.choices[l]={finish_reason:c,index:l,message:{},logprobs:u,...d}),u)if(!e.logprobs)e.logprobs=Object.assign({},u);else{let{content:r,refusal:i,...a}=u;Object.assign(e.logprobs,a),r&&((t=e.logprobs).content??(t.content=[]),e.logprobs.content.push(...r)),i&&((n=e.logprobs).refusal??(n.refusal=[]),e.logprobs.refusal.push(...i))}if(c&&(e.finish_reason=c,o(this,xr,`f`)&&On(o(this,xr,`f`)))){if(c===`length`)throw new oe;if(c===`content_filter`)throw new se}if(Object.assign(e,d),!a)continue;let{content:f,refusal:p,function_call:m,role:h,tool_calls:g,...ee}=a;if(Object.assign(e.message,ee),p&&(e.message.refusal=(e.message.refusal||``)+p),h&&(e.message.role=h),m&&(e.message.function_call?(m.name&&(e.message.function_call.name=m.name),m.arguments&&((r=e.message.function_call).arguments??(r.arguments=``),e.message.function_call.arguments+=m.arguments)):e.message.function_call=m),f&&(e.message.content=(e.message.content||``)+f,!e.message.refusal&&o(this,V,`m`,Ar).call(this)&&(e.message.parsed=e.message.content.trim()?gr(e.message.content):null)),g){e.message.tool_calls||(e.message.tool_calls=[]);for(let{index:t,id:n,type:r,function:a,...s}of g){let c=(i=e.message.tool_calls)[t]??(i[t]={});Object.assign(c,s),n&&(c.id=n),r&&(c.type=r),a&&(c.function??(c.function={name:a.name??``,arguments:``})),a?.name&&(c.function.name=a.name),a?.arguments&&(c.function.arguments+=a.arguments,Dn(o(this,xr,`f`),c)&&(c.function.parsed_arguments=gr(c.function.arguments)))}}}return s},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`chunk`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Mt(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}})),Pr,Fr=e((()=>{Nr(),Pr=class e extends Mr{static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static runTools(t,n,r){let i=new e(n),a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`runTools`}};return i._run(()=>i._runTools(t,n,i,a)),i}}})),Ir,Lr=e((()=>{P(),yn(),A(),I(),dr(),Fr(),Nr(),jn(),Qn(),Ir=class extends N{constructor(){super(...arguments),this.messages=new vn(this._client)}create(e,t){return this._client.post(`/chat/completions`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(F`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(F`/chat/completions/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/chat/completions`,D,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(F`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}parse(e,t){return An(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":`chat.completions.parse`}})._thenUnwrap(t=>wn(t,e))}runTools(e,t){return e.stream?Pr.runTools(this._client,e,t):ur.runTools(this._client,e,t)}stream(e,t){return Mr.createChatCompletion(this._client,e,t)}},Ir.Messages=vn})),Rr,zr=e((()=>{P(),Lr(),Rr=class extends N{constructor(){super(...arguments),this.completions=new Ir(this._client)}},Rr.Completions=Ir})),Br=e((()=>{Lr(),Lr(),yn()})),Vr=e((()=>{zr(),Br()})),Hr=e((()=>{})),Ur,Wr=e((()=>{P(),A(),I(),Ur=class extends N{create(e,t){return this._client.post(`/organization/admin_api_keys`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(F`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/admin_api_keys`,D,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(F`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}}})),Gr,Kr=e((()=>{P(),A(),Gr=class extends N{list(e={},t){return this._client.getAPIList(`/organization/audit_logs`,O,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}}})),qr,Jr=e((()=>{P(),A(),I(),qr=class extends N{create(e,t){return this._client.post(`/organization/certificates`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},n){return this._client.get(F`/organization/certificates/${e}`,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(F`/organization/certificates/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/certificates`,O,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(F`/organization/certificates/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}activate(e,t){return this._client.getAPIList(`/organization/certificates/activate`,E,{body:e,method:`post`,...t,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t){return this._client.getAPIList(`/organization/certificates/deactivate`,E,{body:e,method:`post`,...t,__security:{adminAPIKeyAuth:!0}})}}})),Yr,Xr=e((()=>{P(),Yr=class extends N{retrieve(e){return this._client.get(`/organization/data_retention`,{...e,__security:{adminAPIKeyAuth:!0}})}update(e,t){return this._client.post(`/organization/data_retention`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}}})),Zr,Qr=e((()=>{P(),A(),I(),Zr=class extends N{create(e,t){return this._client.post(`/organization/invites`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(F`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/invites`,O,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(F`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}}})),$r,ei=e((()=>{P(),A(),I(),$r=class extends N{create(e,t){return this._client.post(`/organization/roles`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(F`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(F`/organization/roles/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/roles`,k,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(F`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}}})),ti,ni=e((()=>{P(),A(),I(),ti=class extends N{create(e,t){return this._client.post(`/organization/spend_alerts`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(F`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(F`/organization/spend_alerts/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/spend_alerts`,O,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(F`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}}})),ri,ii=e((()=>{P(),ri=class extends N{audioSpeeches(e,t){return this._client.get(`/organization/usage/audio_speeches`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}audioTranscriptions(e,t){return this._client.get(`/organization/usage/audio_transcriptions`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}codeInterpreterSessions(e,t){return this._client.get(`/organization/usage/code_interpreter_sessions`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}completions(e,t){return this._client.get(`/organization/usage/completions`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}costs(e,t){return this._client.get(`/organization/costs`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}embeddings(e,t){return this._client.get(`/organization/usage/embeddings`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}fileSearchCalls(e,t){return this._client.get(`/organization/usage/file_search_calls`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}images(e,t){return this._client.get(`/organization/usage/images`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}moderations(e,t){return this._client.get(`/organization/usage/moderations`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}vectorStores(e,t){return this._client.get(`/organization/usage/vector_stores`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}webSearchCalls(e,t){return this._client.get(`/organization/usage/web_search_calls`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}}})),ai,oi=e((()=>{P(),A(),I(),ai=class extends N{create(e,t,n){return this._client.post(F`/organization/groups/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{group_id:r}=t;return this._client.get(F`/organization/groups/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(F`/organization/groups/${e}/roles`,k,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{group_id:r}=t;return this._client.delete(F`/organization/groups/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}})),si,ci=e((()=>{P(),A(),I(),si=class extends N{create(e,t,n){return this._client.post(F`/organization/groups/${e}/users`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{group_id:r}=t;return this._client.get(F`/organization/groups/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(F`/organization/groups/${e}/users`,k,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{group_id:r}=t;return this._client.delete(F`/organization/groups/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}})),li,ui=e((()=>{P(),oi(),ci(),A(),I(),li=class extends N{constructor(){super(...arguments),this.users=new si(this._client),this.roles=new ai(this._client)}create(e,t){return this._client.post(`/organization/groups`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(F`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(F`/organization/groups/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/groups`,k,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(F`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},li.Users=si,li.Roles=ai})),di,fi=e((()=>{P(),A(),I(),di=class extends N{retrieve(e,t,n){let{project_id:r}=t;return this._client.get(F`/organization/projects/${r}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(F`/organization/projects/${e}/api_keys`,O,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(F`/organization/projects/${r}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}})),pi,mi=e((()=>{P(),A(),I(),pi=class extends N{list(e,t={},n){return this._client.getAPIList(F`/organization/projects/${e}/certificates`,O,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}activate(e,t,n){return this._client.getAPIList(F`/organization/projects/${e}/certificates/activate`,E,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t,n){return this._client.getAPIList(F`/organization/projects/${e}/certificates/deactivate`,E,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}}})),hi,gi=e((()=>{P(),I(),hi=class extends N{retrieve(e,t){return this._client.get(F`/organization/projects/${e}/data_retention`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(F`/organization/projects/${e}/data_retention`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}}})),_i,vi=e((()=>{P(),I(),_i=class extends N{retrieve(e,t){return this._client.get(F`/organization/projects/${e}/hosted_tool_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(F`/organization/projects/${e}/hosted_tool_permissions`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}}})),yi,bi=e((()=>{P(),I(),yi=class extends N{retrieve(e,t){return this._client.get(F`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(F`/organization/projects/${e}/model_permissions`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(F`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}}})),xi,Si=e((()=>{P(),A(),I(),xi=class extends N{listRateLimits(e,t={},n){return this._client.getAPIList(F`/organization/projects/${e}/rate_limits`,O,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,t,n){let{project_id:r,...i}=t;return this._client.post(F`/organization/projects/${r}/rate_limits/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}}})),Ci,wi=e((()=>{P(),A(),I(),Ci=class extends N{create(e,t,n){return this._client.post(F`/projects/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(F`/projects/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(F`/projects/${r}/roles/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(F`/projects/${e}/roles`,k,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(F`/projects/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}})),Ti,Ei=e((()=>{P(),A(),I(),Ti=class extends N{create(e,t,n){return this._client.post(F`/organization/projects/${e}/service_accounts`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(F`/organization/projects/${r}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(F`/organization/projects/${r}/service_accounts/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(F`/organization/projects/${e}/service_accounts`,O,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(F`/organization/projects/${r}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}})),Di,Oi=e((()=>{P(),A(),I(),Di=class extends N{create(e,t,n){return this._client.post(F`/organization/projects/${e}/spend_alerts`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(F`/organization/projects/${r}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(F`/organization/projects/${r}/spend_alerts/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(F`/organization/projects/${e}/spend_alerts`,O,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(F`/organization/projects/${r}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}})),ki,Ai=e((()=>{P(),A(),I(),ki=class extends N{create(e,t,n){let{project_id:r,...i}=t;return this._client.post(F`/projects/${r}/groups/${e}/roles`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r,group_id:i}=t;return this._client.get(F`/projects/${r}/groups/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t,n){let{project_id:r,...i}=t;return this._client.getAPIList(F`/projects/${r}/groups/${e}/roles`,k,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r,group_id:i}=t;return this._client.delete(F`/projects/${r}/groups/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}})),ji,Mi=e((()=>{P(),Ai(),A(),I(),ji=class extends N{constructor(){super(...arguments),this.roles=new ki(this._client)}create(e,t,n){return this._client.post(F`/organization/projects/${e}/groups`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r,...i}=t;return this._client.get(F`/organization/projects/${r}/groups/${e}`,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(F`/organization/projects/${e}/groups`,k,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(F`/organization/projects/${r}/groups/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},ji.Roles=ki})),Ni,Pi=e((()=>{P(),A(),I(),Ni=class extends N{create(e,t,n){let{project_id:r,...i}=t;return this._client.post(F`/projects/${r}/users/${e}/roles`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r,user_id:i}=t;return this._client.get(F`/projects/${r}/users/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t,n){let{project_id:r,...i}=t;return this._client.getAPIList(F`/projects/${r}/users/${e}/roles`,k,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r,user_id:i}=t;return this._client.delete(F`/projects/${r}/users/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}})),Fi,Ii=e((()=>{P(),Pi(),A(),I(),Fi=class extends N{constructor(){super(...arguments),this.roles=new Ni(this._client)}create(e,t,n){return this._client.post(F`/organization/projects/${e}/users`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(F`/organization/projects/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(F`/organization/projects/${r}/users/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(F`/organization/projects/${e}/users`,O,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(F`/organization/projects/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},Fi.Roles=Ni})),H,Li=e((()=>{P(),fi(),mi(),gi(),vi(),bi(),Si(),wi(),Ei(),Oi(),Mi(),Ii(),A(),I(),H=class extends N{constructor(){super(...arguments),this.users=new Fi(this._client),this.serviceAccounts=new Ti(this._client),this.apiKeys=new di(this._client),this.rateLimits=new xi(this._client),this.modelPermissions=new yi(this._client),this.hostedToolPermissions=new _i(this._client),this.groups=new ji(this._client),this.roles=new Ci(this._client),this.dataRetention=new hi(this._client),this.spendAlerts=new Di(this._client),this.certificates=new pi(this._client)}create(e,t){return this._client.post(`/organization/projects`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(F`/organization/projects/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(F`/organization/projects/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/projects`,O,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}archive(e,t){return this._client.post(F`/organization/projects/${e}/archive`,{...t,__security:{adminAPIKeyAuth:!0}})}},H.Users=Fi,H.ServiceAccounts=Ti,H.APIKeys=di,H.RateLimits=xi,H.ModelPermissions=yi,H.HostedToolPermissions=_i,H.Groups=ji,H.Roles=Ci,H.DataRetention=hi,H.SpendAlerts=Di,H.Certificates=pi})),Ri,zi=e((()=>{P(),A(),I(),Ri=class extends N{create(e,t,n){return this._client.post(F`/organization/users/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{user_id:r}=t;return this._client.get(F`/organization/users/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(F`/organization/users/${e}/roles`,k,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{user_id:r}=t;return this._client.delete(F`/organization/users/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}})),Bi,Vi=e((()=>{P(),zi(),A(),I(),Bi=class extends N{constructor(){super(...arguments),this.roles=new Ri(this._client)}retrieve(e,t){return this._client.get(F`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(F`/organization/users/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/users`,O,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(F`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},Bi.Roles=Ri})),U,Hi=e((()=>{P(),Wr(),Kr(),Jr(),Xr(),Qr(),ei(),ni(),ii(),ui(),Li(),Vi(),U=class extends N{constructor(){super(...arguments),this.auditLogs=new Gr(this._client),this.adminAPIKeys=new Ur(this._client),this.usage=new ri(this._client),this.invites=new Zr(this._client),this.users=new Bi(this._client),this.groups=new li(this._client),this.roles=new $r(this._client),this.dataRetention=new Yr(this._client),this.spendAlerts=new ti(this._client),this.certificates=new qr(this._client),this.projects=new H(this._client)}},U.AuditLogs=Gr,U.AdminAPIKeys=Ur,U.Usage=ri,U.Invites=Zr,U.Users=Bi,U.Groups=li,U.Roles=$r,U.DataRetention=Yr,U.SpendAlerts=ti,U.Certificates=qr,U.Projects=H})),Ui,Wi=e((()=>{P(),Hi(),Ui=class extends N{constructor(){super(...arguments),this.organization=new U(this._client)}},Ui.Organization=U}));function*Gi(e){if(!e)return;if(Ki in e){let{values:t,nulls:n}=e;yield*t.entries();for(let e of n)yield[e,null];return}let t=!1,n;e instanceof Headers?n=e.entries():ve(e)?n=e:(t=!0,n=Object.entries(e??{}));for(let e of n){let n=e[0];if(typeof n!=`string`)throw TypeError(`expected header name to be a string`);let r=ve(e[1])?e[1]:[e[1]],i=!1;for(let e of r)e!==void 0&&(t&&!i&&(i=!0,yield[n,null]),yield[n,e])}}var Ki,W,G=e((()=>{xe(),Ki=Symbol(`brand.privateNullableHeaders`),W=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of Gi(r)){let r=i.toLowerCase();e.has(r)||(t.delete(i),e.add(r)),a===null?(t.delete(i),n.add(r)):(t.append(i,a),n.delete(r))}}return{[Ki]:!0,values:t,nulls:n}}})),qi,Ji=e((()=>{P(),G(),qi=class extends N{create(e,t){return this._client.post(`/audio/speech`,{body:e,...t,headers:W([{Accept:`application/octet-stream`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}})),Yi,Xi=e((()=>{P(),M(),Yi=class extends N{create(e,t){return this._client.post(`/audio/transcriptions`,j({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}}})),Zi,Qi=e((()=>{P(),M(),Zi=class extends N{create(e,t){return this._client.post(`/audio/translations`,j({body:e,...t,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}}})),$i,ea=e((()=>{P(),Ji(),Xi(),Qi(),$i=class extends N{constructor(){super(...arguments),this.transcriptions=new Yi(this._client),this.translations=new Zi(this._client),this.speech=new qi(this._client)}},$i.Transcriptions=Yi,$i.Translations=Zi,$i.Speech=qi})),ta,na=e((()=>{P(),A(),I(),ta=class extends N{create(e,t){return this._client.post(`/batches`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(F`/batches/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/batches`,D,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(F`/batches/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}}})),ra,ia=e((()=>{P(),A(),G(),I(),ra=class extends N{create(e,t){return this._client.post(`/assistants`,{body:e,...t,headers:W([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(F`/assistants/${e}`,{...t,headers:W([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(F`/assistants/${e}`,{body:t,...n,headers:W([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/assistants`,D,{query:e,...t,headers:W([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(F`/assistants/${e}`,{...t,headers:W([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}}})),aa,oa=e((()=>{P(),G(),aa=class extends N{create(e,t){return this._client.post(`/realtime/sessions`,{body:e,...t,headers:W([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}}})),sa,ca=e((()=>{P(),G(),sa=class extends N{create(e,t){return this._client.post(`/realtime/transcription_sessions`,{body:e,...t,headers:W([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}}})),la,ua=e((()=>{P(),oa(),ca(),la=class extends N{constructor(){super(...arguments),this.sessions=new aa(this._client),this.transcriptionSessions=new sa(this._client)}},la.Sessions=aa,la.TranscriptionSessions=sa})),da,fa=e((()=>{P(),G(),I(),da=class extends N{create(e,t){return this._client.post(`/chatkit/sessions`,{body:e,...t,headers:W([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(F`/chatkit/sessions/${e}/cancel`,{...t,headers:W([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}}})),pa,ma=e((()=>{P(),A(),G(),I(),pa=class extends N{retrieve(e,t){return this._client.get(F`/chatkit/threads/${e}`,{...t,headers:W([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/chatkit/threads`,O,{query:e,...t,headers:W([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(F`/chatkit/threads/${e}`,{...t,headers:W([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}listItems(e,t={},n){return this._client.getAPIList(F`/chatkit/threads/${e}/items`,O,{query:t,...n,headers:W([{"OpenAI-Beta":`chatkit_beta=v1`},n?.headers]),__security:{bearerAuth:!0}})}}})),ha,ga=e((()=>{P(),fa(),ma(),ha=class extends N{constructor(){super(...arguments),this.sessions=new da(this._client),this.threads=new pa(this._client)}},ha.Sessions=da,ha.Threads=pa})),_a,va=e((()=>{P(),A(),G(),I(),_a=class extends N{list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(F`/responses/${e}/input_items?beta=true`,D,{query:i,...n,headers:W([{...r?.toString()==null?void 0:{"openai-beta":r?.toString()}},n?.headers]),__security:{bearerAuth:!0}})}}})),ya,ba=e((()=>{P(),G(),ya=class extends N{count(e={},t){let{betas:n,...r}=e??{};return this._client.post(`/responses/input_tokens?beta=true`,{body:r,...t,headers:W([{...n?.toString()==null?void 0:{"openai-beta":n?.toString()}},t?.headers]),__security:{bearerAuth:!0}})}}})),xa,Sa=e((()=>{P(),va(),ba(),G(),I(),xa=class extends N{constructor(){super(...arguments),this.inputItems=new _a(this._client),this.inputTokens=new ya(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/responses?beta=true`,{body:r,...t,headers:W([{...n?.toString()==null?void 0:{"openai-beta":n?.toString()}},t?.headers]),stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t={},n){let{betas:r,...i}=t??{};return this._client.get(F`/responses/${e}?beta=true`,{query:i,...n,headers:W([{...r?.toString()==null?void 0:{"openai-beta":r?.toString()}},n?.headers]),stream:t?.stream??!1,__security:{bearerAuth:!0}})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(F`/responses/${e}?beta=true`,{...n,headers:W([{Accept:`*/*`,...r?.toString()==null?void 0:{"openai-beta":r?.toString()}},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t={},n){let{betas:r}=t??{};return this._client.post(F`/responses/${e}/cancel?beta=true`,{...n,headers:W([{...r?.toString()==null?void 0:{"openai-beta":r?.toString()}},n?.headers]),__security:{bearerAuth:!0}})}compact(e,t){let{betas:n,...r}=e;return this._client.post(`/responses/compact?beta=true`,{body:r,...t,headers:W([{...n?.toString()==null?void 0:{"openai-beta":n?.toString()}},t?.headers]),__security:{bearerAuth:!0}})}},xa.InputItems=_a,xa.InputTokens=ya})),Ca,wa=e((()=>{P(),A(),G(),I(),Ca=class extends N{create(e,t,n){return this._client.post(F`/threads/${e}/messages`,{body:t,...n,headers:W([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(F`/threads/${r}/messages/${e}`,{...n,headers:W([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(F`/threads/${r}/messages/${e}`,{body:i,...n,headers:W([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(F`/threads/${e}/messages`,D,{query:t,...n,headers:W([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{thread_id:r}=t;return this._client.delete(F`/threads/${r}/messages/${e}`,{...n,headers:W([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}}})),Ta,Ea=e((()=>{P(),A(),G(),I(),Ta=class extends N{retrieve(e,t,n){let{thread_id:r,run_id:i,...a}=t;return this._client.get(F`/threads/${r}/runs/${i}/steps/${e}`,{query:a,...n,headers:W([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t,n){let{thread_id:r,...i}=t;return this._client.getAPIList(F`/threads/${r}/runs/${e}/steps`,D,{query:i,...n,headers:W([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}}})),Da,Oa=e((()=>{Da=e=>{if(typeof Buffer<`u`){let t=Buffer.from(e,`base64`);return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}else{let t=atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.charCodeAt(e);return Array.from(new Float32Array(r.buffer))}}})),ka,Aa=e((()=>{ka=e=>{if(globalThis.process!==void 0)return globalThis.process.env?.[e]?.trim()||void 0;if(globalThis.Deno!==void 0)return globalThis.Deno.env?.get?.(e)?.trim()||void 0}})),ja=e((()=>{xe(),Oa(),Aa(),Dt(),l(),Ce(),lt()})),K,Ma,Na,q,Pa,J,Fa,Ia,La,Ra,Y,za,Ba,Va,Ha,Ua,Wa,Ga,Ka,qa,Ja,Ya,Xa,Za,Qa=e((()=>{s(),vr(),L(),Xn(),ja(),Za=class extends Yn{constructor(){super(...arguments),K.add(this),Na.set(this,[]),q.set(this,{}),Pa.set(this,{}),J.set(this,void 0),Fa.set(this,void 0),Ia.set(this,void 0),La.set(this,void 0),Ra.set(this,void 0),Y.set(this,void 0),za.set(this,void 0),Ba.set(this,void 0),Va.set(this,void 0)}[(Na=new WeakMap,q=new WeakMap,Pa=new WeakMap,J=new WeakMap,Fa=new WeakMap,Ia=new WeakMap,La=new WeakMap,Ra=new WeakMap,Y=new WeakMap,za=new WeakMap,Ba=new WeakMap,Va=new WeakMap,K=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`event`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new Ma;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),this._connected();let n=Mt.fromReadableStream(e,this.controller);for await(let e of n)o(this,K,`m`,Ha).call(this,e);if(n.controller.signal?.aborted)throw new h;return this._addRun(o(this,K,`m`,Ua).call(this))}toReadableStream(){return new Mt(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,r){let i=new Ma;return i._run(()=>i._runToolAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createToolAssistantStream(e,t,n,r){this._listenForAbort(r?.signal);let i={...n,stream:!0},a=await e.submitToolOutputs(t,i,{...r,signal:this.controller.signal});this._connected();for await(let e of a)o(this,K,`m`,Ha).call(this,e);if(a.controller.signal?.aborted)throw new h;return this._addRun(o(this,K,`m`,Ua).call(this))}static createThreadAssistantStream(e,t,n){let r=new Ma;return r._run(()=>r._threadAssistantStream(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":`stream`}})),r}static createAssistantStream(e,t,n,r){let i=new Ma;return i._run(()=>i._runAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}currentEvent(){return o(this,za,`f`)}currentRun(){return o(this,Ba,`f`)}currentMessageSnapshot(){return o(this,J,`f`)}currentRunStepSnapshot(){return o(this,Va,`f`)}async finalRunSteps(){return await this.done(),Object.values(o(this,q,`f`))}async finalMessages(){return await this.done(),Object.values(o(this,Pa,`f`))}async finalRun(){if(await this.done(),!o(this,Fa,`f`))throw Error(`Final run was not received.`);return o(this,Fa,`f`)}async _createThreadAssistantStream(e,t,n){this._listenForAbort(n?.signal);let r={...t,stream:!0},i=await e.createAndRun(r,{...n,signal:this.controller.signal});this._connected();for await(let e of i)o(this,K,`m`,Ha).call(this,e);if(i.controller.signal?.aborted)throw new h;return this._addRun(o(this,K,`m`,Ua).call(this))}async _createAssistantStream(e,t,n,r){this._listenForAbort(r?.signal);let i={...n,stream:!0},a=await e.create(t,i,{...r,signal:this.controller.signal});this._connected();for await(let e of a)o(this,K,`m`,Ha).call(this,e);if(a.controller.signal?.aborted)throw new h;return this._addRun(o(this,K,`m`,Ua).call(this))}static accumulateDelta(e,t){for(let[n,r]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=r;continue}let t=e[n];if(t==null){e[n]=r;continue}if(n===`index`||n===`type`){e[n]=r;continue}if(typeof t==`string`&&typeof r==`string`)t+=r;else if(typeof t==`number`&&typeof r==`number`)t+=r;else if(he(t)&&he(r))t=this.accumulateDelta(t,r);else if(Array.isArray(t)&&Array.isArray(r)){if(t.every(e=>typeof e==`string`||typeof e==`number`)){t.push(...r);continue}for(let e of r){if(!he(e))throw Error(`Expected array delta entry to be an object but got: ${e}`);let n=e.index;if(n==null)throw console.error(e),Error("Expected array delta entry to have an `index` property");if(typeof n!=`number`)throw Error(`Expected array delta entry \`index\` property to be a number but got ${n}`);let r=t[n];r==null?t[n]=e:t[n]=this.accumulateDelta(r,e)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${r}, accValue: ${t}`);e[n]=t}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,r){return await this._createAssistantStream(t,e,n,r)}async _runToolAssistantStream(e,t,n,r){return await this._createToolAssistantStream(t,e,n,r)}},Ma=Za,Ha=function(e){if(!this.ended)switch(a(this,za,e,`f`),o(this,K,`m`,Ka).call(this,e),e.event){case`thread.created`:break;case`thread.run.created`:case`thread.run.queued`:case`thread.run.in_progress`:case`thread.run.requires_action`:case`thread.run.completed`:case`thread.run.incomplete`:case`thread.run.failed`:case`thread.run.cancelling`:case`thread.run.cancelled`:case`thread.run.expired`:o(this,K,`m`,Xa).call(this,e);break;case`thread.run.step.created`:case`thread.run.step.in_progress`:case`thread.run.step.delta`:case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:o(this,K,`m`,Ga).call(this,e);break;case`thread.message.created`:case`thread.message.in_progress`:case`thread.message.delta`:case`thread.message.completed`:case`thread.message.incomplete`:o(this,K,`m`,Wa).call(this,e);break;case`error`:throw Error(`Encountered an error event in event processing - errors should be processed earlier`);default:}},Ua=function(){if(this.ended)throw new p(`stream has ended, this shouldn't happen`);if(!o(this,Fa,`f`))throw Error(`Final run has not been received`);return o(this,Fa,`f`)},Wa=function(e){let[t,n]=o(this,K,`m`,Ja).call(this,e,o(this,J,`f`));a(this,J,t,`f`),o(this,Pa,`f`)[t.id]=t;for(let e of n){let n=t.content[e.index];n?.type==`text`&&this._emit(`textCreated`,n.text)}switch(e.event){case`thread.message.created`:this._emit(`messageCreated`,e.data);break;case`thread.message.in_progress`:break;case`thread.message.delta`:if(this._emit(`messageDelta`,e.data.delta,t),e.data.delta.content)for(let n of e.data.delta.content){if(n.type==`text`&&n.text){let e=n.text,r=t.content[n.index];if(r&&r.type==`text`)this._emit(`textDelta`,e,r.text);else throw Error(`The snapshot associated with this text delta is not text or missing`)}if(n.index!=o(this,Ia,`f`)){if(o(this,La,`f`))switch(o(this,La,`f`).type){case`text`:this._emit(`textDone`,o(this,La,`f`).text,o(this,J,`f`));break;case`image_file`:this._emit(`imageFileDone`,o(this,La,`f`).image_file,o(this,J,`f`));break}a(this,Ia,n.index,`f`)}a(this,La,t.content[n.index],`f`)}break;case`thread.message.completed`:case`thread.message.incomplete`:if(o(this,Ia,`f`)!==void 0){let t=e.data.content[o(this,Ia,`f`)];if(t)switch(t.type){case`image_file`:this._emit(`imageFileDone`,t.image_file,o(this,J,`f`));break;case`text`:this._emit(`textDone`,t.text,o(this,J,`f`));break}}o(this,J,`f`)&&this._emit(`messageDone`,e.data),a(this,J,void 0,`f`)}},Ga=function(e){let t=o(this,K,`m`,qa).call(this,e);switch(a(this,Va,t,`f`),e.event){case`thread.run.step.created`:this._emit(`runStepCreated`,e.data);break;case`thread.run.step.delta`:let n=e.data.delta;if(n.step_details&&n.step_details.type==`tool_calls`&&n.step_details.tool_calls&&t.step_details.type==`tool_calls`)for(let e of n.step_details.tool_calls)e.index==o(this,Ra,`f`)?this._emit(`toolCallDelta`,e,t.step_details.tool_calls[e.index]):(o(this,Y,`f`)&&this._emit(`toolCallDone`,o(this,Y,`f`)),a(this,Ra,e.index,`f`),a(this,Y,t.step_details.tool_calls[e.index],`f`),o(this,Y,`f`)&&this._emit(`toolCallCreated`,o(this,Y,`f`)));this._emit(`runStepDelta`,e.data.delta,t);break;case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:a(this,Va,void 0,`f`),e.data.step_details.type==`tool_calls`&&o(this,Y,`f`)&&(this._emit(`toolCallDone`,o(this,Y,`f`)),a(this,Y,void 0,`f`)),this._emit(`runStepDone`,e.data,t);break;case`thread.run.step.in_progress`:break}},Ka=function(e){o(this,Na,`f`).push(e),this._emit(`event`,e)},qa=function(e){switch(e.event){case`thread.run.step.created`:return o(this,q,`f`)[e.data.id]=e.data,e.data;case`thread.run.step.delta`:let t=o(this,q,`f`)[e.data.id];if(!t)throw Error(`Received a RunStepDelta before creation of a snapshot`);let n=e.data;if(n.delta){let r=Ma.accumulateDelta(t,n.delta);o(this,q,`f`)[e.data.id]=r}return o(this,q,`f`)[e.data.id];case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:case`thread.run.step.in_progress`:o(this,q,`f`)[e.data.id]=e.data;break}if(o(this,q,`f`)[e.data.id])return o(this,q,`f`)[e.data.id];throw Error(`No snapshot available`)},Ja=function(e,t){let n=[];switch(e.event){case`thread.message.created`:return[e.data,n];case`thread.message.delta`:if(!t)throw Error(`Received a delta with no existing snapshot (there should be one from message creation)`);let r=e.data;if(r.delta.content)for(let e of r.delta.content)if(e.index in t.content){let n=t.content[e.index];t.content[e.index]=o(this,K,`m`,Ya).call(this,e,n)}else t.content[e.index]=e,n.push(e);return[t,n];case`thread.message.in_progress`:case`thread.message.completed`:case`thread.message.incomplete`:if(t)return[t,n];throw Error(`Received thread message event with no existing snapshot`)}throw Error(`Tried to accumulate a non-message event`)},Ya=function(e,t){return Ma.accumulateDelta(t,e)},Xa=function(e){switch(a(this,Ba,e.data,`f`),e.event){case`thread.run.created`:break;case`thread.run.queued`:break;case`thread.run.in_progress`:break;case`thread.run.requires_action`:case`thread.run.cancelled`:case`thread.run.failed`:case`thread.run.completed`:case`thread.run.expired`:case`thread.run.incomplete`:a(this,Fa,e.data,`f`),o(this,Y,`f`)&&(this._emit(`toolCallDone`,o(this,Y,`f`)),a(this,Y,void 0,`f`));break;case`thread.run.cancelling`:break}}})),$a,eo=e((()=>{P(),Ea(),A(),G(),Qa(),Ce(),I(),$a=class extends N{constructor(){super(...arguments),this.steps=new Ta(this._client)}create(e,t,n){let{include:r,...i}=t;return this._client.post(F`/threads/${e}/runs`,{query:{include:r},body:i,...n,headers:W([{"OpenAI-Beta":`assistants=v2`},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(F`/threads/${r}/runs/${e}`,{...n,headers:W([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(F`/threads/${r}/runs/${e}`,{body:i,...n,headers:W([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(F`/threads/${e}/runs`,D,{query:t,...n,headers:W([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,n){let{thread_id:r}=t;return this._client.post(F`/threads/${r}/runs/${e}/cancel`,{...n,headers:W([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(r.id,{thread_id:e},n)}createAndStream(e,t,n){return Za.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){let r=W([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:i,response:a}=await this.retrieve(e,t,{...n,headers:{...n?.headers,...r}}).withResponse();switch(i.status){case`queued`:case`in_progress`:case`cancelling`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=a.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await Se(e);break;case`requires_action`:case`incomplete`:case`cancelled`:case`completed`:case`failed`:case`expired`:return i}}}stream(e,t,n){return Za.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){let{thread_id:r,...i}=t;return this._client.post(F`/threads/${r}/runs/${e}/submit_tool_outputs`,{body:i,...n,headers:W([{"OpenAI-Beta":`assistants=v2`},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,t,n){let r=await this.submitToolOutputs(e,t,n);return await this.poll(r.id,t,n)}submitToolOutputsStream(e,t,n){return Za.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}},$a.Steps=Ta})),to,no=e((()=>{P(),wa(),eo(),G(),Qa(),I(),to=class extends N{constructor(){super(...arguments),this.runs=new $a(this._client),this.messages=new Ca(this._client)}create(e={},t){return this._client.post(`/threads`,{body:e,...t,headers:W([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(F`/threads/${e}`,{...t,headers:W([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(F`/threads/${e}`,{body:t,...n,headers:W([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(F`/threads/${e}`,{...t,headers:W([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,t){return this._client.post(`/threads/runs`,{body:e,...t,headers:W([{"OpenAI-Beta":`assistants=v2`},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll(e,t){let n=await this.createAndRun(e,t);return await this.runs.poll(n.id,{thread_id:n.thread_id},t)}createAndRunStream(e,t){return Za.createThreadAssistantStream(e,this._client.beta.threads,t)}},to.Runs=$a,to.Messages=Ca})),ro,io=e((()=>{P(),ia(),ua(),ga(),Sa(),no(),ro=class extends N{constructor(){super(...arguments),this.realtime=new la(this._client),this.responses=new xa(this._client),this.chatkit=new ha(this._client),this.assistants=new ra(this._client),this.threads=new to(this._client)}},ro.Realtime=la,ro.Responses=xa,ro.ChatKit=ha,ro.Assistants=ra,ro.Threads=to})),ao,oo=e((()=>{P(),ao=class extends N{create(e,t){return this._client.post(`/completions`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}}})),so,co=e((()=>{P(),G(),I(),so=class extends N{retrieve(e,t,n){let{container_id:r}=t;return this._client.get(F`/containers/${r}/files/${e}/content`,{...n,headers:W([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}})),lo,uo=e((()=>{P(),co(),A(),G(),M(),I(),lo=class extends N{constructor(){super(...arguments),this.content=new so(this._client)}create(e,t,n){return this._client.post(F`/containers/${e}/files`,$t({body:t,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,n){let{container_id:r}=t;return this._client.get(F`/containers/${r}/files/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(F`/containers/${e}/files`,D,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{container_id:r}=t;return this._client.delete(F`/containers/${r}/files/${e}`,{...n,headers:W([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}},lo.Content=so})),fo,po=e((()=>{P(),uo(),A(),G(),I(),fo=class extends N{constructor(){super(...arguments),this.files=new lo(this._client)}create(e,t){return this._client.post(`/containers`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(F`/containers/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/containers`,D,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(F`/containers/${e}`,{...t,headers:W([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}},fo.Files=lo})),mo,ho=e((()=>{P(),A(),I(),mo=class extends N{create(e,t,n){let{include:r,...i}=t;return this._client.post(F`/conversations/${e}/items`,{query:{include:r},body:i,...n,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{conversation_id:r,...i}=t;return this._client.get(F`/conversations/${r}/items/${e}`,{query:i,...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(F`/conversations/${e}/items`,O,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{conversation_id:r}=t;return this._client.delete(F`/conversations/${r}/items/${e}`,{...n,__security:{bearerAuth:!0}})}}})),go,_o=e((()=>{P(),ho(),I(),go=class extends N{constructor(){super(...arguments),this.items=new mo(this._client)}create(e={},t){return this._client.post(`/conversations`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(F`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(F`/conversations/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(F`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}},go.Items=mo})),vo,yo=e((()=>{P(),ja(),vo=class extends N{create(e,t){let n=!!e.encoding_format,r=n?e.encoding_format:`base64`;n&&T(this._client).debug(`embeddings/user defined encoding_format:`,e.encoding_format);let i=this._client.post(`/embeddings`,{body:{...e,encoding_format:r},...t,__security:{bearerAuth:!0}});return n?i:(T(this._client).debug(`embeddings/decoding base64 embeddings from base64`),i._thenUnwrap(e=>(e&&e.data&&e.data.forEach(e=>{let t=e.embedding;e.embedding=Da(t)}),e)))}}})),bo,xo=e((()=>{P(),A(),I(),bo=class extends N{retrieve(e,t,n){let{eval_id:r,run_id:i}=t;return this._client.get(F`/evals/${r}/runs/${i}/output_items/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t,n){let{eval_id:r,...i}=t;return this._client.getAPIList(F`/evals/${r}/runs/${e}/output_items`,D,{query:i,...n,__security:{bearerAuth:!0}})}}})),So,Co=e((()=>{P(),xo(),A(),I(),So=class extends N{constructor(){super(...arguments),this.outputItems=new bo(this._client)}create(e,t,n){return this._client.post(F`/evals/${e}/runs`,{body:t,...n,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{eval_id:r}=t;return this._client.get(F`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(F`/evals/${e}/runs`,D,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{eval_id:r}=t;return this._client.delete(F`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}cancel(e,t,n){let{eval_id:r}=t;return this._client.post(F`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}},So.OutputItems=bo})),wo,To=e((()=>{P(),Co(),A(),I(),wo=class extends N{constructor(){super(...arguments),this.runs=new So(this._client)}create(e,t){return this._client.post(`/evals`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(F`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(F`/evals/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/evals`,D,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(F`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}},wo.Runs=So})),Eo,Do=e((()=>{P(),A(),G(),Ce(),L(),M(),I(),Eo=class extends N{create(e,t){return this._client.post(`/files`,j({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(F`/files/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/files`,D,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(F`/files/${e}`,{...t,__security:{bearerAuth:!0}})}content(e,t){return this._client.get(F`/files/${e}/content`,{...t,headers:W([{Accept:`application/binary`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=1800*1e3}={}){let r=new Set([`processed`,`error`,`deleted`]),i=Date.now(),a=await this.retrieve(e);for(;!a.status||!r.has(a.status);)if(await Se(t),a=await this.retrieve(e),Date.now()-i>n)throw new ee({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return a}}})),Oo,ko=e((()=>{P(),Oo=class extends N{}})),Ao,jo=e((()=>{P(),Ao=class extends N{run(e,t){return this._client.post(`/fine_tuning/alpha/graders/run`,{body:e,...t,__security:{bearerAuth:!0}})}validate(e,t){return this._client.post(`/fine_tuning/alpha/graders/validate`,{body:e,...t,__security:{bearerAuth:!0}})}}})),Mo,No=e((()=>{P(),jo(),Mo=class extends N{constructor(){super(...arguments),this.graders=new Ao(this._client)}},Mo.Graders=Ao})),Po,Fo=e((()=>{P(),A(),I(),Po=class extends N{create(e,t,n){return this._client.getAPIList(F`/fine_tuning/checkpoints/${e}/permissions`,E,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},n){return this._client.get(F`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(F`/fine_tuning/checkpoints/${e}/permissions`,O,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{fine_tuned_model_checkpoint:r}=t;return this._client.delete(F`/fine_tuning/checkpoints/${r}/permissions/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}})),Io,Lo=e((()=>{P(),Fo(),Io=class extends N{constructor(){super(...arguments),this.permissions=new Po(this._client)}},Io.Permissions=Po})),Ro,zo=e((()=>{P(),A(),I(),Ro=class extends N{list(e,t={},n){return this._client.getAPIList(F`/fine_tuning/jobs/${e}/checkpoints`,D,{query:t,...n,__security:{bearerAuth:!0}})}}})),Bo,Vo=e((()=>{P(),zo(),A(),I(),Bo=class extends N{constructor(){super(...arguments),this.checkpoints=new Ro(this._client)}create(e,t){return this._client.post(`/fine_tuning/jobs`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(F`/fine_tuning/jobs/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/fine_tuning/jobs`,D,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(F`/fine_tuning/jobs/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}listEvents(e,t={},n){return this._client.getAPIList(F`/fine_tuning/jobs/${e}/events`,D,{query:t,...n,__security:{bearerAuth:!0}})}pause(e,t){return this._client.post(F`/fine_tuning/jobs/${e}/pause`,{...t,__security:{bearerAuth:!0}})}resume(e,t){return this._client.post(F`/fine_tuning/jobs/${e}/resume`,{...t,__security:{bearerAuth:!0}})}},Bo.Checkpoints=Ro})),Ho,Uo=e((()=>{P(),ko(),No(),Lo(),Vo(),Ho=class extends N{constructor(){super(...arguments),this.methods=new Oo(this._client),this.jobs=new Bo(this._client),this.checkpoints=new Io(this._client),this.alpha=new Mo(this._client)}},Ho.Methods=Oo,Ho.Jobs=Bo,Ho.Checkpoints=Io,Ho.Alpha=Mo})),Wo,Go=e((()=>{P(),Wo=class extends N{}})),Ko,qo=e((()=>{P(),Go(),Ko=class extends N{constructor(){super(...arguments),this.graderModels=new Wo(this._client)}},Ko.GraderModels=Wo})),Jo,Yo=e((()=>{P(),M(),Jo=class extends N{createVariation(e,t){return this._client.post(`/images/variations`,j({body:e,...t,__security:{bearerAuth:!0}},this._client))}edit(e,t){return this._client.post(`/images/edits`,j({body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}},this._client))}generate(e,t){return this._client.post(`/images/generations`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}}})),Xo,Zo=e((()=>{P(),A(),I(),Xo=class extends N{retrieve(e,t){return this._client.get(F`/models/${e}`,{...t,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList(`/models`,E,{...e,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(F`/models/${e}`,{...t,__security:{bearerAuth:!0}})}}})),Qo,$o=e((()=>{P(),Qo=class extends N{create(e,t){return this._client.post(`/moderations`,{body:e,...t,__security:{bearerAuth:!0}})}}})),es,ts=e((()=>{P(),G(),I(),es=class extends N{accept(e,t,n){return this._client.post(F`/realtime/calls/${e}/accept`,{body:t,...n,headers:W([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}hangup(e,t){return this._client.post(F`/realtime/calls/${e}/hangup`,{...t,headers:W([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}refer(e,t,n){return this._client.post(F`/realtime/calls/${e}/refer`,{body:t,...n,headers:W([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}reject(e,t={},n){return this._client.post(F`/realtime/calls/${e}/reject`,{body:t,...n,headers:W([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}}})),ns,rs=e((()=>{P(),ns=class extends N{create(e,t){return this._client.post(`/realtime/client_secrets`,{body:e,...t,__security:{bearerAuth:!0}})}}})),is,as=e((()=>{P(),ts(),rs(),is=class extends N{constructor(){super(...arguments),this.clientSecrets=new ns(this._client),this.calls=new es(this._client)}},is.ClientSecrets=ns,is.Calls=es}));function os(e,t){if(!t||!ls(t)){let t={...e,output_parsed:null,output:e.output.map(e=>e.type===`function_call`?{...e,parsed_arguments:null}:e.type===`message`?{...e,content:e.content.map(e=>({...e,parsed:null}))}:e)};return ps(e,t)&&X(t),t}return ss(e,t)}function ss(e,t){let n=!e.status||e.status===`completed`,r=e.output.map(e=>{if(e.type===`function_call`)return{...e,parsed_arguments:n?fs(t,e):null};if(e.type===`message`){let r=e.content.map(e=>e.type===`output_text`?{...e,parsed:n?cs(t,e.text):null}:e);return{...e,content:r}}return e}),i=Object.assign({},e,{output:r});return ps(e,i)&&X(i),Object.defineProperty(i,"output_parsed",{enumerable:!0,get(){for(let e of i.output)if(e.type===`message`){for(let t of e.content)if(t.type===`output_text`&&t.parsed!==null)return t.parsed}return null}}),i}function cs(e,t){return e.text?.format?.type===`json_schema`?`$parseRaw`in e.text?.format?(e.text?.format).$parseRaw(t):JSON.parse(t):null}function ls(e){return!!xn(e.text?.format)}function us(e){return e?.$brand===`auto-parseable-tool`}function ds(e,t){return e.find(e=>e.type===`function`&&e.name===t)}function fs(e,t){let n=ds(e.tools??[],t.name);return{...t,...t,parsed_arguments:us(n)?n.$parseRaw(t.arguments):n?.strict?JSON.parse(t.arguments):null}}function ps(e,t){return!Object.getOwnPropertyDescriptor(e,`output_text`)||t.output_text==null}function X(e){let t=[];for(let n of e.output)if(n.type===`message`)for(let e of n.content)e.type===`output_text`&&t.push(e.text);e.output_text=t.join(``)}var ms=e((()=>{L(),jn()}));function hs(e,t){if(!t){if(e.type!==`response.created`)throw new p(`When snapshot hasn't been set yet, expected 'response.created' event, got ${e.type}`);return gs(e.response)}switch(e.type){case`response.output_item.added`:t.output.push(structuredClone(e.item)),e.item.type===`message`&&X(t);break;case`response.output_item.done`:Z(t,e.output_index),t.output[e.output_index]=structuredClone(e.item),e.item.type===`message`&&X(t);break;case`response.content_part.added`:{let n=Z(t,e.output_index),r=n.type,i=e.part;r===`message`&&i.type!==`reasoning_text`?(n.content.push(structuredClone(i)),i.type===`output_text`&&X(t)):r===`reasoning`&&i.type===`reasoning_text`&&(n.content||(n.content=[]),n.content.push(structuredClone(i)));break}case`response.content_part.done`:{let n=Z(t,e.output_index),r=e.part;if(n.type===`message`&&r.type!==`reasoning_text`)Q(n.content,e.content_index),n.content[e.content_index]=structuredClone(r),r.type===`output_text`&&X(t);else if(n.type===`reasoning`&&r.type===`reasoning_text`){let t=n.content;if(!t)throw new p(`missing content at index ${e.content_index}`);Q(t,e.content_index),t[e.content_index]=structuredClone(r)}break}case`response.output_text.delta`:{let n=Z(t,e.output_index);if(n.type===`message`){let r=Q(n.content,e.content_index);if(r.type!==`output_text`)throw new p(`expected content to be 'output_text', got ${r.type}`);r.text+=e.delta,t.output_text+=e.delta}break}case`response.output_text.done`:{let n=Z(t,e.output_index);if(n.type===`message`){let r=Q(n.content,e.content_index);if(r.type!==`output_text`)throw new p(`expected content to be 'output_text', got ${r.type}`);r.text=e.text,X(t)}break}case`response.output_text.annotation.added`:{let n=Z(t,e.output_index);if(n.type===`message`){let t=Q(n.content,e.content_index);if(t.type!==`output_text`)throw new p(`expected content to be 'output_text', got ${t.type}`);t.annotations[e.annotation_index]=structuredClone(e.annotation)}break}case`response.refusal.delta`:{let n=Z(t,e.output_index);if(n.type===`message`){let t=Q(n.content,e.content_index);if(t.type!==`refusal`)throw new p(`expected content to be 'refusal', got ${t.type}`);t.refusal+=e.delta}break}case`response.refusal.done`:{let n=Z(t,e.output_index);if(n.type===`message`){let t=Q(n.content,e.content_index);if(t.type!==`refusal`)throw new p(`expected content to be 'refusal', got ${t.type}`);t.refusal=e.refusal}break}case`response.function_call_arguments.delta`:{let n=Z(t,e.output_index);n.type===`function_call`&&(n.arguments+=e.delta);break}case`response.function_call_arguments.done`:{let n=Z(t,e.output_index);n.type===`function_call`&&(n.arguments=e.arguments);break}case`response.reasoning_text.delta`:{let n=Z(t,e.output_index);if(n.type===`reasoning`){if(!n.content)throw new p(`missing content at index ${e.content_index}`);let t=Q(n.content,e.content_index);if(t.type!==`reasoning_text`)throw new p(`expected content to be 'reasoning_text', got ${t.type}`);t.text+=e.delta}break}case`response.reasoning_text.done`:{let n=Z(t,e.output_index);if(n.type===`reasoning`){if(!n.content)throw new p(`missing content at index ${e.content_index}`);let t=Q(n.content,e.content_index);if(t.type!==`reasoning_text`)throw new p(`expected content to be 'reasoning_text', got ${t.type}`);t.text=e.text}break}case`response.reasoning_summary_part.added`:{let n=Z(t,e.output_index);n.type===`reasoning`&&n.summary.push(structuredClone(e.part));break}case`response.reasoning_summary_part.done`:{let n=Z(t,e.output_index);n.type===`reasoning`&&(Q(n.summary,e.summary_index),n.summary[e.summary_index]=structuredClone(e.part));break}case`response.reasoning_summary_text.delta`:{let n=Z(t,e.output_index);if(n.type===`reasoning`){let t=Q(n.summary,e.summary_index);t.text+=e.delta}break}case`response.reasoning_summary_text.done`:{let n=Z(t,e.output_index);if(n.type===`reasoning`){let t=Q(n.summary,e.summary_index);t.text=e.text}break}case`response.custom_tool_call_input.delta`:{let n=Z(t,e.output_index);n.type===`custom_tool_call`&&(n.input+=e.delta);break}case`response.custom_tool_call_input.done`:{let n=Z(t,e.output_index);n.type===`custom_tool_call`&&(n.input=e.input);break}case`response.mcp_call_arguments.delta`:{let n=Z(t,e.output_index);n.type===`mcp_call`&&(n.arguments+=e.delta);break}case`response.mcp_call_arguments.done`:{let n=Z(t,e.output_index);n.type===`mcp_call`&&(n.arguments=e.arguments);break}case`response.code_interpreter_call_code.delta`:{let n=Z(t,e.output_index);n.type===`code_interpreter_call`&&(n.code=(n.code??``)+e.delta);break}case`response.code_interpreter_call_code.done`:{let n=Z(t,e.output_index);n.type===`code_interpreter_call`&&(n.code=e.code);break}case`response.code_interpreter_call.in_progress`:{let n=Z(t,e.output_index);n.type===`code_interpreter_call`&&(n.status=`in_progress`);break}case`response.code_interpreter_call.interpreting`:{let n=Z(t,e.output_index);n.type===`code_interpreter_call`&&(n.status=`interpreting`);break}case`response.code_interpreter_call.completed`:{let n=Z(t,e.output_index);n.type===`code_interpreter_call`&&(n.status=`completed`);break}case`response.file_search_call.in_progress`:{let n=Z(t,e.output_index);n.type===`file_search_call`&&(n.status=`in_progress`);break}case`response.file_search_call.searching`:{let n=Z(t,e.output_index);n.type===`file_search_call`&&(n.status=`searching`);break}case`response.file_search_call.completed`:{let n=Z(t,e.output_index);n.type===`file_search_call`&&(n.status=`completed`);break}case`response.web_search_call.in_progress`:{let n=Z(t,e.output_index);n.type===`web_search_call`&&(n.status=`in_progress`);break}case`response.web_search_call.searching`:{let n=Z(t,e.output_index);n.type===`web_search_call`&&(n.status=`searching`);break}case`response.web_search_call.completed`:{let n=Z(t,e.output_index);n.type===`web_search_call`&&(n.status=`completed`);break}case`response.image_generation_call.in_progress`:{let n=Z(t,e.output_index);n.type===`image_generation_call`&&(n.status=`in_progress`);break}case`response.image_generation_call.generating`:{let n=Z(t,e.output_index);n.type===`image_generation_call`&&(n.status=`generating`);break}case`response.image_generation_call.completed`:{let n=Z(t,e.output_index);n.type===`image_generation_call`&&(n.status=`completed`);break}case`response.mcp_call.in_progress`:{let n=Z(t,e.output_index);n.type===`mcp_call`&&(n.status=`in_progress`);break}case`response.mcp_call.completed`:{let n=Z(t,e.output_index);n.type===`mcp_call`&&(n.status=`completed`);break}case`response.mcp_call.failed`:{let n=Z(t,e.output_index);n.type===`mcp_call`&&(n.status=`failed`);break}case`response.created`:case`response.queued`:case`response.in_progress`:case`response.completed`:case`response.failed`:case`response.incomplete`:t=gs(e.response);break;case`response.audio.delta`:case`response.audio.done`:case`response.audio.transcript.delta`:case`response.audio.transcript.done`:case`response.image_generation_call.partial_image`:case`response.mcp_list_tools.in_progress`:case`response.mcp_list_tools.completed`:case`response.mcp_list_tools.failed`:case`keepalive`:case`error`:break;default:_s(e)}return t}function gs(e){let t=structuredClone(e);return(!Object.getOwnPropertyDescriptor(t,`output_text`)||t.output_text==null)&&X(t),t}function Z(e,t){let n=e.output[t];if(!n)throw new p(`missing output at index ${t}`);return n}function Q(e,t){let n=e[t];if(!n)throw new p(`missing content at index ${t}`);return n}function _s(e){throw new p(`Unhandled response stream event: ${JSON.stringify(e)}`)}var vs=e((()=>{L(),ms()}));function ys(e,t){return os(e,t)}var bs,xs,Ss,Cs,ws,Ts,Es,Ds,Os=e((()=>{s(),L(),Xn(),vs(),ms(),Ds=class e extends Yn{constructor(e){super(),bs.add(this),xs.set(this,void 0),Ss.set(this,void 0),Cs.set(this,void 0),a(this,xs,e,`f`)}static createResponse(t,n,r){let i=new e(n);return i._run(()=>i._createOrRetrieveResponse(t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createOrRetrieveResponse(e,t,n){this._listenForAbort(n?.signal),o(this,bs,`m`,ws).call(this);let r,i=null;`response_id`in t?(r=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):r=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let e of r)o(this,bs,`m`,Ts).call(this,e,i);if(r.controller.signal?.aborted)throw new h;return o(this,bs,`m`,Es).call(this)}[(xs=new WeakMap,Ss=new WeakMap,Cs=new WeakMap,bs=new WeakSet,ws=function(){this.ended||a(this,Ss,void 0,`f`)},Ts=function(e,t){if(this.ended)return;let n=(e,n)=>{(t==null||n.sequence_number>t)&&this._emit(e,n)},r=hs(e,o(this,Ss,`f`));switch(a(this,Ss,r,`f`),n(`event`,e),e.type){case`response.output_text.delta`:{let t=r.output[e.output_index];if(!t)throw new p(`missing output at index ${e.output_index}`);if(t.type===`message`){let r=t.content[e.content_index];if(!r)throw new p(`missing content at index ${e.content_index}`);if(r.type!==`output_text`)throw new p(`expected content to be 'output_text', got ${r.type}`);n(`response.output_text.delta`,{...e,snapshot:r.text})}break}case`response.function_call_arguments.delta`:{let t=r.output[e.output_index];if(!t)throw new p(`missing output at index ${e.output_index}`);t.type===`function_call`&&n(`response.function_call_arguments.delta`,{...e,snapshot:t.arguments});break}default:n(e.type,e);break}},Es=function(){if(this.ended)throw new p(`stream has ended, this shouldn't happen`);let e=o(this,Ss,`f`);if(!e)throw new p(`request ended without sending any events`);a(this,Ss,void 0,`f`);let t=ys(e,o(this,xs,`f`));return a(this,Cs,t,`f`),t},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`event`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=o(this,Cs,`f`);if(!e)throw new p(`stream ended without producing a ChatCompletion`);return e}}})),ks,As=e((()=>{P(),A(),I(),ks=class extends N{list(e,t={},n){return this._client.getAPIList(F`/responses/${e}/input_items`,D,{query:t,...n,__security:{bearerAuth:!0}})}}})),js,Ms=e((()=>{P(),js=class extends N{count(e={},t){return this._client.post(`/responses/input_tokens`,{body:e,...t,__security:{bearerAuth:!0}})}}})),Ns,Ps=e((()=>{ms(),Os(),P(),As(),Ms(),G(),I(),Ns=class extends N{constructor(){super(...arguments),this.inputItems=new ks(this._client),this.inputTokens=new js(this._client)}create(e,t){return this._client.post(`/responses`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&X(e),e))}retrieve(e,t={},n){return this._client.get(F`/responses/${e}`,{query:t,...n,stream:t?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&X(e),e))}delete(e,t){return this._client.delete(F`/responses/${e}`,{...t,headers:W([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(t=>ss(t,e))}stream(e,t){return Ds.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(F`/responses/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}compact(e,t){return this._client.post(`/responses/compact`,{body:e,...t,__security:{bearerAuth:!0}})}},Ns.InputItems=ks,Ns.InputTokens=js})),Fs,Is=e((()=>{P(),G(),I(),Fs=class extends N{retrieve(e,t){return this._client.get(F`/skills/${e}/content`,{...t,headers:W([{Accept:`application/binary`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}})),Ls,Rs=e((()=>{P(),G(),I(),Ls=class extends N{retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(F`/skills/${r}/versions/${e}/content`,{...n,headers:W([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}})),zs,Bs=e((()=>{P(),Rs(),A(),M(),I(),zs=class extends N{constructor(){super(...arguments),this.content=new Ls(this._client)}create(e,t={},n){return this._client.post(F`/skills/${e}/versions`,$t({body:t,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(F`/skills/${r}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(F`/skills/${e}/versions`,D,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{skill_id:r}=t;return this._client.delete(F`/skills/${r}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}},zs.Content=Ls})),Vs,Hs=e((()=>{P(),Is(),Bs(),A(),M(),I(),Vs=class extends N{constructor(){super(...arguments),this.content=new Fs(this._client),this.versions=new zs(this._client)}create(e={},t){return this._client.post(`/skills`,$t({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(F`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(F`/skills/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/skills`,D,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(F`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}},Vs.Content=Fs,Vs.Versions=zs})),Us,Ws=e((()=>{P(),M(),I(),Us=class extends N{create(e,t,n){return this._client.post(F`/uploads/${e}/parts`,j({body:t,...n,__security:{bearerAuth:!0}},this._client))}}})),Gs,Ks=e((()=>{P(),Ws(),I(),Gs=class extends N{constructor(){super(...arguments),this.parts=new Us(this._client)}create(e,t){return this._client.post(`/uploads`,{body:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(F`/uploads/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}complete(e,t,n){return this._client.post(F`/uploads/${e}/complete`,{body:t,...n,__security:{bearerAuth:!0}})}},Gs.Parts=Us})),qs,Js=e((()=>{qs=async e=>{let t=await Promise.allSettled(e),n=t.filter(e=>e.status===`rejected`);if(n.length){for(let e of n)console.error(e.reason);throw Error(`${n.length} promise(s) failed - see the above errors`)}let r=[];for(let e of t)e.status===`fulfilled`&&r.push(e.value);return r}})),Ys,Xs=e((()=>{P(),A(),G(),Ce(),Js(),I(),Ys=class extends N{create(e,t,n){return this._client.post(F`/vector_stores/${e}/file_batches`,{body:t,...n,headers:W([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(F`/vector_stores/${r}/file_batches/${e}`,{...n,headers:W([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,n){let{vector_store_id:r}=t;return this._client.post(F`/vector_stores/${r}/file_batches/${e}/cancel`,{...n,headers:W([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let r=await this.create(e,t);return await this.poll(e,r.id,n)}listFiles(e,t,n){let{vector_store_id:r,...i}=t;return this._client.getAPIList(F`/vector_stores/${r}/file_batches/${e}/files`,D,{query:i,...n,headers:W([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async poll(e,t,n){let r=W([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:i,response:a}=await this.retrieve(t,{vector_store_id:e},{...n,headers:r}).withResponse();switch(i.status){case`in_progress`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=a.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await Se(e);break;case`failed`:case`cancelled`:case`completed`:return i}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},r){if(t==null||t.length==0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let i=r?.maxConcurrency??5,a=Math.min(i,t.length),o=this._client,s=t.values(),c=[...n];async function l(e){for(let t of e){let e=await o.files.create({file:t,purpose:`assistants`},r);c.push(e.id)}}return await qs(Array(a).fill(s).map(l)),await this.createAndPoll(e,{file_ids:c})}}})),Zs,Qs=e((()=>{P(),A(),G(),ja(),I(),Zs=class extends N{create(e,t,n){return this._client.post(F`/vector_stores/${e}/files`,{body:t,...n,headers:W([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(F`/vector_stores/${r}/files/${e}`,{...n,headers:W([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{vector_store_id:r,...i}=t;return this._client.post(F`/vector_stores/${r}/files/${e}`,{body:i,...n,headers:W([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(F`/vector_stores/${e}/files`,D,{query:t,...n,headers:W([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{vector_store_id:r}=t;return this._client.delete(F`/vector_stores/${r}/files/${e}`,{...n,headers:W([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(e,r.id,n)}async poll(e,t,n){let r=W([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let i=await this.retrieve(t,{vector_store_id:e},{...n,headers:r}).withResponse(),a=i.data;switch(a.status){case`in_progress`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=i.response.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await Se(e);break;case`failed`:case`completed`:return a}}}async upload(e,t,n){let r=await this._client.files.create({file:t,purpose:`assistants`},n);return this.create(e,{file_id:r.id},n)}async uploadAndPoll(e,t,n){let r=await this.upload(e,t,n);return await this.poll(e,r.id,n)}content(e,t,n){let{vector_store_id:r}=t;return this._client.getAPIList(F`/vector_stores/${r}/files/${e}/content`,E,{...n,headers:W([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}}})),$s,ec=e((()=>{P(),Xs(),Qs(),A(),G(),I(),$s=class extends N{constructor(){super(...arguments),this.files=new Zs(this._client),this.fileBatches=new Ys(this._client)}create(e,t){return this._client.post(`/vector_stores`,{body:e,...t,headers:W([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(F`/vector_stores/${e}`,{...t,headers:W([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(F`/vector_stores/${e}`,{body:t,...n,headers:W([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/vector_stores`,D,{query:e,...t,headers:W([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(F`/vector_stores/${e}`,{...t,headers:W([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}search(e,t,n){return this._client.getAPIList(F`/vector_stores/${e}/search`,E,{body:t,method:`post`,...n,headers:W([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}},$s.Files=Zs,$s.FileBatches=Ys})),tc,nc=e((()=>{P(),A(),G(),M(),I(),tc=class extends N{create(e,t){return this._client.post(`/videos`,j({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(F`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/videos`,O,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(F`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}createCharacter(e,t){return this._client.post(`/videos/characters`,j({body:e,...t,__security:{bearerAuth:!0}},this._client))}downloadContent(e,t={},n){return this._client.get(F`/videos/${e}/content`,{query:t,...n,headers:W([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,t){return this._client.post(`/videos/edits`,j({body:e,...t,__security:{bearerAuth:!0}},this._client))}extend(e,t){return this._client.post(`/videos/extensions`,j({body:e,...t,__security:{bearerAuth:!0}},this._client))}getCharacter(e,t){return this._client.get(F`/videos/characters/${e}`,{...t,__security:{bearerAuth:!0}})}remix(e,t,n){return this._client.post(F`/videos/${e}/remix`,$t({body:t,...n,__security:{bearerAuth:!0}},this._client))}}})),rc,ic,ac,oc,sc=e((()=>{s(),L(),P(),G(),oc=class extends N{constructor(){super(...arguments),rc.add(this)}async unwrap(e,t,n=this._client.webhookSecret,r=300){return await this.verifySignature(e,t,n,r),JSON.parse(e)}async verifySignature(e,t,n=this._client.webhookSecret,r=300){if(typeof crypto>`u`||typeof crypto.subtle.importKey!=`function`||typeof crypto.subtle.verify!=`function`)throw Error("Webhook signature verification is only supported when the `crypto` global is defined");o(this,rc,`m`,ic).call(this,n);let i=W([t]).values,a=o(this,rc,`m`,ac).call(this,i,`webhook-signature`),s=o(this,rc,`m`,ac).call(this,i,`webhook-timestamp`),c=o(this,rc,`m`,ac).call(this,i,`webhook-id`),l=parseInt(s,10);if(isNaN(l))throw new ce(`Invalid webhook timestamp format`);let u=Math.floor(Date.now()/1e3);if(u-l>r)throw new ce(`Webhook timestamp is too old`);if(l>u+r)throw new ce(`Webhook timestamp is too new`);let d=a.split(` `).map(e=>e.startsWith(`v1,`)?e.substring(3):e),f=n.startsWith(`whsec_`)?Buffer.from(n.replace(`whsec_`,``),`base64`):Buffer.from(n,`utf-8`),p=c?`${c}.${s}.${e}`:`${s}.${e}`,m=await crypto.subtle.importKey(`raw`,f,{name:`HMAC`,hash:`SHA-256`},!1,[`verify`]);for(let e of d)try{let t=Buffer.from(e,`base64`);if(await crypto.subtle.verify(`HMAC`,m,t,new TextEncoder().encode(p)))return}catch{continue}throw new ce(`The given webhook signature does not match the expected signature`)}},rc=new WeakSet,ic=function(e){if(typeof e!=`string`||e.length===0)throw Error(`The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function`)},ac=function(e,t){if(!e)throw Error(`Headers are required`);let n=e.get(t);if(n==null)throw Error(`Missing required header: ${t}`);return n}})),cc=e((()=>{sc()})),lc=e((()=>{cc()})),uc=e((()=>{Vr(),Hr(),Wi(),ea(),na(),io(),oo(),po(),_o(),yo(),To(),Do(),Uo(),qo(),Yo(),Zo(),$o(),as(),Ps(),Hs(),Ks(),ec(),nc(),lc()}));function dc(e){let t=hc.get(e);if(!t)throw Error(`Invalid provider. Providers must be created with createProvider().`);return t.configure()}var fc,pc,mc,hc,gc=e((()=>{fc=Symbol.for(`openai.node.providerDefinitions.v1`),pc=globalThis,mc=pc[fc],hc=mc??new WeakMap,mc||Object.defineProperty(pc,fc,{value:hc})}));function _c(e){if(vc(e))return`Connection error. This may be caused by passing an undici dispatcher, such as ProxyAgent, that is incompatible with the fetch implementation. If you are using undici's ProxyAgent, pass the fetch implementation from the same undici package: import { fetch, ProxyAgent } from 'undici'; new OpenAI({ fetch, fetchOptions: { dispatcher: new ProxyAgent(...) } });`}function vc(e){let t=e;for(let e=0;e<8&&t&&typeof t==`object`;e++){let e=t;if(e.code===`UND_ERR_INVALID_ARG`&&typeof e.message==`string`&&e.message.includes(`invalid onRequestStart method`))return!0;t=e.cause}return!1}var yc,bc,xc,Sc,Cc,$,wc=e((()=>{s(),l(),xe(),Ce(),f(),Pe(),Be(),He(),lt(),Te(),de(),A(),qt(),mn(),uc(),Bt(),na(),oo(),yo(),Do(),Yo(),Zo(),$o(),nc(),Wi(),ea(),io(),zr(),po(),_o(),To(),Uo(),qo(),as(),Ps(),Hs(),Ks(),ec(),sc(),G(),gc(),Aa(),Dt(),Cc=`workload-identity-auth`,$=class{constructor(e={}){yc.add(this),xc.set(this,void 0),this.completions=new ao(this),this.chat=new Rr(this),this.embeddings=new vo(this),this.files=new Eo(this),this.images=new Jo(this),this.audio=new $i(this),this.moderations=new Qo(this),this.models=new Xo(this),this.fineTuning=new Ho(this),this.graders=new Ko(this),this.vectorStores=new $s(this),this.webhooks=new oc(this),this.beta=new ro(this),this.batches=new ta(this),this.uploads=new Gs(this),this.admin=new Ui(this),this.responses=new Ns(this),this.realtime=new is(this),this.conversations=new go(this),this.evals=new wo(this),this.containers=new fo(this),this.skills=new Vs(this),this.videos=new tc(this);let t=e.provider;if(t){let t=[`apiKey`,`adminAPIKey`,`workloadIdentity`,`baseURL`].filter(t=>e[t]!=null);if(t.length)throw new p(`The \`provider\` option cannot be used with ${t.map(e=>`\`${e}\``).join(`, `)}. Configure authentication and the base URL through the provider instead.`)}let{baseURL:n=t?null:ka(`OPENAI_BASE_URL`),apiKey:r=t?null:ka(`OPENAI_API_KEY`)??null,adminAPIKey:i=t?null:ka(`OPENAI_ADMIN_KEY`)??null,organization:o=t?null:ka(`OPENAI_ORG_ID`)??null,project:s=t?null:ka(`OPENAI_PROJECT_ID`)??null,webhookSecret:c=ka(`OPENAI_WEBHOOK_SECRET`)??null,workloadIdentity:l,...u}=e,d=t?dc(t):void 0,f={apiKey:r,adminAPIKey:i,organization:o,project:s,webhookSecret:c,workloadIdentity:l,provider:t,...u,baseURL:d?.baseURL??(n||`https://api.openai.com/v1`)};if(r&&l)throw new p("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!d&&!r&&!i&&!l)throw new p("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!f.dangerouslyAllowBrowser&&Oe())throw new p(`It looks like you're running in a browser-like environment.
8
-
9
- This is disabled by default, as it risks exposing your secret API credentials to attackers.
10
- If you understand the risks and have appropriate mitigations in place,
11
- you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
12
-
13
- new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
14
-
15
- https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
16
- `);this.baseURL=f.baseURL,this.timeout=f.timeout??bc.DEFAULT_TIMEOUT,this.logger=f.logger??console;let m=`warn`;this.logLevel=m,this.logLevel=Ct(f.logLevel,`ClientOptions.logLevel`,this)??Ct(ka(`OPENAI_LOG`),`process.env['OPENAI_LOG']`,this)??m,this.fetchOptions=f.fetchOptions,this.maxRetries=f.maxRetries??2,this.fetch=f.fetch??Fe(),a(this,xc,Ve,`f`);let h=t?void 0:ka(`OPENAI_CUSTOM_HEADERS`);if(h){let e={};for(let t of h.split(`
17
- `)){let n=t.indexOf(`:`);n>=0&&(e[t.substring(0,n).trim()]=t.substring(n+1).trim())}f.defaultHeaders=W([e,f.defaultHeaders])}this._options=f,this._provider=d,l&&(this._workloadIdentityAuth=new Kt(l,this.fetch)),this.apiKey=typeof r==`string`?r:null,this.adminAPIKey=i,this.organization=o,this.project=s,this.webhookSecret=c}withOptions(e){let t=this._options.provider,n=e.provider??t,r={...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret};return n&&(delete r.apiKey,delete r.adminAPIKey,delete r.workloadIdentity,delete r.baseURL,n!==t&&(delete r.organization,delete r.project,delete r.defaultHeaders)),new this.constructor({...r,...e,provider:n})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t},n={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get(`authorization`)||e.get(`api-key`))&&!(t.has(`authorization`)||t.has(`api-key`))&&!(this._workloadIdentityAuth&&n.bearerAuth))throw Error(`Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted`)}async authHeaders(e,t={bearerAuth:!0,adminAPIKeyAuth:!0}){return W([t.bearerAuth?await this.bearerAuth(e):null,t.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return W([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return W([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return W([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return ct(e)}getUserAgent(){return`${this.constructor.name}/JS ${we}`}defaultIdempotencyKey(){return`stainless-node-retry-${c()}`}makeStatusError(e,t,n,r){return m.generate(e,t,n,r)}async _callApiKey(){if(this._provider)return!1;let e=this._options.apiKey;if(typeof e!=`function`)return!1;let t;try{t=await e()}catch(e){throw e instanceof p?e:new p(`Failed to get token from 'apiKey' function: ${e.message}`,{cause:e})}if(typeof t!=`string`||!t)throw new p(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,n){let r=!o(this,yc,`m`,Sc).call(this)&&n||this.baseURL,i=_e(e)?new URL(e):new URL(r+(r.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),a=this.defaultQuery(),s=Object.fromEntries(i.searchParams);return(!pe(a)||!pe(s))&&(t={...s,...a,...t}),typeof t==`object`&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}async prepareOptions(e){this._provider||(e.__security??{bearerAuth:!0}).bearerAuth&&await this._callApiKey()}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest(`get`,e,t)}post(e,t){return this.methodRequest(`post`,e,t)}patch(e,t){return this.methodRequest(`patch`,e,t)}put(e,t){return this.methodRequest(`put`,e,t)}delete(e,t){return this.methodRequest(`delete`,e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new zt(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let r=await e,i=r.maxRetries??this.maxRetries;t??(t=i),await this.prepareOptions(r);let{req:a,url:o,timeout:s}=await this.buildRequest(r,{retryCount:i-t});await this.prepareRequest(a,{url:o,options:r}),await this._provider?.prepareRequest?.(a,{url:o,options:r});let c=`log_`+(Math.random()*(1<<24)|0).toString(16).padStart(6,`0`),l=n===void 0?``:`, retryOf: ${n}`,f=Date.now();if(T(this).debug(`[${c}] sending request`,Et({retryOfRequestLogID:n,method:r.method,url:o,options:r,headers:a.headers})),r.signal?.aborted)throw new h;let p=r.__security??{bearerAuth:!0},m=new AbortController,_=await this.fetchWithAuth(o,a,s,m,p).catch(d),v=Date.now();if(_ instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new h;let i=u(_)||/timed? ?out/i.test(String(_)+(`cause`in _?String(_.cause):``));if(t)return T(this).info(`[${c}] connection ${i?`timed out`:`failed`} - ${e}`),T(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (${e})`,Et({retryOfRequestLogID:n,url:o,durationMs:v-f,message:_.message})),this.retryRequest(r,t,n??c);throw T(this).info(`[${c}] connection ${i?`timed out`:`failed`} - error; no more retries left`),T(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (error; no more retries left)`,Et({retryOfRequestLogID:n,url:o,durationMs:v-f,message:_.message})),_ instanceof le||_ instanceof ue?_:i?new ee:new g({message:_c(_),cause:_})}let y=`[${c}${l}${[..._.headers.entries()].filter(([e])=>e===`x-request-id`).map(([e,t])=>`, `+e+`: `+JSON.stringify(t)).join(``)}] ${a.method} ${o} ${_.ok?`succeeded`:`failed`} with status ${_.status} in ${v-f}ms`;if(!_.ok){if(_.status===401&&this._workloadIdentityAuth&&p.bearerAuth&&!r.__metadata?.hasStreamingBody&&!r.__metadata?.workloadIdentityTokenRefreshed)return await ze(_.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...r,__metadata:{...r.__metadata,workloadIdentityTokenRefreshed:!0}},t,n??c);let e=await this.shouldRetry(_);if(t&&e){let e=`retrying, ${t} attempts remaining`;return await ze(_.body),T(this).info(`${y} - ${e}`),T(this).debug(`[${c}] response error (${e})`,Et({retryOfRequestLogID:n,url:_.url,status:_.status,headers:_.headers,durationMs:v-f})),this.retryRequest(r,t,n??c,_.headers)}let i=e?`error; no more retries left`:`error; not retryable`;T(this).info(`${y} - ${i}`);let a=await _.text().catch(e=>d(e).message),o=be(a),s=o?void 0:a;throw T(this).debug(`[${c}] response error (${i})`,Et({retryOfRequestLogID:n,url:_.url,status:_.status,headers:_.headers,message:s,durationMs:Date.now()-f})),this.makeStatusError(_.status,o,s,_.headers)}return T(this).info(y),T(this).debug(`[${c}] response start`,Et({retryOfRequestLogID:n,url:_.url,status:_.status,headers:_.headers,durationMs:v-f})),{response:_,options:r,controller:m,requestLogID:c,retryOfRequestLogID:n,startTime:f}}getAPIList(e,t,n){return this.requestAPIList(t,n&&`then`in n?n.then(t=>({method:`get`,path:e,...t})):{method:`get`,path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new Ut(this,n,e)}async fetchWithAuth(e,t,n,r,i={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&i.bearerAuth){let e=t.headers,n=e.get(`Authorization`);if(!n||n===`Bearer ${Cc}`){let t=await this._workloadIdentityAuth.getToken();e.set(`Authorization`,`Bearer ${t}`)}}return await this.fetchWithTimeout(e,t,n,r)}async fetchWithTimeout(e,t,n,r){let{signal:i,method:a,...o}=t||{},s=this._makeAbort(r);i&&i.addEventListener(`abort`,s,{once:!0});let c=setTimeout(s,n),l=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body==`object`&&o.body!==null&&Symbol.asyncIterator in o.body,u={signal:r.signal,...l?{duplex:`half`}:{},method:`GET`,...o};a&&(u.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,u)}finally{clearTimeout(c)}}async shouldRetry(e){let t=e.headers.get(`x-should-retry`);return t===`true`?!0:t===`false`?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let i,a=r?.get(`retry-after-ms`);if(a){let e=parseFloat(a);Number.isNaN(e)||(i=e)}let o=r?.get(`retry-after`);if(o&&!i){let e=parseFloat(o);i=Number.isNaN(e)?Date.parse(o)-Date.now():e*1e3}if(i===void 0){let n=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,n)}return await Se(i),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e;return Math.min(.5*2**n,8)*(1-Math.random()*.25)*1e3}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:r,path:i,query:a,defaultBaseURL:o}=n,s=this.buildURL(i,a,o);`timeout`in n&&ye(`timeout`,n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:l,isStreamingBody:u}=this.buildBody({options:n});return u&&(e.__metadata={...e.__metadata,hasStreamingBody:!0}),{req:{method:r,headers:await this.buildHeaders({options:e,method:r,bodyHeaders:c,retryCount:t}),...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:`half`},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:s,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let i={};this.idempotencyHeader&&t!==`get`&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);let a=W([i,{Accept:`application/json`,"User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Ne(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},this._provider?void 0:await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,n,e.headers]);return this._provider||this.validateHeaders(a,e.__security??{bearerAuth:!0}),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:e}){let{body:t,headers:n}=e;if(!t)return t===void 0&&`body`in e?{...o(this,xc,`f`).call(this,{body:t,headers:W([n])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let r=W([n]),i=globalThis.ReadableStream!==void 0&&t instanceof globalThis.ReadableStream,a=!i&&(typeof t==`string`||t instanceof ArrayBuffer||ArrayBuffer.isView(t)||globalThis.Blob!==void 0&&t instanceof globalThis.Blob||t instanceof URLSearchParams||t instanceof FormData);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t==`string`&&r.values.has(`content-type`)||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||i?{bodyHeaders:void 0,body:t,isStreamingBody:!a}:typeof t==`object`&&(Symbol.asyncIterator in t||Symbol.iterator in t&&`next`in t&&typeof t.next==`function`)?{bodyHeaders:void 0,body:Le(t),isStreamingBody:!0}:typeof t==`object`&&r.values.get(`content-type`)===`application/x-www-form-urlencoded`?{bodyHeaders:{"content-type":`application/x-www-form-urlencoded`},body:this.stringifyQuery(t),isStreamingBody:!1}:{...o(this,xc,`f`).call(this,{body:t,headers:r}),isStreamingBody:!1}}},bc=$,xc=new WeakMap,yc=new WeakSet,Sc=function(){return this._provider!==void 0||this.baseURL!==`https://api.openai.com/v1`},$.OpenAI=bc,$.DEFAULT_TIMEOUT=6e5,$.OpenAIError=p,$.APIError=m,$.APIConnectionError=g,$.APIConnectionTimeoutError=ee,$.APIUserAbortError=h,$.NotFoundError=te,$.ConflictError=ne,$.RateLimitError=ie,$.BadRequestError=_,$.AuthenticationError=v,$.InternalServerError=ae,$.PermissionDeniedError=y,$.UnprocessableEntityError=re,$.InvalidWebhookSignatureError=ce,$.toFile=sn,$.Completions=ao,$.Chat=Rr,$.Embeddings=vo,$.Files=Eo,$.Images=Jo,$.Audio=$i,$.Moderations=Qo,$.Models=Xo,$.FineTuning=Ho,$.Graders=Ko,$.VectorStores=$s,$.Webhooks=oc,$.Beta=ro,$.Batches=ta,$.Uploads=Gs,$.Admin=Ui,$.Responses=Ns,$.Realtime=is,$.Conversations=go,$.Evals=wo,$.Containers=fo,$.Skills=Vs,$.Videos=tc})),Tc=e((()=>{L(),ja(),wc()})),Ec=e((()=>{L(),wc(),ja(),ms(),uc()})),Dc=e((()=>{wc(),mn(),Bt(),A(),de(),Tc(),Ec()}));function Oc(e){if(!e)return 0;let t=0,n=/(\d+(?:\.\d+)?)(ms|s|m|h|d)/g,r;for(;(r=n.exec(e))!==null;){let e=Number(r[1]);switch(r[2]){case`ms`:t+=e/1e3;break;case`s`:t+=e;break;case`m`:t+=e*60;break;case`h`:t+=e*3600;break;case`d`:t+=e*86400;break}}if(t===0){let n=Number(e);Number.isFinite(n)&&(t=n)}return t<=0?0:Math.floor(Date.now()/1e3)+t}function kc(e,t){if(e===null||t===null)return null;let n=Number(e),r=Number(t);if(!Number.isFinite(n)||!Number.isFinite(r)||r<=0)return null;let i=Math.max(0,r-n);return Math.min(1,Math.max(0,i/r))}var Ac,jc=e((()=>{Ac={providerId:`openai`,parseHeaders(e){let t=[],n=kc(e.get(`x-ratelimit-remaining-requests`),e.get(`x-ratelimit-limit-requests`));n!==null&&t.push({kind:`requests`,label:`RPM`,utilization:n,resetsAt:Oc(e.get(`x-ratelimit-reset-requests`))||void 0});let r=kc(e.get(`x-ratelimit-remaining-tokens`),e.get(`x-ratelimit-limit-tokens`));return r!==null&&t.push({kind:`tokens`,label:`TPM`,utilization:r,resetsAt:Oc(e.get(`x-ratelimit-reset-tokens`))||void 0}),t}}}));function Mc(e){return async(...t)=>{let n=await e(...t);try{r(`openai`,Ac.parseHeaders(n.headers))}catch{}return n}}function Nc(e){if(Fc)return Fc;let n=process.env.OPENAI_API_KEY||``,r=process.env.OPENAI_BASE_URL,i=Mc(e?.fetchOverride??globalThis.fetch),a=new $({apiKey:n,...r&&{baseURL:r},maxRetries:e?.maxRetries??0,timeout:parseInt(process.env.API_TIMEOUT_MS||`600000`,10),dangerouslyAllowBrowser:!0,...process.env.OPENAI_ORG_ID&&{organization:process.env.OPENAI_ORG_ID},...process.env.OPENAI_PROJECT_ID&&{project:process.env.OPENAI_PROJECT_ID},fetchOptions:t({forAnthropicAPI:!1}),fetch:i});return e?.fetchOverride||(Fc=a),a}function Pc(){Fc=null}var Fc,Ic=e((()=>{Dc(),jc(),i(),n(),Fc=null}));export{$ as a,Dc as i,Nc as n,wc as o,Ic as r,Pc as t};
@@ -1 +0,0 @@
1
- import{r as e,t}from"./client-B7WkO81L.js";e();export{t as clearOpenAIClientCache};
@@ -1 +0,0 @@
1
- import{Nr as e,Pr as t}from"./model-CeG-iOKF.js";t();export{e as getOrganizationUUID};
@@ -1 +0,0 @@
1
- import{Di as e,Li as t,Mi as n}from"./loadAgentsDir-CwEfQDOw.js";t();export{e as clearCommandsCache,n as getCommands};
@@ -1 +0,0 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{t}from"./jsx-runtime-Bb4Xn-E0.js";import{n,t as r}from"./Settings-D_i8HzEW.js";var i,a;e((()=>{n(),i=t(),a=async(e,t)=>(0,i.jsx)(r,{onClose:e,context:t,defaultTab:`Config`})}))();export{a as call};
@@ -1 +0,0 @@
1
- import{n as e,r as t,t as n}from"./context-noninteractive-kACWzgS1.js";t();export{n as call,e as collectContextData};
@@ -1 +0,0 @@
1
- import{n as e,t}from"./conversation-C8w1DtXk.js";e();export{t as clearConversation};
@@ -1 +0,0 @@
1
- import{a as e,i as t,n,r}from"./createSession-BJeDECzt.js";t();export{n as createBridgeSession,r as getBridgeSession,e as updateBridgeSessionTitle};
@@ -1 +0,0 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{t}from"./jsx-runtime-Bb4Xn-E0.js";import{n,t as r}from"./Doctor-CI04juFO.js";var i,a;e((()=>{n(),i=t(),a=(e,t,n)=>Promise.resolve((0,i.jsx)(r,{onDone:e}))}))();export{a as call};
@@ -1 +0,0 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{$d as t,St as n,Zd as r,bT as i,gc as a,hc as o,yT as s,yt as c}from"./loadAgentsDir-CwEfQDOw.js";import{t as l}from"./jsx-runtime-Bb4Xn-E0.js";import{n as u,t as d}from"./ExitFlow-qrCDVA9i.js";import{spawnSync as f}from"child_process";function p(){return i(g)??`Goodbye!`}async function m(e){if(a())return e(),f(`tmux`,[`detach-client`],{stdio:`ignore`}),null;let t=c()!==null;return t?(0,h.jsx)(d,{showWorktree:t,onDone:e,onCancel:()=>e()}):(e(p()),await r(0,`prompt_input_exit`),null)}var h,g;e((()=>{s(),u(),o(),t(),n(),h=l(),g=[`Goodbye!`,`See ya!`,`Bye!`,`Catch you later!`]}))();export{m as call};
@@ -1 +0,0 @@
1
- import{n as e,o as t}from"./rolldown-runtime-DaDcL9Zw.js";import{Dp as n,Op as r,Qu as i,Xh as a,Zh as o,Zu as s,hC as c}from"./loadAgentsDir-CwEfQDOw.js";import{D as l,Gt as u,I as d,P as f,T as p,ai as m,t as h,x as g}from"./src-DL3w8VPk2.js";import{t as _}from"./jsx-runtime-Bb4Xn-E0.js";import{Bt as v,G as y,Gn as b,Gt as x,Kn as S,_ as C,et as w,nt as T,rt as E,tt as D,x as O}from"./model-CeG-iOKF.js";import{n as k,t as A}from"./useExitOnCtrlCDWithKeybindings-D48aDPG9.js";import{n as j,t as M}from"./modelOptions-A5jrCUBp.js";function N({initial:e,sessionModel:t,onSelect:r,onCancel:a,isStandaloneCommand:s,showFastModeNotice:c,headerText:m}){let h=k(),_=e===null?I:e,[v,x]=(0,P.useState)(_),S=o(e=>E()?e.fastMode:!1),[C,w]=(0,P.useState)(()=>new Set(b(_)?[_.replace(/\[1m\]/i,``)]:[])),A=(0,P.useCallback)(()=>{if(!v||v===I)return;let e=v.replace(/\[1m\]/i,``);w(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[v]),j=(0,P.useMemo)(()=>M(S??!1),[S]),N=(0,P.useMemo)(()=>e!==null&&!j.some(t=>t.value===e)?[...j,{value:e,label:O(e),description:`Current model`}]:j,[j,e]),L=(0,P.useMemo)(()=>N.map(e=>({...e,value:e.value===null?I:e.value})),[N]),R=(0,P.useMemo)(()=>L.some(e=>e.value===_)?_:L[0]?.value??void 0,[L,_]),z=Math.min(10,L.length),B=Math.max(0,L.length-z),V=L.find(e=>e.value===v)?.label,H=v!==void 0&&v!==I&&C.has(v.replace(/\[1m\]/i,``)),U=(0,P.useCallback)(e=>{x(e)},[]);u({"modelPicker:toggle1M":()=>A()},{context:`ModelPicker`});function W(e){if(e===I){r(null);return}let t=e.replace(/\[1m\]/i,``);r(C.has(t)?`${t}[1m]`:t)}let G=(0,F.jsxs)(d,{flexDirection:`column`,children:[(0,F.jsxs)(d,{flexDirection:`column`,children:[(0,F.jsxs)(d,{marginBottom:1,flexDirection:`column`,children:[(0,F.jsx)(f,{color:`remember`,bold:!0,children:`Select model`}),(0,F.jsx)(f,{dimColor:!0,children:m??`Choose a model for this and future sessions. Use Space to toggle 1M context.`}),t&&(0,F.jsxs)(f,{dimColor:!0,children:[`Currently using `,O(t),` for this session (set by plan mode). Selecting a model will undo this.`]})]}),(0,F.jsxs)(d,{flexDirection:`column`,marginBottom:1,children:[(0,F.jsx)(d,{flexDirection:`column`,children:(0,F.jsx)(i,{defaultValue:_,defaultFocusValue:R,options:L,onChange:W,onFocus:U,onCancel:a??(()=>{}),visibleOptionCount:z})}),B>0&&(0,F.jsx)(d,{paddingLeft:3,children:(0,F.jsxs)(f,{dimColor:!0,children:[`and `,B,` more…`]})})]}),(0,F.jsx)(d,{marginBottom:1,flexDirection:`column`,children:H?(0,F.jsxs)(f,{dimColor:!0,children:[`1M context on`,(0,F.jsx)(f,{color:`subtle`,children:` · Space to toggle`})]}):(0,F.jsxs)(f,{color:`subtle`,children:[`1M context off`,V?` for ${V}`:``,(0,F.jsx)(f,{color:`subtle`,children:` · Space to toggle`})]})}),E()?c?(0,F.jsx)(d,{marginBottom:1,children:(0,F.jsxs)(f,{dimColor:!0,children:[`Fast mode is `,(0,F.jsx)(f,{bold:!0,children:`ON`}),` and available with `,y,` only (/fast). Switching to other models turn off fast mode.`]})}):D()&&!T()?(0,F.jsx)(d,{marginBottom:1,children:(0,F.jsxs)(f,{dimColor:!0,children:[`Use `,(0,F.jsx)(f,{bold:!0,children:`/fast`}),` to turn on Fast mode (`,y,` only).`]})}):null:null]}),s&&(0,F.jsx)(f,{dimColor:!0,italic:!0,children:h.pending?(0,F.jsxs)(F.Fragment,{children:[`Press `,h.keyName,` again to exit`]}):(0,F.jsxs)(p,{children:[(0,F.jsx)(l,{shortcut:`Enter`,action:`confirm`}),(0,F.jsx)(n,{action:`select:cancel`,context:`Select`,fallback:`Esc`,description:`exit`})]})})]});return s?(0,F.jsx)(g,{color:`permission`,children:G}):G}var P,F,I,L=e((()=>{P=t(m(),1),S(),A(),w(),h(),c(),a(),C(),j(),r(),s(),F=_(),I=`__NO_PREFERENCE__`}));function R(e,t,n){if(!x())return!1;if(t)return!0;if(e===null||!b(e))return!1;let r=e.toLowerCase().replace(/\[1m\]$/,``).trim(),i=r===`opus`||r.includes(`opus-4-6`)||r.includes(`opus-4-7`),a=r===`sonnet`||r.includes(`sonnet-4-6`);return i&&n?!1:i||a}var z=e((()=>{v(),S()}));export{L as i,R as n,N as r,z as t};
@@ -1 +0,0 @@
1
- import{Ac as e,Oc as t,jc as n,kc as r}from"./loadAgentsDir-CwEfQDOw.js";n();export{t as drainPendingExtraction,r as executeExtractMemories,e as initExtractMemories};
@@ -1 +0,0 @@
1
- import{n as e,o as t}from"./rolldown-runtime-DaDcL9Zw.js";import{$h as n,Xh as r,Zh as i,hC as a}from"./loadAgentsDir-CwEfQDOw.js";import{Gt as o,I as s,Lt as c,P as l,ai as u,di as d,fi as f,j as p,t as m,y as h}from"./src-DL3w8VPk2.js";import{t as g}from"./jsx-runtime-Bb4Xn-E0.js";import{Wt as _,g as v,x as y}from"./settings-CvhsRFaT.js";import{c as b,h as x}from"./config-BSkuQZNf.js";import{n as S,r as C}from"./analytics-DJobLaWP.js";import{l as w,v as T}from"./startupProfiler-2sjXZkIP.js";import{G as E,H as D,J as O,K as k,U as A,W as j,X as M,et as N,it as P,lt as F,q as I,rt as L}from"./model-CeG-iOKF.js";import{n as R,t as z}from"./systemTheme-Ceakddth.js";function B({cooldown:e}){return e?(0,H.jsx)(l,{color:`promptBorder`,dimColor:!0,children:`↯`}):(0,H.jsx)(l,{color:`fastMode`,children:`↯`})}function V(e=!0,t=!1){if(!e)return`↯`;let n=R(b().theme);return t?d.dim(p(`promptBorder`,n)(`↯`)):p(`fastMode`,n)(`↯`)}var H,U=e((()=>{f(),_(),m(),x(),z(),H=g()}));function W(e,t){k(),y(`userSettings`,{fastMode:e?!0:void 0}),t(e?e=>{let t=!P(e.mainLoopModel);return{...e,...t?{mainLoopModel:I(),mainLoopModelForSession:null}:{},fastMode:!0}}:e=>({...e,fastMode:!1}))}function G({onDone:e,unavailableReason:t}){let r=i(e=>e.mainLoopModel),a=i(e=>e.fastMode),u=n(),[d,f]=(0,J.useState)(a??!1),p=O(),m=p.status===`cooldown`,g=t!==null,_=D(A(!0));function v(){g||(W(d,u),C(`tengu_fast_mode_toggled`,{enabled:d,source:`picker`}),d?e(`${V(d)} Fast mode ON${P(r)?``:` · model set to ${E}`} · ${_}`):(u(e=>({...e,fastMode:!1})),e(`Fast mode OFF`)))}function y(){if(g){a&&W(!1,u),e(`Fast mode OFF`,{display:`system`});return}e(a?`${V()} Kept Fast mode ON`:`Kept Fast mode OFF`,{display:`system`})}function b(){g||f(e=>!e)}return o({"confirm:yes":v,"confirm:nextField":b,"confirm:next":b,"confirm:previous":b,"confirm:cycleMode":b,"confirm:toggle":b},{context:`Confirmation`}),(0,Y.jsxs)(h,{title:(0,Y.jsxs)(l,{children:[(0,Y.jsx)(B,{cooldown:m}),` Fast mode (research preview)`]}),subtitle:`High-speed mode for ${E}. Billed as extra usage at a premium rate. Separate rate limits apply.`,onCancel:y,color:`fastMode`,inputGuide:e=>e.pending?(0,Y.jsxs)(l,{children:[`Press `,e.keyName,` again to exit`]}):g?(0,Y.jsx)(l,{children:`Esc to cancel`}):(0,Y.jsx)(l,{children:`Tab to toggle · Enter to confirm · Esc to cancel`}),children:[t?(0,Y.jsx)(s,{marginLeft:2,children:(0,Y.jsx)(l,{color:`error`,children:t})}):(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(s,{flexDirection:`column`,gap:0,marginLeft:2,children:(0,Y.jsxs)(s,{flexDirection:`row`,gap:2,children:[(0,Y.jsx)(l,{bold:!0,children:`Fast mode`}),(0,Y.jsx)(l,{color:d?`fastMode`:void 0,bold:d,children:d?`ON `:`OFF`}),(0,Y.jsx)(l,{dimColor:!0,children:_})]})}),m&&p.status===`cooldown`&&(0,Y.jsx)(s,{marginLeft:2,children:(0,Y.jsxs)(l,{color:`warning`,children:[p.reason===`overloaded`?`Fast mode overloaded and is temporarily unavailable`:`You've hit your fast limit`,` · resets in `,w(p.resetAt-Date.now(),{hideTrailingZeros:!0})]})})]}),(0,Y.jsxs)(l,{dimColor:!0,children:[`Learn more:`,` `,(0,Y.jsx)(c,{url:`https://code.workmate.com/docs/en/fast-mode`,children:`https://code.workmate.com/docs/en/fast-mode`})]})]})}async function K(e,t,n){let r=M();if(r)return`Fast mode unavailable: ${r}`;let{mainLoopModel:i}=t();return W(e,n),C(`tengu_fast_mode_toggled`,{enabled:e,source:`shortcut`}),e?`${V(!0)} Fast mode ON${P(i)?``:` · model set to ${E}`} · ${D(A(!0))}`:`Fast mode OFF`}async function q(e,t,n){if(!L())return null;await F();let r=n?.trim().toLowerCase();if(r===`on`||r===`off`)return e(await K(r===`on`,t.getAppState,t.setAppState)),null;let i=M();return C(`tengu_fast_mode_picker_shown`,{unavailable_reason:i??``}),(0,Y.jsx)(G,{onDone:e,unavailableReason:i})}var J,Y,X=e((()=>{J=t(u(),1),m(),U(),a(),S(),r(),N(),T(),j(),v(),Y=g()}));export{U as a,V as i,q as n,X as r,G as t};
@@ -1 +0,0 @@
1
- import{n as e,r as t,t as n}from"./fast-BGU8p2uY.js";t();export{n as FastModePicker,e as call};
@@ -1 +0,0 @@
1
- import{n as e,r as t}from"./firstPartyEventLogger-7pAyUdbp.js";e();export{t as initialize1PEventLogging};
@@ -1 +0,0 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{Ka as t,La as n,Ny as r,Wa as i,Xw as a,Zw as o,it as s,ky as c,pa as l,tt as u}from"./loadAgentsDir-CwEfQDOw.js";import{c as d,i as f}from"./debug-BQj6h99Q.js";import{V as p,W as m}from"./model-CeG-iOKF.js";import{E as h,O as g,T as _,Y as v,j as y,k as b}from"./sessionState-zhvcDpb2.js";import{n as x,t as S}from"./openaiShared-G2-w4gJt.js";import{randomUUID as C}from"crypto";async function*w(e,n,r,o,u){try{let l=v(u.model),f=t(e,r),m=(await Promise.all(r.map(e=>s(e,{getToolPermissionContext:u.getToolPermissionContext,tools:r,agents:u.agents,allowedAgentTypes:u.allowedAgentTypes,model:u.model})))).filter(e=>{let t=e;return t.type!==`advisor_20260301`&&t.type!==`computer_20250124`}),_=y(f,n),S=b(m),w=g(u.toolChoice),T=a({maxRetries:0,fetchOverride:u.fetchOverride,source:u.querySource});d(`[Grok] Calling model=${l}, messages=${_.length}, tools=${S.length}`);let E=h(await T.chat.completions.create({model:l,messages:_,...S.length>0&&{tools:S,...w&&{tool_choice:w}},stream:!0,stream_options:{include_usage:!0},...u.temperatureOverride!==void 0&&{temperature:u.temperatureOverride}},{signal:o}),l),D={},O=null,k={input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0},A=0,j=Date.now();for await(let e of E){switch(e.type){case`message_start`:O=e.message,A=Date.now()-j,e.message.usage&&(k=x(k,e.message.usage));break;case`content_block_start`:{let t=e.index,n=e.content_block;n.type===`tool_use`?D[t]={...n,input:``}:n.type===`text`?D[t]={...n,text:``}:n.type===`thinking`?D[t]={...n,thinking:``,signature:``}:D[t]={...n};break}case`content_block_delta`:{let t=e.index,n=e.delta,r=D[t];if(!r)break;n.type===`text_delta`?r.text=(r.text||``)+n.text:n.type===`input_json_delta`?r.input=(r.input||``)+n.partial_json:n.type===`thinking_delta`?r.thinking=(r.thinking||``)+n.thinking:n.type===`signature_delta`&&(r.signature=n.signature);break}case`content_block_stop`:{let t=D[e.index];if(!t||!O)break;yield{message:{...O,content:i([t],r,u.agentId)},requestId:void 0,type:`assistant`,uuid:C(),timestamp:new Date().toISOString()};break}case`message_delta`:{let t=e.usage;t&&(k=x(k,t));break}case`message_stop`:break}e.type===`message_stop`&&k.input_tokens+k.output_tokens>0&&c(p(l,k),k,u.model),yield{type:`stream_event`,event:e,...e.type===`message_start`?{ttftMs:A}:void 0}}}catch(e){let t=e instanceof Error?e.message:String(e);d(`[Grok] Error: ${t}`,{level:`error`}),yield l({content:`API Error: ${t}`,apiError:`api_error`,error:e instanceof Error?e:Error(String(e))})}}e((()=>{o(),S(),_(),n(),u(),f(),r(),m()}))();export{w as queryModelGrok};