@readmagic/workmate 0.0.14 → 0.0.16

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 (312) hide show
  1. package/dist/chunks/AddWorkspaceDirectory-DAtfMH4o.js +1 -0
  2. package/dist/chunks/{AgentsMdExternalIncludesDialog-D58Vn3SK.js → AgentsMdExternalIncludesDialog-BTYgjY5c.js} +1 -1
  3. package/dist/chunks/AgentsMdExternalIncludesDialog-C6VH6JG6.js +1 -0
  4. package/dist/chunks/{App-CeC-2dzL.js → App-HF0bvxi_.js} +1 -1
  5. package/dist/chunks/ApproveApiKey-B7mKgSqY.js +1 -0
  6. package/dist/chunks/{ApproveApiKey-DFpddLyp.js → ApproveApiKey-BBFLw2B7.js} +1 -1
  7. package/dist/chunks/{BackgroundTasksDialog-9ruzl1jm.js → BackgroundTasksDialog-Coc0ecUd.js} +1 -1
  8. package/dist/chunks/BypassPermissionsModeDialog--Gx9ARd4.js +1 -0
  9. package/dist/chunks/{DiffDialog-LTdtTqsC.js → DiffDialog-tlINuFS1.js} +1 -1
  10. package/dist/chunks/Doctor-BJf49FWX.js +1 -0
  11. package/dist/chunks/{Doctor-Yvrzcrvx.js → Doctor-Wh7z6CnF.js} +2 -2
  12. package/dist/chunks/ExitFlow-B1zHTqQt.js +2 -0
  13. package/dist/chunks/Grove-1Kf7xxIV.js +11 -0
  14. package/dist/chunks/{HybridTransport-CEWG9ZRi.js → HybridTransport-DWqWUZCH.js} +1 -1
  15. package/dist/chunks/{InvalidConfigDialog-Ue3kJUPJ.js → InvalidConfigDialog-OZPFQSnC.js} +1 -1
  16. package/dist/chunks/{InvalidSettingsDialog-BO2AOTVf.js → InvalidSettingsDialog-BNCm-eyC.js} +1 -1
  17. package/dist/chunks/MCPConnectionManager-7H84oi5n.js +1 -0
  18. package/dist/chunks/MCPToolListView-CVgtg3Iq.js +1 -0
  19. package/dist/chunks/{McpParsingWarnings-BsCDFWci.js → McpParsingWarnings-CN8f449l.js} +1 -1
  20. package/dist/chunks/{MessageSelector-DY5K0NHd.js → MessageSelector-B9j6zZ5w.js} +1 -1
  21. package/dist/chunks/Messages-yz1m39eI.js +10 -0
  22. package/dist/chunks/{Onboarding-w0-VVsDz.js → Onboarding-bFbgae8m.js} +1 -1
  23. package/dist/chunks/{PromptInputFooterSuggestions-OEXx0Abp.js → PromptInputFooterSuggestions-CE_yVun1.js} +1 -1
  24. package/dist/chunks/PromptInputHelpMenu-TPWuGwAy.js +1 -0
  25. package/dist/chunks/QueryEngine-CRobcENE.js +1 -0
  26. package/dist/chunks/REPL-BhCC0JP6.js +1 -0
  27. package/dist/chunks/REPL-C33mMf_q.js +128 -0
  28. package/dist/chunks/RemoteSessionManager-BjVD918g.js +2 -0
  29. package/dist/chunks/{ResumeConversation-BbNrpSFB.js → ResumeConversation-CXd8d8po.js} +1 -1
  30. package/dist/chunks/{SSETransport-CLiI2qnD.js → SSETransport-BSilVN9e.js} +1 -1
  31. package/dist/chunks/SearchExtraToolsTool-DoiCI2uJ.js +1 -0
  32. package/dist/chunks/Settings-ClcLl0C1.js +2 -0
  33. package/dist/chunks/{TeleportProgress-IB--CbqZ.js → TeleportProgress-DonJUoPc.js} +1 -1
  34. package/dist/chunks/{TeleportRepoMismatchDialog-KjdlS_gA.js → TeleportRepoMismatchDialog-ByOuSVVz.js} +1 -1
  35. package/dist/chunks/TeleportResumeWrapper-BBtELwF1.js +1 -0
  36. package/dist/chunks/{ThemePicker-BrD_T7xF.js → ThemePicker-1QQJFOEv.js} +1 -1
  37. package/dist/chunks/{TrustDialog-L0rvvpit.js → TrustDialog-DwJ9L_u4.js} +1 -1
  38. package/dist/chunks/{ValidationErrorsList-QZvtUrAy.js → ValidationErrorsList-Cuq6W2yc.js} +1 -1
  39. package/dist/chunks/{add-dir-CpWXReCi.js → add-dir-DOKdPFT2.js} +1 -1
  40. package/dist/chunks/{agentDisplay-CrQvGkTT.js → agentDisplay-TX1bh-lX.js} +1 -1
  41. package/dist/chunks/{agents-C99yMsVF.js → agents-C58tRxpi.js} +1 -1
  42. package/dist/chunks/agents-CbRjX9Pj.js +101 -0
  43. package/dist/chunks/{allErrors-uyOMiF9U.js → allErrors-DRiW7i6Y.js} +1 -1
  44. package/dist/chunks/api-C8uOHD-v.js +1 -0
  45. package/dist/chunks/{api-C5I2xwgd.js → api-CazVavfB.js} +1 -1
  46. package/dist/chunks/auth-BL238vgr.js +1 -0
  47. package/dist/chunks/auth-CfrCl9BZ.js +10 -0
  48. package/dist/chunks/auth-D3GkU6d7.js +1 -0
  49. package/dist/chunks/{backgroundHousekeeping-CjD8bACB.js → backgroundHousekeeping-CPLlaWcV.js} +2 -2
  50. package/dist/chunks/backgroundHousekeeping-Du2tN2WE.js +1 -0
  51. package/dist/chunks/{branch-BOWBZo5K.js → branch-pAa0oBaj.js} +1 -1
  52. package/dist/chunks/{bridgeConfig-CgAVrQfz.js → bridgeConfig-DnFfCpGd.js} +1 -1
  53. package/dist/chunks/bridgeConfig-joBqeK0j.js +1 -0
  54. package/dist/chunks/{bridgeMessaging-cOFtbkf_.js → bridgeMessaging-B_hnuUHb.js} +1 -1
  55. package/dist/chunks/bridgeStatusUtil-Dwz4YHNA.js +1 -0
  56. package/dist/chunks/{btw-B0UmiVKl.js → btw-CkVkYeRr.js} +1 -1
  57. package/dist/chunks/{caches-wN3JyvNE.js → caches-BLQUkrIG.js} +1 -1
  58. package/dist/chunks/caches-DsFl83sh.js +1 -0
  59. package/dist/chunks/{ccrClient-wtUIz75R.js → ccrClient-AfdUbWzY.js} +1 -1
  60. package/dist/chunks/claudeDesktop-CB3UCt7U.js +1 -0
  61. package/dist/chunks/{clear-CNzBoL7O.js → clear-Ac3qYi_-.js} +1 -1
  62. package/dist/chunks/client-BX0r6K3I.js +1 -0
  63. package/dist/chunks/client-Bb2eZnuq.js +1 -0
  64. package/dist/chunks/client-DNEVh6Wu.js +1 -0
  65. package/dist/chunks/client-Pap_HyZZ.js +1 -0
  66. package/dist/chunks/client-zhozU2ws.js +1 -0
  67. package/dist/chunks/commands-BKLsl6gK.js +1 -0
  68. package/dist/chunks/{compact-Bj8mdDYN.js → compact-CXuDr5qM.js} +1 -1
  69. package/dist/chunks/{config-BkbL2e5Q.js → config-BSkuQZNf.js} +1 -1
  70. package/dist/chunks/{config-WMxn2jLl.js → config-D78R57VA.js} +1 -1
  71. package/dist/chunks/config-DrY1SvhQ.js +1 -0
  72. package/dist/chunks/{context-DB1Ar85E.js → context-C2plOqH4.js} +1 -1
  73. package/dist/chunks/context-noninteractive-DpVlZ-wP.js +1 -0
  74. package/dist/chunks/{context-noninteractive-CqnJTDcI.js → context-noninteractive-fVQtwEkw.js} +1 -1
  75. package/dist/chunks/conversation-C0yysXds.js +1 -0
  76. package/dist/chunks/{conversation-DOgBzrm0.js → conversation-DQpS6nvg.js} +1 -1
  77. package/dist/chunks/{createSSHSession-Cf2tOgK_.js → createSSHSession-CfyFuJMH.js} +1 -1
  78. package/dist/chunks/createSession-CmBawnsh.js +1 -0
  79. package/dist/chunks/{createSession-DD5YaQKM.js → createSession-qk9C66lK.js} +1 -1
  80. package/dist/chunks/{crossProjectResume-CkiPQYYE.js → crossProjectResume-DY1ZBO5P.js} +1 -1
  81. package/dist/chunks/{datadog-DcLf1QpG.js → datadog-Cr0VKbct.js} +1 -1
  82. package/dist/chunks/{diff-dfXWiuLA.js → diff-BNjcCXDr.js} +1 -1
  83. package/dist/chunks/{directoryCompletion-BtlRKLzw.js → directoryCompletion-i2oWpaUe.js} +1 -1
  84. package/dist/chunks/doctor-BkCtT7H1.js +1 -0
  85. package/dist/chunks/{entry-wISucmYc.js → entry-o9IZPS4g.js} +3 -3
  86. package/dist/chunks/{esm-CrJVXrKW.js → esm-BI3tFLyy.js} +1 -1
  87. package/dist/chunks/exit-Dlyj7nY8.js +1 -0
  88. package/dist/chunks/extraUsage-5Ueiyw6W.js +1 -0
  89. package/dist/chunks/extractMemories-DnTBWFOW.js +1 -0
  90. package/dist/chunks/fast-B3fRp1xO.js +1 -0
  91. package/dist/chunks/fast-ClOKONyD.js +1 -0
  92. package/dist/chunks/fetchModelList-B8KG79EK.js +1 -0
  93. package/dist/chunks/fetchModelList-gh_jFYai.js +1 -0
  94. package/dist/chunks/{fileSuggestions-Dy2BUZzd.js → fileSuggestions-DK7W8kLF.js} +1 -1
  95. package/dist/chunks/{firstPartyEventLogger-D4yuDP-n.js → firstPartyEventLogger-BMnXb9cv.js} +2 -2
  96. package/dist/chunks/firstPartyEventLogger-YYOb8aIo.js +1 -0
  97. package/dist/chunks/{flushGate-B6ecrC4j.js → flushGate-n4kK6H1U.js} +1 -1
  98. package/dist/chunks/{gemini-BC-BxZmj.js → gemini-C8-QHnsC.js} +1 -1
  99. package/dist/chunks/{generateSessionName-JTR8nPYD.js → generateSessionName-C8DnAVaa.js} +1 -1
  100. package/dist/chunks/{githubRepoPathMapping-Bk4FZrng.js → githubRepoPathMapping-Px3_GeD1.js} +1 -1
  101. package/dist/chunks/{goal-B09SOyra.js → goal-DMmzlZOF.js} +1 -1
  102. package/dist/chunks/grok-LLjpAwP_.js +1 -0
  103. package/dist/chunks/{grove-DsAIY-rZ.js → grove-CQBCzeHf.js} +1 -1
  104. package/dist/chunks/help-JH7WzjZP.js +1 -0
  105. package/dist/chunks/hooks-COhKt_pF.js +1 -0
  106. package/dist/chunks/{hooks-BI4NY5IC.js → hooks-DD2jpRfx.js} +7 -7
  107. package/dist/chunks/initReplBridge-BDaN0hpY.js +1 -0
  108. package/dist/chunks/install-CD4or0vj.js +1 -0
  109. package/dist/chunks/{instrumentation-5cSwEKaF.js → instrumentation-n-otwpYf.js} +4 -4
  110. package/dist/chunks/{job-rW1mEYtm.js → job-B-pEWgXI.js} +1 -1
  111. package/dist/chunks/keybindings-qed9q9tx.js +1 -0
  112. package/dist/chunks/{launchLocalMemory-CPucX8Xj.js → launchLocalMemory-cBovdGMT.js} +1 -1
  113. package/dist/chunks/{launchOnboarding--GCJWeeS.js → launchOnboarding-B__wtt7p.js} +1 -1
  114. package/dist/chunks/{loadAgentsDir-JrGMJN05.js → loadAgentsDir-PPiD2Mfq.js} +574 -574
  115. package/dist/chunks/loadAgentsDir-qvqrTVuS.js +1 -0
  116. package/dist/chunks/{loadPluginHooks-C4zrlV0u.js → loadPluginHooks-DUCuU3_8.js} +1 -1
  117. package/dist/chunks/localSearch-CDk_stXJ.js +1 -0
  118. package/dist/chunks/{localSearch-C-stDP9C.js → localSearch-Cvs9WfoX.js} +1 -1
  119. package/dist/chunks/{logoV2Utils-J2Sqfube.js → logoV2Utils-Bkj74dtY.js} +1 -1
  120. package/dist/chunks/{magicDocs-Dpe3YhyL.js → magicDocs-3U6peChg.js} +2 -2
  121. package/dist/chunks/main-DkjxhBIC.js +356 -0
  122. package/dist/chunks/{managedEnv-C8SisyLk.js → managedEnv-BUrzwaD3.js} +1 -1
  123. package/dist/chunks/managedEnv-XOUMOtEF.js +1 -0
  124. package/dist/chunks/{mappers-CMJorgSL.js → mappers-ZGgwqDOK.js} +1 -1
  125. package/dist/chunks/mcp-COZxwgJZ.js +6 -0
  126. package/dist/chunks/{mcp-SuAh71Ht.js → mcp-CdyNeNzh.js} +1 -1
  127. package/dist/chunks/{mcp-_tBxhPV-.js → mcp-CysOyBIn.js} +1 -1
  128. package/dist/chunks/{memory-DK8bOrUr.js → memory-B5h2TTSS.js} +1 -1
  129. package/dist/chunks/{mode-BhfhEpnW.js → mode-D3yY1fdK.js} +1 -1
  130. package/dist/chunks/model-Bz4JHoU0.js +1 -0
  131. package/dist/chunks/model-g6XBcNAG.js +1 -0
  132. package/dist/chunks/model-sviY1inu.js +1 -0
  133. package/dist/chunks/modelOptions-DYQqTLPi.js +1 -0
  134. package/dist/chunks/{nativeInstaller-xxyUjXbl.js → nativeInstaller-N1xiUpCP.js} +1 -1
  135. package/dist/chunks/{omit-od_CYp5o.js → omit-BOILu8jW.js} +1 -1
  136. package/dist/chunks/{onChangeAppState-CqTb0yEa.js → onChangeAppState-COFFZAXb.js} +1 -1
  137. package/dist/chunks/{openai-qW8mATAs.js → openai-BHM5kEFo.js} +2 -2
  138. package/dist/chunks/openai-CR3CcjCE.js +17 -0
  139. package/dist/chunks/{partition-CYoWXLNU.js → partition-C1SFDk_L.js} +1 -1
  140. package/dist/chunks/{permissions--iKUbWBw.js → permissions-uy_NFbfy.js} +3 -3
  141. package/dist/chunks/{pidLock-BR4hzYgp.js → pidLock-DuMVSwnN.js} +2 -2
  142. package/dist/chunks/{plan-DiHCGXhM.js → plan-DF9YSB5M.js} +1 -1
  143. package/dist/chunks/{plugin-BeC4D7XF.js → plugin-GRPzqgTr.js} +1 -1
  144. package/dist/chunks/{pluginAutoupdate-Bj-CrFuO.js → pluginAutoupdate-AMD-FvKB.js} +1 -1
  145. package/dist/chunks/{pluginBlocklist-DzOs-RS1.js → pluginBlocklist-DNxkAxH6.js} +1 -1
  146. package/dist/chunks/{pluginCliCommands-DwIGn58t.js → pluginCliCommands-BFoR1ZXx.js} +1 -1
  147. package/dist/chunks/{pluginFlagging-BzuymJuf.js → pluginFlagging-CW2IZWSI.js} +1 -1
  148. package/dist/chunks/{pluginOperations-CP1v-nu0.js → pluginOperations-DlWE0idP.js} +1 -1
  149. package/dist/chunks/{pluginStartupCheck-BUeBiYVq.js → pluginStartupCheck-AQGV0DCS.js} +1 -1
  150. package/dist/chunks/pluginStartupCheck-DWpquqxx.js +1 -0
  151. package/dist/chunks/{plugins-D1N31THW.js → plugins-CwUSTE4E.js} +1 -1
  152. package/dist/chunks/poorMode-DD88nPJ4.js +1 -0
  153. package/dist/chunks/{poorMode-D4L_-yWS.js → poorMode-wm2WkPF0.js} +1 -1
  154. package/dist/chunks/print-9wR_ijrL.js +14 -0
  155. package/dist/chunks/{processBashCommand-BGCIqxc9.js → processBashCommand-Deqwq1IE.js} +1 -1
  156. package/dist/chunks/{processSlashCommand-qR_j1DE8.js → processSlashCommand-U9LJ4Keq.js} +2 -2
  157. package/dist/chunks/prompt-BBeDQXIs.js +1 -0
  158. package/dist/chunks/{prompt-DnPppVz8.js → prompt-CQmEvnKN.js} +1 -1
  159. package/dist/chunks/prompt-CXhdqgB7.js +1 -0
  160. package/dist/chunks/{promptEditor-Cilc9N3L.js → promptEditor-Bf72KNF-.js} +1 -1
  161. package/dist/chunks/{protocolHandler-DdbiucQa.js → protocolHandler--eQQuSyx.js} +1 -1
  162. package/dist/chunks/{reconciler-Bte4gdP-.js → reconciler-Css9bs07.js} +1 -1
  163. package/dist/chunks/{refresh-MiZ0acBm.js → refresh-B87z39Zs.js} +1 -1
  164. package/dist/chunks/{registerProtocol-Bpte9dly.js → registerProtocol-DrWIX3Lb.js} +1 -1
  165. package/dist/chunks/{reload-plugins-GdqFZblC.js → reload-plugins-BpmUIkfm.js} +1 -1
  166. package/dist/chunks/{remoteBridgeCore-CAl3_H-O.js → remoteBridgeCore-BCLIIygk.js} +1 -1
  167. package/dist/chunks/{remoteManagedSettings-BcLJLEr7.js → remoteManagedSettings-Ahgn2e80.js} +1 -1
  168. package/dist/chunks/{rename-BDo5qIK0.js → rename-BUt3PliQ.js} +1 -1
  169. package/dist/chunks/{resume-Bbweh2hA.js → resume-uZI9p_FE.js} +1 -1
  170. package/dist/chunks/ripgrep-Di-2j8Ws.js +1 -0
  171. package/dist/chunks/{ripgrep-X5m4gJ-3.js → ripgrep-DsLUmulz.js} +1 -1
  172. package/dist/chunks/{runtimeObserver-CxXxUcrm.js → runtimeObserver-AKOWfdZ_.js} +1 -1
  173. package/dist/chunks/{runtimeObserver-Hjbo43xj.js → runtimeObserver-By59MZKJ.js} +2 -2
  174. package/dist/chunks/sandbox-adapter-D4Uho1vF.js +1 -0
  175. package/dist/chunks/sandbox-toggle-BdvylnWS.js +1 -0
  176. package/dist/chunks/searchExtraTools-BHMkqGBf.js +1 -0
  177. package/dist/chunks/{session-CkuTMD_4.js → session-Tm2-rzBY.js} +1 -1
  178. package/dist/chunks/sessionFileAccessHooks-BaWZ8sqn.js +1 -0
  179. package/dist/chunks/{sessionObserver-CvQ6oyoj.js → sessionObserver-BAr8AWeL.js} +1 -1
  180. package/dist/chunks/sessionObserver-KB1UL_n2.js +1 -0
  181. package/dist/chunks/{sessionState-C2REgUrs.js → sessionState-BTFowSpR.js} +2 -2
  182. package/dist/chunks/sessionStorage-D6nlmaI-.js +1 -0
  183. package/dist/chunks/{sessionTitle-2IWcNB8H.js → sessionTitle-SCqmSDYM.js} +1 -1
  184. package/dist/chunks/{sessionTracing-Bm7hQKHA.js → sessionTracing-CvY4udYI.js} +1 -1
  185. package/dist/chunks/settings-BgHApyGL.js +1 -0
  186. package/dist/chunks/{settings-aUygByiZ.js → settings-CvhsRFaT.js} +1 -1
  187. package/dist/chunks/{settingsSync-DgzCU1BZ.js → settingsSync-nxeaGM2-.js} +1 -1
  188. package/dist/chunks/setup-D4FPeBnM.js +3 -0
  189. package/dist/chunks/{shadowedRuleDetection-CWCQ5dZ0.js → shadowedRuleDetection-Co8m1q1D.js} +1 -1
  190. package/dist/chunks/{sideQuestion-BoW-xYkh.js → sideQuestion-4TJYn-Az.js} +1 -1
  191. package/dist/chunks/{sinks-ZHKfs6gv.js → sinks-Bb2i50kz.js} +1 -1
  192. package/dist/chunks/sinks-D1opmy_x.js +1 -0
  193. package/dist/chunks/skillChangeDetector-BU9AFG0i.js +1 -0
  194. package/dist/chunks/{skillGapStore-CCNeSjIb.js → skillGapStore-BcVP3ZUb.js} +2 -2
  195. package/dist/chunks/{skillLifecycle-wU4JDNYQ.js → skillLifecycle-CG2XmS8f.js} +2 -2
  196. package/dist/chunks/{skillSearchPanel-Cxr1QQn4.js → skillSearchPanel-DOJmUBXB.js} +4 -4
  197. package/dist/chunks/{skills-BghnKnNo.js → skills-DIgCWvzX.js} +1 -1
  198. package/dist/chunks/{stats-unp6R0Ah.js → stats-Dq-5qizS.js} +1 -1
  199. package/dist/chunks/status-Ber2xOXc.js +2 -0
  200. package/dist/chunks/status-CVcXPoOZ.js +1 -0
  201. package/dist/chunks/{statusNoticeHelpers-Dm1aiibR.js → statusNoticeHelpers-CYkrPUpN.js} +1 -1
  202. package/dist/chunks/{switcher-BUNSEJ-7.js → switcher-BIP3rbQn.js} +1 -1
  203. package/dist/chunks/switcher-zbG6T9dN.js +1 -0
  204. package/dist/chunks/syncCache-AMQMQ_HR.js +1 -0
  205. package/dist/chunks/{tasks-BjFot03S.js → tasks-BKERIO4G.js} +1 -1
  206. package/dist/chunks/{teleport-Dj2Kvbmx.js → teleport-DOXbf2sQ.js} +1 -1
  207. package/dist/chunks/{templateJobs-CY7GNRo5.js → templateJobs-dg2F45ZJ.js} +1 -1
  208. package/dist/chunks/{terminalSetup-Ty8T8ePM.js → terminalSetup-DDvQ0K5e.js} +1 -1
  209. package/dist/chunks/{terminalSetup-CpMNk6dc.js → terminalSetup-JJiXmszo.js} +1 -1
  210. package/dist/chunks/{theme-c6grxWNn.js → theme-BGxytGjA.js} +1 -1
  211. package/dist/chunks/{toolEventObserver-D7WbjgFR.js → toolEventObserver-CJhg_p3P.js} +1 -1
  212. package/dist/chunks/toolPool-C0d7Bznl.js +1 -0
  213. package/dist/chunks/{trustedDevice-BF78PNK8.js → trustedDevice-BtXHXu-T.js} +1 -1
  214. package/dist/chunks/trustedDevice-hw3iq84W.js +1 -0
  215. package/dist/chunks/{useExitOnCtrlCDWithKeybindings-qLfN0tc-.js → useExitOnCtrlCDWithKeybindings-C9orgrub.js} +1 -1
  216. package/dist/chunks/useMainLoopModel-BigVcn2T.js +1 -0
  217. package/dist/chunks/{useManagePlugins-E0Qzj-ws.js → useManagePlugins-Bt-DYAnX.js} +1 -1
  218. package/dist/chunks/{useMergedTools-B7iYaNwM.js → useMergedTools-CZeQBdky.js} +1 -1
  219. package/dist/chunks/{useSearchInput-CsxiM9i0.js → useSearchInput-DdKrVHJS.js} +1 -1
  220. package/dist/chunks/{useSettingsErrors-DdVTahNa.js → useSettingsErrors-BR9Wws7D.js} +1 -1
  221. package/dist/chunks/{userAgent-BggRZ-ZE.js → userAgent-DUt0q-Vl.js} +1 -1
  222. package/dist/chunks/{util-Xdy1nOjj.js → util-h-Hmdke_.js} +1 -1
  223. package/dist/chunks/validatePlugin-mWVKNtJa.js +1 -0
  224. package/dist/chunks/{vim-cFcxfuac.js → vim-s-wmybpU.js} +1 -1
  225. package/dist/chunks/{workerRegistry-GrD7IAVQ.js → workerRegistry-dlfqtySm.js} +2 -2
  226. package/dist/chunks/worktree-IxcFe7g-.js +1 -0
  227. package/dist/cli.js +1 -1
  228. package/package.json +1 -1
  229. package/dist/chunks/AddWorkspaceDirectory-m2d3nOQJ.js +0 -1
  230. package/dist/chunks/AgentsMdExternalIncludesDialog-BRXGkHO4.js +0 -1
  231. package/dist/chunks/ApproveApiKey-NXTWIAMj.js +0 -1
  232. package/dist/chunks/BypassPermissionsModeDialog-C4QGpcBT.js +0 -1
  233. package/dist/chunks/Doctor-DmiDH-lg.js +0 -1
  234. package/dist/chunks/ExitFlow-DH0L3tyY.js +0 -2
  235. package/dist/chunks/Grove-BhhnrFX9.js +0 -11
  236. package/dist/chunks/MCPConnectionManager-Ciy9y9VV.js +0 -1
  237. package/dist/chunks/MCPToolListView-Ddmu2UcL.js +0 -1
  238. package/dist/chunks/Messages-LD6ZO301.js +0 -10
  239. package/dist/chunks/PromptInputHelpMenu-DyaUsvNx.js +0 -1
  240. package/dist/chunks/QueryEngine-sH-KjJIq.js +0 -1
  241. package/dist/chunks/REPL-BMH_RItw.js +0 -128
  242. package/dist/chunks/REPL-DkPd3vk5.js +0 -1
  243. package/dist/chunks/RemoteSessionManager-DJhrR1dz.js +0 -2
  244. package/dist/chunks/SearchExtraToolsTool-DupzA6Vm.js +0 -1
  245. package/dist/chunks/Settings-B1EI5LOU.js +0 -2
  246. package/dist/chunks/TeleportResumeWrapper-DnHTI39O.js +0 -1
  247. package/dist/chunks/agents-BYQO6DbG.js +0 -101
  248. package/dist/chunks/api-j0iE1mkR.js +0 -1
  249. package/dist/chunks/auth-BYCRa_mb.js +0 -10
  250. package/dist/chunks/auth-C9FUZzpW.js +0 -1
  251. package/dist/chunks/auth-DwPrlTHv.js +0 -1
  252. package/dist/chunks/backgroundHousekeeping-BxcVB3By.js +0 -1
  253. package/dist/chunks/bridgeConfig-Bxs5dqjH.js +0 -1
  254. package/dist/chunks/bridgeStatusUtil-BQF0AJDO.js +0 -1
  255. package/dist/chunks/caches-C9--b9a7.js +0 -1
  256. package/dist/chunks/claudeDesktop-DPIJpc1V.js +0 -1
  257. package/dist/chunks/client-B7WkO81L.js +0 -17
  258. package/dist/chunks/client-BCzhAEd0.js +0 -1
  259. package/dist/chunks/client-Dr9AYB-r.js +0 -1
  260. package/dist/chunks/commands-DTB0Qzd5.js +0 -1
  261. package/dist/chunks/config-B1kYcRIP.js +0 -1
  262. package/dist/chunks/context-noninteractive-Bno2Xsmp.js +0 -1
  263. package/dist/chunks/conversation-hNXWaswI.js +0 -1
  264. package/dist/chunks/createSession-BZx-2UIB.js +0 -1
  265. package/dist/chunks/doctor-aKE2bG5C.js +0 -1
  266. package/dist/chunks/exit-pjN4EJHV.js +0 -1
  267. package/dist/chunks/extraUsage-CwDhpClH.js +0 -1
  268. package/dist/chunks/extractMemories-WmPLOLUT.js +0 -1
  269. package/dist/chunks/fast-BVABmasw.js +0 -1
  270. package/dist/chunks/fast-Cuj3bfFm.js +0 -1
  271. package/dist/chunks/firstPartyEventLogger-CabA8fu0.js +0 -1
  272. package/dist/chunks/grok-BBo3jGfP.js +0 -1
  273. package/dist/chunks/help-CELr6oJZ.js +0 -1
  274. package/dist/chunks/hooks-9rkDD2iw.js +0 -1
  275. package/dist/chunks/initReplBridge-BYrL6ou1.js +0 -1
  276. package/dist/chunks/install-Dn3_M1Ui.js +0 -1
  277. package/dist/chunks/keybindings-B5kUoxvg.js +0 -1
  278. package/dist/chunks/loadAgentsDir-D-a1uUb5.js +0 -1
  279. package/dist/chunks/localSearch-hOERAH9v.js +0 -1
  280. package/dist/chunks/main-C_PDzJdv.js +0 -356
  281. package/dist/chunks/managedEnv-AEhH_HUs.js +0 -1
  282. package/dist/chunks/mcp-B2mJmWKt.js +0 -6
  283. package/dist/chunks/model-BCM7RpVk.js +0 -1
  284. package/dist/chunks/model-BWR43D3c.js +0 -1
  285. package/dist/chunks/model-CmDF8O9G.js +0 -1
  286. package/dist/chunks/modelOptions-DEQat7lU.js +0 -1
  287. package/dist/chunks/pluginStartupCheck-BGN6Je6d.js +0 -1
  288. package/dist/chunks/poorMode-XDBnxTiF.js +0 -1
  289. package/dist/chunks/print-DaJi1wF_.js +0 -14
  290. package/dist/chunks/prompt-B0gADAvI.js +0 -1
  291. package/dist/chunks/prompt-DqyEtC_I2.js +0 -1
  292. package/dist/chunks/ripgrep-DrpZ79Pp.js +0 -1
  293. package/dist/chunks/sandbox-adapter-DQ_fJSIo.js +0 -1
  294. package/dist/chunks/sandbox-toggle-DmNSThQK.js +0 -1
  295. package/dist/chunks/searchExtraTools-C7b2x2p_.js +0 -1
  296. package/dist/chunks/sessionFileAccessHooks-CQvGAbvL.js +0 -1
  297. package/dist/chunks/sessionObserver-BoQY7nOa.js +0 -1
  298. package/dist/chunks/sessionStorage-BeaEgnaa.js +0 -1
  299. package/dist/chunks/settings-Da6ax5aI.js +0 -1
  300. package/dist/chunks/setup-CvaG4nl5.js +0 -3
  301. package/dist/chunks/sinks-B_ehGpvp.js +0 -1
  302. package/dist/chunks/skillChangeDetector-C-HWR_8v.js +0 -1
  303. package/dist/chunks/status-BraYBx4N.js +0 -2
  304. package/dist/chunks/status-DwyWiaVc.js +0 -1
  305. package/dist/chunks/switcher-DDUnWU_4.js +0 -1
  306. package/dist/chunks/syncCache-1s9xV8WV.js +0 -1
  307. package/dist/chunks/toolPool-O5nkEFb1.js +0 -1
  308. package/dist/chunks/trustedDevice-D_z7bAQh.js +0 -1
  309. package/dist/chunks/updateCCB-ts7Joyve.js +0 -5
  310. package/dist/chunks/useMainLoopModel-DkjG_ikT.js +0 -1
  311. package/dist/chunks/validatePlugin-Be5aSSnP.js +0 -1
  312. package/dist/chunks/worktree-V7xiUAtl.js +0 -1
@@ -1,4 +1,4 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{c as t,l as n,o as r}from"./envUtils-DcaKZlRU.js";import{F_ as i,Ka as a,La as o,N_ as s,Ny as c,P_ as l,Sa as u,Wa as d,it as ee,ky as f,pa as p,tt as m}from"./loadAgentsDir-JrGMJN05.js";import{c as h,i as g}from"./debug-BQj6h99Q.js";import{Kn as _,Un as te,V as v,W as y}from"./model-CmDF8O9G.js";import{i as ne,r as b,t as x,vn as re,xn as ie,yn as S}from"./prompt-DnPppVz8.js";import{E as C,O as w,T,Z as E,j as D,k as ae}from"./sessionState-C2REgUrs.js";import{n as oe,r as O}from"./client-B7WkO81L.js";import{n as se,t as k}from"./openaiShared-G2-w4gJt.js";import{homedir as A}from"os";import{join as j}from"path";import{randomUUID as M}from"crypto";import{chmod as ce,mkdir as N,readFile as P,writeFile as F}from"fs/promises";function I(){return j(L(),J)}function L(){return(process.env.WORKMATE_CONFIG_DIR??j(A(),`.workmate`)).normalize(`NFC`)}function R(){return j(process.env.CODEX_HOME??j(process.env.HOME??``,`.codex`),`auth.json`)}function z(e){return typeof e==`string`&&e.length>0?e:void 0}function B(e){try{let t=JSON.parse(e);return t&&typeof t==`object`?t:null}catch{return null}}function V(e){let[,t]=e.split(`.`);if(!t)return null;try{let e=t.replace(/-/g,`+`).replace(/_/g,`/`),n=e.padEnd(e.length+(4-e.length%4)%4,`=`);return B(Buffer.from(n,`base64`).toString(`utf8`))}catch{return null}}function H(e){let t=V(e),n=t?.[`https://api.openai.com/auth`];return n&&typeof n==`object`?n:t??{}}function U(e){let t=V(e)?.exp;return typeof t==`number`?t*1e3:null}function W(e){if(e.accountId)return e.accountId;for(let t of[e.idToken,e.accessToken]){if(!t)continue;let e=H(t),n=z(e.chatgpt_account_id)??z(e.chatgpt_account_user_id)??z(e.account_id);if(n)return n}}async function G(e){try{let t=await P(e,`utf8`),n=JSON.parse(t),r=n.tokens,i=r?.id_token,a=r?.access_token,o=r?.refresh_token;return!i||!a||!o?null:{idToken:i,accessToken:a,refreshToken:o,accountId:W({idToken:i,accessToken:a,accountId:r.account_id}),lastRefresh:n.last_refresh}}catch{return null}}async function le(e){let t=I();await N(L(),{recursive:!0});let n={auth_mode:`chatgpt`,tokens:{id_token:e.idToken,access_token:e.accessToken,refresh_token:e.refreshToken,account_id:W(e)},last_refresh:new Date().toISOString()};await F(t,`${JSON.stringify(n,null,2)}\n`,{mode:384}),await ce(t,384).catch(()=>void 0)}async function ue(e,t){let n=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:t});if(!n.ok){let e=await n.text().catch(()=>``);throw Error(`ChatGPT token request failed (${n.status})${e?`: ${e}`:``}`)}return await n.json()}async function de(e){let t=new URLSearchParams({grant_type:`refresh_token`,refresh_token:e.refreshToken,client_id:q,scope:`openid profile email offline_access api.connectors.read api.connectors.invoke`}),n=await ue(`${K}/oauth/token`,t);return{idToken:n.id_token,accessToken:n.access_token,refreshToken:n.refresh_token??e.refreshToken,accountId:W({idToken:n.id_token,accessToken:n.access_token,accountId:e.accountId})}}function fe(){return process.env.OPENAI_AUTH_MODE===`chatgpt`}async function pe(){let e=await G(I());if(e||(e=await G(R()),e&&h(`[OpenAI] Using ChatGPT auth from Codex auth.json`)),!e)throw Error(`ChatGPT account is not logged in.`);let t=U(e.accessToken);return t!==null&&t<=Date.now()+Y&&(e=await de(e),await le(e)),{accessToken:e.accessToken,accountId:e.accountId??W(e)}}var K,q,J,Y,X=e((()=>{g(),K=`https://auth.openai.com`,q=`app_EMoamEEZ73f0CkXaXp7hrann`,J=`openai-chatgpt-auth.json`,Y=300*1e3}));function Z(e){return typeof e==`string`?e:Array.isArray(e)?e.map(e=>{if(!e||typeof e!=`object`)return``;let t=e;return typeof t.text==`string`?t.text:``}).filter(Boolean).join(`
1
+ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{c as t,l as n,o as r}from"./envUtils-DcaKZlRU.js";import{F_ as i,Ka as a,La as o,N_ as s,Ny as c,P_ as l,Sa as u,Wa as d,it as ee,ky as f,pa as p,tt as m}from"./loadAgentsDir-PPiD2Mfq.js";import{c as h,i as g}from"./debug-BQj6h99Q.js";import{Bn as _,F as te,Ln as v,R as y}from"./model-sviY1inu.js";import{i as ne,r as b,t as x,vn as re,xn as ie,yn as S}from"./prompt-CQmEvnKN.js";import{E as C,O as w,T,Z as E,j as D,k as ae}from"./sessionState-BTFowSpR.js";import{n as oe,r as O}from"./client-Bb2eZnuq.js";import{n as se,t as k}from"./openaiShared-G2-w4gJt.js";import{homedir as A}from"os";import{join as j}from"path";import{randomUUID as M}from"crypto";import{chmod as ce,mkdir as N,readFile as P,writeFile as F}from"fs/promises";function I(){return j(L(),J)}function L(){return(process.env.WORKMATE_CONFIG_DIR??j(A(),`.workmate`)).normalize(`NFC`)}function R(){return j(process.env.CODEX_HOME??j(process.env.HOME??``,`.codex`),`auth.json`)}function z(e){return typeof e==`string`&&e.length>0?e:void 0}function B(e){try{let t=JSON.parse(e);return t&&typeof t==`object`?t:null}catch{return null}}function V(e){let[,t]=e.split(`.`);if(!t)return null;try{let e=t.replace(/-/g,`+`).replace(/_/g,`/`),n=e.padEnd(e.length+(4-e.length%4)%4,`=`);return B(Buffer.from(n,`base64`).toString(`utf8`))}catch{return null}}function H(e){let t=V(e),n=t?.[`https://api.openai.com/auth`];return n&&typeof n==`object`?n:t??{}}function U(e){let t=V(e)?.exp;return typeof t==`number`?t*1e3:null}function W(e){if(e.accountId)return e.accountId;for(let t of[e.idToken,e.accessToken]){if(!t)continue;let e=H(t),n=z(e.chatgpt_account_id)??z(e.chatgpt_account_user_id)??z(e.account_id);if(n)return n}}async function G(e){try{let t=await P(e,`utf8`),n=JSON.parse(t),r=n.tokens,i=r?.id_token,a=r?.access_token,o=r?.refresh_token;return!i||!a||!o?null:{idToken:i,accessToken:a,refreshToken:o,accountId:W({idToken:i,accessToken:a,accountId:r.account_id}),lastRefresh:n.last_refresh}}catch{return null}}async function le(e){let t=I();await N(L(),{recursive:!0});let n={auth_mode:`chatgpt`,tokens:{id_token:e.idToken,access_token:e.accessToken,refresh_token:e.refreshToken,account_id:W(e)},last_refresh:new Date().toISOString()};await F(t,`${JSON.stringify(n,null,2)}\n`,{mode:384}),await ce(t,384).catch(()=>void 0)}async function ue(e,t){let n=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:t});if(!n.ok){let e=await n.text().catch(()=>``);throw Error(`ChatGPT token request failed (${n.status})${e?`: ${e}`:``}`)}return await n.json()}async function de(e){let t=new URLSearchParams({grant_type:`refresh_token`,refresh_token:e.refreshToken,client_id:q,scope:`openid profile email offline_access api.connectors.read api.connectors.invoke`}),n=await ue(`${K}/oauth/token`,t);return{idToken:n.id_token,accessToken:n.access_token,refreshToken:n.refresh_token??e.refreshToken,accountId:W({idToken:n.id_token,accessToken:n.access_token,accountId:e.accountId})}}function fe(){return process.env.OPENAI_AUTH_MODE===`chatgpt`}async function pe(){let e=await G(I());if(e||(e=await G(R()),e&&h(`[OpenAI] Using ChatGPT auth from Codex auth.json`)),!e)throw Error(`ChatGPT account is not logged in.`);let t=U(e.accessToken);return t!==null&&t<=Date.now()+Y&&(e=await de(e),await le(e)),{accessToken:e.accessToken,accountId:e.accountId??W(e)}}var K,q,J,Y,X=e((()=>{g(),K=`https://auth.openai.com`,q=`app_EMoamEEZ73f0CkXaXp7hrann`,J=`openai-chatgpt-auth.json`,Y=300*1e3}));function Z(e){return typeof e==`string`?e:Array.isArray(e)?e.map(e=>{if(!e||typeof e!=`object`)return``;let t=e;return typeof t.text==`string`?t.text:``}).filter(Boolean).join(`
2
2
  `):``}function me(e){if(typeof e==`string`)return e;if(!Array.isArray(e))return Z(e);let t=[];for(let n of e){if(!n||typeof n!=`object`)continue;let e=n;if(e.type===`text`&&typeof e.text==`string`)t.push({type:`input_text`,text:e.text});else if(e.type===`image_url`){let n=e.image_url;typeof n?.url==`string`&&t.push({type:`input_image`,image_url:n.url})}}return t.length>0?t:Z(e)}function he(e){let t=[],n=[];for(let r of e){if(!r||typeof r!=`object`)continue;let e=r,i=e.role;if(i===`system`||i===`developer`){let t=Z(e.content);t&&n.push(t);continue}if(i===`tool`){let n=e.tool_call_id;typeof n==`string`&&t.push({type:`function_call_output`,call_id:n,output:Z(e.content)});continue}if(i===`assistant`){let n=Z(e.content);n&&t.push({role:`assistant`,content:n});let r=e.tool_calls;if(Array.isArray(r))for(let e of r){if(!e||typeof e!=`object`)continue;let n=e,r=n.function,i=typeof n.id==`string`?n.id:void 0,a=typeof r?.name==`string`?r.name:void 0;!i||!a||t.push({type:`function_call`,call_id:i,name:a,arguments:typeof r?.arguments==`string`?r.arguments:`{}`})}continue}i===`user`&&t.push({role:`user`,content:me(e.content)})}return{input:t,instructions:n.length>0?n.join(`
3
3
 
4
4
  `):void 0}}function ge(e){let t=[];for(let n of e){if(!n||typeof n!=`object`)continue;let e=n.function,r=typeof e?.name==`string`?e.name:void 0;r&&t.push({type:`function`,name:r,description:typeof e?.description==`string`?e.description:``,parameters:e?.parameters&&typeof e.parameters==`object`?e.parameters:{type:`object`,properties:{}},strict:!1})}return t}function _e(e){if(e===`required`)return`required`;if(e===`auto`)return`auto`;if(!e||typeof e!=`object`)return e;let t=e,n=t.function;return t.type===`function`&&typeof n?.name==`string`?{type:`function`,name:n.name}:e}function ve(e){let{input:t,instructions:n}=he(e.messages),r=ge(e.tools);return{model:e.model,stream:!0,store:!1,input:t,...n?{instructions:n}:{},...r.length>0?{tools:r}:{},...e.toolChoice?{tool_choice:_e(e.toolChoice)}:{},parallel_tool_calls:!0}}async function*ye(e){if(!e.body)throw Error(`ChatGPT response did not include a body`);let t=e.body.getReader(),n=new TextDecoder,r=``;for(;;){let{done:e,value:i}=await t.read();if(e)break;r+=n.decode(i,{stream:!0});let a=r.indexOf(`
@@ -7,4 +7,4 @@ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{c as t,l as n,o as r}f
7
7
  `);if(t&&t!==`[DONE]`){let e=JSON.parse(t);e&&typeof e==`object`&&(yield e)}a=r.indexOf(`
8
8
 
9
9
  `)}}}function be(e){let t=e?.usage,n=t?.input_tokens_details;return{input_tokens:typeof t?.input_tokens==`number`?t.input_tokens:0,output_tokens:typeof t?.output_tokens==`number`?t.output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:typeof n?.cached_tokens==`number`?n.cached_tokens:0}}function xe(e){return e?.status===`incomplete`?`max_tokens`:`end_turn`}async function*Q(e,t){let n=`msg_${M().replace(/-/g,``).slice(0,24)}`,r=new Map,i=!1,a=-1,o=!1,s=!1,c=async function*(){i||(i=!0,yield{type:`message_start`,message:{id:n,type:`message`,role:`assistant`,content:[],model:t,stop_reason:null,stop_sequence:null,usage:{input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0}}})};for await(let t of e){for await(let e of c())yield e;let e=t.type;if(e===`response.output_text.delta`){o||(s&&(yield{type:`content_block_stop`,index:a},s=!1),a++,o=!0,yield{type:`content_block_start`,index:a,content_block:{type:`text`,text:``}}),yield{type:`content_block_delta`,index:a,delta:{type:`text_delta`,text:String(t.delta??``)}};continue}if(e===`response.reasoning_text.delta`){s||(o&&(yield{type:`content_block_stop`,index:a},o=!1),a++,s=!0,yield{type:`content_block_start`,index:a,content_block:{type:`thinking`,thinking:``,signature:``}}),yield{type:`content_block_delta`,index:a,delta:{type:`thinking_delta`,thinking:String(t.delta??``)}};continue}if(e===`response.output_item.added`){let e=t.item,n=typeof t.output_index==`number`?t.output_index:-1;if(e?.type===`function_call`&&n>=0){o&&(yield{type:`content_block_stop`,index:a},o=!1),s&&(yield{type:`content_block_stop`,index:a},s=!1),a++;let t=String(e.call_id??e.id??`call_${n}`),i=String(e.name??``);r.set(n,{contentIndex:a,open:!0,name:i,id:t}),yield{type:`content_block_start`,index:a,content_block:{type:`tool_use`,id:t,name:i,input:{}}}}continue}if(e===`response.function_call_arguments.delta`){let e=typeof t.output_index==`number`?t.output_index:-1,n=r.get(e);n&&(yield{type:`content_block_delta`,index:n.contentIndex,delta:{type:`input_json_delta`,partial_json:String(t.delta??``)}});continue}if(e===`response.output_item.done`){let e=typeof t.output_index==`number`?t.output_index:-1,n=r.get(e);n?.open&&(yield{type:`content_block_stop`,index:n.contentIndex},n.open=!1);continue}if(e===`response.error`){let e=t.error;throw Error(String(e?.message??`ChatGPT Responses API error`))}if(e===`response.failed`){let e=t.response?.error;throw Error(String(e?.message??`ChatGPT Responses API failed`))}if(e===`response.completed`||e===`response.incomplete`){o&&(yield{type:`content_block_stop`,index:a},o=!1),s&&(yield{type:`content_block_stop`,index:a},s=!1);let e=t.response;yield{type:`message_delta`,delta:{stop_reason:xe(e),stop_sequence:null},usage:be(e)},yield{type:`message_stop`}}}}async function Se(e){let t=await pe(),n=e.fetchOverride??globalThis.fetch,r={Authorization:`Bearer ${t.accessToken}`,"Content-Type":`application/json`,Accept:`text/event-stream`,"OpenAI-Beta":`responses=experimental`,Origin:`https://chatgpt.com`,Referer:`https://chatgpt.com/`,originator:`workmate`};t.accountId&&(r[`ChatGPT-Account-Id`]=t.accountId);let i=await n(`https://chatgpt.com/backend-api/codex/responses`,{method:`POST`,headers:r,body:JSON.stringify(e.request),signal:e.signal});if(!i.ok){let e=await i.text().catch(()=>``);throw Error(`ChatGPT Responses API request failed (${i.status})${e?`: ${e.slice(0,500)}`:``}`)}return ye(i)}var Ce=e((()=>{X()}));function we(e){if(t(process.env.OPENAI_ENABLE_THINKING))return!1;if(n(process.env.OPENAI_ENABLE_THINKING))return!0;let r=e.toLowerCase();return r.includes(`deepseek`)||r.includes(`mimo`)}function Te(e,t){return t??(process.env.OPENAI_MAX_TOKENS&&parseInt(process.env.OPENAI_MAX_TOKENS,10)||void 0)??(process.env.CLAUDE_CODE_MAX_OUTPUT_TOKENS&&parseInt(process.env.CLAUDE_CODE_MAX_OUTPUT_TOKENS,10)||void 0)??e}function Ee(e){let{model:t,messages:n,tools:r,toolChoice:i,enableThinking:a,maxTokens:o,temperatureOverride:s}=e;return{model:t,messages:n,max_tokens:o,...r.length>0&&{tools:r,...i&&{tool_choice:i}},stream:!0,stream_options:{include_usage:!0},...a&&{thinking:{type:`enabled`},enable_thinking:!0,chat_template_kwargs:{thinking:!0,enable_thinking:!0}},...!a&&s!==void 0&&{temperature:s}}}var De=e((()=>{r()}));function Oe(e,t,n,r){if(!r||l())return e;let i=t.filter(e=>n.has(e.name)).map(x).sort().join(`
10
- `);return i?[u({content:`<available-deferred-tools>\n${i}\n</available-deferred-tools>`,isMeta:!0}),...e]:e}function ke(e){return e.type===`assistant`||e.type===`user`}function $(e){let{partialMessage:t,contentBlocks:n,tools:r,agentId:i,usage:a,stopReason:o,maxTokens:s}=e,c=[],l=Object.keys(n).sort((e,t)=>Number(e)-Number(t)).map(e=>n[Number(e)]).filter(Boolean);return l.length>0&&t&&c.push({message:{...t,content:d(l,r,i),usage:a,stop_reason:o,stop_sequence:null},requestId:void 0,type:`assistant`,uuid:M(),timestamp:new Date().toISOString()}),o===`max_tokens`&&c.push(p({content:`Output truncated: response exceeded the ${s} token limit. Set OPENAI_MAX_TOKENS or CLAUDE_CODE_MAX_OUTPUT_TOKENS to override.`,apiError:`max_output_tokens`,error:`max_output_tokens`})),c}async function*Ae(e,t,n,r,o){try{let s=E(o.model),c=a(e,n),l=await i(o.model,n,o.getToolPermissionContext||(async()=>re()),o.agents||[],o.querySource),u=new Set;if(l)for(let e of n)ne(e)&&u.add(e.name);let d=n;l&&u.size>0&&(d=n.filter(e=>!!(!u.has(e.name)||ie(e,`SearchExtraTools`))));let p=(await Promise.all(d.map(e=>ee(e,{getToolPermissionContext:o.getToolPermissionContext,tools:n,agents:o.agents,allowedAgentTypes:o.allowedAgentTypes,model:o.model,deferLoading:l&&u.has(e.name)})))).filter(e=>{let t=e;return t.type!==`advisor_20260301`&&t.type!==`computer_20250124`}),m=we(s),g=D(Oe(c.filter(ke),n,u,l),t,{enableThinking:m}),_=ae(p),y=w(o.toolChoice);if(l){let e=d.filter(e=>u.has(e.name)).length;h(`[OpenAI] Tool search enabled: ${e}/${u.size} deferred tools included, total tools=${_.length}`)}else h(`[OpenAI] Tool search disabled, total tools=${_.length}`);let{upperLimit:b}=te(s),x=Te(b,o.maxOutputTokensOverride);h(`[OpenAI] Calling model=${s}, messages=${g.length}, tools=${_.length}, thinking=${m}`);let S=fe()?Q(await Se({request:ve({model:s,messages:g,tools:_,toolChoice:y}),signal:r,fetchOverride:o.fetchOverride}),s):C(await oe({maxRetries:0,fetchOverride:o.fetchOverride,source:o.querySource}).chat.completions.create(Ee({model:s,messages:g,tools:_,toolChoice:y,enableThinking:m,maxTokens:x,temperatureOverride:o.temperatureOverride}),{signal:r}),s),T={},O=null,k=null,A={input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0},j=0,M=Date.now();for await(let e of S){switch(e.type){case`message_start`:O=e.message,j=Date.now()-M,e.message.usage&&(A={...A,...e.message.usage});break;case`content_block_start`:{let t=e.index,n=e.content_block;n.type===`tool_use`?T[t]={...n,input:``}:n.type===`text`?T[t]={...n,text:``}:n.type===`thinking`?T[t]={...n,thinking:``,signature:``}:T[t]={...n};break}case`content_block_delta`:{let t=e.index,n=e.delta,r=T[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`:break;case`message_delta`:{let t=e.usage;t&&(A=se(A,t)),e.delta.stop_reason!=null&&(k=e.delta.stop_reason);break}case`message_stop`:if(O){for(let e of $({partialMessage:O,contentBlocks:T,tools:n,agentId:o.agentId,usage:A,stopReason:k,maxTokens:x}))yield e;O=null}A.input_tokens+A.output_tokens>0&&f(v(s,A),A,o.model);break}yield{type:`stream_event`,event:e,...e.type===`message_start`?{ttftMs:j}:void 0}}if(O)for(let e of $({partialMessage:O,contentBlocks:T,tools:n,agentId:o.agentId,usage:A,stopReason:k,maxTokens:x}))yield e}catch(e){let t=e instanceof Error?e.message:String(e);h(`[OpenAI] Error: ${t}`,{level:`error`}),yield p({content:`API Error: ${t}`,apiError:`api_error`,error:e instanceof Error?e:Error(String(e))})}}e((()=>{O(),k(),T(),X(),Ce(),o(),m(),S(),g(),c(),y(),De(),_(),s(),b()}))();export{Ae as queryModelOpenAI};
10
+ `);return i?[u({content:`<available-deferred-tools>\n${i}\n</available-deferred-tools>`,isMeta:!0}),...e]:e}function ke(e){return e.type===`assistant`||e.type===`user`}function $(e){let{partialMessage:t,contentBlocks:n,tools:r,agentId:i,usage:a,stopReason:o,maxTokens:s}=e,c=[],l=Object.keys(n).sort((e,t)=>Number(e)-Number(t)).map(e=>n[Number(e)]).filter(Boolean);return l.length>0&&t&&c.push({message:{...t,content:d(l,r,i),usage:a,stop_reason:o,stop_sequence:null},requestId:void 0,type:`assistant`,uuid:M(),timestamp:new Date().toISOString()}),o===`max_tokens`&&c.push(p({content:`Output truncated: response exceeded the ${s} token limit. Set OPENAI_MAX_TOKENS or CLAUDE_CODE_MAX_OUTPUT_TOKENS to override.`,apiError:`max_output_tokens`,error:`max_output_tokens`})),c}async function*Ae(e,t,n,r,o){try{let s=E(o.model),c=a(e,n),l=await i(o.model,n,o.getToolPermissionContext||(async()=>re()),o.agents||[],o.querySource),u=new Set;if(l)for(let e of n)ne(e)&&u.add(e.name);let d=n;l&&u.size>0&&(d=n.filter(e=>!!(!u.has(e.name)||ie(e,`SearchExtraTools`))));let p=(await Promise.all(d.map(e=>ee(e,{getToolPermissionContext:o.getToolPermissionContext,tools:n,agents:o.agents,allowedAgentTypes:o.allowedAgentTypes,model:o.model,deferLoading:l&&u.has(e.name)})))).filter(e=>{let t=e;return t.type!==`advisor_20260301`&&t.type!==`computer_20250124`}),m=we(s),g=D(Oe(c.filter(ke),n,u,l),t,{enableThinking:m}),_=ae(p),y=w(o.toolChoice);if(l){let e=d.filter(e=>u.has(e.name)).length;h(`[OpenAI] Tool search enabled: ${e}/${u.size} deferred tools included, total tools=${_.length}`)}else h(`[OpenAI] Tool search disabled, total tools=${_.length}`);let{upperLimit:b}=v(s),x=Te(b,o.maxOutputTokensOverride);h(`[OpenAI] Calling model=${s}, messages=${g.length}, tools=${_.length}, thinking=${m}`);let S=fe()?Q(await Se({request:ve({model:s,messages:g,tools:_,toolChoice:y}),signal:r,fetchOverride:o.fetchOverride}),s):C(await oe({maxRetries:0,fetchOverride:o.fetchOverride,source:o.querySource}).chat.completions.create(Ee({model:s,messages:g,tools:_,toolChoice:y,enableThinking:m,maxTokens:x,temperatureOverride:o.temperatureOverride}),{signal:r}),s),T={},O=null,k=null,A={input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0},j=0,M=Date.now();for await(let e of S){switch(e.type){case`message_start`:O=e.message,j=Date.now()-M,e.message.usage&&(A={...A,...e.message.usage});break;case`content_block_start`:{let t=e.index,n=e.content_block;n.type===`tool_use`?T[t]={...n,input:``}:n.type===`text`?T[t]={...n,text:``}:n.type===`thinking`?T[t]={...n,thinking:``,signature:``}:T[t]={...n};break}case`content_block_delta`:{let t=e.index,n=e.delta,r=T[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`:break;case`message_delta`:{let t=e.usage;t&&(A=se(A,t)),e.delta.stop_reason!=null&&(k=e.delta.stop_reason);break}case`message_stop`:if(O){for(let e of $({partialMessage:O,contentBlocks:T,tools:n,agentId:o.agentId,usage:A,stopReason:k,maxTokens:x}))yield e;O=null}A.input_tokens+A.output_tokens>0&&f(te(s,A),A,o.model);break}yield{type:`stream_event`,event:e,...e.type===`message_start`?{ttftMs:j}:void 0}}if(O)for(let e of $({partialMessage:O,contentBlocks:T,tools:n,agentId:o.agentId,usage:A,stopReason:k,maxTokens:x}))yield e}catch(e){let t=e instanceof Error?e.message:String(e);h(`[OpenAI] Error: ${t}`,{level:`error`}),yield p({content:`API Error: ${t}`,apiError:`api_error`,error:e instanceof Error?e:Error(String(e))})}}e((()=>{O(),k(),T(),X(),Ce(),o(),m(),S(),g(),c(),y(),De(),_(),s(),b()}))();export{Ae as queryModelOpenAI};
@@ -0,0 +1,17 @@
1
+ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";function t(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 n(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 r=e((()=>{})),i,a=e((()=>{i=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return i=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 o(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}var s,c=e((()=>{s=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)}})),l,u,d,f,p,m,h,g,ee,_,v,y,te,ne,re,b,ie,ae,x=e((()=>{c(),l=class extends Error{},u=class e extends l{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 f({message:r,cause:s(n)});let a=n?.error;return t===400?new m(t,a,r,i):t===401?new h(t,a,r,i):t===403?new g(t,a,r,i):t===404?new ee(t,a,r,i):t===409?new _(t,a,r,i):t===422?new v(t,a,r,i):t===429?new y(t,a,r,i):t>=500?new te(t,a,r,i):new e(t,a,r,i)}},d=class extends u{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},f=class extends u{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},p=class extends f{constructor({message:e}={}){super({message:e??`Request timed out.`})}},m=class extends u{},h=class extends u{},g=class extends u{},ee=class extends u{},_=class extends u{},v=class extends u{},y=class extends u{},te=class extends u{},ne=class extends l{constructor(){super(`Could not parse response content as the length limit was reached`)}},re=class extends l{constructor(){super(`Could not parse response content as the request was rejected by the content filter`)}},b=class extends Error{constructor(e){super(e)}},ie=class extends u{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}},ae=class extends l{constructor(e,t,n){super(e),this.provider=t,this.cause=n}}}));function oe(e){return typeof e==`object`?e??{}:{}}function se(e){if(!e)return!0;for(let t in e)return!1;return!0}function ce(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function le(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var ue,de,S,fe,pe,me,he=e((()=>{x(),ue=/^[a-z][a-z0-9+.-]*:/i,de=e=>ue.test(e),S=e=>(S=Array.isArray,S(e)),fe=S,pe=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new l(`${e} must be an integer`);if(t<0)throw new l(`${e} must be a positive integer`);return t},me=e=>{try{return JSON.parse(e)}catch{return}}})),ge,_e=e((()=>{ge=e=>new Promise(t=>setTimeout(t,e))})),ve,ye=e((()=>{ve=`6.46.0`}));function be(){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 xe(){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 Se,Ce,we,Te,Ee,De,Oe=e((()=>{ye(),Se=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`,Ce=()=>{let e=be();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":ve,"X-Stainless-OS":Te(Deno.build.os),"X-Stainless-Arch":we(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":ve,"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":ve,"X-Stainless-OS":Te(globalThis.process.platform??`unknown`),"X-Stainless-Arch":we(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=xe();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":ve,"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":ve,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}},we=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,Te=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`),De=()=>Ee??(Ee=Ce())}));function ke(){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 Ae(...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 je(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return Ae({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function Me(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 Ne(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 Pe=e((()=>{})),Fe,Ie=e((()=>{Fe=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)})})),Le,Re,ze,Be=e((()=>{Le=`RFC3986`,Re=e=>String(e),ze={RFC1738:e=>String(e).replace(/%20/g,`+`),RFC3986:Re}}));function Ve(e){return!e||typeof e!=`object`?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function He(e,t){if(S(e)){let n=[];for(let r=0;r<e.length;r+=1)n.push(t(e[r]));return n}return t(e)}var Ue,C,We,Ge,Ke=e((()=>{Be(),he(),Ue=(e,t)=>(Ue=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Ue(e,t)),C=(()=>{let e=[];for(let t=0;t<256;++t)e.push(`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase());return e})(),We=1024,Ge=(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+=We){let t=a.length>=We?a.slice(e,e+We):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]=C[r];continue}if(r<2048){n[n.length]=C[192|r>>6]+C[128|r&63];continue}if(r<55296||r>=57344){n[n.length]=C[224|r>>12]+C[128|r>>6&63]+C[128|r&63];continue}e+=1,r=65536+((r&1023)<<10|t.charCodeAt(e)&1023),n[n.length]=C[240|r>>18]+C[128|r>>12&63]+C[128|r>>6&63]+C[128|r&63]}o+=n.join(``)}return o}}));function qe(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`symbol`||typeof e==`bigint`}function Je(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(et))!==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(et)===void 0&&(y=0)}if(typeof l==`function`?_=l(t,_):_ instanceof Date?_=f?.(_):n===`comma`&&S(_)&&(_=He(_,function(e){return e instanceof Date?f?.(e):e})),_===null){if(a)return c&&!h?c(t,w.encoder,g,`key`,p):t;_=``}if(qe(_)||Ve(_)){if(c){let e=h?t:c(t,w.encoder,g,`key`,p);return[m?.(e)+`=`+m?.(c(_,w.encoder,g,`value`,p))]}return[m?.(t)+`=`+m?.(String(_))]}let ne=[];if(_===void 0)return ne;let re;if(n===`comma`&&S(_))h&&c&&(_=He(_,c)),re=[{value:_.length>0?_.join(`,`)||null:void 0}];else if(S(l))re=l;else{let e=Object.keys(_);re=u?e.sort(u):e}let b=s?String(t).replace(/\./g,`%2E`):String(t),ie=r&&S(_)&&_.length===1?b+`[]`:b;if(i&&S(_)&&_.length===0)return ie+`[]`;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 b=d&&s?v.replace(/\./g,`%2E`):v,ae=S(_)?typeof n==`function`?n(ie,b):ie:ie+(d?`.`+b:`[`+b+`]`);ee.set(e,y);let x=new WeakMap;x.set(et,ee),Qe(ne,Je(te,ae,n,r,i,a,o,s,n===`comma`&&h&&S(_)?null:c,l,u,d,f,p,m,h,g,x))}return ne}function Ye(e=w){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||w.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=Le;if(e.format!==void 0){if(!Ue(ze,e.format))throw TypeError(`Unknown format option provided.`);n=e.format}let r=ze[n],i=w.filter;(typeof e.filter==`function`||S(e.filter))&&(i=e.filter);let a;if(a=e.arrayFormat&&e.arrayFormat in Ze?e.arrayFormat:`indices`in e?e.indices?`indices`:`repeat`:w.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:w.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix==`boolean`?e.addQueryPrefix:w.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays==`boolean`?!!e.allowEmptyArrays:w.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel==`boolean`?e.charsetSentinel:w.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:e.delimiter===void 0?w.delimiter:e.delimiter,encode:typeof e.encode==`boolean`?e.encode:w.encode,encodeDotInKeys:typeof e.encodeDotInKeys==`boolean`?e.encodeDotInKeys:w.encodeDotInKeys,encoder:typeof e.encoder==`function`?e.encoder:w.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==`boolean`?e.encodeValuesOnly:w.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:typeof e.serializeDate==`function`?e.serializeDate:w.serializeDate,skipNulls:typeof e.skipNulls==`boolean`?e.skipNulls:w.skipNulls,sort:typeof e.sort==`function`?e.sort:null,strictNullHandling:typeof e.strictNullHandling==`boolean`?e.strictNullHandling:w.strictNullHandling}}function Xe(e,t={}){let n=e,r=Ye(t),i,a;typeof r.filter==`function`?(a=r.filter,n=a(``,n)):S(r.filter)&&(a=r.filter,i=a);let o=[];if(typeof n!=`object`||!n)return``;let s=Ze[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||Qe(o,Je(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 Ze,Qe,$e,w,et,tt=e((()=>{Ke(),Be(),he(),Ze={brackets(e){return String(e)+`[]`},comma:`comma`,indices(e,t){return String(e)+`[`+t+`]`},repeat(e){return String(e)}},Qe=function(e,t){Array.prototype.push.apply(e,S(t)?t:[t])},w={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:`indices`,charset:`utf-8`,charsetSentinel:!1,delimiter:`&`,encode:!0,encodeDotInKeys:!1,encoder:Ge,encodeValuesOnly:!1,format:Le,formatter:Re,indices:!1,serializeDate(e){return($e??($e=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1},et={}}));function nt(e){return Xe(e,{arrayFormat:`brackets`})}var rt=e((()=>{tt()}));function it(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 at(e){let t;return(st??(t=new globalThis.TextEncoder,st=t.encode.bind(t)))(e)}function ot(e){let t;return(ct??(t=new globalThis.TextDecoder,ct=t.decode.bind(t)))(e)}var st,ct,lt=e((()=>{}));function ut(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 dt(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 T,E,ft,pt=e((()=>{r(),lt(),ft=class{constructor(){T.set(this,void 0),E.set(this,void 0),t(this,T,new Uint8Array,`f`),t(this,E,null,`f`)}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==`string`?at(e):e;t(this,T,it([n(this,T,`f`),r]),`f`);let i=[],a;for(;(a=ut(n(this,T,`f`),n(this,E,`f`)))!=null;){if(a.carriage&&n(this,E,`f`)==null){t(this,E,a.index,`f`);continue}if(n(this,E,`f`)!=null&&(a.index!==n(this,E,`f`)+1||a.carriage)){i.push(ot(n(this,T,`f`).subarray(0,n(this,E,`f`)-1))),t(this,T,n(this,T,`f`).subarray(n(this,E,`f`)),`f`),t(this,E,null,`f`);continue}let e=n(this,E,`f`)===null?a.preceding:a.preceding-1,r=ot(n(this,T,`f`).subarray(0,e));i.push(r),t(this,T,n(this,T,`f`).subarray(a.index),`f`),t(this,E,null,`f`)}return i}flush(){return n(this,T,`f`).length?this.decode(`
2
+ `):[]}},T=new WeakMap,E=new WeakMap,ft.NEWLINE_CHARS=new Set([`
3
+ `,`\r`]),ft.NEWLINE_REGEXP=/\r\n|[\n\r]/g}));function mt(){}function ht(e,t,n){return!t||gt[e]>gt[n]?mt:t[e].bind(t)}function D(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return vt;let r=yt.get(t);if(r&&r[0]===n)return r[1];let i={error:ht(`error`,t,n),warn:ht(`warn`,t,n),info:ht(`info`,t,n),debug:ht(`debug`,t,n)};return yt.set(t,[n,i]),i}var gt,_t,vt,yt,bt,xt=e((()=>{he(),gt={off:0,error:200,warn:300,info:400,debug:500},_t=(e,t,n)=>{if(e){if(ce(gt,e))return e;D(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(gt))}`)}},vt={error:mt,warn:mt,info:mt,debug:mt},yt=new WeakMap,bt=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*St(e,t){if(!e.body)throw t.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new l(`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 l(`Attempted to iterate over a response with no body`);let n=new Dt,r=new ft,i=Me(e.body);for await(let e of Ct(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*Ct(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`?at(n):n,r=new Uint8Array(t.length+e.length);r.set(t),r.set(e,t.length),t=r;let i;for(;(i=dt(t))!==-1;)yield t.slice(0,i),t=t.slice(i)}t.length>0&&(yield t)}function wt(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.substring(0,n),t,e.substring(n+t.length)]}var Tt,Et,Dt,Ot=e((()=>{r(),x(),Pe(),pt(),c(),lt(),xt(),Et=class e{constructor(e,n,r){this.iterator=e,Tt.set(this,void 0),this.controller=n,t(this,Tt,r,`f`)}static fromSSEResponse(t,n,r,i){let a=!1,s=r?D(r):console;async function*c(){if(a)throw new l("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");a=!0;let e=!1;try{for await(let r of St(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 s.error(`Could not parse message into JSON:`,r.data),s.error(`From chunk:`,r.raw),e}if(e&&e.error)throw new u(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 u(void 0,e.error,e.message,void 0);yield{event:r.event,data:e}}}e=!0}catch(e){if(o(e))return;throw e}finally{e||n.abort()}}return new e(c,n,r)}static fromReadableStream(t,n,r){let i=!1;async function*a(){let e=new ft,n=Me(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*s(){if(i)throw new l("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(o(e))return;throw e}finally{e||n.abort()}}return new e(s,n,r)}[(Tt=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let t=[],r=[],i=this.iterator(),a=e=>({next:()=>{if(e.length===0){let e=i.next();t.push(e),r.push(e)}return e.shift()}});return[new e(()=>a(t),this.controller,n(this,Tt,`f`)),new e(()=>a(r),this.controller,n(this,Tt,`f`))]}toReadableStream(){let e=this,t;return Ae({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=at(JSON.stringify(n)+`
4
+ `);e.enqueue(i)}catch(t){e.error(t)}},async cancel(){await t.return?.()}})}},Dt=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]=wt(e,`:`);return r.startsWith(` `)&&(r=r.substring(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}}}));async function kt(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(t.options.stream)return D(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):Et.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:At(await n.json(),n):await n.text()})();return D(e).debug(`[${r}] response parsed`,bt({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}function At(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 jt=e((()=>{Ot(),xt()})),Mt,Nt,Pt=e((()=>{r(),jt(),Nt=class e extends Promise{constructor(e,n,r=kt){super(e=>{e(null)}),this.responsePromise=n,this.parseResponse=r,Mt.set(this,void 0),t(this,Mt,e,`f`)}_thenUnwrap(t){return new e(n(this,Mt,`f`),this.responsePromise,async(e,n)=>At(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(n(this,Mt,`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)}},Mt=new WeakMap})),Ft,It,Lt,Rt,O,k,A,j=e((()=>{r(),x(),jt(),Pt(),he(),It=class{constructor(e,n,r,i){Ft.set(this,void 0),t(this,Ft,e,`f`),this.options=i,this.response=n,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new l("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await n(this,Ft,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Ft=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Lt=class extends Nt{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await kt(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},Rt=class extends It{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}},O=class extends It{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:{...oe(this.options.query),after:t}}:null}},k=class extends It{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:{...oe(this.options.query),after:e}}:null}},A=class extends It{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:{...oe(this.options.query),after:e}}:null}}})),zt,Bt,Vt,Ht=e((()=>{Pe(),x(),zt={jwt:`urn:ietf:params:oauth:token-type:jwt`,id:`urn:ietf:params:oauth:token-type:id_token`},Bt=`urn:ietf:params:oauth:grant-type:token-exchange`,Vt=class{constructor(e,t){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl=`https://auth.openai.com/oauth/token`,this.config=e,this.fetch=t??ke()}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:Bt,subject_token:e,subject_token_type:zt[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 ie(n.status,t,n.headers):u.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 l(`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 Ut(e,t,n){return Kt(),new File(e,t??`unknown_file`,n)}function Wt(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 Gt(e){let t=typeof e==`function`?e:e.fetch,n=Yt.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 Yt.set(t,r),r}var Kt,qt,Jt,M,Yt,Xt,Zt,Qt,$t,en,N=e((()=>{Pe(),Kt=()=>{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`,Jt=async(e,t)=>$t(e.body)?{...e,body:await Xt(e.body,t)}:e,M=async(e,t)=>({...e,body:await Xt(e.body,t)}),Yt=new WeakMap,Xt=async(e,t)=>{if(!await Gt(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])=>en(n,e,t))),n},Zt=e=>e instanceof Blob&&`name`in e,Qt=e=>typeof e==`object`&&!!e&&(e instanceof Response||qt(e)||Zt(e)),$t=e=>{if(Qt(e))return!0;if(Array.isArray(e))return e.some($t);if(e&&typeof e==`object`){for(let t in e)if($t(e[t]))return!0}return!1},en=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,Ut([await n.blob()],Wt(n)));else if(qt(n))e.append(t,Ut([await new Response(je(n)).blob()],Wt(n)));else if(Zt(n))e.append(t,n,Wt(n));else if(Array.isArray(n))await Promise.all(n.map(n=>en(e,t+`[]`,n)));else if(typeof n==`object`)await Promise.all(Object.entries(n).map(([n,r])=>en(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 tn(e,t,n){if(Kt(),e=await e,on(e))return e instanceof File?e:Ut([await e.arrayBuffer()],e.name);if(sn(e)){let r=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),Ut(await nn(r),t,n)}let r=await nn(e);if(t||(t=Wt(e)),!n?.type){let e=r.find(e=>typeof e==`object`&&`type`in e&&e.type);typeof e==`string`&&(n={...n,type:e})}return Ut(r,t,n)}async function nn(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(an(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(qt(e))for await(let n of e)t.push(...await nn(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${rn(e)}`)}return t}function rn(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var an,on,sn,cn=e((()=>{N(),an=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`,on=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&an(e),sn=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`})),ln=e((()=>{cn()})),P,F=e((()=>{P=class{constructor(e){this._client=e}}}));function un(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var dn,fn,I,L=e((()=>{x(),dn=Object.freeze(Object.create(null)),fn=(e=un)=>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??dn)??dn)?.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 l(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
6
+ `)}\n${a}\n${t}`)}return a},I=fn(un)})),pn,mn=e((()=>{F(),j(),L(),pn=class extends P{list(e,t={},n){return this._client.getAPIList(I`/chat/completions/${e}/messages`,O,{query:t,...n,__security:{bearerAuth:!0}})}}})),R=e((()=>{x()}));function hn(e){return e!==void 0&&`function`in e&&e.function!==void 0}function gn(e){return e?.$brand===`auto-parseable-response-format`}function _n(e){return e?.$brand===`auto-parseable-tool`}function vn(e,t){return!t||!Cn(t)?{...e,choices:e.choices.map(e=>(wn(e.message.tool_calls),{...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}}))}:yn(e,t)}function yn(e,t){let n=e.choices.map(e=>{if(e.finish_reason===`length`)throw new ne;if(e.finish_reason===`content_filter`)throw new re;return wn(e.message.tool_calls),{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map(e=>xn(t,e))??void 0}:void 0,parsed:e.message.content&&!e.message.refusal?bn(t,e.message.content):null}}});return{...e,choices:n}}function bn(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 xn(e,t){let n=e.tools?.find(e=>hn(e)&&e.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:_n(n)?n.$parseRaw(t.function.arguments):n?.function.strict?JSON.parse(t.function.arguments):null}}}function Sn(e,t){if(!e||!(`tools`in e)||!e.tools)return!1;let n=e.tools?.find(e=>hn(e)&&e.function?.name===t.function.name);return hn(n)&&(_n(n)||n?.function.strict||!1)}function Cn(e){return gn(e.response_format)?!0:e.tools?.some(e=>_n(e)||e.type===`function`&&e.function.strict===!0)??!1}function wn(e){for(let t of e||[])if(t.type!==`function`)throw new l(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}function Tn(e){for(let t of e??[]){if(t.type!==`function`)throw new l(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(t.function.strict!==!0)throw new l(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var En=e((()=>{R()})),Dn,On,kn=e((()=>{Dn=e=>e?.role===`assistant`,On=e=>e?.role===`tool`})),An,jn,Mn,Nn,Pn,Fn,In,Ln,Rn,zn,Bn,Vn,Hn,Un,Wn,Gn,Kn=e((()=>{r(),R(),Gn=class{constructor(){An.add(this),this.controller=new AbortController,jn.set(this,void 0),Mn.set(this,()=>{}),Nn.set(this,()=>{}),Pn.set(this,void 0),Fn.set(this,()=>{}),In.set(this,()=>{}),Ln.set(this,{}),Rn.set(this,[]),zn.set(this,!1),Bn.set(this,!1),Vn.set(this,!1),Hn.set(this,!1),t(this,jn,new Promise((e,n)=>{t(this,Mn,e,`f`),t(this,Nn,n,`f`)}),`f`),t(this,Pn,new Promise((e,n)=>{t(this,Fn,e,`f`),t(this,In,n,`f`)}),`f`),n(this,jn,`f`).catch(()=>{}),n(this,Pn,`f`).catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit(`end`)},n(this,An,`m`,Wn).bind(this))},0)}_connected(){this.ended||(n(this,Mn,`f`).call(this),this._emit(`connect`))}get ended(){return n(this,zn,`f`)}get errored(){return n(this,Bn,`f`)}get aborted(){return n(this,Vn,`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}),n(this,Rn,`f`).push({signal:e,listener:t})}on(e,t){return(n(this,Ln,`f`)[e]||(n(this,Ln,`f`)[e]=[])).push({listener:t}),this}off(e,t){let r=n(this,Ln,`f`)[e];if(!r)return this;let i=r.findIndex(e=>e.listener===t);return i>=0&&r.splice(i,1),this}once(e,t){return(n(this,Ln,`f`)[e]||(n(this,Ln,`f`)[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((n,r)=>{t(this,Hn,!0,`f`),e!==`error`&&this.once(`error`,r),this.once(e,n)})}async done(){t(this,Hn,!0,`f`),await n(this,Pn,`f`)}_emit(e,...r){if(n(this,zn,`f`))return;e===`end`&&(n(this,An,`m`,Un).call(this),t(this,zn,!0,`f`),n(this,Fn,`f`).call(this));let i=n(this,Ln,`f`)[e];if(i&&(n(this,Ln,`f`)[e]=i.filter(e=>!e.once),i.forEach(({listener:e})=>e(...r))),e===`abort`){let e=r[0];!n(this,Hn,`f`)&&!i?.length&&Promise.reject(e),n(this,Nn,`f`).call(this,e),n(this,In,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=r[0];!n(this,Hn,`f`)&&!i?.length&&Promise.reject(e),n(this,Nn,`f`).call(this,e),n(this,In,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){}},jn=new WeakMap,Mn=new WeakMap,Nn=new WeakMap,Pn=new WeakMap,Fn=new WeakMap,In=new WeakMap,Ln=new WeakMap,Rn=new WeakMap,zn=new WeakMap,Bn=new WeakMap,Vn=new WeakMap,Hn=new WeakMap,An=new WeakSet,Un=function(){for(let{signal:e,listener:t}of n(this,Rn,`f`).splice(0))e.removeEventListener(`abort`,t)},Wn=function(e){if(t(this,Bn,!0,`f`),e instanceof Error&&e.name===`AbortError`&&(e=new d),e instanceof d)return t(this,Vn,!0,`f`),this._emit(`abort`,e);if(e instanceof l)return this._emit(`error`,e);if(e instanceof Error){let t=new l(e.message);return t.cause=e,this._emit(`error`,t)}return this._emit(`error`,new l(String(e)))}}));function qn(e){return typeof e.parse==`function`}var Jn=e((()=>{}));function Yn(e){for(let t of e.choices)for(let e of t.message.tool_calls??[])e.id||(e.id=`call_${i()}`)}var z,Xn,Zn,Qn,$n,er,tr,nr,rr,ir,ar=e((()=>{r(),R(),a(),En(),kn(),Kn(),Jn(),rr=10,ir=class extends Gn{constructor(){super(...arguments),z.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){Yn(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),On(e)&&e.content)this._emit(`functionToolCallResult`,e.content);else if(Dn(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 l(`stream ended without producing a ChatCompletion`);return e}async finalContent(){return await this.done(),n(this,z,`m`,Xn).call(this)}async finalMessage(){return await this.done(),n(this,z,`m`,Zn).call(this)}async finalFunctionToolCall(){return await this.done(),n(this,z,`m`,Qn).call(this)}async finalFunctionToolCallResult(){return await this.done(),n(this,z,`m`,$n).call(this)}async totalUsage(){return await this.done(),n(this,z,`m`,er).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit(`finalChatCompletion`,e);let t=n(this,z,`m`,Zn).call(this);t&&this._emit(`finalMessage`,t);let r=n(this,z,`m`,Xn).call(this);r&&this._emit(`finalContent`,r);let i=n(this,z,`m`,Qn).call(this);i&&this._emit(`finalFunctionToolCall`,i);let a=n(this,z,`m`,$n).call(this);a!=null&&this._emit(`finalFunctionToolCallResult`,a),this._chatCompletions.some(e=>e.usage)&&this._emit(`totalUsage`,n(this,z,`m`,er).call(this))}async _createChatCompletion(e,t,r){this._listenForAbort(r?.signal),n(this,z,`m`,tr).call(this,t);let i=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(yn(i,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,r,i){let a=`tool`,{tool_choice:o=`auto`,stream:s,...c}=t,u=typeof o!=`string`&&o.type===`function`&&o?.function?.name,{maxChatCompletions:d=rr,afterCompletion:f}=i||{},p=t.tools.map(e=>{if(_n(e)){if(!e.$callback)throw new l("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 p)e.type===`function`&&(m[e.function.name||e.function.function.name]=e.function);let h=`tools`in t?p.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:i,arguments:o}=e.function,s=m[i];if(!s){let e=`Invalid tool_call: ${JSON.stringify(i)}. Available options are: ${Object.keys(m).map(e=>JSON.stringify(e)).join(`, `)}. Please try again`;return{message:{role:a,tool_call_id:t,content:e},functionCalled:!1}}if(u&&u!==i){let e=`Invalid tool_call: ${JSON.stringify(i)}. ${JSON.stringify(u)} requested. Please try again`;return{message:{role:a,tool_call_id:t,content:e},functionCalled:!1}}let c;if(qn(s)){let e;try{e=await s.parse(o)}catch(e){let n=e instanceof Error?e.message:String(e);return{message:{role:a,tool_call_id:t,content:n},functionCalled:!1}}c=await s.function(e,r)}else c=await s.function(o,r);let l=n(this,z,`m`,nr).call(this,c);return{message:{role:a,tool_call_id:t,content:l},functionCalled:!0}};for(let n=0;n<d;++n){let n=await this._createChatCompletion(e,{...c,tool_choice:o,tools:h,messages:[...this.messages]},i),a=n.choices[0]?.message;if(!a)throw new l(`missing message in ChatCompletion response`);if(!a.tool_calls?.length){await f?.(n,r);return}if(u||t.parallel_tool_calls===!1)for(let e of a.tool_calls){let t=await g(e);if(t.message&&this._addMessage(t.message),u&&t.functionCalled){await f?.(n,r);return}}else{let e=await Promise.allSettled(a.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 f?.(n,r)}}},z=new WeakSet,Xn=function(){return n(this,z,`m`,Zn).call(this).content??null},Zn=function(){let e=this.messages.length;for(;e-->0;){let t=this.messages[e];if(Dn(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new l(`stream ended without producing a ChatCompletionMessage with role=assistant`)},Qn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Dn(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}}},$n=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(On(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}},er=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},tr=function(e){if(e.n!=null&&e.n>1)throw new l(`ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.`)},nr=function(e){return typeof e==`string`?e:e===void 0?`undefined`:JSON.stringify(e)}})),or,sr=e((()=>{ar(),kn(),or=class e extends ir{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),Dn(e)&&e.content&&this._emit(`content`,e.content)}}}));function cr(e,t=B.ALL){if(typeof e!=`string`)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return dr(e.trim(),t)}var B,lr,ur,dr,fr,pr=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},lr=class extends Error{},ur=class extends Error{},dr=(e,t)=>{let n=e.length,r=0,i=e=>{throw new lr(`${e} at position ${r}`)},a=e=>{throw new ur(`${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()},fr=e=>cr(e,B.ALL^B.NUM)})),mr=e((()=>{Ot()}));function hr(e,t){let{id:n,choices:r,created:a,model:o,system_fingerprint:s,...c}=e;return vn({...c,id:n,choices:r.map(({message:t,finish_reason:n,index:r,logprobs:a,...o})=>{if(!n)throw new l(`missing finish_reason for choice ${r}`);let{content:s=null,function_call:c,tool_calls:u,...d}=t,f=t.role;if(!f)throw new l(`missing role for choice ${r}`);if(c){let{arguments:e,name:i}=c;if(e==null)throw new l(`missing function_call.arguments for choice ${r}`);if(!i)throw new l(`missing function_call.name for choice ${r}`);return{...o,message:{content:s,function_call:{arguments:e,name:i},role:f,refusal:t.refusal??null},finish_reason:n,index:r,logprobs:a}}return u?{...o,index:r,finish_reason:n,logprobs:a,message:{...d,role:f,content:s,refusal:t.refusal??null,tool_calls:u.map((t,n)=>{let{function:a,type:o,id:s,...c}=t,{arguments:u,name:d,...f}=a||{};if(o==null)throw new l(`missing choices[${r}].tool_calls[${n}].type\n${gr(e)}`);if(d==null)throw new l(`missing choices[${r}].tool_calls[${n}].function.name\n${gr(e)}`);if(u==null)throw new l(`missing choices[${r}].tool_calls[${n}].function.arguments\n${gr(e)}`);return{...c,id:s||`call_${i()}`,type:o,function:{...f,name:d,arguments:u}}})}}:{...o,message:{...d,content:s,role:f,refusal:t.refusal??null},finish_reason:n,index:r,logprobs:a}}),created:a,model:o,object:`chat.completion`,...s?{system_fingerprint:s}:{}},t)}function gr(e){return JSON.stringify(e)}var V,_r,vr,yr,br,xr,Sr,Cr,wr,Tr,Er,Dr,Or,kr=e((()=>{r(),pr(),R(),a(),En(),mr(),ar(),Or=class e extends ir{constructor(e){super(),V.add(this),_r.set(this,void 0),vr.set(this,void 0),yr.set(this,void 0),t(this,_r,e,`f`),t(this,vr,[],`f`)}get currentChatCompletionSnapshot(){return n(this,yr,`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,r){super._createChatCompletion,this._listenForAbort(r?.signal),n(this,V,`m`,br).call(this);let i=await e.chat.completions.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let e of i)n(this,V,`m`,Sr).call(this,e);if(i.controller.signal?.aborted)throw new d;return this._addChatCompletion(n(this,V,`m`,Tr).call(this))}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),n(this,V,`m`,br).call(this),this._connected();let r=Et.fromReadableStream(e,this.controller),i;for await(let e of r)i&&i!==e.id&&this._addChatCompletion(n(this,V,`m`,Tr).call(this)),n(this,V,`m`,Sr).call(this,e),i=e.id;if(r.controller.signal?.aborted)throw new d;return this._addChatCompletion(n(this,V,`m`,Tr).call(this))}[(_r=new WeakMap,vr=new WeakMap,yr=new WeakMap,V=new WeakSet,br=function(){this.ended||t(this,yr,void 0,`f`)},xr=function(e){let t=n(this,vr,`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},n(this,vr,`f`)[e.index]=t,t)},Sr=function(e){if(this.ended)return;let t=n(this,V,`m`,Dr).call(this,e);this._emit(`chunk`,e,t);for(let r of e.choices){let e=t.choices[r.index];r.delta.content!=null&&e.message?.role===`assistant`&&e.message?.content&&(this._emit(`content`,r.delta.content,e.message.content),this._emit(`content.delta`,{delta:r.delta.content,snapshot:e.message.content,parsed:e.message.parsed})),r.delta.refusal!=null&&e.message?.role===`assistant`&&e.message?.refusal&&this._emit(`refusal.delta`,{delta:r.delta.refusal,snapshot:e.message.refusal}),r.logprobs?.content!=null&&e.message?.role===`assistant`&&this._emit(`logprobs.content.delta`,{content:r.logprobs?.content,snapshot:e.logprobs?.content??[]}),r.logprobs?.refusal!=null&&e.message?.role===`assistant`&&this._emit(`logprobs.refusal.delta`,{refusal:r.logprobs?.refusal,snapshot:e.logprobs?.refusal??[]});let i=n(this,V,`m`,xr).call(this,e);e.finish_reason&&(n(this,V,`m`,wr).call(this,e),i.current_tool_call_index!=null&&n(this,V,`m`,Cr).call(this,e,i.current_tool_call_index));for(let t of r.delta.tool_calls??[])i.current_tool_call_index!==t.index&&(n(this,V,`m`,wr).call(this,e),i.current_tool_call_index!=null&&n(this,V,`m`,Cr).call(this,e,i.current_tool_call_index)),i.current_tool_call_index=t.index;for(let t of r.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)}}},Cr=function(e,t){if(n(this,V,`m`,xr).call(this,e).done_tool_calls.has(t))return;let r=e.message.tool_calls?.[t];if(!r)throw Error(`no tool call snapshot`);if(!r.type)throw Error("tool call snapshot missing `type`");if(r.type===`function`){let e=n(this,_r,`f`)?.tools?.find(e=>hn(e)&&e.function.name===r.function.name);this._emit(`tool_calls.function.arguments.done`,{name:r.function.name,index:t,arguments:r.function.arguments,parsed_arguments:_n(e)?e.$parseRaw(r.function.arguments):e?.function.strict?JSON.parse(r.function.arguments):null})}else r.type},wr=function(e){let t=n(this,V,`m`,xr).call(this,e);if(e.message.content&&!t.content_done){t.content_done=!0;let r=n(this,V,`m`,Er).call(this);this._emit(`content.done`,{content:e.message.content,parsed:r?r.$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}))},Tr=function(){if(this.ended)throw new l(`stream has ended, this shouldn't happen`);let e=n(this,yr,`f`);if(!e)throw new l(`request ended without sending any chunks`);return t(this,yr,void 0,`f`),t(this,vr,[],`f`),hr(e,n(this,_r,`f`))},Er=function(){let e=n(this,_r,`f`)?.response_format;return gn(e)?e:null},Dr=function(e){var r,i,a,o;let s=n(this,yr,`f`),{choices:c,...l}=e;s?Object.assign(s,l):s=t(this,yr,{...l,choices:[]},`f`);for(let{delta:t,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:t,refusal:n,...a}=u;Object.assign(e.logprobs,a),t&&((r=e.logprobs).content??(r.content=[]),e.logprobs.content.push(...t)),n&&((i=e.logprobs).refusal??(i.refusal=[]),e.logprobs.refusal.push(...n))}if(c&&(e.finish_reason=c,n(this,_r,`f`)&&Cn(n(this,_r,`f`)))){if(c===`length`)throw new ne;if(c===`content_filter`)throw new re}if(Object.assign(e,d),!t)continue;let{content:f,refusal:p,function_call:m,role:h,tool_calls:g,...ee}=t;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&&((a=e.message.function_call).arguments??(a.arguments=``),e.message.function_call.arguments+=m.arguments)):e.message.function_call=m),f&&(e.message.content=(e.message.content||``)+f,!e.message.refusal&&n(this,V,`m`,Er).call(this)&&(e.message.parsed=e.message.content.trim()?fr(e.message.content):null)),g){e.message.tool_calls||(e.message.tool_calls=[]);for(let{index:t,id:r,type:i,function:a,...s}of g){let c=(o=e.message.tool_calls)[t]??(o[t]={});Object.assign(c,s),r&&(c.id=r),i&&(c.type=i),a&&(c.function??(c.function={name:a.name??``,arguments:``})),a?.name&&(c.function.name=a.name),a?.arguments&&(c.function.arguments+=a.arguments,Sn(n(this,_r,`f`),c)&&(c.function.parsed_arguments=fr(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 Et(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}})),Ar,jr=e((()=>{kr(),Ar=class e extends Or{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}}})),Mr,Nr=e((()=>{F(),mn(),j(),L(),sr(),jr(),kr(),En(),Jn(),Mr=class extends P{constructor(){super(...arguments),this.messages=new pn(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(I`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(I`/chat/completions/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/chat/completions`,O,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(I`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}parse(e,t){return Tn(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":`chat.completions.parse`}})._thenUnwrap(t=>yn(t,e))}runTools(e,t){return e.stream?Ar.runTools(this._client,e,t):or.runTools(this._client,e,t)}stream(e,t){return Or.createChatCompletion(this._client,e,t)}},Mr.Messages=pn})),Pr,Fr=e((()=>{F(),Nr(),Pr=class extends P{constructor(){super(...arguments),this.completions=new Mr(this._client)}},Pr.Completions=Mr})),Ir=e((()=>{Nr(),Nr(),mn()})),Lr=e((()=>{Fr(),Ir()})),Rr=e((()=>{})),zr,Br=e((()=>{F(),j(),L(),zr=class extends P{create(e,t){return this._client.post(`/organization/admin_api_keys`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(I`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/admin_api_keys`,O,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(I`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}}})),Vr,Hr=e((()=>{F(),j(),Vr=class extends P{list(e={},t){return this._client.getAPIList(`/organization/audit_logs`,k,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}}})),Ur,Wr=e((()=>{F(),j(),L(),Ur=class extends P{create(e,t){return this._client.post(`/organization/certificates`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},n){return this._client.get(I`/organization/certificates/${e}`,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(I`/organization/certificates/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/certificates`,k,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(I`/organization/certificates/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}activate(e,t){return this._client.getAPIList(`/organization/certificates/activate`,Rt,{body:e,method:`post`,...t,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t){return this._client.getAPIList(`/organization/certificates/deactivate`,Rt,{body:e,method:`post`,...t,__security:{adminAPIKeyAuth:!0}})}}})),Gr,Kr=e((()=>{F(),Gr=class extends P{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}})}}})),qr,Jr=e((()=>{F(),j(),L(),qr=class extends P{create(e,t){return this._client.post(`/organization/invites`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(I`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/invites`,k,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(I`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}}})),Yr,Xr=e((()=>{F(),j(),L(),Yr=class extends P{create(e,t){return this._client.post(`/organization/roles`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(I`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(I`/organization/roles/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/roles`,A,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(I`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}}})),Zr,Qr=e((()=>{F(),j(),L(),Zr=class extends P{create(e,t){return this._client.post(`/organization/spend_alerts`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(I`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(I`/organization/spend_alerts/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/spend_alerts`,k,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(I`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}}})),$r,ei=e((()=>{F(),$r=class extends P{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}})}}})),ti,ni=e((()=>{F(),j(),L(),ti=class extends P{create(e,t,n){return this._client.post(I`/organization/groups/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{group_id:r}=t;return this._client.get(I`/organization/groups/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/organization/groups/${e}/roles`,A,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{group_id:r}=t;return this._client.delete(I`/organization/groups/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}})),ri,ii=e((()=>{F(),j(),L(),ri=class extends P{create(e,t,n){return this._client.post(I`/organization/groups/${e}/users`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{group_id:r}=t;return this._client.get(I`/organization/groups/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/organization/groups/${e}/users`,A,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{group_id:r}=t;return this._client.delete(I`/organization/groups/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}})),ai,oi=e((()=>{F(),ni(),ii(),j(),L(),ai=class extends P{constructor(){super(...arguments),this.users=new ri(this._client),this.roles=new ti(this._client)}create(e,t){return this._client.post(`/organization/groups`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(I`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(I`/organization/groups/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/groups`,A,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(I`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},ai.Users=ri,ai.Roles=ti})),si,ci=e((()=>{F(),j(),L(),si=class extends P{retrieve(e,t,n){let{project_id:r}=t;return this._client.get(I`/organization/projects/${r}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/organization/projects/${e}/api_keys`,k,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(I`/organization/projects/${r}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}})),li,ui=e((()=>{F(),j(),L(),li=class extends P{list(e,t={},n){return this._client.getAPIList(I`/organization/projects/${e}/certificates`,k,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}activate(e,t,n){return this._client.getAPIList(I`/organization/projects/${e}/certificates/activate`,Rt,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t,n){return this._client.getAPIList(I`/organization/projects/${e}/certificates/deactivate`,Rt,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}}})),di,fi=e((()=>{F(),L(),di=class extends P{retrieve(e,t){return this._client.get(I`/organization/projects/${e}/data_retention`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(I`/organization/projects/${e}/data_retention`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}}})),pi,mi=e((()=>{F(),L(),pi=class extends P{retrieve(e,t){return this._client.get(I`/organization/projects/${e}/hosted_tool_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(I`/organization/projects/${e}/hosted_tool_permissions`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}}})),hi,gi=e((()=>{F(),L(),hi=class extends P{retrieve(e,t){return this._client.get(I`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(I`/organization/projects/${e}/model_permissions`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(I`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}}})),_i,vi=e((()=>{F(),j(),L(),_i=class extends P{listRateLimits(e,t={},n){return this._client.getAPIList(I`/organization/projects/${e}/rate_limits`,k,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,t,n){let{project_id:r,...i}=t;return this._client.post(I`/organization/projects/${r}/rate_limits/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}}})),yi,bi=e((()=>{F(),j(),L(),yi=class extends P{create(e,t,n){return this._client.post(I`/projects/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(I`/projects/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(I`/projects/${r}/roles/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/projects/${e}/roles`,A,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(I`/projects/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}})),xi,Si=e((()=>{F(),j(),L(),xi=class extends P{create(e,t,n){return this._client.post(I`/organization/projects/${e}/service_accounts`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(I`/organization/projects/${r}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(I`/organization/projects/${r}/service_accounts/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/organization/projects/${e}/service_accounts`,k,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(I`/organization/projects/${r}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}})),Ci,wi=e((()=>{F(),j(),L(),Ci=class extends P{create(e,t,n){return this._client.post(I`/organization/projects/${e}/spend_alerts`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(I`/organization/projects/${r}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(I`/organization/projects/${r}/spend_alerts/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/organization/projects/${e}/spend_alerts`,k,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(I`/organization/projects/${r}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}})),Ti,Ei=e((()=>{F(),j(),L(),Ti=class extends P{create(e,t,n){let{project_id:r,...i}=t;return this._client.post(I`/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(I`/projects/${r}/groups/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t,n){let{project_id:r,...i}=t;return this._client.getAPIList(I`/projects/${r}/groups/${e}/roles`,A,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r,group_id:i}=t;return this._client.delete(I`/projects/${r}/groups/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}})),Di,Oi=e((()=>{F(),Ei(),j(),L(),Di=class extends P{constructor(){super(...arguments),this.roles=new Ti(this._client)}create(e,t,n){return this._client.post(I`/organization/projects/${e}/groups`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r,...i}=t;return this._client.get(I`/organization/projects/${r}/groups/${e}`,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/organization/projects/${e}/groups`,A,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(I`/organization/projects/${r}/groups/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},Di.Roles=Ti})),ki,Ai=e((()=>{F(),j(),L(),ki=class extends P{create(e,t,n){let{project_id:r,...i}=t;return this._client.post(I`/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(I`/projects/${r}/users/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t,n){let{project_id:r,...i}=t;return this._client.getAPIList(I`/projects/${r}/users/${e}/roles`,A,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r,user_id:i}=t;return this._client.delete(I`/projects/${r}/users/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}})),ji,Mi=e((()=>{F(),Ai(),j(),L(),ji=class extends P{constructor(){super(...arguments),this.roles=new ki(this._client)}create(e,t,n){return this._client.post(I`/organization/projects/${e}/users`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(I`/organization/projects/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(I`/organization/projects/${r}/users/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/organization/projects/${e}/users`,k,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(I`/organization/projects/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},ji.Roles=ki})),H,Ni=e((()=>{F(),ci(),ui(),fi(),mi(),gi(),vi(),bi(),Si(),wi(),Oi(),Mi(),j(),L(),H=class extends P{constructor(){super(...arguments),this.users=new ji(this._client),this.serviceAccounts=new xi(this._client),this.apiKeys=new si(this._client),this.rateLimits=new _i(this._client),this.modelPermissions=new hi(this._client),this.hostedToolPermissions=new pi(this._client),this.groups=new Di(this._client),this.roles=new yi(this._client),this.dataRetention=new di(this._client),this.spendAlerts=new Ci(this._client),this.certificates=new li(this._client)}create(e,t){return this._client.post(`/organization/projects`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(I`/organization/projects/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(I`/organization/projects/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/projects`,k,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}archive(e,t){return this._client.post(I`/organization/projects/${e}/archive`,{...t,__security:{adminAPIKeyAuth:!0}})}},H.Users=ji,H.ServiceAccounts=xi,H.APIKeys=si,H.RateLimits=_i,H.ModelPermissions=hi,H.HostedToolPermissions=pi,H.Groups=Di,H.Roles=yi,H.DataRetention=di,H.SpendAlerts=Ci,H.Certificates=li})),Pi,Fi=e((()=>{F(),j(),L(),Pi=class extends P{create(e,t,n){return this._client.post(I`/organization/users/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{user_id:r}=t;return this._client.get(I`/organization/users/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/organization/users/${e}/roles`,A,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{user_id:r}=t;return this._client.delete(I`/organization/users/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}})),Ii,Li=e((()=>{F(),Fi(),j(),L(),Ii=class extends P{constructor(){super(...arguments),this.roles=new Pi(this._client)}retrieve(e,t){return this._client.get(I`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(I`/organization/users/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/users`,k,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(I`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},Ii.Roles=Pi})),U,Ri=e((()=>{F(),Br(),Hr(),Wr(),Kr(),Jr(),Xr(),Qr(),ei(),oi(),Ni(),Li(),U=class extends P{constructor(){super(...arguments),this.auditLogs=new Vr(this._client),this.adminAPIKeys=new zr(this._client),this.usage=new $r(this._client),this.invites=new qr(this._client),this.users=new Ii(this._client),this.groups=new ai(this._client),this.roles=new Yr(this._client),this.dataRetention=new Gr(this._client),this.spendAlerts=new Zr(this._client),this.certificates=new Ur(this._client),this.projects=new H(this._client)}},U.AuditLogs=Vr,U.AdminAPIKeys=zr,U.Usage=$r,U.Invites=qr,U.Users=Ii,U.Groups=ai,U.Roles=Yr,U.DataRetention=Gr,U.SpendAlerts=Zr,U.Certificates=Ur,U.Projects=H})),zi,Bi=e((()=>{F(),Ri(),zi=class extends P{constructor(){super(...arguments),this.organization=new U(this._client)}},zi.Organization=U}));function*Vi(e){if(!e)return;if(Hi 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():fe(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=fe(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 Hi,W,G=e((()=>{he(),Hi=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 Vi(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{[Hi]:!0,values:t,nulls:n}}})),Ui,Wi=e((()=>{F(),G(),Ui=class extends P{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})}}})),Gi,Ki=e((()=>{F(),N(),Gi=class extends P{create(e,t){return this._client.post(`/audio/transcriptions`,M({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}}})),qi,Ji=e((()=>{F(),N(),qi=class extends P{create(e,t){return this._client.post(`/audio/translations`,M({body:e,...t,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}}})),Yi,Xi=e((()=>{F(),Wi(),Ki(),Ji(),Yi=class extends P{constructor(){super(...arguments),this.transcriptions=new Gi(this._client),this.translations=new qi(this._client),this.speech=new Ui(this._client)}},Yi.Transcriptions=Gi,Yi.Translations=qi,Yi.Speech=Ui})),Zi,Qi=e((()=>{F(),j(),L(),Zi=class extends P{create(e,t){return this._client.post(`/batches`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(I`/batches/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/batches`,O,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(I`/batches/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}}})),$i,ea=e((()=>{F(),j(),G(),L(),$i=class extends P{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(I`/assistants/${e}`,{...t,headers:W([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(I`/assistants/${e}`,{body:t,...n,headers:W([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/assistants`,O,{query:e,...t,headers:W([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(I`/assistants/${e}`,{...t,headers:W([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}}})),ta,na=e((()=>{F(),G(),ta=class extends P{create(e,t){return this._client.post(`/realtime/sessions`,{body:e,...t,headers:W([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}}})),ra,ia=e((()=>{F(),G(),ra=class extends P{create(e,t){return this._client.post(`/realtime/transcription_sessions`,{body:e,...t,headers:W([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}}})),aa,oa=e((()=>{F(),na(),ia(),aa=class extends P{constructor(){super(...arguments),this.sessions=new ta(this._client),this.transcriptionSessions=new ra(this._client)}},aa.Sessions=ta,aa.TranscriptionSessions=ra})),sa,ca=e((()=>{F(),G(),L(),sa=class extends P{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(I`/chatkit/sessions/${e}/cancel`,{...t,headers:W([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}}})),la,ua=e((()=>{F(),j(),G(),L(),la=class extends P{retrieve(e,t){return this._client.get(I`/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`,k,{query:e,...t,headers:W([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(I`/chatkit/threads/${e}`,{...t,headers:W([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}listItems(e,t={},n){return this._client.getAPIList(I`/chatkit/threads/${e}/items`,k,{query:t,...n,headers:W([{"OpenAI-Beta":`chatkit_beta=v1`},n?.headers]),__security:{bearerAuth:!0}})}}})),da,fa=e((()=>{F(),ca(),ua(),da=class extends P{constructor(){super(...arguments),this.sessions=new sa(this._client),this.threads=new la(this._client)}},da.Sessions=sa,da.Threads=la})),pa,ma=e((()=>{F(),j(),G(),L(),pa=class extends P{list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(I`/responses/${e}/input_items?beta=true`,O,{query:i,...n,headers:W([{...r?.toString()==null?void 0:{"openai-beta":r?.toString()}},n?.headers]),__security:{bearerAuth:!0}})}}})),ha,ga=e((()=>{F(),G(),ha=class extends P{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}})}}})),_a,va=e((()=>{F(),ma(),ga(),G(),L(),_a=class extends P{constructor(){super(...arguments),this.inputItems=new pa(this._client),this.inputTokens=new ha(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(I`/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(I`/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(I`/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}})}},_a.InputItems=pa,_a.InputTokens=ha})),ya,ba=e((()=>{F(),j(),G(),L(),ya=class extends P{create(e,t,n){return this._client.post(I`/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(I`/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(I`/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(I`/threads/${e}/messages`,O,{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(I`/threads/${r}/messages/${e}`,{...n,headers:W([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}}})),xa,Sa=e((()=>{F(),j(),G(),L(),xa=class extends P{retrieve(e,t,n){let{thread_id:r,run_id:i,...a}=t;return this._client.get(I`/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(I`/threads/${r}/runs/${e}/steps`,O,{query:i,...n,headers:W([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}}})),Ca,wa=e((()=>{Ca=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))}}})),Ta,Ea=e((()=>{Ta=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}})),Da=e((()=>{he(),wa(),Ea(),xt(),a(),_e(),rt()})),K,Oa,ka,q,Aa,J,ja,Ma,Na,Pa,Y,Fa,Ia,La,Ra,za,Ba,Va,Ha,Ua,Wa,Ga,Ka,qa,Ja=e((()=>{r(),mr(),R(),Kn(),Da(),qa=class extends Gn{constructor(){super(...arguments),K.add(this),ka.set(this,[]),q.set(this,{}),Aa.set(this,{}),J.set(this,void 0),ja.set(this,void 0),Ma.set(this,void 0),Na.set(this,void 0),Pa.set(this,void 0),Y.set(this,void 0),Fa.set(this,void 0),Ia.set(this,void 0),La.set(this,void 0)}[(ka=new WeakMap,q=new WeakMap,Aa=new WeakMap,J=new WeakMap,ja=new WeakMap,Ma=new WeakMap,Na=new WeakMap,Pa=new WeakMap,Y=new WeakMap,Fa=new WeakMap,Ia=new WeakMap,La=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 Oa;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),this._connected();let r=Et.fromReadableStream(e,this.controller);for await(let e of r)n(this,K,`m`,Ra).call(this,e);if(r.controller.signal?.aborted)throw new d;return this._addRun(n(this,K,`m`,za).call(this))}toReadableStream(){return new Et(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,r){let i=new Oa;return i._run(()=>i._runToolAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createToolAssistantStream(e,t,r,i){this._listenForAbort(i?.signal);let a={...r,stream:!0},o=await e.submitToolOutputs(t,a,{...i,signal:this.controller.signal});this._connected();for await(let e of o)n(this,K,`m`,Ra).call(this,e);if(o.controller.signal?.aborted)throw new d;return this._addRun(n(this,K,`m`,za).call(this))}static createThreadAssistantStream(e,t,n){let r=new Oa;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 Oa;return i._run(()=>i._runAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}currentEvent(){return n(this,Fa,`f`)}currentRun(){return n(this,Ia,`f`)}currentMessageSnapshot(){return n(this,J,`f`)}currentRunStepSnapshot(){return n(this,La,`f`)}async finalRunSteps(){return await this.done(),Object.values(n(this,q,`f`))}async finalMessages(){return await this.done(),Object.values(n(this,Aa,`f`))}async finalRun(){if(await this.done(),!n(this,ja,`f`))throw Error(`Final run was not received.`);return n(this,ja,`f`)}async _createThreadAssistantStream(e,t,r){this._listenForAbort(r?.signal);let i={...t,stream:!0},a=await e.createAndRun(i,{...r,signal:this.controller.signal});this._connected();for await(let e of a)n(this,K,`m`,Ra).call(this,e);if(a.controller.signal?.aborted)throw new d;return this._addRun(n(this,K,`m`,za).call(this))}async _createAssistantStream(e,t,r,i){this._listenForAbort(i?.signal);let a={...r,stream:!0},o=await e.create(t,a,{...i,signal:this.controller.signal});this._connected();for await(let e of o)n(this,K,`m`,Ra).call(this,e);if(o.controller.signal?.aborted)throw new d;return this._addRun(n(this,K,`m`,za).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(le(t)&&le(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(!le(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)}},Oa=qa,Ra=function(e){if(!this.ended)switch(t(this,Fa,e,`f`),n(this,K,`m`,Ha).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`:n(this,K,`m`,Ka).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`:n(this,K,`m`,Va).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`:n(this,K,`m`,Ba).call(this,e);break;case`error`:throw Error(`Encountered an error event in event processing - errors should be processed earlier`);default:}},za=function(){if(this.ended)throw new l(`stream has ended, this shouldn't happen`);if(!n(this,ja,`f`))throw Error(`Final run has not been received`);return n(this,ja,`f`)},Ba=function(e){let[r,i]=n(this,K,`m`,Wa).call(this,e,n(this,J,`f`));t(this,J,r,`f`),n(this,Aa,`f`)[r.id]=r;for(let e of i){let t=r.content[e.index];t?.type==`text`&&this._emit(`textCreated`,t.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,r),e.data.delta.content)for(let i of e.data.delta.content){if(i.type==`text`&&i.text){let e=i.text,t=r.content[i.index];if(t&&t.type==`text`)this._emit(`textDelta`,e,t.text);else throw Error(`The snapshot associated with this text delta is not text or missing`)}if(i.index!=n(this,Ma,`f`)){if(n(this,Na,`f`))switch(n(this,Na,`f`).type){case`text`:this._emit(`textDone`,n(this,Na,`f`).text,n(this,J,`f`));break;case`image_file`:this._emit(`imageFileDone`,n(this,Na,`f`).image_file,n(this,J,`f`));break}t(this,Ma,i.index,`f`)}t(this,Na,r.content[i.index],`f`)}break;case`thread.message.completed`:case`thread.message.incomplete`:if(n(this,Ma,`f`)!==void 0){let t=e.data.content[n(this,Ma,`f`)];if(t)switch(t.type){case`image_file`:this._emit(`imageFileDone`,t.image_file,n(this,J,`f`));break;case`text`:this._emit(`textDone`,t.text,n(this,J,`f`));break}}n(this,J,`f`)&&this._emit(`messageDone`,e.data),t(this,J,void 0,`f`)}},Va=function(e){let r=n(this,K,`m`,Ua).call(this,e);switch(t(this,La,r,`f`),e.event){case`thread.run.step.created`:this._emit(`runStepCreated`,e.data);break;case`thread.run.step.delta`:let i=e.data.delta;if(i.step_details&&i.step_details.type==`tool_calls`&&i.step_details.tool_calls&&r.step_details.type==`tool_calls`)for(let e of i.step_details.tool_calls)e.index==n(this,Pa,`f`)?this._emit(`toolCallDelta`,e,r.step_details.tool_calls[e.index]):(n(this,Y,`f`)&&this._emit(`toolCallDone`,n(this,Y,`f`)),t(this,Pa,e.index,`f`),t(this,Y,r.step_details.tool_calls[e.index],`f`),n(this,Y,`f`)&&this._emit(`toolCallCreated`,n(this,Y,`f`)));this._emit(`runStepDelta`,e.data.delta,r);break;case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:t(this,La,void 0,`f`),e.data.step_details.type==`tool_calls`&&n(this,Y,`f`)&&(this._emit(`toolCallDone`,n(this,Y,`f`)),t(this,Y,void 0,`f`)),this._emit(`runStepDone`,e.data,r);break;case`thread.run.step.in_progress`:break}},Ha=function(e){n(this,ka,`f`).push(e),this._emit(`event`,e)},Ua=function(e){switch(e.event){case`thread.run.step.created`:return n(this,q,`f`)[e.data.id]=e.data,e.data;case`thread.run.step.delta`:let t=n(this,q,`f`)[e.data.id];if(!t)throw Error(`Received a RunStepDelta before creation of a snapshot`);let r=e.data;if(r.delta){let i=Oa.accumulateDelta(t,r.delta);n(this,q,`f`)[e.data.id]=i}return n(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`:n(this,q,`f`)[e.data.id]=e.data;break}if(n(this,q,`f`)[e.data.id])return n(this,q,`f`)[e.data.id];throw Error(`No snapshot available`)},Wa=function(e,t){let r=[];switch(e.event){case`thread.message.created`:return[e.data,r];case`thread.message.delta`:if(!t)throw Error(`Received a delta with no existing snapshot (there should be one from message creation)`);let i=e.data;if(i.delta.content)for(let e of i.delta.content)if(e.index in t.content){let r=t.content[e.index];t.content[e.index]=n(this,K,`m`,Ga).call(this,e,r)}else t.content[e.index]=e,r.push(e);return[t,r];case`thread.message.in_progress`:case`thread.message.completed`:case`thread.message.incomplete`:if(t)return[t,r];throw Error(`Received thread message event with no existing snapshot`)}throw Error(`Tried to accumulate a non-message event`)},Ga=function(e,t){return Oa.accumulateDelta(t,e)},Ka=function(e){switch(t(this,Ia,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`:t(this,ja,e.data,`f`),n(this,Y,`f`)&&(this._emit(`toolCallDone`,n(this,Y,`f`)),t(this,Y,void 0,`f`));break;case`thread.run.cancelling`:break}}})),Ya,Xa=e((()=>{F(),Sa(),j(),G(),Ja(),_e(),L(),Ya=class extends P{constructor(){super(...arguments),this.steps=new xa(this._client)}create(e,t,n){let{include:r,...i}=t;return this._client.post(I`/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(I`/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(I`/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(I`/threads/${e}/runs`,O,{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(I`/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 qa.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 ge(e);break;case`requires_action`:case`incomplete`:case`cancelled`:case`completed`:case`failed`:case`expired`:return i}}}stream(e,t,n){return qa.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){let{thread_id:r,...i}=t;return this._client.post(I`/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 qa.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}},Ya.Steps=xa})),Za,Qa=e((()=>{F(),ba(),Xa(),G(),Ja(),L(),Za=class extends P{constructor(){super(...arguments),this.runs=new Ya(this._client),this.messages=new ya(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(I`/threads/${e}`,{...t,headers:W([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(I`/threads/${e}`,{body:t,...n,headers:W([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(I`/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 qa.createThreadAssistantStream(e,this._client.beta.threads,t)}},Za.Runs=Ya,Za.Messages=ya})),$a,eo=e((()=>{F(),ea(),oa(),fa(),va(),Qa(),$a=class extends P{constructor(){super(...arguments),this.realtime=new aa(this._client),this.responses=new _a(this._client),this.chatkit=new da(this._client),this.assistants=new $i(this._client),this.threads=new Za(this._client)}},$a.Realtime=aa,$a.Responses=_a,$a.ChatKit=da,$a.Assistants=$i,$a.Threads=Za})),to,no=e((()=>{F(),to=class extends P{create(e,t){return this._client.post(`/completions`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}}})),ro,io=e((()=>{F(),G(),L(),ro=class extends P{retrieve(e,t,n){let{container_id:r}=t;return this._client.get(I`/containers/${r}/files/${e}/content`,{...n,headers:W([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}})),ao,oo=e((()=>{F(),io(),j(),G(),N(),L(),ao=class extends P{constructor(){super(...arguments),this.content=new ro(this._client)}create(e,t,n){return this._client.post(I`/containers/${e}/files`,Jt({body:t,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,n){let{container_id:r}=t;return this._client.get(I`/containers/${r}/files/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/containers/${e}/files`,O,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{container_id:r}=t;return this._client.delete(I`/containers/${r}/files/${e}`,{...n,headers:W([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}},ao.Content=ro})),so,co=e((()=>{F(),oo(),j(),G(),L(),so=class extends P{constructor(){super(...arguments),this.files=new ao(this._client)}create(e,t){return this._client.post(`/containers`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(I`/containers/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/containers`,O,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(I`/containers/${e}`,{...t,headers:W([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}},so.Files=ao})),lo,uo=e((()=>{F(),j(),L(),lo=class extends P{create(e,t,n){let{include:r,...i}=t;return this._client.post(I`/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(I`/conversations/${r}/items/${e}`,{query:i,...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/conversations/${e}/items`,k,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{conversation_id:r}=t;return this._client.delete(I`/conversations/${r}/items/${e}`,{...n,__security:{bearerAuth:!0}})}}})),fo,po=e((()=>{F(),uo(),L(),fo=class extends P{constructor(){super(...arguments),this.items=new lo(this._client)}create(e={},t){return this._client.post(`/conversations`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(I`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(I`/conversations/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(I`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}},fo.Items=lo})),mo,ho=e((()=>{F(),Da(),mo=class extends P{create(e,t){let n=!!e.encoding_format,r=n?e.encoding_format:`base64`;n&&D(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:(D(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=Ca(t)}),e)))}}})),go,_o=e((()=>{F(),j(),L(),go=class extends P{retrieve(e,t,n){let{eval_id:r,run_id:i}=t;return this._client.get(I`/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(I`/evals/${r}/runs/${e}/output_items`,O,{query:i,...n,__security:{bearerAuth:!0}})}}})),vo,yo=e((()=>{F(),_o(),j(),L(),vo=class extends P{constructor(){super(...arguments),this.outputItems=new go(this._client)}create(e,t,n){return this._client.post(I`/evals/${e}/runs`,{body:t,...n,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{eval_id:r}=t;return this._client.get(I`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/evals/${e}/runs`,O,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{eval_id:r}=t;return this._client.delete(I`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}cancel(e,t,n){let{eval_id:r}=t;return this._client.post(I`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}},vo.OutputItems=go})),bo,xo=e((()=>{F(),yo(),j(),L(),bo=class extends P{constructor(){super(...arguments),this.runs=new vo(this._client)}create(e,t){return this._client.post(`/evals`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(I`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(I`/evals/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/evals`,O,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(I`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}},bo.Runs=vo})),So,Co=e((()=>{F(),j(),G(),_e(),R(),N(),L(),So=class extends P{create(e,t){return this._client.post(`/files`,M({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(I`/files/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/files`,O,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(I`/files/${e}`,{...t,__security:{bearerAuth:!0}})}content(e,t){return this._client.get(I`/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 ge(t),a=await this.retrieve(e),Date.now()-i>n)throw new p({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return a}}})),wo,To=e((()=>{F(),wo=class extends P{}})),Eo,Do=e((()=>{F(),Eo=class extends P{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}})}}})),Oo,ko=e((()=>{F(),Do(),Oo=class extends P{constructor(){super(...arguments),this.graders=new Eo(this._client)}},Oo.Graders=Eo})),Ao,jo=e((()=>{F(),j(),L(),Ao=class extends P{create(e,t,n){return this._client.getAPIList(I`/fine_tuning/checkpoints/${e}/permissions`,Rt,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},n){return this._client.get(I`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/fine_tuning/checkpoints/${e}/permissions`,k,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{fine_tuned_model_checkpoint:r}=t;return this._client.delete(I`/fine_tuning/checkpoints/${r}/permissions/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}})),Mo,No=e((()=>{F(),jo(),Mo=class extends P{constructor(){super(...arguments),this.permissions=new Ao(this._client)}},Mo.Permissions=Ao})),Po,Fo=e((()=>{F(),j(),L(),Po=class extends P{list(e,t={},n){return this._client.getAPIList(I`/fine_tuning/jobs/${e}/checkpoints`,O,{query:t,...n,__security:{bearerAuth:!0}})}}})),Io,Lo=e((()=>{F(),Fo(),j(),L(),Io=class extends P{constructor(){super(...arguments),this.checkpoints=new Po(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(I`/fine_tuning/jobs/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/fine_tuning/jobs`,O,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(I`/fine_tuning/jobs/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}listEvents(e,t={},n){return this._client.getAPIList(I`/fine_tuning/jobs/${e}/events`,O,{query:t,...n,__security:{bearerAuth:!0}})}pause(e,t){return this._client.post(I`/fine_tuning/jobs/${e}/pause`,{...t,__security:{bearerAuth:!0}})}resume(e,t){return this._client.post(I`/fine_tuning/jobs/${e}/resume`,{...t,__security:{bearerAuth:!0}})}},Io.Checkpoints=Po})),Ro,zo=e((()=>{F(),To(),ko(),No(),Lo(),Ro=class extends P{constructor(){super(...arguments),this.methods=new wo(this._client),this.jobs=new Io(this._client),this.checkpoints=new Mo(this._client),this.alpha=new Oo(this._client)}},Ro.Methods=wo,Ro.Jobs=Io,Ro.Checkpoints=Mo,Ro.Alpha=Oo})),Bo,Vo=e((()=>{F(),Bo=class extends P{}})),Ho,Uo=e((()=>{F(),Vo(),Ho=class extends P{constructor(){super(...arguments),this.graderModels=new Bo(this._client)}},Ho.GraderModels=Bo})),Wo,Go=e((()=>{F(),N(),Wo=class extends P{createVariation(e,t){return this._client.post(`/images/variations`,M({body:e,...t,__security:{bearerAuth:!0}},this._client))}edit(e,t){return this._client.post(`/images/edits`,M({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}})}}})),Ko,qo=e((()=>{F(),j(),L(),Ko=class extends P{retrieve(e,t){return this._client.get(I`/models/${e}`,{...t,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList(`/models`,Rt,{...e,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(I`/models/${e}`,{...t,__security:{bearerAuth:!0}})}}})),Jo,Yo=e((()=>{F(),Jo=class extends P{create(e,t){return this._client.post(`/moderations`,{body:e,...t,__security:{bearerAuth:!0}})}}})),Xo,Zo=e((()=>{F(),G(),L(),Xo=class extends P{accept(e,t,n){return this._client.post(I`/realtime/calls/${e}/accept`,{body:t,...n,headers:W([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}hangup(e,t){return this._client.post(I`/realtime/calls/${e}/hangup`,{...t,headers:W([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}refer(e,t,n){return this._client.post(I`/realtime/calls/${e}/refer`,{body:t,...n,headers:W([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}reject(e,t={},n){return this._client.post(I`/realtime/calls/${e}/reject`,{body:t,...n,headers:W([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}}})),Qo,$o=e((()=>{F(),Qo=class extends P{create(e,t){return this._client.post(`/realtime/client_secrets`,{body:e,...t,__security:{bearerAuth:!0}})}}})),es,ts=e((()=>{F(),Zo(),$o(),es=class extends P{constructor(){super(...arguments),this.clientSecrets=new Qo(this._client),this.calls=new Xo(this._client)}},es.ClientSecrets=Qo,es.Calls=Xo}));function ns(e,t){if(!t||!as(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 ls(e,t)&&X(t),t}return rs(e,t)}function rs(e,t){let n=!e.status||e.status===`completed`,r=e.output.map(e=>{if(e.type===`function_call`)return{...e,parsed_arguments:n?cs(t,e):null};if(e.type===`message`){let r=e.content.map(e=>e.type===`output_text`?{...e,parsed:n?is(t,e.text):null}:e);return{...e,content:r}}return e}),i=Object.assign({},e,{output:r});return ls(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 is(e,t){return e.text?.format?.type===`json_schema`?`$parseRaw`in e.text?.format?(e.text?.format).$parseRaw(t):JSON.parse(t):null}function as(e){return!!gn(e.text?.format)}function os(e){return e?.$brand===`auto-parseable-tool`}function ss(e,t){return e.find(e=>e.type===`function`&&e.name===t)}function cs(e,t){let n=ss(e.tools??[],t.name);return{...t,...t,parsed_arguments:os(n)?n.$parseRaw(t.arguments):n?.strict?JSON.parse(t.arguments):null}}function ls(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 us=e((()=>{R(),En()}));function ds(e,t){if(!t){if(e.type!==`response.created`)throw new l(`When snapshot hasn't been set yet, expected 'response.created' event, got ${e.type}`);return fs(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 l(`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 l(`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 l(`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 l(`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 l(`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 l(`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 l(`missing content at index ${e.content_index}`);let t=Q(n.content,e.content_index);if(t.type!==`reasoning_text`)throw new l(`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 l(`missing content at index ${e.content_index}`);let t=Q(n.content,e.content_index);if(t.type!==`reasoning_text`)throw new l(`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=fs(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:ps(e)}return t}function fs(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 l(`missing output at index ${t}`);return n}function Q(e,t){let n=e[t];if(!n)throw new l(`missing content at index ${t}`);return n}function ps(e){throw new l(`Unhandled response stream event: ${JSON.stringify(e)}`)}var ms=e((()=>{R(),us()}));function hs(e,t){return ns(e,t)}var gs,_s,vs,ys,bs,xs,Ss,Cs,ws=e((()=>{r(),R(),Kn(),ms(),us(),Cs=class e extends Gn{constructor(e){super(),gs.add(this),_s.set(this,void 0),vs.set(this,void 0),ys.set(this,void 0),t(this,_s,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,r){this._listenForAbort(r?.signal),n(this,gs,`m`,bs).call(this);let i,a=null;`response_id`in t?(i=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),a=t.starting_after??null):i=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(let e of i)n(this,gs,`m`,xs).call(this,e,a);if(i.controller.signal?.aborted)throw new d;return n(this,gs,`m`,Ss).call(this)}[(_s=new WeakMap,vs=new WeakMap,ys=new WeakMap,gs=new WeakSet,bs=function(){this.ended||t(this,vs,void 0,`f`)},xs=function(e,r){if(this.ended)return;let i=(e,t)=>{(r==null||t.sequence_number>r)&&this._emit(e,t)},a=ds(e,n(this,vs,`f`));switch(t(this,vs,a,`f`),i(`event`,e),e.type){case`response.output_text.delta`:{let t=a.output[e.output_index];if(!t)throw new l(`missing output at index ${e.output_index}`);if(t.type===`message`){let n=t.content[e.content_index];if(!n)throw new l(`missing content at index ${e.content_index}`);if(n.type!==`output_text`)throw new l(`expected content to be 'output_text', got ${n.type}`);i(`response.output_text.delta`,{...e,snapshot:n.text})}break}case`response.function_call_arguments.delta`:{let t=a.output[e.output_index];if(!t)throw new l(`missing output at index ${e.output_index}`);t.type===`function_call`&&i(`response.function_call_arguments.delta`,{...e,snapshot:t.arguments});break}default:i(e.type,e);break}},Ss=function(){if(this.ended)throw new l(`stream has ended, this shouldn't happen`);let e=n(this,vs,`f`);if(!e)throw new l(`request ended without sending any events`);t(this,vs,void 0,`f`);let r=hs(e,n(this,_s,`f`));return t(this,ys,r,`f`),r},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=n(this,ys,`f`);if(!e)throw new l(`stream ended without producing a ChatCompletion`);return e}}})),Ts,Es=e((()=>{F(),j(),L(),Ts=class extends P{list(e,t={},n){return this._client.getAPIList(I`/responses/${e}/input_items`,O,{query:t,...n,__security:{bearerAuth:!0}})}}})),Ds,Os=e((()=>{F(),Ds=class extends P{count(e={},t){return this._client.post(`/responses/input_tokens`,{body:e,...t,__security:{bearerAuth:!0}})}}})),ks,As=e((()=>{us(),ws(),F(),Es(),Os(),G(),L(),ks=class extends P{constructor(){super(...arguments),this.inputItems=new Ts(this._client),this.inputTokens=new Ds(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(I`/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(I`/responses/${e}`,{...t,headers:W([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(t=>rs(t,e))}stream(e,t){return Cs.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(I`/responses/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}compact(e,t){return this._client.post(`/responses/compact`,{body:e,...t,__security:{bearerAuth:!0}})}},ks.InputItems=Ts,ks.InputTokens=Ds})),js,Ms=e((()=>{F(),G(),L(),js=class extends P{retrieve(e,t){return this._client.get(I`/skills/${e}/content`,{...t,headers:W([{Accept:`application/binary`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}})),Ns,Ps=e((()=>{F(),G(),L(),Ns=class extends P{retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(I`/skills/${r}/versions/${e}/content`,{...n,headers:W([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}})),Fs,Is=e((()=>{F(),Ps(),j(),N(),L(),Fs=class extends P{constructor(){super(...arguments),this.content=new Ns(this._client)}create(e,t={},n){return this._client.post(I`/skills/${e}/versions`,Jt({body:t,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(I`/skills/${r}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/skills/${e}/versions`,O,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{skill_id:r}=t;return this._client.delete(I`/skills/${r}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}},Fs.Content=Ns})),Ls,Rs=e((()=>{F(),Ms(),Is(),j(),N(),L(),Ls=class extends P{constructor(){super(...arguments),this.content=new js(this._client),this.versions=new Fs(this._client)}create(e={},t){return this._client.post(`/skills`,Jt({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(I`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(I`/skills/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/skills`,O,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(I`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}},Ls.Content=js,Ls.Versions=Fs})),zs,Bs=e((()=>{F(),N(),L(),zs=class extends P{create(e,t,n){return this._client.post(I`/uploads/${e}/parts`,M({body:t,...n,__security:{bearerAuth:!0}},this._client))}}})),Vs,Hs=e((()=>{F(),Bs(),L(),Vs=class extends P{constructor(){super(...arguments),this.parts=new zs(this._client)}create(e,t){return this._client.post(`/uploads`,{body:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(I`/uploads/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}complete(e,t,n){return this._client.post(I`/uploads/${e}/complete`,{body:t,...n,__security:{bearerAuth:!0}})}},Vs.Parts=zs})),Us,Ws=e((()=>{Us=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}})),Gs,Ks=e((()=>{F(),j(),G(),_e(),Ws(),L(),Gs=class extends P{create(e,t,n){return this._client.post(I`/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(I`/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(I`/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(I`/vector_stores/${r}/file_batches/${e}/files`,O,{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 ge(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 Us(Array(a).fill(s).map(l)),await this.createAndPoll(e,{file_ids:c})}}})),qs,Js=e((()=>{F(),j(),G(),Da(),L(),qs=class extends P{create(e,t,n){return this._client.post(I`/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(I`/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(I`/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(I`/vector_stores/${e}/files`,O,{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(I`/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 ge(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(I`/vector_stores/${r}/files/${e}/content`,Rt,{...n,headers:W([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}}})),Ys,Xs=e((()=>{F(),Ks(),Js(),j(),G(),L(),Ys=class extends P{constructor(){super(...arguments),this.files=new qs(this._client),this.fileBatches=new Gs(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(I`/vector_stores/${e}`,{...t,headers:W([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(I`/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`,O,{query:e,...t,headers:W([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(I`/vector_stores/${e}`,{...t,headers:W([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}search(e,t,n){return this._client.getAPIList(I`/vector_stores/${e}/search`,Rt,{body:t,method:`post`,...n,headers:W([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}},Ys.Files=qs,Ys.FileBatches=Gs})),Zs,Qs=e((()=>{F(),j(),G(),N(),L(),Zs=class extends P{create(e,t){return this._client.post(`/videos`,M({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(I`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/videos`,k,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(I`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}createCharacter(e,t){return this._client.post(`/videos/characters`,M({body:e,...t,__security:{bearerAuth:!0}},this._client))}downloadContent(e,t={},n){return this._client.get(I`/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`,M({body:e,...t,__security:{bearerAuth:!0}},this._client))}extend(e,t){return this._client.post(`/videos/extensions`,M({body:e,...t,__security:{bearerAuth:!0}},this._client))}getCharacter(e,t){return this._client.get(I`/videos/characters/${e}`,{...t,__security:{bearerAuth:!0}})}remix(e,t,n){return this._client.post(I`/videos/${e}/remix`,Jt({body:t,...n,__security:{bearerAuth:!0}},this._client))}}})),$s,ec,tc,nc,rc=e((()=>{r(),R(),F(),G(),nc=class extends P{constructor(){super(...arguments),$s.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,r=this._client.webhookSecret,i=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");n(this,$s,`m`,ec).call(this,r);let a=W([t]).values,o=n(this,$s,`m`,tc).call(this,a,`webhook-signature`),s=n(this,$s,`m`,tc).call(this,a,`webhook-timestamp`),c=n(this,$s,`m`,tc).call(this,a,`webhook-id`),l=parseInt(s,10);if(isNaN(l))throw new b(`Invalid webhook timestamp format`);let u=Math.floor(Date.now()/1e3);if(u-l>i)throw new b(`Webhook timestamp is too old`);if(l>u+i)throw new b(`Webhook timestamp is too new`);let d=o.split(` `).map(e=>e.startsWith(`v1,`)?e.substring(3):e),f=r.startsWith(`whsec_`)?Buffer.from(r.replace(`whsec_`,``),`base64`):Buffer.from(r,`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 b(`The given webhook signature does not match the expected signature`)}},$s=new WeakSet,ec=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`)},tc=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}})),ic=e((()=>{rc()})),ac=e((()=>{ic()})),oc=e((()=>{Lr(),Rr(),Bi(),Xi(),Qi(),eo(),no(),co(),po(),ho(),xo(),Co(),zo(),Uo(),Go(),qo(),Yo(),ts(),As(),Rs(),Hs(),Xs(),Qs(),ac()}));function sc(e){let t=dc.get(e);if(!t)throw Error(`Invalid provider. Providers must be created with createProvider().`);return t.configure()}var cc,lc,uc,dc,fc=e((()=>{cc=Symbol.for(`openai.node.providerDefinitions.v1`),lc=globalThis,uc=lc[cc],dc=uc??new WeakMap,uc||Object.defineProperty(lc,cc,{value:dc})}));function pc(e){if(mc(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 mc(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 hc,gc,_c,vc,yc,$,bc=e((()=>{r(),a(),he(),_e(),c(),Oe(),Pe(),Ie(),rt(),ye(),x(),j(),Ht(),ln(),oc(),Pt(),Qi(),no(),ho(),Co(),Go(),qo(),Yo(),Qs(),Bi(),Xi(),eo(),Fr(),co(),po(),xo(),zo(),Uo(),ts(),As(),Rs(),Hs(),Xs(),rc(),G(),fc(),Ea(),xt(),yc=`workload-identity-auth`,$=class{constructor(e={}){hc.add(this),_c.set(this,void 0),this.completions=new to(this),this.chat=new Pr(this),this.embeddings=new mo(this),this.files=new So(this),this.images=new Wo(this),this.audio=new Yi(this),this.moderations=new Jo(this),this.models=new Ko(this),this.fineTuning=new Ro(this),this.graders=new Ho(this),this.vectorStores=new Ys(this),this.webhooks=new nc(this),this.beta=new $a(this),this.batches=new Zi(this),this.uploads=new Vs(this),this.admin=new zi(this),this.responses=new ks(this),this.realtime=new es(this),this.conversations=new fo(this),this.evals=new bo(this),this.containers=new so(this),this.skills=new Ls(this),this.videos=new Zs(this);let n=e.provider;if(n){let t=[`apiKey`,`adminAPIKey`,`workloadIdentity`,`baseURL`].filter(t=>e[t]!=null);if(t.length)throw new l(`The \`provider\` option cannot be used with ${t.map(e=>`\`${e}\``).join(`, `)}. Configure authentication and the base URL through the provider instead.`)}let{baseURL:r=n?null:Ta(`OPENAI_BASE_URL`),apiKey:i=n?null:Ta(`OPENAI_API_KEY`)??null,adminAPIKey:a=n?null:Ta(`OPENAI_ADMIN_KEY`)??null,organization:o=n?null:Ta(`OPENAI_ORG_ID`)??null,project:s=n?null:Ta(`OPENAI_PROJECT_ID`)??null,webhookSecret:c=Ta(`OPENAI_WEBHOOK_SECRET`)??null,workloadIdentity:u,...d}=e,f=n?sc(n):void 0,p={apiKey:i,adminAPIKey:a,organization:o,project:s,webhookSecret:c,workloadIdentity:u,provider:n,...d,baseURL:f?.baseURL??(r||`https://api.openai.com/v1`)};if(i&&u)throw new l("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!f&&!i&&!a&&!u)throw new l("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!p.dangerouslyAllowBrowser&&Se())throw new l(`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=p.baseURL,this.timeout=p.timeout??gc.DEFAULT_TIMEOUT,this.logger=p.logger??console;let m=`warn`;this.logLevel=m,this.logLevel=_t(p.logLevel,`ClientOptions.logLevel`,this)??_t(Ta(`OPENAI_LOG`),`process.env['OPENAI_LOG']`,this)??m,this.fetchOptions=p.fetchOptions,this.maxRetries=p.maxRetries??2,this.fetch=p.fetch??ke(),t(this,_c,Fe,`f`);let h=n?void 0:Ta(`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())}p.defaultHeaders=W([e,p.defaultHeaders])}this._options=p,this._provider=f,u&&(this._workloadIdentityAuth=new Vt(u,this.fetch)),this.apiKey=typeof i==`string`?i:null,this.adminAPIKey=a,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 nt(e)}getUserAgent(){return`${this.constructor.name}/JS ${ve}`}defaultIdempotencyKey(){return`stainless-node-retry-${i()}`}makeStatusError(e,t,n,r){return u.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 l?e:new l(`Failed to get token from 'apiKey' function: ${e.message}`,{cause:e})}if(typeof t!=`string`||!t)throw new l(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,r){let i=!n(this,hc,`m`,vc).call(this)&&r||this.baseURL,a=de(e)?new URL(e):new URL(i+(i.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),o=this.defaultQuery(),s=Object.fromEntries(a.searchParams);return(!se(o)||!se(s))&&(t={...s,...o,...t}),typeof t==`object`&&t&&!Array.isArray(t)&&(a.search=this.stringifyQuery(t)),a.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 Nt(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:c,timeout:l}=await this.buildRequest(r,{retryCount:i-t});await this.prepareRequest(a,{url:c,options:r}),await this._provider?.prepareRequest?.(a,{url:c,options:r});let u=`log_`+(Math.random()*(1<<24)|0).toString(16).padStart(6,`0`),m=n===void 0?``:`, retryOf: ${n}`,h=Date.now();if(D(this).debug(`[${u}] sending request`,bt({retryOfRequestLogID:n,method:r.method,url:c,options:r,headers:a.headers})),r.signal?.aborted)throw new d;let g=r.__security??{bearerAuth:!0},ee=new AbortController,_=await this.fetchWithAuth(c,a,l,ee,g).catch(s),v=Date.now();if(_ instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new d;let i=o(_)||/timed? ?out/i.test(String(_)+(`cause`in _?String(_.cause):``));if(t)return D(this).info(`[${u}] connection ${i?`timed out`:`failed`} - ${e}`),D(this).debug(`[${u}] connection ${i?`timed out`:`failed`} (${e})`,bt({retryOfRequestLogID:n,url:c,durationMs:v-h,message:_.message})),this.retryRequest(r,t,n??u);throw D(this).info(`[${u}] connection ${i?`timed out`:`failed`} - error; no more retries left`),D(this).debug(`[${u}] connection ${i?`timed out`:`failed`} (error; no more retries left)`,bt({retryOfRequestLogID:n,url:c,durationMs:v-h,message:_.message})),_ instanceof ie||_ instanceof ae?_:i?new p:new f({message:pc(_),cause:_})}let y=`[${u}${m}${[..._.headers.entries()].filter(([e])=>e===`x-request-id`).map(([e,t])=>`, `+e+`: `+JSON.stringify(t)).join(``)}] ${a.method} ${c} ${_.ok?`succeeded`:`failed`} with status ${_.status} in ${v-h}ms`;if(!_.ok){if(_.status===401&&this._workloadIdentityAuth&&g.bearerAuth&&!r.__metadata?.hasStreamingBody&&!r.__metadata?.workloadIdentityTokenRefreshed)return await Ne(_.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...r,__metadata:{...r.__metadata,workloadIdentityTokenRefreshed:!0}},t,n??u);let e=await this.shouldRetry(_);if(t&&e){let e=`retrying, ${t} attempts remaining`;return await Ne(_.body),D(this).info(`${y} - ${e}`),D(this).debug(`[${u}] response error (${e})`,bt({retryOfRequestLogID:n,url:_.url,status:_.status,headers:_.headers,durationMs:v-h})),this.retryRequest(r,t,n??u,_.headers)}let i=e?`error; no more retries left`:`error; not retryable`;D(this).info(`${y} - ${i}`);let a=await _.text().catch(e=>s(e).message),o=me(a),c=o?void 0:a;throw D(this).debug(`[${u}] response error (${i})`,bt({retryOfRequestLogID:n,url:_.url,status:_.status,headers:_.headers,message:c,durationMs:Date.now()-h})),this.makeStatusError(_.status,o,c,_.headers)}return D(this).info(y),D(this).debug(`[${u}] response start`,bt({retryOfRequestLogID:n,url:_.url,status:_.status,headers:_.headers,durationMs:v-h})),{response:_,options:r,controller:ee,requestLogID:u,retryOfRequestLogID:n,startTime:h}}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 Lt(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 ${yc}`){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 ge(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&&pe(`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))}:{},...De(),"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:r}=e;if(!t)return t===void 0&&`body`in e?{...n(this,_c,`f`).call(this,{body:t,headers:W([r])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let i=W([r]),a=globalThis.ReadableStream!==void 0&&t instanceof globalThis.ReadableStream,o=!a&&(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`&&i.values.has(`content-type`)||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||a?{bodyHeaders:void 0,body:t,isStreamingBody:!o}:typeof t==`object`&&(Symbol.asyncIterator in t||Symbol.iterator in t&&`next`in t&&typeof t.next==`function`)?{bodyHeaders:void 0,body:je(t),isStreamingBody:!0}:typeof t==`object`&&i.values.get(`content-type`)===`application/x-www-form-urlencoded`?{bodyHeaders:{"content-type":`application/x-www-form-urlencoded`},body:this.stringifyQuery(t),isStreamingBody:!1}:{...n(this,_c,`f`).call(this,{body:t,headers:i}),isStreamingBody:!1}}},gc=$,_c=new WeakMap,hc=new WeakSet,vc=function(){return this._provider!==void 0||this.baseURL!==`https://api.openai.com/v1`},$.OpenAI=gc,$.DEFAULT_TIMEOUT=6e5,$.OpenAIError=l,$.APIError=u,$.APIConnectionError=f,$.APIConnectionTimeoutError=p,$.APIUserAbortError=d,$.NotFoundError=ee,$.ConflictError=_,$.RateLimitError=y,$.BadRequestError=m,$.AuthenticationError=h,$.InternalServerError=te,$.PermissionDeniedError=g,$.UnprocessableEntityError=v,$.InvalidWebhookSignatureError=b,$.toFile=tn,$.Completions=to,$.Chat=Pr,$.Embeddings=mo,$.Files=So,$.Images=Wo,$.Audio=Yi,$.Moderations=Jo,$.Models=Ko,$.FineTuning=Ro,$.Graders=Ho,$.VectorStores=Ys,$.Webhooks=nc,$.Beta=$a,$.Batches=Zi,$.Uploads=Vs,$.Admin=zi,$.Responses=ks,$.Realtime=es,$.Conversations=fo,$.Evals=bo,$.Containers=so,$.Skills=Ls,$.Videos=Zs})),xc=e((()=>{R(),Da(),bc()})),Sc=e((()=>{R(),bc(),Da(),us(),oc()})),Cc=e((()=>{bc(),ln(),Pt(),j(),x(),xc(),Sc()}));export{$ as n,bc as r,Cc as t};
@@ -1 +1 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{DT as t,OT as n}from"./loadAgentsDir-JrGMJN05.js";import{Cr as r,Sr as i,bi as a,xi as o}from"./state-BPFYBqm1.js";function s(e,t,n,r){for(var i=-1,a=e==null?0:e.length;++i<a;){var o=e[i];t(r,o,n(o),e)}return r}var c=e((()=>{}));function l(e,n,r,i){return t(e,function(e,t,a){n(i,e,r(e),a)}),i}var u=e((()=>{n()}));function d(e,t){return function(n,r){var a=o(n)?s:l,c=t?t():{};return a(n,e,i(r,2),c)}}var f=e((()=>{c(),u(),r(),a()})),p,m=e((()=>{f(),p=d(function(e,t,n){e[+!n].push(t)},function(){return[[],[]]})}));export{p as n,m as t};
1
+ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{ET as t,TT as n}from"./loadAgentsDir-PPiD2Mfq.js";import{Cr as r,Sr as i,bi as a,xi as o}from"./state-BPFYBqm1.js";function s(e,t,n,r){for(var i=-1,a=e==null?0:e.length;++i<a;){var o=e[i];t(r,o,n(o),e)}return r}var c=e((()=>{}));function l(e,t,r,i){return n(e,function(e,n,a){t(i,e,r(e),a)}),i}var u=e((()=>{t()}));function d(e,t){return function(n,r){var a=o(n)?s:l,c=t?t():{};return a(n,e,i(r,2),c)}}var f=e((()=>{c(),u(),r(),a()})),p,m=e((()=>{f(),p=d(function(e,t,n){e[+!n].push(t)},function(){return[[],[]]})}));export{p as n,m as t};
@@ -1,3 +1,3 @@
1
- import{n as e,o as t}from"./rolldown-runtime-DaDcL9Zw.js";import{n,t as r}from"./figures-5ThXQEtq.js";import{$h as i,$u as a,Gg as o,H as s,Hg as c,I as l,Kg as u,L as d,La as f,Qu as p,R as m,Um as h,V as ee,Wm as g,Xh as te,Zh as ne,_a as _,aT as v,cT as re,cd as ie,hC as y,ld as b,xC as x,z as ae}from"./loadAgentsDir-JrGMJN05.js";import{I as S,P as C,Wt as oe,Xn as se,a as w,ai as T,di as E,fi as D,hn as O,k,kt as A,n as j,o as M,ot as ce,r as le,s as ue,t as N,x as de,y as P}from"./src-DL3w8VPk2.js";import{t as F}from"./jsx-runtime-Bb4Xn-E0.js";import{Wt as fe,et as I}from"./state-BPFYBqm1.js";import{C as L,x as pe}from"./debug-BQj6h99Q.js";import{H as R,V as z,g as me,ln as B,o as he,rn as ge,z as V}from"./settings-aUygByiZ.js";import{l as _e,o as ve}from"./stringUtils-BjnclTLB.js";import{n as ye,t as be}from"./useExitOnCtrlCDWithKeybindings-qLfN0tc-.js";import{n as xe,t as Se}from"./AddWorkspaceDirectory-m2d3nOQJ.js";import{t as Ce}from"./SearchBox-CwwV0W-w.js";import{n as we,t as Te}from"./useSearchInput-CsxiM9i0.js";import{n as H,t as Ee}from"./shadowedRuleDetection-CWCQ5dZ0.js";function De(){return U}var U,Oe=e((()=>{U=[]}));function ke({ruleValue:e}){switch(e.toolName){case h.name:return e.ruleContent?e.ruleContent.endsWith(`:*`)?(0,W.jsxs)(C,{dimColor:!0,children:[`Any Bash command starting with `,(0,W.jsx)(C,{bold:!0,children:e.ruleContent.slice(0,-2)})]}):(0,W.jsxs)(C,{dimColor:!0,children:[`The Bash command `,(0,W.jsx)(C,{bold:!0,children:e.ruleContent})]}):(0,W.jsx)(C,{dimColor:!0,children:`Any Bash command`});default:return e.ruleContent?null:(0,W.jsxs)(C,{dimColor:!0,children:[`Any use of the `,(0,W.jsx)(C,{bold:!0,children:e.toolName}),` tool`]})}}var W,Ae=e((()=>{N(),g(),W=F()}));function je(e){switch(e){case`localSettings`:return{label:`Project settings (local)`,description:`Saved in ${he(`localSettings`)}`,value:e};case`projectSettings`:return{label:`Project settings`,description:`Checked in at ${he(`projectSettings`)}`,value:e};case`userSettings`:return{label:`User settings`,description:`Saved in at ~/.workmate/settings.json`,value:e}}}function Me({onAddRules:e,onCancel:t,ruleValues:n,ruleBehavior:r,initialContext:i,setToolPermissionContext:a}){let o=ge.map(je),s=(0,Ne.useCallback)(o=>{if(o===`cancel`){t();return}else if(ge.includes(o)){let t=o,s=c(i,{type:`addRules`,rules:n,behavior:r,destination:t});u({type:`addRules`,rules:n,behavior:r,destination:t}),a(s);let l=n.map(e=>({ruleValue:e,ruleBehavior:r,source:t})),d=Ee(s,{sandboxAutoAllowEnabled:v.isSandboxingEnabled()&&v.isAutoAllowBashIfSandboxedEnabled()}).filter(e=>n.some(t=>t.toolName===e.rule.ruleValue.toolName&&t.ruleContent===e.rule.ruleValue.ruleContent));e(l,d.length>0?d:void 0)}},[e,t,n,r,i,a]);return(0,G.jsxs)(P,{title:`Add ${r} permission ${_e(n.length,`rule`)}`,onCancel:t,color:`permission`,children:[(0,G.jsx)(S,{flexDirection:`column`,paddingX:2,children:n.map(e=>(0,G.jsxs)(S,{flexDirection:`column`,children:[(0,G.jsx)(C,{bold:!0,children:R(e)}),(0,G.jsx)(ke,{ruleValue:e})]},R(e)))}),(0,G.jsxs)(S,{flexDirection:`column`,marginY:1,children:[(0,G.jsx)(C,{children:n.length===1?`Where should this rule be saved?`:`Where should these rules be saved?`}),(0,G.jsx)(p,{options:o,onChange:s})]})]})}var Ne,G,Pe=e((()=>{Ne=t(T(),1),a(),N(),o(),V(),H(),re(),B(),me(),ve(),Ae(),G=F()}));function Fe({onCancel:e,onSubmit:t,ruleBehavior:n}){let[i,a]=(0,Ie.useState)(``),[o,s]=(0,Ie.useState)(0),c=ye();oe(`confirm:no`,e,{context:`Settings`});let{columns:l}=ce(),u=l-6;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(S,{flexDirection:`column`,gap:1,borderStyle:`round`,paddingLeft:1,paddingRight:1,borderColor:`permission`,children:[(0,K.jsxs)(C,{bold:!0,color:`permission`,children:[`Add `,n,` permission rule`]}),(0,K.jsxs)(S,{flexDirection:`column`,children:[(0,K.jsxs)(C,{children:[`Permission rules are a tool name, optionally followed by a specifier in parentheses.`,(0,K.jsx)(A,{}),`e.g., `,(0,K.jsx)(C,{bold:!0,children:R({toolName:h.name})}),(0,K.jsx)(C,{bold:!1,children:` or `}),(0,K.jsx)(C,{bold:!0,children:R({toolName:h.name,ruleContent:`ls:*`})})]}),(0,K.jsx)(S,{borderDimColor:!0,borderStyle:`round`,marginY:1,paddingLeft:1,children:(0,K.jsx)(ie,{showCursor:!0,value:i,onChange:a,onSubmit:e=>{let r=e.trim();r.length!==0&&t(z(r),n)},placeholder:`Enter permission rule${r.ellipsis}`,columns:u,cursorOffset:o,onChangeCursorOffset:s})})]})]}),(0,K.jsx)(S,{marginLeft:3,children:c.pending?(0,K.jsxs)(C,{dimColor:!0,children:[`Press `,c.keyName,` again to exit`]}):(0,K.jsx)(C,{dimColor:!0,children:`Enter to submit · Esc to cancel`})})]})}var Ie,K,Le=e((()=>{n(),Ie=t(T(),1),b(),be(),x(),N(),y(),g(),V(),K=F()}));function Re({onHeaderFocusChange:e,onStateChange:t}){let{headerFocused:n,focusHeader:r}=w();(0,q.useEffect)(()=>{e?.(n)},[n,e]);let[i]=(0,q.useState)(()=>De()),[a,o]=(0,q.useState)(()=>new Set),[s,c]=(0,q.useState)(()=>new Set),[l,u]=(0,q.useState)(0);(0,q.useEffect)(()=>{t({approved:a,retry:s,denials:i})},[a,s,i,t]);let d=(0,q.useCallback)(e=>{let t=Number(e);o(e=>{let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n})},[]),f=(0,q.useCallback)(e=>{u(Number(e))},[]);if(O((e,t)=>{e===`r`&&(c(e=>{let t=new Set(e);return t.has(l)?t.delete(l):t.add(l),t}),o(e=>{if(e.has(l))return e;let t=new Set(e);return t.add(l),t}))},{isActive:i.length>0}),i.length===0)return(0,J.jsx)(C,{dimColor:!0,children:`No recent denials. Commands denied by the auto mode classifier will appear here.`});let m=i.map((e,t)=>{let n=a.has(t),r=s.has(t)?` (retry)`:``;return{label:(0,J.jsxs)(C,{children:[(0,J.jsx)(ue,{status:n?`success`:`error`,withSpace:!0}),e.display,(0,J.jsx)(C,{dimColor:!0,children:r})]}),value:String(t)}});return(0,J.jsxs)(S,{flexDirection:`column`,children:[(0,J.jsx)(C,{children:`Commands recently denied by the auto mode classifier.`}),(0,J.jsx)(S,{marginTop:1,children:(0,J.jsx)(p,{options:m,onChange:d,onFocus:f,visibleOptionCount:Math.min(10,m.length),isDisabled:n,onUpFromFirstItem:r})})]})}var q,J,ze=e((()=>{q=t(T(),1),N(),Oe(),a(),J=F()}));function Be({directoryPath:e,onRemove:t,onCancel:n,permissionContext:r,setPermissionContext:i}){let a=(0,Ve.useCallback)(()=>{i(c(r,{type:`removeDirectories`,directories:[e],destination:`session`})),t()},[e,r,i,t]),o=(0,Ve.useCallback)(e=>{e===`yes`?a():n()},[a,n]);return(0,Y.jsxs)(P,{title:`Remove directory from workspace?`,onCancel:n,color:`error`,children:[(0,Y.jsx)(S,{marginX:2,flexDirection:`column`,children:(0,Y.jsx)(C,{bold:!0,children:e})}),(0,Y.jsx)(C,{children:`Claude Code will no longer have access to files in this directory.`}),(0,Y.jsx)(p,{onChange:o,onCancel:n,options:[{label:`Yes`,value:`yes`},{label:`No`,value:`no`}]})]})}var Ve,Y,He=e((()=>{Ve=t(T(),1),a(),N(),o(),Y=F()}));function Ue({onExit:e,toolPermissionContext:t,onRequestAddDirectory:n,onRequestRemoveDirectory:i,onHeaderFocusChange:a}){let{headerFocused:o,focusHeader:s}=w();(0,X.useEffect)(()=>{a?.(o)},[o,a]);let c=We.useMemo(()=>Array.from(t.additionalWorkingDirectories.keys()).map(e=>({path:e,isCurrent:!1,isDeletable:!0})),[t.additionalWorkingDirectories]),l=(0,X.useCallback)(e=>{if(e===`add-directory`){n();return}let t=c.find(t=>t.path===e);t?.isDeletable&&i(t.path)},[c,n,i]),u=(0,X.useCallback)(()=>e(`Workspace dialog dismissed`,{display:`system`}),[e]),d=We.useMemo(()=>{let e=c.map(e=>({label:e.path,value:e.path}));return e.push({label:`Add directory${r.ellipsis}`,value:`add-directory`}),e},[c]);return(0,Z.jsxs)(S,{flexDirection:`column`,marginBottom:1,children:[(0,Z.jsxs)(S,{flexDirection:`row`,marginTop:1,marginLeft:2,gap:1,children:[(0,Z.jsx)(C,{children:`- ${I()}`}),(0,Z.jsx)(C,{dimColor:!0,children:`(Original working directory)`})]}),(0,Z.jsx)(p,{options:d,onChange:l,onCancel:u,visibleOptionCount:Math.min(10,d.length),onUpFromFirstItem:s,isDisabled:o})]})}var We,X,Z,Ge=e((()=>{n(),We=t(T(),1),X=t(T(),1),fe(),a(),N(),Z=F()}));function Ke({rule:e}){return(0,$.jsx)(C,{dimColor:!0,children:`From ${s(e.source)}`})}function qe(e){switch(e){case`allow`:return`allowed`;case`deny`:return`denied`;case`ask`:return`ask`}}function Je({rule:e,onDelete:t,onCancel:n}){let r=ye();oe(`confirm:no`,n,{context:`Confirmation`});let i=(0,$.jsxs)(S,{flexDirection:`column`,marginX:2,children:[(0,$.jsx)(C,{bold:!0,children:R(e.ruleValue)}),(0,$.jsx)(ke,{ruleValue:e.ruleValue}),(0,$.jsx)(Ke,{rule:e})]}),a=(0,$.jsx)(S,{marginLeft:3,children:r.pending?(0,$.jsxs)(C,{dimColor:!0,children:[`Press `,r.keyName,` again to exit`]}):(0,$.jsx)(C,{dimColor:!0,children:`Esc to cancel`})});return e.source===`policySettings`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(S,{flexDirection:`column`,gap:1,borderStyle:`round`,paddingLeft:1,paddingRight:1,borderColor:`permission`,children:[(0,$.jsx)(C,{bold:!0,color:`permission`,children:`Rule details`}),i,(0,$.jsxs)(C,{italic:!0,children:[`This rule is configured by managed settings and cannot be modified.`,`
2
- `,`Contact your system administrator for more information.`]})]}),a]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(S,{flexDirection:`column`,gap:1,borderStyle:`round`,paddingLeft:1,paddingRight:1,borderColor:`error`,children:[(0,$.jsxs)(C,{bold:!0,color:`error`,children:[`Delete `,qe(e.ruleBehavior),` tool?`]}),i,(0,$.jsx)(C,{children:`Are you sure you want to delete this permission rule?`}),(0,$.jsx)(p,{onChange:e=>e===`yes`?t():n(),onCancel:n,options:[{label:`Yes`,value:`yes`},{label:`No`,value:`no`}]})]}),a]})}function Ye(e){let{options:t,searchQuery:n,isSearchMode:r,isFocused:i,onSelect:a,onCancel:o,lastFocusedRuleKey:s,cursorOffset:c,onHeaderFocusChange:l}=e,u=M(),{headerFocused:d,focusHeader:f,blurHeader:m}=w();return(0,Q.useEffect)(()=>{r&&d&&m()},[r,d,m]),(0,Q.useEffect)(()=>{l?.(d)},[d,l]),(0,$.jsxs)(S,{flexDirection:`column`,children:[(0,$.jsx)(S,{marginBottom:1,flexDirection:`column`,children:(0,$.jsx)(k,{query:n,isFocused:r&&!d,isTerminalFocused:i,width:u,cursorOffset:c})}),(0,$.jsx)(p,{options:t,onChange:a,onCancel:o,visibleOptionCount:Math.min(10,t.length),isDisabled:r||d,defaultFocusValue:s,onUpFromFirstItem:f})]})}function Xe({tab:e,getRulesOptions:t,handleToolSelect:n,...r}){return(0,$.jsxs)(S,{flexDirection:`column`,flexShrink:e===`allow`?0:void 0,children:[(0,$.jsx)(C,{children:{allow:`Claude Code won't ask before using allowed tools.`,ask:`Claude Code will always ask for confirmation before using these tools.`,deny:`Claude Code will always reject requests to use denied tools.`}[e]}),(0,$.jsx)(Ye,{options:t(e,r.searchQuery).options,onSelect:t=>n(t,e),...r})]})}function Ze({onExit:e,initialTab:t,onRetryDenials:n}){let a=De().length>0,o=t??(a?`recent`:`allow`),[s,f]=(0,Q.useState)([]),p=ne(e=>e.toolPermissionContext),h=i(),ee=se(),g=(0,Q.useRef)({approved:new Set,retry:new Set,denials:[]}),te=(0,Q.useCallback)(e=>{g.current=e},[]),[_,v]=(0,Q.useState)(),[re,ie]=(0,Q.useState)(),[y,b]=(0,Q.useState)(null),[x,w]=(0,Q.useState)(null),[T,D]=(0,Q.useState)(!1),[O,k]=(0,Q.useState)(null),[A,M]=(0,Q.useState)(!1),[ce,ue]=(0,Q.useState)(!0),N=(0,Q.useCallback)(e=>{ue(e)},[]),P=(0,Q.useMemo)(()=>{let e=new Map;return d(p).forEach(t=>{e.set(L(t),t)}),e},[p]),F=(0,Q.useMemo)(()=>{let e=new Map;return ae(p).forEach(t=>{e.set(L(t),t)}),e},[p]),fe=(0,Q.useMemo)(()=>{let e=new Map;return m(p).forEach(t=>{e.set(L(t),t)}),e},[p]),I=(0,Q.useCallback)((e,t=``)=>{let n=(()=>{switch(e){case`allow`:return P;case`deny`:return F;case`ask`:return fe;case`workspace`:case`recent`:return new Map}})(),i=[];e!==`workspace`&&e!==`recent`&&!t&&i.push({label:`Add a new rule${r.ellipsis}`,value:`add-new-rule`});let a=Array.from(n.keys()).sort((e,t)=>{let r=n.get(e),i=n.get(t);if(r&&i){let e=R(r.ruleValue).toLowerCase(),t=R(i.ruleValue).toLowerCase();return e.localeCompare(t)}return 0}),o=t.toLowerCase();for(let e of a){let r=n.get(e);if(r){let n=R(r.ruleValue);if(t&&!n.toLowerCase().includes(o))continue;i.push({label:n,value:e})}}return{options:i,rulesByKey:n}},[P,F,fe]),pe=ye(),z=!_&&!y&&!x&&!T&&!O,{query:me,setQuery:B,cursorOffset:he}=we({isActive:z&&A,onExit:()=>{M(!1)}}),ge=(0,Q.useCallback)(e=>{z&&(A||e.ctrl||e.meta||(e.key===`/`?(e.preventDefault(),M(!0),B(``)):e.key.length===1&&e.key!==`j`&&e.key!==`k`&&e.key!==`m`&&e.key!==`i`&&e.key!==`r`&&e.key!==` `&&(e.preventDefault(),M(!0),B(e.key))))},[z,A,B]),V=(0,Q.useCallback)((e,t)=>{let{rulesByKey:n}=I(t);if(e===`add-new-rule`){b(t);return}else{v(n.get(e));return}},[I]),_e=(0,Q.useCallback)(()=>{b(null)},[]),ve=(0,Q.useCallback)((e,t)=>{w({ruleValue:e,ruleBehavior:t}),b(null)},[]),be=(0,Q.useCallback)((e,t)=>{w(null);for(let t of e)f(e=>[...e,`Added ${t.ruleBehavior} rule ${E.bold(R(t.ruleValue))}`]);if(t&&t.length>0)for(let e of t){let t=e.shadowType===`deny`?`blocked`:`shadowed`;f(n=>[...n,E.yellow(`${r.warning} Warning: ${R(e.rule.ruleValue)} is ${t}`),E.dim(` ${e.reason}`),E.dim(` Fix: ${e.fix}`)])}},[]),xe=(0,Q.useCallback)(()=>{w(null)},[]),Ce=(0,Q.useCallback)(()=>D(!0),[]),Te=(0,Q.useCallback)(e=>k(e),[]),H=(0,Q.useCallback)(()=>{let t=g.current,r=e=>Array.from(e).map(e=>t.denials[e]).filter(e=>e!==void 0),i=r(t.retry);if(i.length>0){let t=i.map(e=>e.display);n?.(t),e(void 0,{shouldQuery:!0,metaMessages:[`Permission granted for: ${t.join(`, `)}. You may now retry ${t.length===1?`this command`:`these commands`} if you would like.`]});return}let a=r(t.approved);a.length>0||s.length>0?e([...a.length>0?[`Approved ${a.map(e=>E.bold(e.display)).join(`, `)}`]:[],...s].join(`
3
- `)):e(`Permissions dialog dismissed`,{display:`system`})},[s,e,n]);oe(`confirm:no`,H,{context:`Settings`,isActive:z&&!A});let Ee=()=>{if(!_)return;let{options:e}=I(_.ruleBehavior),t=L(_),n=e.filter(e=>e.value!==`add-new-rule`).map(e=>e.value),r=n.indexOf(t),i;r!==-1&&(r<n.length-1?i=n[r+1]:r>0&&(i=n[r-1])),ie(i),l({rule:_,initialContext:p,setToolPermissionContext(e){h(t=>({...t,toolPermissionContext:e}))}}),f(e=>[...e,`Deleted ${_.ruleBehavior} rule ${E.bold(R(_.ruleValue))}`]),v(void 0)};if(_)return(0,$.jsx)(Je,{rule:_,onDelete:Ee,onCancel:()=>v(void 0)});if(y&&y!==`workspace`&&y!==`recent`)return(0,$.jsx)(Fe,{onCancel:_e,onSubmit:ve,ruleBehavior:y});if(x)return(0,$.jsx)(Me,{onAddRules:be,onCancel:xe,ruleValues:[x.ruleValue],ruleBehavior:x.ruleBehavior,initialContext:p,setToolPermissionContext:e=>{h(t=>({...t,toolPermissionContext:e}))}});if(T)return(0,$.jsx)(Se,{onAddDirectory:(e,t)=>{let n={type:`addDirectories`,directories:[e],destination:t?`localSettings`:`session`},r=c(p,n);h(e=>({...e,toolPermissionContext:r})),t&&u(n),f(n=>[...n,`Added directory ${E.bold(e)} to workspace${t?` and saved to local settings`:` for this session`}`]),D(!1)},onCancel:()=>D(!1),permissionContext:p});if(O)return(0,$.jsx)(Be,{directoryPath:O,onRemove:()=>{f(e=>[...e,`Removed directory ${E.bold(O)} from workspace`]),k(null)},onCancel:()=>k(null),permissionContext:p,setPermissionContext:e=>{h(t=>({...t,toolPermissionContext:e}))}});let U={searchQuery:me,isSearchMode:A,isFocused:ee,onCancel:H,lastFocusedRuleKey:re,cursorOffset:he,getRulesOptions:I,handleToolSelect:V,onHeaderFocusChange:N};return(0,$.jsx)(S,{flexDirection:`column`,onKeyDown:ge,children:(0,$.jsxs)(de,{color:`permission`,children:[(0,$.jsxs)(le,{title:`Permissions:`,color:`permission`,defaultTab:o,hidden:!!_||!!y||!!x||T||!!O,initialHeaderFocused:!a,navFromContent:!A,children:[(0,$.jsx)(j,{id:`recent`,title:`Recently denied`,children:(0,$.jsx)(Re,{onHeaderFocusChange:N,onStateChange:te})}),(0,$.jsx)(j,{id:`allow`,title:`Allow`,children:(0,$.jsx)(Xe,{tab:`allow`,...U})}),(0,$.jsx)(j,{id:`ask`,title:`Ask`,children:(0,$.jsx)(Xe,{tab:`ask`,...U})}),(0,$.jsx)(j,{id:`deny`,title:`Deny`,children:(0,$.jsx)(Xe,{tab:`deny`,...U})}),(0,$.jsx)(j,{id:`workspace`,title:`Workspace`,children:(0,$.jsxs)(S,{flexDirection:`column`,children:[(0,$.jsx)(C,{children:`Work Mate can read files in the workspace, and make edits when auto-accept edits is on.`}),(0,$.jsx)(Ue,{onExit:e,toolPermissionContext:p,onRequestAddDirectory:Ce,onRequestRemoveDirectory:Te,onHeaderFocusChange:N})]})})]}),(0,$.jsx)(S,{marginTop:1,paddingLeft:1,children:(0,$.jsx)(C,{dimColor:!0,children:pe.pending?(0,$.jsxs)($.Fragment,{children:[`Press `,pe.keyName,` again to exit`]}):ce?(0,$.jsx)($.Fragment,{children:`←/→ tab switch · ↓ return · Esc cancel`}):A?(0,$.jsx)($.Fragment,{children:`Type to filter · Enter/↓ select · ↑ tabs · Esc clear`}):a&&o===`recent`?(0,$.jsx)($.Fragment,{children:`Enter approve · r retry · ↑↓ navigate · ←/→ switch · Esc cancel`}):(0,$.jsx)($.Fragment,{children:`↑↓ navigate · Enter select · Type to search · ←/→ switch · Esc cancel`})})})]})})}var Q,$,Qe=e((()=>{D(),n(),Q=t(T(),1),te(),o(),a(),be(),Te(),N(),y(),Oe(),V(),ee(),pe(),Ce(),Pe(),xe(),Ae(),Le(),ze(),He(),Ge(),$=F()})),$e,et;e((()=>{Qe(),f(),$e=F(),et=async(e,t)=>(0,$e.jsx)(Ze,{onExit:e,onRetryDenials:e=>{t.setMessages(t=>[...t,_(e)])}})}))();export{et as call};
1
+ import{n as e,o as t}from"./rolldown-runtime-DaDcL9Zw.js";import{n,t as r}from"./figures-5ThXQEtq.js";import{$h as i,$u as a,Gg as o,H as s,Hg as c,I as l,Kg as u,L as d,La as f,Qu as p,R as m,Um as h,V as ee,Wm as g,Xh as te,Zh as ne,_a as _,cd as v,hC as re,ld as ie,oT as y,rT as b,xC as x,z as ae}from"./loadAgentsDir-PPiD2Mfq.js";import{I as S,P as C,Wt as oe,Xn as se,a as w,ai as T,di as E,fi as D,hn as O,k,kt as A,n as j,o as M,ot as ce,r as le,s as ue,t as N,x as de,y as P}from"./src-DL3w8VPk2.js";import{t as F}from"./jsx-runtime-Bb4Xn-E0.js";import{Wt as fe,et as I}from"./state-BPFYBqm1.js";import{C as L,x as pe}from"./debug-BQj6h99Q.js";import{H as R,V as z,g as me,ln as B,o as he,rn as ge,z as V}from"./settings-CvhsRFaT.js";import{l as _e,o as ve}from"./stringUtils-BjnclTLB.js";import{n as ye,t as be}from"./useExitOnCtrlCDWithKeybindings-C9orgrub.js";import{n as xe,t as Se}from"./AddWorkspaceDirectory-DAtfMH4o.js";import{t as Ce}from"./SearchBox-CwwV0W-w.js";import{n as we,t as Te}from"./useSearchInput-DdKrVHJS.js";import{n as H,t as Ee}from"./shadowedRuleDetection-Co8m1q1D.js";function De(){return U}var U,Oe=e((()=>{U=[]}));function ke({ruleValue:e}){switch(e.toolName){case h.name:return e.ruleContent?e.ruleContent.endsWith(`:*`)?(0,W.jsxs)(C,{dimColor:!0,children:[`Any Bash command starting with `,(0,W.jsx)(C,{bold:!0,children:e.ruleContent.slice(0,-2)})]}):(0,W.jsxs)(C,{dimColor:!0,children:[`The Bash command `,(0,W.jsx)(C,{bold:!0,children:e.ruleContent})]}):(0,W.jsx)(C,{dimColor:!0,children:`Any Bash command`});default:return e.ruleContent?null:(0,W.jsxs)(C,{dimColor:!0,children:[`Any use of the `,(0,W.jsx)(C,{bold:!0,children:e.toolName}),` tool`]})}}var W,Ae=e((()=>{N(),g(),W=F()}));function je(e){switch(e){case`localSettings`:return{label:`Project settings (local)`,description:`Saved in ${he(`localSettings`)}`,value:e};case`projectSettings`:return{label:`Project settings`,description:`Checked in at ${he(`projectSettings`)}`,value:e};case`userSettings`:return{label:`User settings`,description:`Saved in at ~/.workmate/settings.json`,value:e}}}function Me({onAddRules:e,onCancel:t,ruleValues:n,ruleBehavior:r,initialContext:i,setToolPermissionContext:a}){let o=ge.map(je),s=(0,Ne.useCallback)(o=>{if(o===`cancel`){t();return}else if(ge.includes(o)){let t=o,s=c(i,{type:`addRules`,rules:n,behavior:r,destination:t});u({type:`addRules`,rules:n,behavior:r,destination:t}),a(s);let l=n.map(e=>({ruleValue:e,ruleBehavior:r,source:t})),d=Ee(s,{sandboxAutoAllowEnabled:b.isSandboxingEnabled()&&b.isAutoAllowBashIfSandboxedEnabled()}).filter(e=>n.some(t=>t.toolName===e.rule.ruleValue.toolName&&t.ruleContent===e.rule.ruleValue.ruleContent));e(l,d.length>0?d:void 0)}},[e,t,n,r,i,a]);return(0,G.jsxs)(P,{title:`Add ${r} permission ${_e(n.length,`rule`)}`,onCancel:t,color:`permission`,children:[(0,G.jsx)(S,{flexDirection:`column`,paddingX:2,children:n.map(e=>(0,G.jsxs)(S,{flexDirection:`column`,children:[(0,G.jsx)(C,{bold:!0,children:R(e)}),(0,G.jsx)(ke,{ruleValue:e})]},R(e)))}),(0,G.jsxs)(S,{flexDirection:`column`,marginY:1,children:[(0,G.jsx)(C,{children:n.length===1?`Where should this rule be saved?`:`Where should these rules be saved?`}),(0,G.jsx)(p,{options:o,onChange:s})]})]})}var Ne,G,Pe=e((()=>{Ne=t(T(),1),a(),N(),o(),V(),H(),y(),B(),me(),ve(),Ae(),G=F()}));function Fe({onCancel:e,onSubmit:t,ruleBehavior:n}){let[i,a]=(0,Ie.useState)(``),[o,s]=(0,Ie.useState)(0),c=ye();oe(`confirm:no`,e,{context:`Settings`});let{columns:l}=ce(),u=l-6;return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(S,{flexDirection:`column`,gap:1,borderStyle:`round`,paddingLeft:1,paddingRight:1,borderColor:`permission`,children:[(0,K.jsxs)(C,{bold:!0,color:`permission`,children:[`Add `,n,` permission rule`]}),(0,K.jsxs)(S,{flexDirection:`column`,children:[(0,K.jsxs)(C,{children:[`Permission rules are a tool name, optionally followed by a specifier in parentheses.`,(0,K.jsx)(A,{}),`e.g., `,(0,K.jsx)(C,{bold:!0,children:R({toolName:h.name})}),(0,K.jsx)(C,{bold:!1,children:` or `}),(0,K.jsx)(C,{bold:!0,children:R({toolName:h.name,ruleContent:`ls:*`})})]}),(0,K.jsx)(S,{borderDimColor:!0,borderStyle:`round`,marginY:1,paddingLeft:1,children:(0,K.jsx)(v,{showCursor:!0,value:i,onChange:a,onSubmit:e=>{let r=e.trim();r.length!==0&&t(z(r),n)},placeholder:`Enter permission rule${r.ellipsis}`,columns:u,cursorOffset:o,onChangeCursorOffset:s})})]})]}),(0,K.jsx)(S,{marginLeft:3,children:c.pending?(0,K.jsxs)(C,{dimColor:!0,children:[`Press `,c.keyName,` again to exit`]}):(0,K.jsx)(C,{dimColor:!0,children:`Enter to submit · Esc to cancel`})})]})}var Ie,K,Le=e((()=>{n(),Ie=t(T(),1),ie(),be(),x(),N(),re(),g(),V(),K=F()}));function Re({onHeaderFocusChange:e,onStateChange:t}){let{headerFocused:n,focusHeader:r}=w();(0,q.useEffect)(()=>{e?.(n)},[n,e]);let[i]=(0,q.useState)(()=>De()),[a,o]=(0,q.useState)(()=>new Set),[s,c]=(0,q.useState)(()=>new Set),[l,u]=(0,q.useState)(0);(0,q.useEffect)(()=>{t({approved:a,retry:s,denials:i})},[a,s,i,t]);let d=(0,q.useCallback)(e=>{let t=Number(e);o(e=>{let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n})},[]),f=(0,q.useCallback)(e=>{u(Number(e))},[]);if(O((e,t)=>{e===`r`&&(c(e=>{let t=new Set(e);return t.has(l)?t.delete(l):t.add(l),t}),o(e=>{if(e.has(l))return e;let t=new Set(e);return t.add(l),t}))},{isActive:i.length>0}),i.length===0)return(0,J.jsx)(C,{dimColor:!0,children:`No recent denials. Commands denied by the auto mode classifier will appear here.`});let m=i.map((e,t)=>{let n=a.has(t),r=s.has(t)?` (retry)`:``;return{label:(0,J.jsxs)(C,{children:[(0,J.jsx)(ue,{status:n?`success`:`error`,withSpace:!0}),e.display,(0,J.jsx)(C,{dimColor:!0,children:r})]}),value:String(t)}});return(0,J.jsxs)(S,{flexDirection:`column`,children:[(0,J.jsx)(C,{children:`Commands recently denied by the auto mode classifier.`}),(0,J.jsx)(S,{marginTop:1,children:(0,J.jsx)(p,{options:m,onChange:d,onFocus:f,visibleOptionCount:Math.min(10,m.length),isDisabled:n,onUpFromFirstItem:r})})]})}var q,J,ze=e((()=>{q=t(T(),1),N(),Oe(),a(),J=F()}));function Be({directoryPath:e,onRemove:t,onCancel:n,permissionContext:r,setPermissionContext:i}){let a=(0,Ve.useCallback)(()=>{i(c(r,{type:`removeDirectories`,directories:[e],destination:`session`})),t()},[e,r,i,t]),o=(0,Ve.useCallback)(e=>{e===`yes`?a():n()},[a,n]);return(0,Y.jsxs)(P,{title:`Remove directory from workspace?`,onCancel:n,color:`error`,children:[(0,Y.jsx)(S,{marginX:2,flexDirection:`column`,children:(0,Y.jsx)(C,{bold:!0,children:e})}),(0,Y.jsx)(C,{children:`Work Mate will no longer have access to files in this directory.`}),(0,Y.jsx)(p,{onChange:o,onCancel:n,options:[{label:`Yes`,value:`yes`},{label:`No`,value:`no`}]})]})}var Ve,Y,He=e((()=>{Ve=t(T(),1),a(),N(),o(),Y=F()}));function Ue({onExit:e,toolPermissionContext:t,onRequestAddDirectory:n,onRequestRemoveDirectory:i,onHeaderFocusChange:a}){let{headerFocused:o,focusHeader:s}=w();(0,X.useEffect)(()=>{a?.(o)},[o,a]);let c=We.useMemo(()=>Array.from(t.additionalWorkingDirectories.keys()).map(e=>({path:e,isCurrent:!1,isDeletable:!0})),[t.additionalWorkingDirectories]),l=(0,X.useCallback)(e=>{if(e===`add-directory`){n();return}let t=c.find(t=>t.path===e);t?.isDeletable&&i(t.path)},[c,n,i]),u=(0,X.useCallback)(()=>e(`Workspace dialog dismissed`,{display:`system`}),[e]),d=We.useMemo(()=>{let e=c.map(e=>({label:e.path,value:e.path}));return e.push({label:`Add directory${r.ellipsis}`,value:`add-directory`}),e},[c]);return(0,Z.jsxs)(S,{flexDirection:`column`,marginBottom:1,children:[(0,Z.jsxs)(S,{flexDirection:`row`,marginTop:1,marginLeft:2,gap:1,children:[(0,Z.jsx)(C,{children:`- ${I()}`}),(0,Z.jsx)(C,{dimColor:!0,children:`(Original working directory)`})]}),(0,Z.jsx)(p,{options:d,onChange:l,onCancel:u,visibleOptionCount:Math.min(10,d.length),onUpFromFirstItem:s,isDisabled:o})]})}var We,X,Z,Ge=e((()=>{n(),We=t(T(),1),X=t(T(),1),fe(),a(),N(),Z=F()}));function Ke({rule:e}){return(0,$.jsx)(C,{dimColor:!0,children:`From ${s(e.source)}`})}function qe(e){switch(e){case`allow`:return`allowed`;case`deny`:return`denied`;case`ask`:return`ask`}}function Je({rule:e,onDelete:t,onCancel:n}){let r=ye();oe(`confirm:no`,n,{context:`Confirmation`});let i=(0,$.jsxs)(S,{flexDirection:`column`,marginX:2,children:[(0,$.jsx)(C,{bold:!0,children:R(e.ruleValue)}),(0,$.jsx)(ke,{ruleValue:e.ruleValue}),(0,$.jsx)(Ke,{rule:e})]}),a=(0,$.jsx)(S,{marginLeft:3,children:r.pending?(0,$.jsxs)(C,{dimColor:!0,children:[`Press `,r.keyName,` again to exit`]}):(0,$.jsx)(C,{dimColor:!0,children:`Esc to cancel`})});return e.source===`policySettings`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(S,{flexDirection:`column`,gap:1,borderStyle:`round`,paddingLeft:1,paddingRight:1,borderColor:`permission`,children:[(0,$.jsx)(C,{bold:!0,color:`permission`,children:`Rule details`}),i,(0,$.jsxs)(C,{italic:!0,children:[`This rule is configured by managed settings and cannot be modified.`,`
2
+ `,`Contact your system administrator for more information.`]})]}),a]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(S,{flexDirection:`column`,gap:1,borderStyle:`round`,paddingLeft:1,paddingRight:1,borderColor:`error`,children:[(0,$.jsxs)(C,{bold:!0,color:`error`,children:[`Delete `,qe(e.ruleBehavior),` tool?`]}),i,(0,$.jsx)(C,{children:`Are you sure you want to delete this permission rule?`}),(0,$.jsx)(p,{onChange:e=>e===`yes`?t():n(),onCancel:n,options:[{label:`Yes`,value:`yes`},{label:`No`,value:`no`}]})]}),a]})}function Ye(e){let{options:t,searchQuery:n,isSearchMode:r,isFocused:i,onSelect:a,onCancel:o,lastFocusedRuleKey:s,cursorOffset:c,onHeaderFocusChange:l}=e,u=M(),{headerFocused:d,focusHeader:f,blurHeader:m}=w();return(0,Q.useEffect)(()=>{r&&d&&m()},[r,d,m]),(0,Q.useEffect)(()=>{l?.(d)},[d,l]),(0,$.jsxs)(S,{flexDirection:`column`,children:[(0,$.jsx)(S,{marginBottom:1,flexDirection:`column`,children:(0,$.jsx)(k,{query:n,isFocused:r&&!d,isTerminalFocused:i,width:u,cursorOffset:c})}),(0,$.jsx)(p,{options:t,onChange:a,onCancel:o,visibleOptionCount:Math.min(10,t.length),isDisabled:r||d,defaultFocusValue:s,onUpFromFirstItem:f})]})}function Xe({tab:e,getRulesOptions:t,handleToolSelect:n,...r}){return(0,$.jsxs)(S,{flexDirection:`column`,flexShrink:e===`allow`?0:void 0,children:[(0,$.jsx)(C,{children:{allow:`Work Mate won't ask before using allowed tools.`,ask:`Work Mate will always ask for confirmation before using these tools.`,deny:`Work Mate will always reject requests to use denied tools.`}[e]}),(0,$.jsx)(Ye,{options:t(e,r.searchQuery).options,onSelect:t=>n(t,e),...r})]})}function Ze({onExit:e,initialTab:t,onRetryDenials:n}){let a=De().length>0,o=t??(a?`recent`:`allow`),[s,f]=(0,Q.useState)([]),p=ne(e=>e.toolPermissionContext),h=i(),ee=se(),g=(0,Q.useRef)({approved:new Set,retry:new Set,denials:[]}),te=(0,Q.useCallback)(e=>{g.current=e},[]),[_,v]=(0,Q.useState)(),[re,ie]=(0,Q.useState)(),[y,b]=(0,Q.useState)(null),[x,w]=(0,Q.useState)(null),[T,D]=(0,Q.useState)(!1),[O,k]=(0,Q.useState)(null),[A,M]=(0,Q.useState)(!1),[ce,ue]=(0,Q.useState)(!0),N=(0,Q.useCallback)(e=>{ue(e)},[]),P=(0,Q.useMemo)(()=>{let e=new Map;return d(p).forEach(t=>{e.set(L(t),t)}),e},[p]),F=(0,Q.useMemo)(()=>{let e=new Map;return ae(p).forEach(t=>{e.set(L(t),t)}),e},[p]),fe=(0,Q.useMemo)(()=>{let e=new Map;return m(p).forEach(t=>{e.set(L(t),t)}),e},[p]),I=(0,Q.useCallback)((e,t=``)=>{let n=(()=>{switch(e){case`allow`:return P;case`deny`:return F;case`ask`:return fe;case`workspace`:case`recent`:return new Map}})(),i=[];e!==`workspace`&&e!==`recent`&&!t&&i.push({label:`Add a new rule${r.ellipsis}`,value:`add-new-rule`});let a=Array.from(n.keys()).sort((e,t)=>{let r=n.get(e),i=n.get(t);if(r&&i){let e=R(r.ruleValue).toLowerCase(),t=R(i.ruleValue).toLowerCase();return e.localeCompare(t)}return 0}),o=t.toLowerCase();for(let e of a){let r=n.get(e);if(r){let n=R(r.ruleValue);if(t&&!n.toLowerCase().includes(o))continue;i.push({label:n,value:e})}}return{options:i,rulesByKey:n}},[P,F,fe]),pe=ye(),z=!_&&!y&&!x&&!T&&!O,{query:me,setQuery:B,cursorOffset:he}=we({isActive:z&&A,onExit:()=>{M(!1)}}),ge=(0,Q.useCallback)(e=>{z&&(A||e.ctrl||e.meta||(e.key===`/`?(e.preventDefault(),M(!0),B(``)):e.key.length===1&&e.key!==`j`&&e.key!==`k`&&e.key!==`m`&&e.key!==`i`&&e.key!==`r`&&e.key!==` `&&(e.preventDefault(),M(!0),B(e.key))))},[z,A,B]),V=(0,Q.useCallback)((e,t)=>{let{rulesByKey:n}=I(t);if(e===`add-new-rule`){b(t);return}else{v(n.get(e));return}},[I]),_e=(0,Q.useCallback)(()=>{b(null)},[]),ve=(0,Q.useCallback)((e,t)=>{w({ruleValue:e,ruleBehavior:t}),b(null)},[]),be=(0,Q.useCallback)((e,t)=>{w(null);for(let t of e)f(e=>[...e,`Added ${t.ruleBehavior} rule ${E.bold(R(t.ruleValue))}`]);if(t&&t.length>0)for(let e of t){let t=e.shadowType===`deny`?`blocked`:`shadowed`;f(n=>[...n,E.yellow(`${r.warning} Warning: ${R(e.rule.ruleValue)} is ${t}`),E.dim(` ${e.reason}`),E.dim(` Fix: ${e.fix}`)])}},[]),xe=(0,Q.useCallback)(()=>{w(null)},[]),Ce=(0,Q.useCallback)(()=>D(!0),[]),Te=(0,Q.useCallback)(e=>k(e),[]),H=(0,Q.useCallback)(()=>{let t=g.current,r=e=>Array.from(e).map(e=>t.denials[e]).filter(e=>e!==void 0),i=r(t.retry);if(i.length>0){let t=i.map(e=>e.display);n?.(t),e(void 0,{shouldQuery:!0,metaMessages:[`Permission granted for: ${t.join(`, `)}. You may now retry ${t.length===1?`this command`:`these commands`} if you would like.`]});return}let a=r(t.approved);a.length>0||s.length>0?e([...a.length>0?[`Approved ${a.map(e=>E.bold(e.display)).join(`, `)}`]:[],...s].join(`
3
+ `)):e(`Permissions dialog dismissed`,{display:`system`})},[s,e,n]);oe(`confirm:no`,H,{context:`Settings`,isActive:z&&!A});let Ee=()=>{if(!_)return;let{options:e}=I(_.ruleBehavior),t=L(_),n=e.filter(e=>e.value!==`add-new-rule`).map(e=>e.value),r=n.indexOf(t),i;r!==-1&&(r<n.length-1?i=n[r+1]:r>0&&(i=n[r-1])),ie(i),l({rule:_,initialContext:p,setToolPermissionContext(e){h(t=>({...t,toolPermissionContext:e}))}}),f(e=>[...e,`Deleted ${_.ruleBehavior} rule ${E.bold(R(_.ruleValue))}`]),v(void 0)};if(_)return(0,$.jsx)(Je,{rule:_,onDelete:Ee,onCancel:()=>v(void 0)});if(y&&y!==`workspace`&&y!==`recent`)return(0,$.jsx)(Fe,{onCancel:_e,onSubmit:ve,ruleBehavior:y});if(x)return(0,$.jsx)(Me,{onAddRules:be,onCancel:xe,ruleValues:[x.ruleValue],ruleBehavior:x.ruleBehavior,initialContext:p,setToolPermissionContext:e=>{h(t=>({...t,toolPermissionContext:e}))}});if(T)return(0,$.jsx)(Se,{onAddDirectory:(e,t)=>{let n={type:`addDirectories`,directories:[e],destination:t?`localSettings`:`session`},r=c(p,n);h(e=>({...e,toolPermissionContext:r})),t&&u(n),f(n=>[...n,`Added directory ${E.bold(e)} to workspace${t?` and saved to local settings`:` for this session`}`]),D(!1)},onCancel:()=>D(!1),permissionContext:p});if(O)return(0,$.jsx)(Be,{directoryPath:O,onRemove:()=>{f(e=>[...e,`Removed directory ${E.bold(O)} from workspace`]),k(null)},onCancel:()=>k(null),permissionContext:p,setPermissionContext:e=>{h(t=>({...t,toolPermissionContext:e}))}});let U={searchQuery:me,isSearchMode:A,isFocused:ee,onCancel:H,lastFocusedRuleKey:re,cursorOffset:he,getRulesOptions:I,handleToolSelect:V,onHeaderFocusChange:N};return(0,$.jsx)(S,{flexDirection:`column`,onKeyDown:ge,children:(0,$.jsxs)(de,{color:`permission`,children:[(0,$.jsxs)(le,{title:`Permissions:`,color:`permission`,defaultTab:o,hidden:!!_||!!y||!!x||T||!!O,initialHeaderFocused:!a,navFromContent:!A,children:[(0,$.jsx)(j,{id:`recent`,title:`Recently denied`,children:(0,$.jsx)(Re,{onHeaderFocusChange:N,onStateChange:te})}),(0,$.jsx)(j,{id:`allow`,title:`Allow`,children:(0,$.jsx)(Xe,{tab:`allow`,...U})}),(0,$.jsx)(j,{id:`ask`,title:`Ask`,children:(0,$.jsx)(Xe,{tab:`ask`,...U})}),(0,$.jsx)(j,{id:`deny`,title:`Deny`,children:(0,$.jsx)(Xe,{tab:`deny`,...U})}),(0,$.jsx)(j,{id:`workspace`,title:`Workspace`,children:(0,$.jsxs)(S,{flexDirection:`column`,children:[(0,$.jsx)(C,{children:`Work Mate can read files in the workspace, and make edits when auto-accept edits is on.`}),(0,$.jsx)(Ue,{onExit:e,toolPermissionContext:p,onRequestAddDirectory:Ce,onRequestRemoveDirectory:Te,onHeaderFocusChange:N})]})})]}),(0,$.jsx)(S,{marginTop:1,paddingLeft:1,children:(0,$.jsx)(C,{dimColor:!0,children:pe.pending?(0,$.jsxs)($.Fragment,{children:[`Press `,pe.keyName,` again to exit`]}):ce?(0,$.jsx)($.Fragment,{children:`←/→ tab switch · ↓ return · Esc cancel`}):A?(0,$.jsx)($.Fragment,{children:`Type to filter · Enter/↓ select · ↑ tabs · Esc clear`}):a&&o===`recent`?(0,$.jsx)($.Fragment,{children:`Enter approve · r retry · ↑↓ navigate · ←/→ switch · Esc cancel`}):(0,$.jsx)($.Fragment,{children:`↑↓ navigate · Enter select · Type to search · ←/→ switch · Esc cancel`})})})]})})}var Q,$,Qe=e((()=>{D(),n(),Q=t(T(),1),te(),o(),a(),be(),Te(),N(),re(),Oe(),V(),ee(),pe(),Ce(),Pe(),xe(),Ae(),Le(),ze(),He(),Ge(),$=F()})),$e,et;e((()=>{Qe(),f(),$e=F(),et=async(e,t)=>(0,$e.jsx)(Ze,{onExit:e,onRetryDenials:e=>{t.setMessages(t=>[...t,_(e)])}})}))();export{et as call};