claude-code-best 2.6.5 → 2.6.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -5
- package/dist/chunks/{AddWorkspaceDirectory-BYyM_V0q.js → AddWorkspaceDirectory-YmrkKVv2.js} +1 -1
- package/dist/chunks/{App-BboadKdn.js → App-IAjCdPUn.js} +1 -1
- package/dist/chunks/ApproveApiKey-CAvlRKLr.js +1 -0
- package/dist/chunks/{ApproveApiKey-BLp4742y.js → ApproveApiKey-DhsT69v7.js} +1 -1
- package/dist/chunks/{AssistantSessionChooser-B88DM0Oq.js → AssistantSessionChooser-DCUVNGfn.js} +1 -1
- package/dist/chunks/BackgroundTasksDialog-Di_gH2TW.js +2 -0
- package/dist/chunks/BypassPermissionsModeDialog-BeZqE75e.js +1 -0
- package/dist/chunks/{ClaudeInChromeOnboarding-B6XNhFqq.js → ClaudeInChromeOnboarding-CZHktpPE.js} +1 -1
- package/dist/chunks/{ClaudeMdExternalIncludesDialog-BNhlq7_K.js → ClaudeMdExternalIncludesDialog-Dofr1TYr.js} +1 -1
- package/dist/chunks/ClaudeMdExternalIncludesDialog-DrkzPawC.js +1 -0
- package/dist/chunks/ConsoleOAuthFlow-CtqOQRDT.js +1 -0
- package/dist/chunks/{DesktopHandoff-S-w4bs5T.js → DesktopHandoff-C8_CDNft.js} +1 -1
- package/dist/chunks/DevChannelsDialog-DkGWCFpL.js +1 -0
- package/dist/chunks/DiffDialog-93P95op8.js +3 -0
- package/dist/chunks/Doctor-CheDaF3O.js +1 -0
- package/dist/chunks/Doctor-Zd0UaR5d.js +3 -0
- package/dist/chunks/{ExitFlow-CSBDxw9H.js → ExitFlow-4edARxmd.js} +2 -2
- package/dist/chunks/Feedback-CZY-BikO.js +2 -0
- package/dist/chunks/Grove-CbcR0CsI.js +1 -0
- package/dist/chunks/{Grove-DSXRnXKv.js → Grove-TYf1glGP.js} +1 -1
- package/dist/chunks/{HybridTransport-CuT3KI5e.js → HybridTransport-BNexuwcN.js} +2 -2
- package/dist/chunks/{ITermBackend-mokGZVH_.js → ITermBackend-DuomVpsD.js} +1 -1
- package/dist/chunks/{InvalidConfigDialog-Bi4RKYlk.js → InvalidConfigDialog-Byury3Zx.js} +1 -1
- package/dist/chunks/{InvalidSettingsDialog-0zKo4-so.js → InvalidSettingsDialog-B8_0AvWo.js} +1 -1
- package/dist/chunks/MCPConnectionManager-xL_wQCda.js +1 -0
- package/dist/chunks/{McpParsingWarnings-EzgsOoHw.js → McpParsingWarnings-C6u4RM2a.js} +1 -1
- package/dist/chunks/MessageSelector-DAyH1noQ.js +3 -0
- package/dist/chunks/Messages-QH8_sB13.js +11 -0
- package/dist/chunks/{Onboarding-odmthwzz.js → Onboarding-XWhelEBr.js} +1 -1
- package/dist/chunks/{OverageCreditUpsell-Cpk_5Lv0.js → OverageCreditUpsell-BvPz1jLU.js} +1 -1
- package/dist/chunks/PluginSettings-D1YHfrE1.js +17 -0
- package/dist/chunks/{PromptInputFooterSuggestions-DrrkNOuS.js → PromptInputFooterSuggestions-rqUoa9Ch.js} +1 -1
- package/dist/chunks/{PromptInputHelpMenu-DMsF4D6d.js → PromptInputHelpMenu-OTViHSR0.js} +1 -1
- package/dist/chunks/QueryEngine-DigBggXq.js +1 -0
- package/dist/chunks/REPL-Cxh0Qnnt.js +1 -0
- package/dist/chunks/REPL-D2p-vgct.js +97 -0
- package/dist/chunks/{RemoteCallout-CnpCWRPk.js → RemoteCallout-CCIWIrd-.js} +1 -1
- package/dist/chunks/{RemoteSessionManager-OWg_Yccq.js → RemoteSessionManager-Dx81p5dH.js} +2 -2
- package/dist/chunks/ResumeConversation-73r3Zh5P.js +1 -0
- package/dist/chunks/{SSETransport-BpnapvlK.js → SSETransport-C9hd2v-w.js} +1 -1
- package/dist/chunks/SearchExtraToolsTool-BNpA8JzR.js +1 -0
- package/dist/chunks/SentryErrorBoundary-BFwcMSIK.js +1 -0
- package/dist/chunks/{SentryErrorBoundary-C-NlfQZw.js → SentryErrorBoundary-z8tMb-zO.js} +1 -1
- package/dist/chunks/Settings-D9qdaMe5.js +2 -0
- package/dist/chunks/{TeleportProgress-CYXay2ZL.js → TeleportProgress-CPXN7u3Z.js} +1 -1
- package/dist/chunks/{TeleportRepoMismatchDialog-_zbZTvcJ.js → TeleportRepoMismatchDialog-CiyXjTxq.js} +1 -1
- package/dist/chunks/{TeleportResumeWrapper-DiHQeZIM.js → TeleportResumeWrapper-Dao8ktHk.js} +1 -1
- package/dist/chunks/{ThemePicker-BRh027fA.js → ThemePicker-CFYFNnPp.js} +1 -1
- package/dist/chunks/{TmuxBackend-BaX2U7iZ.js → TmuxBackend-B5DBBugq.js} +1 -1
- package/dist/chunks/TrustDialog-DtIXHMR_.js +1 -0
- package/dist/chunks/{ValidationErrorsList-CdCUgfIl.js → ValidationErrorsList-BK0wOS55.js} +1 -1
- package/dist/chunks/{WelcomeV2-DCXcYd2x.js → WelcomeV2-BjUbi9vp.js} +1 -1
- package/dist/chunks/WindowsTerminalBackend-DFLLlAOp.js +2 -0
- package/dist/chunks/{add-dir-ldGd3Ppz.js → add-dir-JoVgNFOk.js} +1 -1
- package/dist/chunks/{agentDisplay-CVnAeURF.js → agentDisplay-B3RjWR-3.js} +1 -1
- package/dist/chunks/{agents-DH5fmbVw.js → agents-BUyLUAIu.js} +7 -7
- package/dist/chunks/{agents-C08NzRZx.js → agents-UqS5PhD2.js} +1 -1
- package/dist/chunks/{ant-DJren1Aa.js → ant-Bq1wIvnP.js} +1 -1
- package/dist/chunks/{api-CGOR_Xfl.js → api-O4eHGLTY.js} +1 -1
- package/dist/chunks/api-kAjsowcb.js +1 -0
- package/dist/chunks/{assistant-aWkDcurV.js → assistant-CMIbt3Ir.js} +1 -1
- package/dist/chunks/{assistant-BlzrMSkM.js → assistant-D5Tg_1ry.js} +1 -1
- package/dist/chunks/assistant-nOCkNa3_.js +1 -0
- package/dist/chunks/auth-CDOk9J9A.js +1 -0
- package/dist/chunks/{auth-CSB2RDKF.js → auth-D3SKo0wT.js} +1 -1
- package/dist/chunks/{autoMode-CWvZs1jO.js → autoMode-BIVJlkBM.js} +6 -6
- package/dist/chunks/{autonomy-DK42aJYt.js → autonomy-BYi6z9LD.js} +1 -1
- package/dist/chunks/{autonomy-BkVcSMCZ.js → autonomy-Mi7Fkq1J.js} +7 -7
- package/dist/chunks/{autonomyPanel-Cn4IhXgE.js → autonomyPanel-D_GsUMOf.js} +1 -1
- package/dist/chunks/backgroundHousekeeping-BG_UYxFF.js +17 -0
- package/dist/chunks/backgroundHousekeeping-wHy1eAso.js +1 -0
- package/dist/chunks/{branch-juox_fko.js → branch-BC-K45fw.js} +1 -1
- package/dist/chunks/{bridge-DudsCZkh.js → bridge-DBteRzgS.js} +2 -2
- package/dist/chunks/{bridgeConfig-lRZfQqmA.js → bridgeConfig-C_GoD1k5.js} +1 -1
- package/dist/chunks/bridgeConfig-V_pmBzSH.js +1 -0
- package/dist/chunks/bridgeEnabled-BxtxHb8R.js +1 -0
- package/dist/chunks/{bridgeEnabled-D2IykaHE.js → bridgeEnabled-cSK8a7tN.js} +1 -1
- package/dist/chunks/bridgeMain-CMNptMs4.js +1 -0
- package/dist/chunks/bridgeMain-QbfEOTqV.js +68 -0
- package/dist/chunks/{bridgeMessaging-CqNURC4-.js → bridgeMessaging-CqXQzew4.js} +1 -1
- package/dist/chunks/{btw-DKlE3Dea.js → btw-DBtPlEWc.js} +1 -1
- package/dist/chunks/{buddy-DQYgHR63.js → buddy-BYwTgNnf.js} +1 -1
- package/dist/chunks/{bypassPermissionsKillswitch-Bof-UtM-.js → bypassPermissionsKillswitch-DkYLp9m0.js} +1 -1
- package/dist/chunks/caches-B-GiT9hm.js +1 -0
- package/dist/chunks/{caches-B5QZDncQ.js → caches-DGW9ovtw.js} +2 -2
- package/dist/chunks/{ccrClient-BaWg4E9-.js → ccrClient-B9pi3b8Y.js} +1 -1
- package/dist/chunks/changeDetector-S1Jti1bW.js +1 -0
- package/dist/chunks/channelNotification-Bx6dpA7I.js +1 -0
- package/dist/chunks/{channelNotification-B7A-9DIl.js → channelNotification-n7Avue-9.js} +1 -1
- package/dist/chunks/{chrome-jMAks7-w.js → chrome-BwZPfW9Z.js} +1 -1
- package/dist/chunks/clear-BXv0Sq3m.js +1 -0
- package/dist/chunks/client-DNQukPEE.js +1 -0
- package/dist/chunks/color-BsBrog6H.js +1 -0
- package/dist/chunks/commands-BK3ugb0u.js +1 -0
- package/dist/chunks/commitAttribution-CtQYmnw-.js +1 -0
- package/dist/chunks/{commitAttribution-C22a3OCi.js → commitAttribution-q7SEukgl.js} +1 -1
- package/dist/chunks/{compact-BWvnb4or.js → compact-DiY1w7pT.js} +3 -3
- package/dist/chunks/{companion-Bkn2lSLj.js → companion-D18UNnC7.js} +1 -1
- package/dist/chunks/{config-BvpTbJ5p.js → config-CSHnElBp.js} +1 -1
- package/dist/chunks/{config-D-dzD6n-.js → config-D3QKcEKz.js} +1 -1
- package/dist/chunks/{context-DzNahdyP.js → context-DnyYrN2X.js} +1 -1
- package/dist/chunks/context-noninteractive-0YpW67KZ.js +1 -0
- package/dist/chunks/{context-noninteractive-yiyJriiw.js → context-noninteractive-CFlod2Eg.js} +2 -2
- package/dist/chunks/conversation-CRoOMglD.js +1 -0
- package/dist/chunks/conversation-DCG0fiGV.js +1 -0
- package/dist/chunks/{copy-9k9JPRqW.js → copy-CHGX-YpC.js} +2 -2
- package/dist/chunks/{createSSHSession-BZf-Loo5.js → createSSHSession-Bf-8h3Sw.js} +1 -1
- package/dist/chunks/createSession-BYf27ahD.js +1 -0
- package/dist/chunks/{createSession-kiTHYXSL.js → createSession-rRZIkjl3.js} +1 -1
- package/dist/chunks/{cronJitterConfig-CYP7yrQu.js → cronJitterConfig-DmBBJDTf.js} +3 -3
- package/dist/chunks/crossProjectResume-BQxLBpDD.js +40 -0
- package/dist/chunks/{datadog-Bg-zL-i7.js → datadog-Bb65d6yd.js} +1 -1
- package/dist/chunks/datadog-NnzM1Mu3.js +1 -0
- package/dist/chunks/{desktop-DpaStjc-.js → desktop-DiCA6RUU.js} +1 -1
- package/dist/chunks/{diff-N_VSBo3Z.js → diff-BvLQ-t8P.js} +1 -1
- package/dist/chunks/{doctor-CUWjbh1X.js → doctor-bmTXLycZ.js} +1 -1
- package/dist/chunks/{effort-loH1TUvE.js → effort-CSTwkB2B.js} +2 -2
- package/dist/chunks/{entry-D58E-E6Y.js → entry-BUwwv2dM.js} +4 -4
- package/dist/chunks/{envLessBridgeConfig-SPEr9oqO.js → envLessBridgeConfig-DJJKeDBT.js} +1 -1
- package/dist/chunks/envLessBridgeConfig-Dq02Vvx1.js +1 -0
- package/dist/chunks/{exit-D-tuPpbx.js → exit-eirVuF-n.js} +1 -1
- package/dist/chunks/{export-BIZ_SPXJ.js → export-CcJD8r8U.js} +1 -1
- package/dist/chunks/{exportRenderer-CWPSMaqM.js → exportRenderer-DtezFcml.js} +1 -1
- package/dist/chunks/{extra-usage-CCMwIa85.js → extra-usage-CBcgeIcJ.js} +1 -1
- package/dist/chunks/extra-usage-DhB0NElh.js +1 -0
- package/dist/chunks/{extra-usage-core-BNW4VT7o.js → extra-usage-core-DWM0Q56J.js} +1 -1
- package/dist/chunks/{extra-usage-noninteractive-B_WjXO1E.js → extra-usage-noninteractive-BvJEi4WX.js} +1 -1
- package/dist/chunks/{extraUsage-CNMMTNJi.js → extraUsage-CWde-Mi0.js} +1 -1
- package/dist/chunks/extractMemories-wcRNh_jz.js +1 -0
- package/dist/chunks/{fast-CG1v3fRr.js → fast-DQyJ7c7s.js} +1 -1
- package/dist/chunks/fast-ukzN3wl2.js +1 -0
- package/dist/chunks/{feedback-CG4mS_-B.js → feedback-BzBBKT2y.js} +1 -1
- package/dist/chunks/{firstPartyEventLogger-Y_jAnHoR.js → firstPartyEventLogger-BOHIpp-w.js} +1 -1
- package/dist/chunks/{flushGate-COPcye5f.js → flushGate-DeCDhkKp.js} +1 -1
- package/dist/chunks/{gates-CSKxLmMJ.js → gates-CAVdjC23.js} +1 -1
- package/dist/chunks/gates-CB_pFChT.js +1 -0
- package/dist/chunks/{gemini-B3uSLiNp.js → gemini-CFrOUVS4.js} +1 -1
- package/dist/chunks/{generateRecap-D7rG3jIm.js → generateRecap-Bcp5DiiO.js} +1 -1
- package/dist/chunks/{generateSessionName-zbqanivg.js → generateSessionName-DeFGkHct.js} +1 -1
- package/dist/chunks/{githubRepoPathMapping-B04nEUDG.js → githubRepoPathMapping-B07Wb07_.js} +1 -1
- package/dist/chunks/grok-DtidcVWD.js +1 -0
- package/dist/chunks/{growthbook-C_EY78Sn.js → growthbook-gLwBDK-r.js} +1 -1
- package/dist/chunks/{heapdump-CpmhJ55b.js → heapdump-BxQYlnPR.js} +1 -1
- package/dist/chunks/{help-EHn2neTv.js → help-Bi0sABuv.js} +1 -1
- package/dist/chunks/hooks-BTBhK9sh.js +1 -0
- package/dist/chunks/{hooks-BV6HqbU4.js → hooks-Cc_DxF9N.js} +2 -2
- package/dist/chunks/{hostAdapter-_SmFAVNf.js → hostAdapter-D9_d4gU0.js} +1 -1
- package/dist/chunks/{ide-DkN0KdTR.js → ide-3wDIOoZF.js} +2 -2
- package/dist/chunks/inboundAttachments-DBaPmCTv.js +1 -0
- package/dist/chunks/{inboundAttachments-DnGQw7Pf.js → inboundAttachments-DPMETKd6.js} +1 -1
- package/dist/chunks/initReplBridge-BWP41EGm.js +1 -0
- package/dist/chunks/{insights-Bs9kJDG6.js → insights-w7qM4YyA.js} +24 -24
- package/dist/chunks/{install-CFX_ph9z.js → install-N2FgArWv.js} +1 -1
- package/dist/chunks/{install-github-app-CvRjY1Wi.js → install-github-app-By39Zi78.js} +2 -2
- package/dist/chunks/{install-slack-app-DjhnVSe0.js → install-slack-app-CVwZphU-.js} +1 -1
- package/dist/chunks/{instrumentation-c5zlOWom.js → instrumentation-BkLEupDC.js} +3 -3
- package/dist/chunks/{job-3QwLq609.js → job-CgBE27O7.js} +1 -1
- package/dist/chunks/{keybindings-7mDm3UKD.js → keybindings-DHXJzU3E.js} +2 -2
- package/dist/chunks/{lang-DyyjY20G.js → lang-DLneRt1b.js} +1 -1
- package/dist/chunks/{language-CPRGmY8Q.js → language-BVAzlrRz.js} +1 -1
- package/dist/chunks/language-ZBygqv6V.js +1 -0
- package/dist/chunks/{launchAgentsPlatform-CpsMsTqQ.js → launchAgentsPlatform-CtfK0qPa.js} +1 -1
- package/dist/chunks/launchAutofixPr-CQBv0rQ0.js +18 -0
- package/dist/chunks/{launchLocalMemory-DlYQcEQJ.js → launchLocalMemory-BNE09TKr.js} +2 -2
- package/dist/chunks/{launchLocalVault-CP0AyPjj.js → launchLocalVault-Dw_NJUnd.js} +3 -3
- package/dist/chunks/{launchMemoryStores-BHoDFkJ5.js → launchMemoryStores-CRRB6Z5A.js} +1 -1
- package/dist/chunks/{launchOnboarding-CFTNXcnc.js → launchOnboarding-nMAF5iv7.js} +1 -1
- package/dist/chunks/{launchSchedule-5KQr6x_A.js → launchSchedule-Akq1AmK8.js} +1 -1
- package/dist/chunks/{launchSkillStore-D0yGuE68.js → launchSkillStore-Zwtasj13.js} +1 -1
- package/dist/chunks/{launchTeleport-DRKnXOwY.js → launchTeleport-BzlIYyll.js} +3 -3
- package/dist/chunks/{launchVault-XA-zAswX.js → launchVault-BevXlxJB.js} +1 -1
- package/dist/chunks/{loadAgentsDir-DI1a76pd.js → loadAgentsDir-DF6FgRn-.js} +812 -785
- package/dist/chunks/loadAgentsDir-OIIKHPq9.js +1 -0
- package/dist/chunks/loadPluginHooks-DBHkyJaj.js +1 -0
- package/dist/chunks/localSearch-DslXIfeC.js +1 -0
- package/dist/chunks/{localSearch-CDOJNc_E.js → localSearch-v4itMlCM.js} +1 -1
- package/dist/chunks/{login-nwTOoyxv.js → login-CKodBzyZ.js} +1 -1
- package/dist/chunks/login-CTIVwgFU.js +1 -0
- package/dist/chunks/{logoV2Utils-DDUoPClc.js → logoV2Utils-VebeEs7Y.js} +1 -1
- package/dist/chunks/logout-B3MyP8fk.js +1 -0
- package/dist/chunks/{magicDocs-CmUlOWjI.js → magicDocs-uX5n3NKh.js} +2 -2
- package/dist/chunks/{main-CeG_nUsC.js → main-Cd_i0ZPo.js} +40 -40
- package/dist/chunks/{mappers-CJ8IO1o1.js → mappers-CPL2ni36.js} +1 -1
- package/dist/chunks/{mcp-CanCqnch.js → mcp-Ci_TbB5m.js} +2 -2
- package/dist/chunks/mcp-DeWOD4B4.js +1 -0
- package/dist/chunks/mcp-Dhp1SaId.js +6 -0
- package/dist/chunks/{mcpServer-lIneUZ5p.js → mcpServer-CPJo2eKm.js} +1 -1
- package/dist/chunks/{mcpServer-DPHQVYdC.js → mcpServer-CTuPkyD6.js} +1 -1
- package/dist/chunks/{memory-BcWBkKV8.js → memory-enMuKEnU.js} +1 -1
- package/dist/chunks/{model-DJLzVvcF.js → model-4f3U2YMu.js} +1 -1
- package/dist/chunks/model-BsHyPvD0.js +1 -0
- package/dist/chunks/{onChangeAppState-Dxbl8fvk.js → onChangeAppState-DxTGoS7j.js} +1 -1
- package/dist/chunks/openai-CwG_KpH1.js +10 -0
- package/dist/chunks/openaiShared-Bjrci9n8.js +1 -0
- package/dist/chunks/{overageCreditGrant-DLKadMYU.js → overageCreditGrant-CCkJVN9k.js} +1 -1
- package/dist/chunks/{passes-BIfuerjL.js → passes-O0VEQz1a.js} +1 -1
- package/dist/chunks/{paths-BBvuDQl9.js → paths-o5iA-EnQ.js} +6 -6
- package/dist/chunks/permissions-BtYQvivG.js +3 -0
- package/dist/chunks/{pipeTransport-DVoIA1uN.js → pipeTransport-BEfqa7Uh.js} +1 -1
- package/dist/chunks/{plan--lnWxB3Q.js → plan-Jw4GjVL0.js} +1 -1
- package/dist/chunks/{plugin-DWLyrLw4.js → plugin-DZq0voFR.js} +1 -1
- package/dist/chunks/{pluginAutoupdate-CGXIWBrb.js → pluginAutoupdate-D19vNoOp.js} +1 -1
- package/dist/chunks/{pluginBlocklist-DJrMdzT0.js → pluginBlocklist-DeX8I4dK.js} +1 -1
- package/dist/chunks/{pluginCliCommands-C08q9dHk.js → pluginCliCommands-CMgqxOaT.js} +1 -1
- package/dist/chunks/{pluginFlagging-Dggxke70.js → pluginFlagging-DFLE5fkh.js} +1 -1
- package/dist/chunks/{pluginOperations-CNCImIe8.js → pluginOperations-BTz69m3_.js} +2 -2
- package/dist/chunks/{pluginStartupCheck-BW2fjg2P.js → pluginStartupCheck-CWWKwD5F.js} +1 -1
- package/dist/chunks/pluginStartupCheck-Non969kz.js +1 -0
- package/dist/chunks/{plugins-DQ3CRWWO.js → plugins-BPUnAc0r.js} +4 -4
- package/dist/chunks/policyLimits-D6dpS-CU.js +1 -0
- package/dist/chunks/{pollConfig-DAQ-ives.js → pollConfig-DyHumJli.js} +1 -1
- package/dist/chunks/{poor-DqfrQT61.js → poor-CHHZIPDW.js} +1 -1
- package/dist/chunks/{poorMode-DzYT47KW.js → poorMode-7N6J6YN2.js} +1 -1
- package/dist/chunks/poorMode-DX4EXe0o.js +1 -0
- package/dist/chunks/print-QCXJDmz0.js +39 -0
- package/dist/chunks/{privacy-settings-agwqjYJo.js → privacy-settings-DR0_P3JF.js} +1 -1
- package/dist/chunks/processBashCommand-CkqKsBSD.js +1 -0
- package/dist/chunks/processSlashCommand-DIk_hLHW.js +6 -0
- package/dist/chunks/prompt-2ia5b-QO.js +1 -0
- package/dist/chunks/prompt-CNtVpGdl.js +1 -0
- package/dist/chunks/{prompt-CjFAtm3w.js → prompt-DiHksuOs.js} +1 -1
- package/dist/chunks/{promptEditor-EgosPsy-.js → promptEditor-B3S5E5Q7.js} +2 -2
- package/dist/chunks/{protocolHandler-mtPUT9U0.js → protocolHandler-D1XT2l3j.js} +1 -1
- package/dist/chunks/rate-limit-options-DHh1ksB5.js +1 -0
- package/dist/chunks/rcDebugLog-BNojB_eB.js +11 -0
- package/dist/chunks/{referral-DeDr9zAE.js → referral-BADm5sBf.js} +1 -1
- package/dist/chunks/refresh-D48fjYJ4.js +1 -0
- package/dist/chunks/{registerProtocol-BZBH8Zgl.js → registerProtocol-Dzmi6VC4.js} +1 -1
- package/dist/chunks/{registry-Dz6AbiYP.js → registry-CEu_N3dS.js} +1 -1
- package/dist/chunks/{release-notes-DiUNOrg9.js → release-notes-Dr61jYDO.js} +1 -1
- package/dist/chunks/{releaseNotes-CnhQit0y.js → releaseNotes-5SV7C5aV.js} +2 -2
- package/dist/chunks/{reload-plugins-Dx52GcaG.js → reload-plugins-BxuE-21F.js} +1 -1
- package/dist/chunks/{remote-env-B67Oo3sI.js → remote-env-BaQjT5em.js} +1 -1
- package/dist/chunks/{remoteBridgeCore-BzSUgPbt.js → remoteBridgeCore-B8MjcW6f.js} +1 -1
- package/dist/chunks/{remoteControlServer-L8smP7Zu.js → remoteControlServer-BvoNcg9D.js} +2 -2
- package/dist/chunks/{rename-C4PauyTZ.js → rename-B3q0tgmd.js} +1 -1
- package/dist/chunks/{resume-CrSn26xq.js → resume-BSGOqus7.js} +2 -2
- package/dist/chunks/{runtimeObserver-YNy3mIb7.js → runtimeObserver-Bb6wSUMJ.js} +1 -1
- package/dist/chunks/{runtimeObserver-nAhH4Wca.js → runtimeObserver-BbwUiToa.js} +2 -2
- package/dist/chunks/sandbox-adapter-Cr6f6gjf.js +1 -0
- package/dist/chunks/{sandbox-toggle-BYqbcI5d.js → sandbox-toggle-L7YPKXba.js} +1 -1
- package/dist/chunks/searchExtraTools-DRVIhwVJ.js +1 -0
- package/dist/chunks/{sentry-BNVxoVLS.js → sentry-DG3ru8XE.js} +1 -1
- package/dist/chunks/{session-BuEmHrqM.js → session-B5wA2K9M.js} +2 -2
- package/dist/chunks/{sessionDiscovery-Mcsfa0g-.js → sessionDiscovery-DijWFNjj.js} +1 -1
- package/dist/chunks/sessionFileAccessHooks-DnbPctQc.js +1 -0
- package/dist/chunks/sessionMemory-BOT9f5f0.js +1 -0
- package/dist/chunks/sessionMemory-CeWjRuFL.js +1 -0
- package/dist/chunks/sessionMemoryUtils-B47JMJa2.js +1 -0
- package/dist/chunks/sessionObserver-BNZflr2e.js +1 -0
- package/dist/chunks/{sessionObserver-DG2zQgfi.js → sessionObserver-CsDT2GnB.js} +1 -1
- package/dist/chunks/sessionStorage-BUuPrnU0.js +1 -0
- package/dist/chunks/{sessionTitle-zUVSAHO7.js → sessionTitle-CxmvZO71.js} +2 -2
- package/dist/chunks/{sessionTracing-DoRJ4nSa.js → sessionTracing-Cy5dAplG.js} +1 -1
- package/dist/chunks/{settingsSync-B9bz77E1.js → settingsSync-54E8xV8N.js} +1 -1
- package/dist/chunks/setup-B5CMpp0c.js +2 -0
- package/dist/chunks/{setup-CCOLlRtP.js → setup-GJtdESQj.js} +1 -1
- package/dist/chunks/{setup-B1JbPepL.js → setup-KWELOokh.js} +1 -1
- package/dist/chunks/{shadowedRuleDetection-BBR3uEgx.js → shadowedRuleDetection-C4NGjljb.js} +1 -1
- package/dist/chunks/{sideQuestion-DHW5rgKz.js → sideQuestion-DBrzdgkl.js} +1 -1
- package/dist/chunks/{sink-DxDOsLa2.js → sink-BKc24wdw.js} +1 -1
- package/dist/chunks/sink-DG0SNHP7.js +1 -0
- package/dist/chunks/{sinks-BrrTUxkC.js → sinks-BTS1DWM4.js} +2 -2
- package/dist/chunks/sinks-Cbp-8X1S.js +1 -0
- package/dist/chunks/{skill-learning-C0nOKZfg.js → skill-learning-C5NrosiL.js} +1 -1
- package/dist/chunks/skillChangeDetector-NJrEtU47.js +1 -0
- package/dist/chunks/{skillGapStore-_YuJP5KI.js → skillGapStore-D1rkePoo.js} +2 -2
- package/dist/chunks/{skillGapStore-Czi5jKjJ.js → skillGapStore-uXpRqLGG.js} +1 -1
- package/dist/chunks/{skillGenerator-kbaRbpqJ.js → skillGenerator-Deog7yBO.js} +2 -2
- package/dist/chunks/skillLearning-BHjRTDJw.js +1 -0
- package/dist/chunks/skillLearning-By7jxHSI.js +1 -0
- package/dist/chunks/{skillPanel-BxDvlPzd.js → skillPanel-Bx63GX9w.js} +3 -3
- package/dist/chunks/{skillSearchPanel-D-MX6Qgt.js → skillSearchPanel-CM5EZGkH.js} +4 -4
- package/dist/chunks/{skills-NpEgFkFZ.js → skills-JvC7Ms0P.js} +1 -1
- package/dist/chunks/{sprites-DD4eIkN7.js → sprites-YBiqlYch.js} +1 -1
- package/dist/chunks/{stats-xL3NHwhp.js → stats-BJMKNvVK.js} +1 -1
- package/dist/chunks/{status-B5E70xRv.js → status-DAJ28yxZ.js} +1 -1
- package/dist/chunks/{statusNoticeHelpers-DcssRhLw.js → statusNoticeHelpers-B7nbsqLz.js} +1 -1
- package/dist/chunks/{tag-BELr-qIa.js → tag-B4y7cBqH.js} +1 -1
- package/dist/chunks/{tasks-CrdWcSt-.js → tasks-CSye58Ap.js} +1 -1
- package/dist/chunks/{teamHelpers--3ZyNDlv.js → teamHelpers-BFZ4eVwW.js} +1 -1
- package/dist/chunks/teamHelpers-CKBoDEPj.js +1 -0
- package/dist/chunks/teammateModeSnapshot-BfOLEMKn.js +1 -0
- package/dist/chunks/{teammateModeSnapshot-DOQMTKbQ.js → teammateModeSnapshot-DXc2vyo2.js} +1 -1
- package/dist/chunks/teleport-NN6zSxxe.js +1 -0
- package/dist/chunks/{templateJobs-8IY2Cgig.js → templateJobs-DAVqqU0g.js} +1 -1
- package/dist/chunks/{terminalSetup-Lyg4NbGA.js → terminalSetup-DqL65XR2.js} +1 -1
- package/dist/chunks/{terminalSetup-C4psrmpb.js → terminalSetup-jZKBoPTc.js} +1 -1
- package/dist/chunks/{theme-B8GNnJ_q.js → theme-DPv2L3ut.js} +1 -1
- package/dist/chunks/thinkback-B0OSwcPG.js +1 -0
- package/dist/chunks/thinkback-play-D_uOESmO.js +1 -0
- package/dist/chunks/thinkback-tcfR5Uod.js +1 -0
- package/dist/chunks/{toolEventObserver-DzLd0MSn.js → toolEventObserver-CtApZXry.js} +1 -1
- package/dist/chunks/{toolEventObserver-D0TSHm01.js → toolEventObserver-D6ZTtdh_.js} +1 -1
- package/dist/chunks/toolPool-DFpa-yul.js +1 -0
- package/dist/chunks/toolPool-DqemSx_r.js +1 -0
- package/dist/chunks/{trustedDevice-BvYYXfd8.js → trustedDevice-Bxn7WW5C.js} +1 -1
- package/dist/chunks/{trustedDevice-1iTu4LEm.js → trustedDevice-DsgCQRsJ.js} +1 -1
- package/dist/chunks/{ultrareviewCommand-BTXAN2wP.js → ultrareviewCommand-BfuSrdXz.js} +2 -2
- package/dist/chunks/undercover-B-R6dhHB.js +1 -0
- package/dist/chunks/{undercover-DvvnEmsX.js → undercover-CM8zTx5g.js} +1 -1
- package/dist/chunks/{updateCCB-C-qfLi0j.js → updateCCB-DTArxdyR.js} +4 -4
- package/dist/chunks/upgrade-CCrHxXrm.js +1 -0
- package/dist/chunks/{upgrade-DTBZSxwv.js → upgrade-CEd1Jxw_.js} +1 -1
- package/dist/chunks/{upload-BF8tf_Eo.js → upload-DNo3bZLc.js} +1 -1
- package/dist/chunks/{usage-DvSTXEYY.js → usage-DEwRsc7E.js} +1 -1
- package/dist/chunks/{usage-BRYRRgNt.js → usage-X4-qec8g.js} +1 -1
- package/dist/chunks/useMainLoopModel-2A9HV1H3.js +1 -0
- package/dist/chunks/{useManagePlugins-GmnI9K53.js → useManagePlugins-D9MBag8O.js} +1 -1
- package/dist/chunks/{useMergedTools-Dah5KDMi.js → useMergedTools-DCYrP_YE.js} +1 -1
- package/dist/chunks/{useSearchInput-BV_azHiA.js → useSearchInput-CepwLBvi.js} +1 -1
- package/dist/chunks/useSettingsErrors-C8ffWXbY.js +1 -0
- package/dist/chunks/{useVoice-DR69NLxp.js → useVoice-vHZVaTAN.js} +1 -1
- package/dist/chunks/{util-BpyJ4Bom.js → util-B13MVSse.js} +1 -1
- package/dist/chunks/utils-C-vk0zpl.js +1 -0
- package/dist/chunks/{validatePlugin-vptAYuYu.js → validatePlugin-Cf_toBOJ.js} +1 -1
- package/dist/chunks/{vim-DvOw8dfR.js → vim-6p7eiRPG.js} +1 -1
- package/dist/chunks/{voice-B3BZs53f.js → voice-Bvc_BxoI.js} +2 -2
- package/dist/chunks/{voiceModeEnabled-DA76xN1Q.js → voiceModeEnabled-BPbOh6jd.js} +1 -1
- package/dist/chunks/voiceModeEnabled-JSBux8GA.js +1 -0
- package/dist/chunks/{voiceStreamSTT-_w1VjIOs.js → voiceStreamSTT-CzCUhap3.js} +1 -1
- package/dist/chunks/voiceStreamSTT-D9ER6Ml3.js +1 -0
- package/dist/chunks/{workerRegistry-2_MZVih1.js → workerRegistry-DCtC-WN3.js} +1 -1
- package/dist/chunks/worktree-Dv0mPuy_.js +1 -0
- package/dist/chunks/{xml-Dx--sNE1.js → xml-CqxiCY4v.js} +1 -1
- package/dist/cli.js +1 -1
- package/package.json +1 -1
- package/dist/chunks/ApproveApiKey-DiEe4eui.js +0 -1
- package/dist/chunks/BackgroundTasksDialog-ByraVuXh.js +0 -2
- package/dist/chunks/BypassPermissionsModeDialog-BDvmz12S.js +0 -1
- package/dist/chunks/ClaudeMdExternalIncludesDialog-B4ocUjev.js +0 -1
- package/dist/chunks/ConsoleOAuthFlow-BvaB9b0y.js +0 -1
- package/dist/chunks/DevChannelsDialog-BljR0X9X.js +0 -1
- package/dist/chunks/DiffDialog-BhQ2QaLW.js +0 -3
- package/dist/chunks/Doctor-BXb0qv6n.js +0 -3
- package/dist/chunks/Doctor-C5DYPEGl.js +0 -1
- package/dist/chunks/Feedback-DwHzc4UT.js +0 -2
- package/dist/chunks/Grove-DnTo982-.js +0 -1
- package/dist/chunks/MCPConnectionManager-DYGoS1Ht.js +0 -1
- package/dist/chunks/MessageSelector-DTmUuEKJ.js +0 -3
- package/dist/chunks/Messages-DWiKTx5o.js +0 -11
- package/dist/chunks/PluginSettings-eYcWehI8.js +0 -17
- package/dist/chunks/QueryEngine-C_KZts4y.js +0 -1
- package/dist/chunks/REPL-C6YR0VKU.js +0 -1
- package/dist/chunks/REPL-DzHz-LOY.js +0 -97
- package/dist/chunks/ResumeConversation-BktSnsCm.js +0 -1
- package/dist/chunks/SearchExtraToolsTool-CqFD8vVS.js +0 -1
- package/dist/chunks/SentryErrorBoundary-BUirJRWU.js +0 -1
- package/dist/chunks/Settings-vfFvcweR.js +0 -2
- package/dist/chunks/TrustDialog-CVbzrv6g.js +0 -1
- package/dist/chunks/WindowsTerminalBackend-BE9NX5IH.js +0 -2
- package/dist/chunks/api-6tcwJlf_.js +0 -1
- package/dist/chunks/assistant-CwbhlCM-.js +0 -1
- package/dist/chunks/auth-GxZhOvQ1.js +0 -1
- package/dist/chunks/backgroundHousekeeping-BIZTAYho.js +0 -17
- package/dist/chunks/backgroundHousekeeping-Csh58CxV.js +0 -1
- package/dist/chunks/bridgeConfig-D4tpc568.js +0 -1
- package/dist/chunks/bridgeEnabled-B8_c_Ppq.js +0 -1
- package/dist/chunks/bridgeMain-C5RDihlX.js +0 -68
- package/dist/chunks/bridgeMain-D7_lg2iJ.js +0 -1
- package/dist/chunks/caches-dGk7xsDu.js +0 -1
- package/dist/chunks/changeDetector-DoLfg8a6.js +0 -1
- package/dist/chunks/channelNotification-DDErroWn.js +0 -1
- package/dist/chunks/clear-OudnCGa7.js +0 -1
- package/dist/chunks/client-DxDmXXTh.js +0 -1
- package/dist/chunks/color-DG_R5-hl.js +0 -1
- package/dist/chunks/commands-BWIOEBPs.js +0 -1
- package/dist/chunks/commitAttribution-BA4fcbHf.js +0 -1
- package/dist/chunks/context-noninteractive-CM1-lUSe.js +0 -1
- package/dist/chunks/conversation-DKlz47xf.js +0 -1
- package/dist/chunks/conversation-cUxdb8MN.js +0 -1
- package/dist/chunks/createSession-BuJcoBAj.js +0 -1
- package/dist/chunks/crossProjectResume-BJisir9Z.js +0 -40
- package/dist/chunks/datadog-CVeFkaQu.js +0 -1
- package/dist/chunks/envLessBridgeConfig-CT8sdmFu.js +0 -1
- package/dist/chunks/extra-usage-rdJ7ecEb.js +0 -1
- package/dist/chunks/extractMemories-BrvZVsmM.js +0 -1
- package/dist/chunks/fast-CLKKsx2H.js +0 -1
- package/dist/chunks/gates-CSHuXnUx.js +0 -1
- package/dist/chunks/grok-CDOpos8E.js +0 -1
- package/dist/chunks/hooks-BFdX17Za.js +0 -1
- package/dist/chunks/inboundAttachments-BVUunfAX.js +0 -1
- package/dist/chunks/initReplBridge-tPRGPBq7.js +0 -1
- package/dist/chunks/language-Cf6bMI4N.js +0 -1
- package/dist/chunks/launchAutofixPr-D9h6YAZY.js +0 -2
- package/dist/chunks/loadAgentsDir-DCyiY0MN.js +0 -1
- package/dist/chunks/loadPluginHooks-C0Ei-0E2.js +0 -1
- package/dist/chunks/localSearch-MBx7KzC2.js +0 -1
- package/dist/chunks/login-D8UKKaud.js +0 -1
- package/dist/chunks/logout-B0BjqlGi.js +0 -1
- package/dist/chunks/mcp-Dq0kxZFx.js +0 -6
- package/dist/chunks/mcp-zbxZM9BP.js +0 -1
- package/dist/chunks/model-H3rtl6eR.js +0 -1
- package/dist/chunks/openai-DkYK4THc.js +0 -10
- package/dist/chunks/openaiShared-D5lOejS1.js +0 -16
- package/dist/chunks/permissions-S2EvIRKj.js +0 -3
- package/dist/chunks/pluginStartupCheck-DpxQPXJE.js +0 -1
- package/dist/chunks/policyLimits-BotYrS-v.js +0 -1
- package/dist/chunks/poorMode-DEAe3hiK.js +0 -1
- package/dist/chunks/print-GGVp62vj.js +0 -39
- package/dist/chunks/processBashCommand-DHHN8Ca4.js +0 -1
- package/dist/chunks/processSlashCommand-COtIO6Jy.js +0 -6
- package/dist/chunks/prompt-CO160cIr.js +0 -1
- package/dist/chunks/prompt-GY9hlRvI.js +0 -1
- package/dist/chunks/rate-limit-options-C6SFOHue.js +0 -1
- package/dist/chunks/rcDebugLog-CPKZCtR8.js +0 -11
- package/dist/chunks/refresh-D7pdoY_X.js +0 -1
- package/dist/chunks/sandbox-adapter-CzwHes1i.js +0 -1
- package/dist/chunks/searchExtraTools-CcpdCO6l.js +0 -1
- package/dist/chunks/sessionFileAccessHooks-qnNiGMnE.js +0 -1
- package/dist/chunks/sessionMemory-CMahwDdW.js +0 -1
- package/dist/chunks/sessionMemory-pFSn4HSN.js +0 -1
- package/dist/chunks/sessionMemoryUtils-Du5jUl7M.js +0 -1
- package/dist/chunks/sessionObserver-Je868MC9.js +0 -1
- package/dist/chunks/sessionStorage-D3FhAADV.js +0 -1
- package/dist/chunks/setup-DWkSjA49.js +0 -2
- package/dist/chunks/sink-cQOgsnw3.js +0 -1
- package/dist/chunks/sinks-Djiz_5-Z.js +0 -1
- package/dist/chunks/skillChangeDetector-D8C-uQSQ.js +0 -1
- package/dist/chunks/skillLearning-3KWrBczS.js +0 -1
- package/dist/chunks/skillLearning-DBbdGbk-.js +0 -1
- package/dist/chunks/teamHelpers-CUAiXng3.js +0 -1
- package/dist/chunks/teammateModeSnapshot-C6EWhR0X.js +0 -1
- package/dist/chunks/teleport-LXFOan9C.js +0 -1
- package/dist/chunks/thinkback-DPXwEK3B.js +0 -1
- package/dist/chunks/thinkback-DZW3Mcx_.js +0 -1
- package/dist/chunks/thinkback-play-BMOE-ceh.js +0 -1
- package/dist/chunks/toolPool-DVOfpjDz.js +0 -1
- package/dist/chunks/toolPool-Dq-Vtvrj.js +0 -1
- package/dist/chunks/undercover-C_44e3oN.js +0 -1
- package/dist/chunks/upgrade-CGXa5Dwy.js +0 -1
- package/dist/chunks/useMainLoopModel-CwvuTRXn.js +0 -1
- package/dist/chunks/useSettingsErrors-C-j_Zt7g.js +0 -1
- package/dist/chunks/utils-CrZcpypC.js +0 -1
- package/dist/chunks/voiceModeEnabled-DIveLYGb.js +0 -1
- package/dist/chunks/voiceStreamSTT-hpzWd_zl.js +0 -1
- package/dist/chunks/worktree-CCuDwRmS.js +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as e}from"./chunk-DR8-3Aex.js";import{d as t,s as n,u as r}from"./envUtils-BWeoiL4Y.js";import{Ct as i,cn as a,ot as o}from"./state-sIHsFpDu.js";import{Ac as s,Jt as c,Pc as l,Pt as u,S as d,Sc as f,la as p,nn as m,on as h,ua as g,v as _}from"./paths-BBvuDQl9.js";import{L as v,V as y,X as ee,Y as b,d as x,s as S}from"./debug-UI3T040K.js";import{n as te,r as C}from"./analytics-DqMQntaB.js";import{F as w,P as T,i as ne,m as re,v as E}from"./git-CN3qtTb_.js";import{g as D,m as O}from"./log-CzsijfHZ.js";import{n as k,t as A}from"./sleep-8Eb9j_Ly.js";import{Aa as ie,Ar as ae,Ba as j,Ca as M,Da as N,Ea as oe,Eo as se,Gv as P,Ka as ce,Lo as F,Ma as I,Oa as le,Oo as L,Ra as R,Sa as ue,Ta as de,Vo as fe,Wv as pe,cd as z,fd as me,hr as B,ja as V,ka as he,wa as ge}from"./loadAgentsDir-DI1a76pd.js";import{O as H,_ as _e,d as U,k as ve,n as ye,t as W}from"./rcDebugLog-CPKZCtR8.js";import{a as G,c as K,d as be,f as xe,o as q,r as Se,s as J,u as Y}from"./debugUtils-BBMFODKH.js";import{a as Ce,i as we}from"./trustedDevice-BvYYXfd8.js";import{a as X,i as Te,n as Z,o as Q,t as $}from"./bridgeConfig-lRZfQqmA.js";import{a as Ee,o as De,r as Oe,s as ke,t as Ae}from"./bridgeEnabled-D2IykaHE.js";import{i as je,t as Me}from"./assistant-BlzrMSkM.js";import{t as Ne}from"./capacityWake-BXlUpptF.js";import{n as Pe,t as Fe}from"./pollConfig-DAQ-ives.js";import{a as Ie,n as Le,r as Re,t as ze}from"./workSecret-mS2OrpxF.js";import{a as Be,i as Ve,n as He,t as Ue}from"./createSession-kiTHYXSL.js";import{i as We,n as Ge}from"./envLessBridgeConfig-SPEr9oqO.js";import{n as Ke,o as qe}from"./mappers-CJ8IO1o1.js";import{n as Je,r as Ye,t as Xe}from"./sessionTitle-zUVSAHO7.js";import{a as Ze,i as Qe,n as $e,o as et,r as tt,t as nt}from"./bridgeMessaging-CqNURC4-.js";import{t as rt}from"./HybridTransport-CuT3KI5e.js";import{n as it,r as at,t as ot}from"./flushGate-COPcye5f.js";import{hostname as st}from"os";import{randomUUID as ct}from"crypto";a(),O(),E(),s(),g(),h(),d(),X(),P(),Oe(),F(),R(),ae(),Ve(),We(),Ke(),Ye(),he(),S(),W(),T(),te(),b(),K(),z(),Ce(),H(),U(),n(),q(),y(),A(),M();var lt=2e3,ut=6e4,dt=900*1e3,ft=0;async function pt(e){let{dir:n,machineName:i,branch:a,gitRepoUrl:o,title:s,baseUrl:c,sessionIngressUrl:l,workerType:u,getAccessToken:d,createSession:f,archiveSession:p,getCurrentTitle:m=()=>s,toSDKMessages:h=()=>{throw Error(`BridgeCoreParams.toSDKMessages not provided. Pass it if you use writeMessages() or initialMessages — daemon callers that only use writeSdkMessages() never hit this path.`)},onAuth401:g,getPollIntervalConfig:_=()=>Pe,initialHistoryCap:y=200,initialMessages:b,previouslyFlushedUUIDs:S,onInboundMessage:te,onPermissionResponse:T,onInterrupt:ne,onSetModel:re,onSetMaxThinkingTokens:E,onSetPermissionMode:D,onStateChange:O,onUserMessage:k,perpetual:A,initialSSESequenceNum:ie=0}=e,ae=++ft,{writeBridgePointer:j,clearBridgePointer:M,readBridgePointer:N}=await import(`./bridgePointer-FvAMj3re.js`),se=A?await N(n):null,P=se?.source===`repl`?se:null;x(`[bridge:repl] initBridgeCore #${ae} starting (initialMessages=${b?.length??0}${P?` perpetual prior=env:${P.environmentId}`:``})`);let ce=le({baseUrl:c,getAccessToken:d,runnerVersion:`2.6.5`,onDebug:x,onAuth401:g,getTrustedDeviceToken:we}),F=process.env.USER_TYPE===`ant`?oe(ce):ce,I={dir:n,machineName:i,branch:a,gitRepoUrl:o,maxSessions:1,spawnMode:`single-session`,verbose:!1,sandbox:!1,bridgeId:ct(),workerType:u,environmentId:ct(),reuseEnvironmentId:P?.environmentId,apiBaseUrl:c,sessionIngressUrl:l},L,R;try{let e=await F.registerBridgeEnvironment(I);L=e.environment_id,R=e.environment_secret}catch(e){return J(`registration_failed`,`[bridge:repl] Environment registration failed: ${v(e)}`),P&&await M(n),O?.(`failed`,v(e)),null}x(`[bridge:repl] Environment registered: ${L}`),w(`info`,`bridge_repl_env_registered`),C(`tengu_bridge_repl_env_registered`,{});async function fe(e,t){if(L!==e)return x(`[bridge:repl] Env mismatch (requested ${e}, got ${L}) — cannot reconnect in place`),!1;let n=xe(t),r=n===t?[t]:[t,n];for(let e of r)try{return await F.reconnectSession(L,e),x(`[bridge:repl] Reconnected session ${e} in place on env ${L}`),!0}catch(t){x(`[bridge:repl] reconnectSession(${e}) failed: ${v(t)}`)}return x(`[bridge:repl] reconnectSession exhausted — falling through to fresh session`),!1}let pe=P?await fe(P.environmentId,P.sessionId):!1;P&&!pe&&await M(n);let z;if(pe&&P){if(z=P.sessionId,x(`[bridge:repl] Perpetual session reused: ${z}`),b&&S)for(let e of b)S.add(e.uuid)}else{let e=await f({environmentId:L,title:s,gitRepoUrl:o,branch:a,signal:AbortSignal.timeout(15e3)});if(!e)return x(`[bridge:repl] Session creation failed, deregistering environment`),C(`tengu_bridge_repl_session_failed`,{}),await F.deregisterEnvironment(L).catch(()=>{}),O?.(`failed`,`Session creation failed`),null;z=e,x(`[bridge:repl] Session created: ${z}`)}await j(n,{sessionId:z,environmentId:L,source:`repl`}),w(`info`,`bridge_repl_session_created`),C(`tengu_bridge_repl_started`,{has_initial_messages:!!(b&&b.length>0),inProtectedNamespace:t()});let B=new Set;if(b)for(let e of b)B.add(e.uuid);let V=new nt(2e3);for(let e of B)V.add(e);let he=new nt(2e3),H=new AbortController,U=null;_e(e=>{H.signal.aborted||U?.reportMetadata(e)},{replayCurrent:!0});let W=0,G=pe?ie:0,K=null,q=null,Se=Ne(H.signal),Y=Se.wake,Ce=Se.signal,X=new ot,Te=!k,Z=0,Q=null;async function $(){if(Q)return Q;Q=Ee();try{return await Q}finally{Q=null}}async function Ee(){if(Z++,ye(`doReconnect: attempt=${Z}/3 envId=${L} sessionId=${z} workId=${K}`),W++,x(`[bridge:repl] Reconnecting after env lost (attempt ${Z}/3)`),Z>3)return x(`[bridge:repl] Environment reconnect limit reached (3), giving up`),!1;if(U){let e=U.getLastSequenceNum();e>G&&(G=e),U.close(),U=null}if(Y(),X.drop(),K){let e=K;if(await F.stopWork(L,e,!1).catch(()=>{}),K!==e)return x(`[bridge:repl] Poll loop recovered during stopWork await — deferring to it`),Z=0,!0;K=null,q=null}if(H.signal.aborted)return x(`[bridge:repl] Reconnect aborted by teardown`),!1;let e=L;I.reuseEnvironmentId=e;try{let e=await F.registerBridgeEnvironment(I);L=e.environment_id,R=e.environment_secret}catch(e){return I.reuseEnvironmentId=void 0,x(`[bridge:repl] Environment re-registration failed: ${v(e)}`),!1}if(I.reuseEnvironmentId=void 0,x(`[bridge:repl] Re-registered: requested=${e} got=${L}`),H.signal.aborted)return x(`[bridge:repl] Reconnect aborted after env registration, cleaning up`),await F.deregisterEnvironment(L).catch(()=>{}),!1;if(U!==null)return x(`[bridge:repl] Poll loop recovered during registerBridgeEnvironment await — deferring to it`),Z=0,!0;if(await fe(e,z))return C(`tengu_bridge_repl_reconnected_in_place`,{}),Z=0,!0;if(L!==e&&C(`tengu_bridge_repl_env_expired_fresh_session`,{}),await p(z),H.signal.aborted)return x(`[bridge:repl] Reconnect aborted after archive, cleaning up`),await F.deregisterEnvironment(L).catch(()=>{}),!1;let t=m(),r=await f({environmentId:L,title:t,gitRepoUrl:o,branch:a,signal:AbortSignal.timeout(15e3)});return r?H.signal.aborted?(x(`[bridge:repl] Reconnect aborted after session creation, cleaning up`),await p(r),!1):(z=r,me(be(r)).catch(()=>{}),G=0,he.clear(),Te=!k,x(`[bridge:repl] Re-created session: ${z}`),await j(n,{sessionId:z,environmentId:L,source:`repl`}),S?.clear(),Z=0,!0):(x(`[bridge:repl] Session creation failed during reconnection`),!1)}function De(){return d()}function Oe(){let e=X.end();if(e.length===0)return;if(!U){x(`[bridge:repl] Cannot drain ${e.length} pending message(s): no transport`);return}for(let t of e)V.add(t.uuid);let t=h(e).map(e=>({...e,session_id:z}));x(`[bridge:repl] Drained ${e.length} pending message(s) after flush`),U.writeBatch(t)}let ke=null;function Ae(){ke?.()}function je(e){if(ye(`handleTransportPermanentClose: code=${e} transport=${U?`exists`:`null`} pollAborted=${H.signal.aborted}`),x(`[bridge:repl] Transport permanently closed: code=${e}`),C(`tengu_bridge_repl_ws_closed`,{code:e}),U){let e=U.getLastSequenceNum();e>G&&(G=e),U=null}Y();let t=X.drop();if(t>0&&x(`[bridge:repl] Dropping ${t} pending message(s) on transport close (code=${e})`,{level:`warn`}),e===1e3){O?.(`failed`,`session ended`),H.abort(),Ae();return}O?.(`reconnecting`,`Remote Control connection lost (code ${e})`),x(`[bridge:repl] Transport reconnect budget exhausted (code=${e}), attempting env reconnect`),$().then(t=>{t||H.signal.aborted||(x(`[bridge:repl] reconnectEnvironmentWithSession resolved false — tearing down`),C(`tengu_bridge_repl_reconnect_failed`,{close_code:e}),O?.(`failed`,`reconnection failed`),Ae())})}let Me;process.env.USER_TYPE===`ant`&&process.platform!==`win32`&&(Me=()=>{x(`[bridge:repl] SIGUSR2 received — forcing doReconnect() for testing`),$()},process.on(`SIGUSR2`,Me));let Fe=null;process.env.USER_TYPE===`ant`&&de({fireClose:e=>{if(!Fe){x(`[bridge:debug] fireClose: no transport wired yet`);return}x(`[bridge:debug] fireClose(${e}) — injecting`),Fe(e)},forceReconnect:()=>{x(`[bridge:debug] forceReconnect — injecting`),$()},injectFault:ge,wakePollLoop:Y,describe:()=>`env=${L} session=${z} transport=${U?.getStateLabel()??`null`} workId=${K??`null`}`}),mt({api:F,getCredentials:()=>({environmentId:L,environmentSecret:R}),signal:H.signal,getPollIntervalConfig:_,onStateChange:O,getWsState:()=>U?.getStateLabel()??`null`,isAtCapacity:()=>U!==null,capacitySignal:Ce,onFatalError:Ae,getHeartbeatInfo:()=>!K||!q?null:{environmentId:L,workId:K,sessionToken:q},onHeartbeatFatal:e=>{if(x(`[bridge:repl] heartbeatWork fatal (status=${e.status}) — tearing down work item for fast re-dispatch`),U){let e=U.getLastSequenceNum();e>G&&(G=e),U.close(),U=null}X.drop(),K&&F.stopWork(L,K,!1).catch(e=>{x(`[bridge:repl] stopWork after heartbeat fatal: ${v(e)}`)}),K=null,q=null,Y(),O?.(`reconnecting`,`Work item lease expired, fetching fresh token`)},async onEnvironmentLost(){return await $()?{environmentId:L,environmentSecret:R}:null},onWorkReceived:(e,t,i,a)=>{if(U?.isConnectedStatus()&&x(`[bridge:repl] Work received while transport connected, replacing with fresh token (workId=${i})`),x(`[bridge:repl] Work received: workId=${i} workSessionId=${e} currentSessionId=${z} match=${Ie(e,z)}`),j(n,{sessionId:z,environmentId:L,source:`repl`}),!Ie(e,z)){x(`[bridge:repl] Rejecting foreign session: expected=${z} got=${e}`);return}K=i,q=t;let o=a||r(process.env.CLAUDE_BRIDGE_USE_CCR_V2),s;if(!o){if(s=De(),!s){x(`[bridge:repl] No OAuth token available for session ingress, skipping work`);return}ve(s)}if(C(`tengu_bridge_repl_work_received`,{}),U){let e=U;U=null;let t=e.getLastSequenceNum();t>G&&(G=t),e.close()}X.deactivate();let u=e=>Qe(e,{transport:U,sessionId:z,onInterrupt:ne,onSetModel:re,onSetMaxThinkingTokens:E,onSetPermissionMode:D}),d=!1,f=e=>{U=e,e.setOnConnect(()=>{if(U===e){if(x(`[bridge:repl] Ingress transport connected`),C(`tengu_bridge_repl_ws_connected`,{}),!o){let e=De();e&&ve(e)}if(He=!1,!d&&b&&b.length>0){d=!0;let t=y,n=b.filter(e=>Ze(e)&&!S?.has(e.uuid)),r=t>0&&n.length>t?n.slice(-t):n;r.length<n.length&&(x(`[bridge:repl] Capped initial flush: ${n.length} -> ${r.length} (cap=${t})`),C(`tengu_bridge_repl_history_capped`,{eligible_count:n.length,capped_count:r.length}));let i=h(r);if(i.length>0){x(`[bridge:repl] Flushing ${i.length} initial message(s) via transport`);let t=i.map(e=>({...e,session_id:z})),n=e.droppedBatchCount;e.writeBatch(t).then(()=>{if(e.droppedBatchCount>n){x(`[bridge:repl] Initial flush dropped ${e.droppedBatchCount-n} batch(es) — not marking ${i.length} UUID(s) as flushed`);return}if(S)for(let e of i)e.uuid&&S.add(e.uuid)}).catch(e=>x(`[bridge:repl] Initial flush failed: ${e}`)).finally(()=>{U===e&&(Oe(),O?.(`connected`))})}else Oe(),O?.(`connected`)}else X.active||O?.(`connected`)}}),e.setOnData(e=>{try{let t=JSON.parse(e);ye(`ingress: type=${t.type}${t.type===`control_request`?` subtype=${t.request?.subtype} request_id=${t.request_id}`:``}${t.type===`control_response`?` subtype=${t.response?.subtype} request_id=${t.response?.request_id}`:``}${t.type===`user`?` uuid=${t.uuid}`:``}${t.type===`keep_alive`?``:` len=${e.length}`}`)}catch{ye(`ingress (non-JSON): ${String(e).slice(0,200)}`)}tt(e,V,he,te,T,u)}),Fe=je,e.setOnClose(t=>{U===e&&(ye(`transport onClose: code=${t} connected=${e.isConnectedStatus()} state=${e.getStateLabel()} seq=${e.getLastSequenceNum()}`),je(t))}),!d&&b&&b.length>0&&X.start(),e.connect()};if(W++,o){let n=ze(c,e),r=W;x(`[bridge:repl] CCR v2: sessionUrl=${n} session=${e} gen=${r}`),at({sessionUrl:n,ingressToken:t,sessionId:e,initialSequenceNum:G}).then(e=>{if(H.signal.aborted){e.close();return}if(r!==W){x(`[bridge:repl] CCR v2: discarding stale handshake gen=${r} current=${W}`),e.close();return}f(e)},e=>{x(`[bridge:repl] CCR v2: createV2ReplTransport failed: ${v(e)}`,{level:`error`}),C(`tengu_bridge_repl_ccr_v2_init_failed`,{}),r===W&&(K&&(F.stopWork(L,K,!1).catch(e=>{x(`[bridge:repl] stopWork after v2 init failure: ${v(e)}`)}),K=null,q=null),Y())})}else{let t=Le(l,e);x(`[bridge:repl] Ingress URL: ${t}`),x(`[bridge:repl] Creating HybridTransport: session=${e}`);let n=s??``;f(it(new rt(new URL(t),{Authorization:`Bearer ${n}`,"anthropic-version":`2023-06-01`},e,()=>({Authorization:`Bearer ${De()??n}`,"anthropic-version":`2023-06-01`}),{maxConsecutiveFailures:50,isBridge:!0,onBatchDropped:()=>{O?.(`reconnecting`,`Lost sync with Remote Control — events could not be delivered`),Y()}})))}}});let Re=A?setInterval(()=>{Q||j(n,{sessionId:z,environmentId:L,source:`repl`})},60*6e4):null;Re?.unref?.();let Be=_().session_keepalive_interval_v2_ms,Ve=Be>0?setInterval(()=>{U&&(x(`[bridge:repl] keep_alive sent`),U.write({type:`keep_alive`}).catch(e=>{x(`[bridge:repl] keep_alive write failed: ${v(e)}`)}))},Be):null;Ve?.unref?.();let He=!1;ke=async()=>{if(He){x(`[bridge:repl] Teardown already in progress, skipping duplicate call env=${L} session=${z}`);return}He=!0;let e=Date.now();if(x(`[bridge:repl] Teardown starting: env=${L} session=${z} workId=${K??`none`} transportState=${U?.getStateLabel()??`null`}`),Re!==null&&clearInterval(Re),Ve!==null&&clearInterval(Ve),Me&&process.off(`SIGUSR2`,Me),process.env.USER_TYPE===`ant`&&(ue(),Fe=null),H.abort(),x(`[bridge:repl] Teardown: poll loop aborted`),U){let e=U.getLastSequenceNum();e>G&&(G=e)}if(A){U=null,X.drop(),await j(n,{sessionId:z,environmentId:L,source:`repl`}),x(`[bridge:repl] Teardown (perpetual): leaving env=${L} session=${z} alive on server, duration=${Date.now()-e}ms`);return}let t=U;if(U=null,X.drop(),t){let e={...et(z),session_id:z};t.write(e)}let r=K?F.stopWork(L,K,!0).then(()=>{x(`[bridge:repl] Teardown: stopWork completed`)}).catch(e=>{x(`[bridge:repl] Teardown stopWork failed: ${v(e)}`)}):Promise.resolve();await Promise.all([r,p(z)]),t?.close(),x(`[bridge:repl] Teardown: transport closed`),await F.deregisterEnvironment(L).catch(e=>{x(`[bridge:repl] Teardown deregister failed: ${v(e)}`)}),await M(n),x(`[bridge:repl] Teardown complete: env=${L} duration=${Date.now()-e}ms`)};let Ue=ee(()=>ke?.());return x(`[bridge:repl] Ready: env=${L} session=${z}`),O?.(`ready`),{get bridgeSessionId(){return z},get environmentId(){return L},getSSESequenceNum(){let e=U?.getLastSequenceNum()??0;return Math.max(G,e)},sessionIngressUrl:l,writeMessages(e){let t=e.filter(e=>Ze(e)&&!B.has(e.uuid)&&!V.has(e.uuid));if(t.length===0)return;if(!Te)for(let e of t){let t=$e(e);if(t!==void 0&&k?.(t,z)){Te=!0;break}}if(X.enqueue(...t)){x(`[bridge:repl] Queued ${t.length} message(s) during initial flush`);return}if(!U){let e=t.map(e=>e.type).join(`,`);x(`[bridge:repl] Transport not configured, dropping ${t.length} message(s) [${e}] for session=${z}`,{level:`warn`});return}for(let e of t)V.add(e.uuid);x(`[bridge:repl] Sending ${t.length} message(s) via transport`);let n=h(t).map(e=>({...e,session_id:z}));U.writeBatch(n)},writeSdkMessages(e){let t=e.filter(e=>!e.uuid||!V.has(e.uuid));if(t.length===0)return;if(!U){x(`[bridge:repl] Transport not configured, dropping ${t.length} SDK message(s) for session=${z}`,{level:`warn`});return}for(let e of t)e.uuid&&V.add(e.uuid);let n=t.map(e=>({...e,session_id:z}));U.writeBatch(n)},sendControlRequest(e){if(!U){x(`[bridge:repl] Transport not configured, skipping control_request`);return}let t={...e,session_id:z};U.write(t),x(`[bridge:repl] Sent control_request request_id=${e.request_id}`)},sendControlResponse(e){if(!U){x(`[bridge:repl] Transport not configured, skipping control_response`);return}let t={...e,session_id:z};U.write(t),x(`[bridge:repl] Sent control_response`)},sendControlCancelRequest(e){if(!U){x(`[bridge:repl] Transport not configured, skipping control_cancel_request`);return}let t={type:`control_cancel_request`,request_id:e,session_id:z};U.write(t),x(`[bridge:repl] Sent control_cancel_request request_id=${e}`)},sendResult(){if(!U){x(`[bridge:repl] sendResult: skipping, transport not configured session=${z}`);return}U.reportState(`idle`);let e={...et(z),session_id:z};U.write(e),x(`[bridge:repl] Sent result for session=${z}`)},async teardown(){Ue(),await ke?.(),x(`[bridge:repl] Torn down`),C(`tengu_bridge_repl_teardown`,{})}}}async function mt({api:e,getCredentials:t,signal:n,onStateChange:r,onWorkReceived:i,onEnvironmentLost:a,getWsState:o,isAtCapacity:s,capacitySignal:c,onFatalError:l,getPollIntervalConfig:u=()=>Pe,getHeartbeatInfo:d,onHeartbeatFatal:f}){x(`[bridge:repl] Starting work poll loop for env=${t().environmentId}`);let p=0,m=null,h=null,g=0,_=!1;for(;!n.aborted;){let{environmentId:y,environmentSecret:ee}=t(),b=u();try{let t=await e.pollForWork(y,ee,n,b.reclaim_older_than_ms);if(g=0,p>0&&(x(`[bridge:repl] Poll recovered after ${p} consecutive error(s)`),p=0,m=null,h=null,r?.(`ready`)),!t){let t=_;if(_=!1,s?.()&&c&&!t){let t=b.poll_interval_ms_at_capacity;if(b.non_exclusive_heartbeat_interval_ms>0&&d){C(`tengu_bridge_heartbeat_mode_entered`,{heartbeat_interval_ms:b.non_exclusive_heartbeat_interval_ms});let r=t>0?Date.now()+t:null,i=!1,a=0;for(;!n.aborted&&s()&&(r===null||Date.now()<r);){let t=u();if(t.non_exclusive_heartbeat_interval_ms<=0)break;let n=d();if(!n)break;let r=c();try{await e.heartbeatWork(n.environmentId,n.workId,n.sessionToken)}catch(e){if(x(`[bridge:repl:heartbeat] Failed: ${v(e)}`),e instanceof N){r.cleanup(),C(`tengu_bridge_heartbeat_error`,{status:e.status,error_type:e.status===401||e.status===403?`auth_failed`:`fatal`}),f?(f(e),x(`[bridge:repl:heartbeat] Fatal (status=${e.status}), work state cleared — fast-polling for re-dispatch`)):i=!0;break}}a++,await k(t.non_exclusive_heartbeat_interval_ms,r.signal),r.cleanup()}let o=i?`error`:n.aborted?`shutdown`:s()?r!==null&&Date.now()>=r?`poll_due`:`config_disabled`:`capacity_changed`;if(C(`tengu_bridge_heartbeat_mode_exited`,{reason:o,heartbeat_cycles:a}),!i){o===`poll_due`&&x(`[bridge:repl] Heartbeat poll_due after ${a} cycles — falling through to pollForWork`);continue}}let r=t>0?t:b.non_exclusive_heartbeat_interval_ms;if(r>0){let e=c(),t=Date.now();await k(r,e.signal),e.cleanup();let n=Date.now()-t-r;n>6e4&&(x(`[bridge:repl] At-capacity sleep overran by ${Math.round(n/1e3)}s — process suspension detected, forcing one fast-poll cycle`),C(`tengu_bridge_repl_suspension_detected`,{overrun_ms:n}),_=!0)}}else await k(b.poll_interval_ms_not_at_capacity,n);continue}let a;try{a=Re(t.secret)}catch(n){x(`[bridge:repl] Failed to decode work secret: ${v(n)}`),C(`tengu_bridge_repl_work_secret_failed`,{}),await e.stopWork(y,t.id,!1).catch(()=>{});continue}x(`[bridge:repl] Acknowledging workId=${t.id}`);try{await e.acknowledgeWork(y,t.id,a.session_ingress_token)}catch(e){x(`[bridge:repl] Acknowledge failed workId=${t.id}: ${v(e)}`)}if(t.data.type===`healthcheck`){x(`[bridge:repl] Healthcheck received`);continue}if(t.data.type===`session`){let e=t.data.id;try{I(e,`session_id`)}catch{x(`[bridge:repl] Invalid session_id in work: ${e}`);continue}i(e,a.session_ingress_token,t.id,a.use_code_sessions===!0),x(`[bridge:repl] Work accepted, continuing poll loop`)}}catch(i){if(n.aborted)break;if(i instanceof N&&i.status===404&&a){let e=t().environmentId;if(y!==e){x(`[bridge:repl] Stale poll error for old env=${y}, current env=${e} — skipping onEnvironmentLost`),p=0,m=null;continue}if(g++,x(`[bridge:repl] Environment deleted, attempting re-registration (attempt ${g}/3)`),C(`tengu_bridge_repl_env_lost`,{attempt:g}),g>3){x(`[bridge:repl] Environment re-registration limit reached (3), giving up`),r?.(`failed`,`Environment deleted and re-registration limit reached`),l?.();break}r?.(`reconnecting`,`environment lost, recreating session`);let i=await a();if(n.aborted)break;if(i){p=0,m=null,r?.(`ready`),x(`[bridge:repl] Re-registered environment: ${i.environmentId}`);continue}r?.(`failed`,`Environment deleted and re-registration failed`),l?.();break}if(i instanceof N){let e=ie(i.errorType),t=V(i);x(`[bridge:repl] Fatal poll error: ${i.message} (status=${i.status}, type=${i.errorType??`unknown`})${t?` (suppressed)`:``}`),C(`tengu_bridge_repl_fatal_error`,{status:i.status,error_type:i.errorType}),w(e?`info`:`error`,`bridge_repl_fatal_error`,{status:i.status,error_type:i.errorType}),t||r?.(`failed`,e?`session expired · /remote-control to reconnect`:i.message),l?.();break}let s=Date.now();h!==null&&s-h>6e4*2&&(x(`[bridge:repl] Detected system sleep (${Math.round((s-h)/1e3)}s gap), resetting poll error budget`),w(`info`,`bridge_repl_poll_sleep_detected`,{gapMs:s-h}),p=0,m=null),h=s,p++,m===null&&(m=s);let c=s-m,f=G(i),_=Se(i),v=o?.()??`unknown`;if(x(`[bridge:repl] Poll error (attempt ${p}, elapsed ${Math.round(c/1e3)}s, ws=${v}): ${_}`),C(`tengu_bridge_repl_poll_error`,{status:f,consecutiveErrors:p,elapsedMs:c}),p===1&&r?.(`reconnecting`,_),c>=9e5){x(`[bridge:repl] Poll failures exceeded ${dt/1e3}s (${p} errors), giving up`),w(`info`,`bridge_repl_poll_give_up`),C(`tengu_bridge_repl_poll_give_up`,{consecutiveErrors:p,elapsedMs:c,lastStatus:f}),r?.(`failed`,`connection to server lost`);break}let ee=Math.min(lt*2**(p-1),ut);if(u().non_exclusive_heartbeat_interval_ms>0){let t=d?.();if(t)try{await e.heartbeatWork(t.environmentId,t.workId,t.sessionToken)}catch{}}await k(ee,n)}}x(`[bridge:repl] Work poll loop ended (aborted=${n.aborted}) env=${t().environmentId}`)}S(),y(),q(),K();async function ht(t){let{onInboundMessage:n,onPermissionResponse:r,onInterrupt:a,onSetModel:s,onSetMaxThinkingTokens:d,onSetPermissionMode:h,onStateChange:g,initialMessages:y,getMessages:ee,previouslyFlushedUUIDs:b,initialName:S,perpetual:te,outboundOnly:C,tags:w}=t??{};if(Y(De),!await Ee())return J(`not_enabled`,`[bridge:repl] Skipping: bridge not enabled`),null;if(!$())return J(`no_oauth`,`[bridge:repl] Skipping: no OAuth tokens`),g?.(`failed`,`/login`),null;if(await ce(),!j(`allow_remote_control`))return J(`policy_denied`,`[bridge:repl] Skipping: allow_remote_control policy not allowed`),g?.(`failed`,`disabled by your organization's policy`),null;if(!Te()){let e=f();if(e.bridgeOauthDeadExpiresAt!=null&&(e.bridgeOauthDeadFailCount??0)>=3&&c()?.expiresAt===e.bridgeOauthDeadExpiresAt)return x(`[bridge:repl] Skipping: cross-process backoff (dead token seen ${e.bridgeOauthDeadFailCount} times)`),null;await u();let t=c();if(t&&t.expiresAt!==null&&t.expiresAt<=Date.now()){J(`oauth_expired_unrefreshable`,`[bridge:repl] Skipping: OAuth token expired and refresh failed (re-login required)`),g?.(`failed`,`/login`);let e=t.expiresAt;return l(t=>({...t,bridgeOauthDeadExpiresAt:e,bridgeOauthDeadFailCount:t.bridgeOauthDeadExpiresAt===e?(t.bridgeOauthDeadFailCount??0)+1:1})),null}}let T=Z(),E=`remote-control-${pe()}`,D=!1,O=!1;if(S)E=S,D=!0,O=!0;else{let e=i(),t=e?B(e):void 0;if(t)E=t,D=!0,O=!0;else if(y&&y.length>0)for(let e=y.length-1;e>=0;e--){let t=y[e];if(t.type!==`user`||t.isMeta||t.toolUseResult||t.isCompactSummary||t.origin&&t.origin.kind!==`human`||fe(t))continue;let n=se(t.message.content);if(!n)continue;let r=_t(n);if(r){E=r,D=!0;break}}}let k=0,A,ie=0,ae=(e,t,n)=>{D=!0,E=e,x(`[bridge:repl] derived title from message ${n}: ${e}`),Be(t,e,{baseUrl:T,getAccessToken:$}).catch(()=>{})},M=(e,t)=>{let n=++ie,r=k;Je(e,AbortSignal.timeout(15e3)).then(e=>{e&&n===ie&&A===t&&!B(i())&&ae(e,t,r)})},N=(e,t)=>{if(O||B(i()))return!0;if(A!==void 0&&A!==t&&(k=0),A=t,k++,k===1&&!D){let n=_t(e);n&&ae(n,t,k),M(e,t)}else if(k===3){let n=ee?.();M(n?Xe(L(n)):e,t)}return k>=3},oe=_(`tengu_bridge_initial_history_cap`,200,300*1e3),P=Q()?`self-hosted`:await p();if(!P)return J(`no_org_uuid`,`[bridge:repl] Skipping: no org UUID`),g?.(`failed`,`/login`),null;if(ke()&&!te){let e=await Ge();if(e)return J(`version_too_old`,`[bridge:repl] Skipping: ${e}`,!0),g?.(`failed`,"run `claude update` to upgrade"),null;x(`[bridge:repl] Using env-less bridge path (tengu_bridge_repl_v2)`);let{initEnvLessBridgeCore:t}=await import(`./remoteBridgeCore-BzSUgPbt.js`);return t({baseUrl:T,orgUUID:P,title:E,getAccessToken:$,onAuth401:m,toSDKMessages:qe,initialHistoryCap:oe,initialMessages:y,onInboundMessage:n,onUserMessage:N,onPermissionResponse:r,onInterrupt:a,onSetModel:s,onSetMaxThinkingTokens:d,onSetPermissionMode:h,onStateChange:g,outboundOnly:C,tags:w})}let F=Ae();if(F)return J(`version_too_old`,`[bridge:repl] Skipping: ${F}`),g?.(`failed`,"run `claude update` to upgrade"),null;let I=await ne(),le=await re(),R=process.env.CLAUDE_BRIDGE_SESSION_INGRESS_URL||T,ue=`claude_code`;{let{isAssistantMode:t}=(je(),e(Me));t()&&(ue=`claude_code_assistant`)}return pt({dir:o(),machineName:st(),branch:I,gitRepoUrl:le,title:E,baseUrl:T,sessionIngressUrl:R,workerType:ue,getAccessToken:$,createSession:e=>He({...e,events:[],baseUrl:T,getAccessToken:$}),archiveSession:e=>Ue(e,{baseUrl:T,getAccessToken:$,timeoutMs:1500}).catch(e=>{x(`[bridge:repl] archiveBridgeSession threw: ${v(e)}`,{level:`error`})}),getCurrentTitle:()=>B(i())??E,onUserMessage:N,toSDKMessages:qe,onAuth401:m,getPollIntervalConfig:Fe,initialHistoryCap:oe,initialMessages:y,previouslyFlushedUUIDs:b,onInboundMessage:n,onPermissionResponse:r,onInterrupt:a,onSetModel:s,onSetMaxThinkingTokens:d,onSetPermissionMode:h,onStateChange:g,perpetual:te})}var gt=50;function _t(e){let t=D(e),n=(/^(.*?[.!?])\s/.exec(t)?.[1]??t).replace(/\s+/g,` `).trim();if(n)return n.length>gt?n.slice(0,gt-1)+`…`:n}export{ht as initReplBridge};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{n as e,r as t}from"./language-CPRGmY8Q.js";t();export{e as getResolvedLanguage};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{n as e,o as t}from"./chunk-DR8-3Aex.js";import{Rn as n,b as r,t as i,x as a}from"./src-Di342QoJ.js";import{t as o}from"./jsx-runtime-D-D469L8.js";import{Ct as s,cn as c}from"./state-sIHsFpDu.js";import{n as l,r as u}from"./analytics-DqMQntaB.js";import{$_ as d,Q_ as f,X_ as p,Y_ as m,Z_ as h,cv as g,rv as _}from"./loadAgentsDir-DI1a76pd.js";import{a as v,r as y}from"./detectRepository-CBk3S2zv.js";import{join as b}from"node:path";import{existsSync as x}from"node:fs";import{randomUUID as S}from"node:crypto";function C(e){return D.indexOf(e)}function w({phase:e,target:t,sessionUrl:n,errorMessage:i}){let o=C(e),s=e===`error`;return(0,T.jsxs)(a,{flexDirection:`column`,marginTop:1,marginBottom:1,children:[(0,T.jsxs)(a,{children:[(0,T.jsx)(r,{bold:!0,children:`Autofix PR `}),(0,T.jsx)(r,{color:`claude`,children:t})]}),D.map((e,t)=>{let n=o>t,i=o===t&&!s;return(0,T.jsx)(a,{marginLeft:2,children:(0,T.jsxs)(r,{color:n?`success`:i?`warning`:`subtle`,children:[n?`✓`:i?`→`:`·`,` `,E[e]]})},e)}),s&&i&&(0,T.jsx)(a,{marginLeft:2,marginTop:1,children:(0,T.jsxs)(r,{color:`error`,children:[`✗ `,i]})}),n&&(0,T.jsxs)(a,{marginTop:1,marginLeft:2,children:[(0,T.jsx)(r,{color:`subtle`,children:`Track: `}),(0,T.jsx)(r,{color:`claude`,children:n})]})]})}var T,E,D,O=e((()=>{n(),i(),T=o(),E={detecting:`Detecting repository...`,checking_eligibility:`Checking remote agent eligibility...`,acquiring_lock:`Acquiring monitor lock...`,launching:`Launching remote session...`,registered:`Session registered`,done:`Autofix launched`,error:`Error`},D=[`detecting`,`checking_eligibility`,`acquiring_lock`,`launching`,`registered`,`done`]}));function k(e,t){return{agentId:S(),agentName:`autofix-pr`,teamName:`_autofix`,color:void 0,planModeRequired:!1,parentSessionId:s(),abortController:new AbortController,taskId:S()}}var A=e((()=>{c()}));function j(){return F}function M(e){return F?!1:(F=e,!0)}function N(e){F&&(e&&F.taskId!==e||(F.abortController.abort(),F=null))}function P(e,t,n){return F?.owner===e&&F?.repo===t&&F?.prNumber===n}var F,I=e((()=>{F=null}));function L(e){if(!/^[1-9]\d{0,9}$/.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null}function R(e){let t=e.trim();if(!t)return{action:`invalid`,reason:`empty`};if(t===`stop`||t===`off`)return{action:`stop`};let n=L(t);if(n!==null)return{action:`start`,prNumber:n};let r=t.match(/^([\w.-]+)\/([\w.-]+)#(\d+)$/);if(r){let e=L(r[3]);return e===null?{action:`invalid`,reason:`pr_number_out_of_range`}:{action:`start`,owner:r[1],repo:r[2],prNumber:e}}return{action:`freeform`,prompt:t}}var z=e((()=>{}));function B(e){return[`AUTOFIX.md`,`.claude/skills/autofix.md`,`.claude/skills/autofix-pr/SKILL.md`].filter(t=>x(b(e,t)))}function V(e){return e.length===0?``:` Run ${e.join(` and `)} for custom instructions on how to autofix.`}var H=e((()=>{}));function U(e,t){return u(`tengu_autofix_pr_result`,{result:`failed`,error_code:t}),`Autofix PR failed: ${e}`}var W,G;e((()=>{W=t(n(),1),l(),f(),v(),_(),O(),A(),I(),z(),H(),G=async(e,t,n)=>{try{let r=R(n);if(r.action===`stop`){let t=j();return t?(N(),e(`Stopped local monitoring of ${t.repo}#${t.prNumber}. Any already-running remote session continues until it finishes or is cancelled from claude.ai/code.`,{display:`system`}),null):(e(`No active autofix monitor.`,{display:`system`}),null)}if(r.action===`invalid`)return e(`Invalid args: ${r.reason}. Use /autofix-pr <pr-number> | stop | <owner>/<repo>#<n>`,{display:`system`}),null;if(r.action===`freeform`)return e(`Freeform prompt mode not yet supported. Use /autofix-pr <pr-number>.`,{display:`system`}),null;u(`tengu_autofix_pr_started`,{action:`start`,has_pr_number:`true`,has_repo_path:String(!!(r.owner&&r.repo))});let i;try{i=await y()}catch{return e(U(`Cannot detect GitHub repo from current directory.`,`session_create_failed`),{display:`system`}),null}if(!i||i.host!==`github.com`)return e(U(`Cannot detect GitHub repo from current directory.`,`session_create_failed`),{display:`system`}),null;if(r.owner&&r.owner!==i.owner||r.repo&&r.repo!==i.name)return e(U(`Cross-repo autofix is not supported from this directory. Run from ${i.owner}/${i.name} or pass only the PR number.`,`repo_mismatch`),{display:`system`}),null;let a=i.owner,o=i.name,{prNumber:s}=r;if(P(a,o,s))return u(`tengu_autofix_pr_result`,{result:`success_rc`}),e(`Already monitoring ${o}#${s} in background.`,{display:`system`}),null;let c=await m({skipBundle:!0});if(!c.eligible){let t=c.errors.filter(e=>e.type!==`no_remote_environment`);if(t.length>0)return e(U(`Remote agent not available:\n${t.map(p).join(`
|
|
2
|
-
`)}`,`session_create_failed`),{display:`system`}),null}let l=V(B(process.cwd())),f=`${a}/${o}#${s}`,_=`refs/pull/${s}/head`,v=`Auto-fix failing CI checks on PR #${s} in ${a}/${o}.${l}`,b=k(v,f);if(!M({taskId:b.taskId,owner:a,repo:o,prNumber:s,abortController:b.abortController,startedAt:Date.now()})){let t=j();return e(U(`already monitoring ${t?.repo}#${t?.prNumber}. Run /autofix-pr stop first.`,`rc_already_monitoring_other`),{display:`system`}),null}let x,S=e=>{x=e},C=null;try{C=await g({initialMessage:v,source:`autofix_pr`,branchName:_,skipBundle:!0,title:`Autofix PR: ${f}`,useDefaultEnvironment:!0,signal:b.abortController.signal,githubPr:{owner:a,repo:o,number:s},onBundleFail:S,onCreateFail:S})}catch(t){return N(b.taskId),e(U(`teleport failed: ${t instanceof Error?t.message:String(t)}`,`teleport_failed`),{display:`system`}),null}if(!C)return N(b.taskId),e(U(x??`remote session creation failed.`,`session_create_failed`),{display:`system`}),null;try{d({remoteTaskType:`autofix-pr`,session:C,command:`/autofix-pr ${s}`,context:t,isLongRunning:!0,remoteTaskMetadata:{owner:a,repo:o,prNumber:s}})}catch(t){return N(b.taskId),e(U(`task registration failed: ${t instanceof Error?t.message:String(t)}`,`registration_failed`),{display:`system`}),null}let T=h(C.id);return u(`tengu_autofix_pr_result`,{result:`success_rc`}),e(`Autofix launched for ${f}. Track: ${T}`,{display:`system`}),W.createElement(w,{phase:`done`,target:f,sessionUrl:T})}catch(t){let n=t instanceof Error?t.message:String(t);return u(`tengu_autofix_pr_result`,{result:`failed`,error_code:`exception`}),e(`Autofix PR failed: ${n}`,{display:`system`}),null}}}))();export{G as callAutofixPr};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{o as e,t}from"./loadAgentsDir-DI1a76pd.js";e();export{t as clearAgentDefinitionsCache};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Ov as e,jv as t,kv as n}from"./loadAgentsDir-DI1a76pd.js";e();export{n as loadPluginHooks,t as setupPluginHookHotReload};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as e,c as t,o as n,t as r}from"./localSearch-CDOJNc_E.js";n();export{r as clearSkillIndexCache,e as getSkillIndex,t as searchSkills};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{n as e,r as t,t as n}from"./login-nwTOoyxv.js";t();export{n as Login,e as call};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{DT as e,ET as t,TT as n,wT as r}from"./loadAgentsDir-DI1a76pd.js";t();export{r as call,n as clearAuthRelatedCaches,e as performLogout};
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{o as e}from"./chunk-DR8-3Aex.js";import{n as t,t as n}from"./p-map-D7WEmnBE.js";import{Mt as r,Rn as i,T as a,b as o,f as s,g as c,h as l,t as u,v as ee,x as te}from"./src-Di342QoJ.js";import{t as d}from"./jsx-runtime-D-D469L8.js";import{Ac as f,Nc as p,Po as m,Sc as h,bc as g,jo as ne}from"./paths-BBvuDQl9.js";import{V as re,W as ie}from"./debug-UI3T040K.js";import{n as _,r as v}from"./analytics-DqMQntaB.js";import{n as y,o as ae}from"./process-DMKLUQIO.js";import{i as b,o as x}from"./platform-CuyedWpe.js";import{s as S,u as C}from"./types-Csi32ZXh.js";import{$C as w,AS as T,CC as E,Cx as D,GT as O,JS as k,RC as A,TC as j,XC as M,YC as N,YS as P,_x as F,ay as I,bC as L,iw as R,iy as z,jS as B,lw as V,ly as H,ow as U,pw as W,qT as G,sw as K,uy as q,vC as oe,xC as se,xx as ce,yC as le,zC as J}from"./loadAgentsDir-DI1a76pd.js";import{n as Y,t as X}from"./exit-_obETqBv.js";import{stat as ue}from"fs/promises";import{cwd as de}from"process";n();var Z=e(i(),1);G(),y(),u(),V(),ne(),P(),q();var Q=d();function fe({servers:e,scope:t,onDone:n}){let r=Object.keys(e),[i,u]=(0,Z.useState)({});(0,Z.useEffect)(()=>{R().then(({servers:e})=>u(e))},[]);let d=r.filter(e=>i[e]!==void 0);async function f(n){let r=0;for(let a of n){let n=e[a];if(n){let e=a;if(i[e]!==void 0){let t=1;for(;i[`${a}_${t}`]!==void 0;)t++;e=`${a}_${t}`}await w(e,n,t),r++}}h(r)}let[p]=a(),h=(0,Z.useCallback)(e=>{ae(e>0?`\n${ee(`success`,p)(`Successfully imported ${e} MCP ${m(e,`server`)} to ${t} config.`)}\n`:`
|
|
2
|
-
No servers were imported.`),n(),O()},[p,t,n]),g=(0,Z.useCallback)(()=>{h(0)},[h]);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(s,{title:`Import MCP Servers from Claude Desktop`,subtitle:`Found ${r.length} MCP ${m(r.length,`server`)} in Claude Desktop.`,color:`success`,onCancel:g,hideInputGuide:!0,children:[d.length>0&&(0,Q.jsx)(o,{color:`warning`,children:`Note: Some servers already exist with the same name. If selected, they will be imported with a numbered suffix.`}),(0,Q.jsx)(o,{children:`Please select the servers you want to import:`}),(0,Q.jsx)(H,{options:r.map(e=>({label:`${e}${d.includes(e)?` (already exists)`:``}`,value:e})),defaultValue:r.filter(e=>!d.includes(e)),onSubmit:f,onCancel:g,hideIndexes:!0})]}),(0,Q.jsx)(te,{paddingX:1,children:(0,Q.jsx)(o,{dimColor:!0,italic:!0,children:(0,Q.jsxs)(l,{children:[(0,Q.jsx)(c,{shortcut:`Space`,action:`select`}),(0,Q.jsx)(c,{shortcut:`Enter`,action:`confirm`}),(0,Q.jsx)(k,{action:`confirm:no`,context:`Confirmation`,fallback:`Esc`,description:`cancel`})]})})})]})}u(),I(),_(),se(),D(),V(),M(),B(),f(),re(),G(),S(),x();async function $(e,t){try{let n=await F(e,t);return n.type===`connected`?`✓ Connected`:n.type===`needs-auth`?`! Needs authentication`:`✗ Failed to connect`}catch{return`✗ Connection error`}}async function pe({debug:e,verbose:t}){let n=de();v(`tengu_mcp_start`,{});try{await ue(n)}catch(e){throw ie(e)&&X(`Error: Directory ${n} does not exist`),e}try{let{setup:r}=await import(`./setup-DWkSjA49.js`);await r(n,`default`,!1,!1,void 0,!1);let{startMCPServer:i}=await import(`./mcp-CanCqnch.js`);await i(n,e??!1,t??!1)}catch(e){X(`Error: Failed to start MCP server: ${e}`)}}async function me(e,t){let n=U(e),r=()=>{n&&(n.type===`sse`||n.type===`http`)&&(le(e,n),oe(e,n))};try{if(t.scope){let n=J(t.scope);v(`tengu_mcp_delete`,{name:e,scope:n}),await W(e,n),r(),process.stdout.write(`Removed MCP server ${e} from ${n} config\n`),Y(`File modified: ${A(n)}`)}let n=g(),i=h(),{servers:a}=K(`project`),o=!!a[e],s=[];if(n.mcpServers?.[e]&&s.push(`local`),o&&s.push(`project`),i.mcpServers?.[e]&&s.push(`user`),s.length===0)X(`No MCP server found with name: "${e}"`);else if(s.length===1){let t=s[0];v(`tengu_mcp_delete`,{name:e,scope:t}),await W(e,t),r(),process.stdout.write(`Removed MCP server "${e}" from ${t} config\n`),Y(`File modified: ${A(t)}`)}else process.stderr.write(`MCP server "${e}" exists in multiple scopes:\n`),s.forEach(e=>{process.stderr.write(` - ${N(e)} (${A(e)})\n`)}),process.stderr.write(`
|
|
3
|
-
To remove from a specific scope, use:
|
|
4
|
-
`),s.forEach(t=>{process.stderr.write(` claude mcp remove "${e}" -s ${t}\n`)}),X()}catch(e){X(e.message)}}async function he(){v(`tengu_mcp_list`,{});let{servers:e}=await R();if(Object.keys(e).length===0)console.log("No MCP servers configured. Use `claude mcp add` to add a server.");else{console.log(`Checking MCP server health...
|
|
5
|
-
`);let n=await t(Object.entries(e),async([e,t])=>({name:e,server:t,status:await $(e,t)}),{concurrency:ce()});for(let{name:e,server:t,status:r}of n)if(t.type===`sse`)console.log(`${e}: ${t.url} (SSE) - ${r}`);else if(t.type===`http`)console.log(`${e}: ${t.url} (HTTP) - ${r}`);else if(t.type===`claudeai-proxy`)console.log(`${e}: ${t.url} - ${r}`);else if(!t.type||t.type===`stdio`){let n=t,i=Array.isArray(n.args)?n.args:[];console.log(`${e}: ${n.command} ${i.join(` `)} - ${r}`)}}await O(0)}async function ge(e){v(`tengu_mcp_get`,{name:e});let t=U(e);t||X(`No MCP server found with name: ${e}`),console.log(`${e}:`),console.log(` Scope: ${N(t.scope)}`);let n=await $(e,t);if(console.log(` Status: ${n}`),t.type===`sse`){if(console.log(` Type: sse`),console.log(` URL: ${t.url}`),t.headers){console.log(` Headers:`);for(let[e,n]of Object.entries(t.headers))console.log(` ${e}: ${n}`)}if(t.oauth?.clientId||t.oauth?.callbackPort){let n=[];t.oauth.clientId&&(n.push(`client_id configured`),L(e,t)?.clientSecret&&n.push(`client_secret configured`)),t.oauth.callbackPort&&n.push(`callback_port ${t.oauth.callbackPort}`),console.log(` OAuth: ${n.join(`, `)}`)}}else if(t.type===`http`){if(console.log(` Type: http`),console.log(` URL: ${t.url}`),t.headers){console.log(` Headers:`);for(let[e,n]of Object.entries(t.headers))console.log(` ${e}: ${n}`)}if(t.oauth?.clientId||t.oauth?.callbackPort){let n=[];t.oauth.clientId&&(n.push(`client_id configured`),L(e,t)?.clientSecret&&n.push(`client_secret configured`)),t.oauth.callbackPort&&n.push(`callback_port ${t.oauth.callbackPort}`),console.log(` OAuth: ${n.join(`, `)}`)}}else if(t.type===`stdio`){console.log(` Type: stdio`),console.log(` Command: ${t.command}`);let e=Array.isArray(t.args)?t.args:[];if(console.log(` Args: ${e.join(` `)}`),t.env){console.log(` Environment:`);for(let[e,n]of Object.entries(t.env))console.log(` ${e}=${n}`)}}console.log(`\nTo remove this server, run: claude mcp remove "${e}" -s ${t.scope}`),await O(0)}async function _e(e,t,n){try{let r=J(n.scope),i=C(t),a=n.clientSecret&&i&&typeof i==`object`&&`type`in i&&(i.type===`sse`||i.type===`http`)&&`url`in i&&typeof i.url==`string`&&`oauth`in i&&i.oauth&&typeof i.oauth==`object`&&`clientId`in i.oauth?await E():void 0;await w(e,i,r);let o=i&&typeof i==`object`&&`type`in i?String(i.type||`stdio`):`stdio`;a&&i&&typeof i==`object`&&`type`in i&&(i.type===`sse`||i.type===`http`)&&`url`in i&&typeof i.url==`string`&&j(e,{type:i.type,url:i.url},a),v(`tengu_mcp_add`,{scope:r,source:`json`,type:o}),Y(`Added ${o} MCP server ${e} to ${r} config`)}catch(e){X(e.message)}}async function ve(e){try{let t=J(e.scope);v(`tengu_mcp_add`,{scope:t,platform:b(),source:`desktop`});let{readClaudeDesktopMcpServers:n}=await import(`./claudeDesktop-D0S1eq1F.js`),i=await n();Object.keys(i).length===0&&Y(`No MCP servers found in Claude Desktop configuration or configuration file does not exist.`);let{unmount:a}=await r((0,Q.jsx)(T,{children:(0,Q.jsx)(z,{children:(0,Q.jsx)(fe,{servers:i,scope:t,onDone:()=>{a()}})})}),{exitOnCtrlC:!0})}catch(e){X(e.message)}}async function ye(){v(`tengu_mcp_reset_mcpjson_choices`,{}),p(e=>({...e,enabledMcpjsonServers:[],disabledMcpjsonServers:[],enableAllProjectMcpServers:!1})),Y(`All project-scoped (.mcp.json) server approvals and rejections have been reset.
|
|
6
|
-
You will be prompted for approval next time you start Claude Code.`)}export{ve as mcpAddFromDesktopHandler,_e as mcpAddJsonHandler,ge as mcpGetHandler,he as mcpListHandler,me as mcpRemoveHandler,ye as mcpResetChoicesHandler,pe as mcpServeHandler};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{n as e,o as t}from"./chunk-DR8-3Aex.js";import{n,t as r}from"./figures-gfT9mM8P.js";import{Q as i,Rn as a,T as o,b as s,f as c,g as l,h as u,nt as d,t as f,tt as p,v as m,x as h}from"./src-Di342QoJ.js";import{t as g}from"./jsx-runtime-D-D469L8.js";import{Do as _,Po as v,jo as y}from"./paths-BBvuDQl9.js";import{c as b,s as x}from"./debug-UI3T040K.js";import{Dx as S,GC as C,JS as w,MS as T,NS as E,RC as D,SC as ee,XC as O,YS as k,_C as A,cy as j,gC as M,gy as N,jS as P,my as te,qC as F,xC as I}from"./loadAgentsDir-DI1a76pd.js";import{D as ne,O as re}from"./rcDebugLog-CPKZCtR8.js";import{t as ie}from"./useKeybinding-FsOnjW6T.js";import{i as ae,n as oe,r as se}from"./MCPConnectionManager-DYGoS1Ht.js";import{n as ce,t as le}from"./McpParsingWarnings-EzgsOoHw.js";import{a as ue,c as L,i as R,l as de,n as fe,o as z,r as pe,s as me,t as he,u as B}from"./PluginSettings-eYcWehI8.js";function ge({agentServer:e,onCancel:t,onComplete:n}){let[a]=o(),[d,f]=(0,V.useState)(!1),[g,v]=(0,V.useState)(null),[y,b]=(0,V.useState)(null),x=(0,V.useRef)(null);(0,V.useEffect)(()=>()=>x.current?.abort(),[]),p(`confirm:no`,(0,V.useCallback)(()=>{d&&(x.current?.abort(),x.current=null,f(!1),b(null))},[d]),{context:`Confirmation`,isActive:d});let C=(0,V.useCallback)(async()=>{if(!e.needsAuth||!e.url)return;f(!0),v(null);let t=new AbortController;x.current=t;try{let r={type:e.transport,url:e.url};await ee(e.name,r,b,t.signal),n?.(`Authentication successful for ${e.name}. The server will connect when the agent runs.`)}catch(e){e instanceof Error&&!(e instanceof M)&&v(e.message)}finally{f(!1),x.current=null}},[e,n]),T=_(String(e.name));if(d)return(0,H.jsxs)(h,{flexDirection:`column`,gap:1,padding:1,children:[(0,H.jsxs)(s,{color:`claude`,children:[`Authenticating with `,e.name,`…`]}),(0,H.jsxs)(h,{children:[(0,H.jsx)(te,{}),(0,H.jsx)(s,{children:` A browser window will open for authentication`})]}),y&&(0,H.jsxs)(h,{flexDirection:`column`,children:[(0,H.jsx)(s,{dimColor:!0,children:`If your browser doesn't open automatically, copy this URL manually:`}),(0,H.jsx)(i,{url:y})]}),(0,H.jsx)(h,{marginLeft:3,children:(0,H.jsxs)(s,{dimColor:!0,children:[`Return here after authenticating in your browser.`,` `,(0,H.jsx)(w,{action:`confirm:no`,context:`Confirmation`,fallback:`Esc`,description:`go back`})]})})]});let E=[];return e.needsAuth&&E.push({label:e.isAuthenticated?`Re-authenticate`:`Authenticate`,value:`auth`}),E.push({label:`Back`,value:`back`}),(0,H.jsxs)(c,{title:`${T} MCP Server`,subtitle:`agent-only`,onCancel:t,inputGuide:e=>e.pending?(0,H.jsxs)(s,{children:[`Press `,e.keyName,` again to exit`]}):(0,H.jsxs)(u,{children:[(0,H.jsx)(l,{shortcut:`↑↓`,action:`navigate`}),(0,H.jsx)(l,{shortcut:`Enter`,action:`confirm`}),(0,H.jsx)(w,{action:`confirm:no`,context:`Confirmation`,fallback:`Esc`,description:`go back`})]}),children:[(0,H.jsxs)(h,{flexDirection:`column`,gap:0,children:[(0,H.jsxs)(h,{children:[(0,H.jsx)(s,{bold:!0,children:`Type: `}),(0,H.jsx)(s,{dimColor:!0,children:e.transport})]}),e.url&&(0,H.jsxs)(h,{children:[(0,H.jsx)(s,{bold:!0,children:`URL: `}),(0,H.jsx)(s,{dimColor:!0,children:e.url})]}),e.command&&(0,H.jsxs)(h,{children:[(0,H.jsx)(s,{bold:!0,children:`Command: `}),(0,H.jsx)(s,{dimColor:!0,children:e.command})]}),(0,H.jsxs)(h,{children:[(0,H.jsx)(s,{bold:!0,children:`Used by: `}),(0,H.jsx)(s,{dimColor:!0,children:e.sourceAgents.join(`, `)})]}),(0,H.jsxs)(h,{marginTop:1,children:[(0,H.jsx)(s,{bold:!0,children:`Status: `}),(0,H.jsxs)(s,{children:[m(`inactive`,a)(r.radioOff),` not connected (agent-only)`]})]}),e.needsAuth&&(0,H.jsxs)(h,{children:[(0,H.jsx)(s,{bold:!0,children:`Auth: `}),e.isAuthenticated?(0,H.jsxs)(s,{children:[m(`success`,a)(r.tick),` authenticated`]}):(0,H.jsxs)(s,{children:[m(`warning`,a)(r.triangleUpOutline),` may need authentication`]})]})]}),(0,H.jsx)(h,{children:(0,H.jsx)(s,{dimColor:!0,children:`This server connects only when running the agent.`})}),g&&(0,H.jsx)(h,{children:(0,H.jsxs)(s,{color:`error`,children:[`Error: `,g]})}),(0,H.jsx)(h,{children:(0,H.jsx)(S,{options:E,onChange:async e=>{switch(e){case`auth`:await C();break;case`back`:t();break}},onCancel:t})})]})}var V,H,U=e((()=>{n(),V=t(a(),1),f(),ie(),I(),y(),k(),j(),N(),H=g()}));function W(e){switch(e){case`project`:return{label:`Project MCPs`,path:D(e)};case`user`:return{label:`User MCPs`,path:D(e)};case`local`:return{label:`Local MCPs`,path:D(e)};case`enterprise`:return{label:`Enterprise MCPs`};case`dynamic`:return{label:`Built-in MCPs`,path:`always available`};default:return{label:e}}}function _e(e){let t=new Map;for(let n of e){let e=n.scope;t.has(e)||t.set(e,[]),t.get(e).push(n)}for(let[,e]of t)e.sort((e,t)=>e.name.localeCompare(t.name));return t}function ve({servers:e,agentServers:t=[],onSelectServer:n,onSelectAgentServer:a,onComplete:f}){let[p]=o(),[g,_]=(0,G.useState)(0),y=G.useMemo(()=>_e(e.filter(e=>e.client.config.type!==`claudeai-proxy`)),[e]),x=G.useMemo(()=>e.filter(e=>e.client.config.type===`claudeai-proxy`).sort((e,t)=>e.name.localeCompare(t.name)),[e]),S=G.useMemo(()=>(y.get(`dynamic`)??[]).sort((e,t)=>e.name.localeCompare(t.name)),[y]),C=W(`dynamic`),T=G.useMemo(()=>{let e=[];for(let t of q){let n=y.get(t)??[];for(let t of n)e.push({type:`server`,server:t})}for(let t of x)e.push({type:`server`,server:t});for(let n of t)e.push({type:`agent-server`,agentServer:n});for(let t of S)e.push({type:`server`,server:t});return e},[y,x,t,S]),E=(0,G.useCallback)(()=>{f(`MCP dialog dismissed`,{display:`system`})},[f]);d({"confirm:previous":()=>_(e=>e===0?T.length-1:e-1),"confirm:next":()=>_(e=>e===T.length-1?0:e+1),"confirm:yes":(0,G.useCallback)(()=>{let e=T[g];e&&(e.type===`server`?n(e.server):e.type===`agent-server`&&a&&a(e.agentServer))},[T,g,n,a]),"confirm:no":E},{context:`Confirmation`});let D=e=>T.findIndex(t=>t.type===`server`&&t.server===e),ee=e=>T.findIndex(t=>t.type===`agent-server`&&t.agentServer===e),O=b(),k=e.some(e=>e.client.type===`failed`);if(e.length===0&&t.length===0)return null;let A=e=>{let t=D(e),n=g===t,i=``,a=``;if(e.client.type===`disabled`)i=m(`inactive`,p)(r.radioOff),a=`disabled`;else if(e.client.type===`connected`)i=m(`success`,p)(r.tick),a=`connected`;else if(e.client.type===`pending`){i=m(`inactive`,p)(r.radioOff);let{reconnectAttempt:t,maxReconnectAttempts:n}=e.client;a=t&&n?`reconnecting (${t}/${n})…`:`connecting…`}else e.client.type===`needs-auth`?(i=m(`warning`,p)(r.triangleUpOutline),a=`needs authentication`):(i=m(`error`,p)(r.cross),a=`failed`);return(0,K.jsxs)(h,{children:[(0,K.jsx)(s,{color:n?`suggestion`:void 0,children:n?`${r.pointer} `:` `}),(0,K.jsx)(s,{color:n?`suggestion`:void 0,children:e.name}),(0,K.jsxs)(s,{dimColor:!n,children:[` · `,i,` `]}),(0,K.jsx)(s,{dimColor:!n,children:a})]},`${e.name}-${t}`)},j=e=>{let t=ee(e),n=g===t,i=e.needsAuth?m(`warning`,p)(r.triangleUpOutline):m(`inactive`,p)(r.radioOff),a=e.needsAuth?`may need auth`:`agent-only`;return(0,K.jsxs)(h,{children:[(0,K.jsx)(s,{color:n?`suggestion`:void 0,children:n?`${r.pointer} `:` `}),(0,K.jsx)(s,{color:n?`suggestion`:void 0,children:e.name}),(0,K.jsxs)(s,{dimColor:!n,children:[` · `,i,` `]}),(0,K.jsx)(s,{dimColor:!n,children:a})]},`agent-${e.name}-${t}`)},M=e.length+t.length;return(0,K.jsxs)(h,{flexDirection:`column`,children:[(0,K.jsx)(le,{}),(0,K.jsx)(c,{title:`Manage MCP servers`,subtitle:`${M} ${v(M,`server`)}`,onCancel:E,hideInputGuide:!0,children:(0,K.jsxs)(h,{flexDirection:`column`,children:[q.map(e=>{let t=y.get(e);if(!t||t.length===0)return null;let n=W(e);return(0,K.jsxs)(h,{flexDirection:`column`,marginBottom:1,children:[(0,K.jsxs)(h,{paddingLeft:2,children:[(0,K.jsx)(s,{bold:!0,children:n.label}),n.path&&(0,K.jsxs)(s,{dimColor:!0,children:[` (`,n.path,`)`]})]}),t.map(e=>A(e))]},e)}),x.length>0&&(0,K.jsxs)(h,{flexDirection:`column`,marginBottom:1,children:[(0,K.jsx)(h,{paddingLeft:2,children:(0,K.jsx)(s,{bold:!0,children:`claude.ai`})}),x.map(e=>A(e))]}),t.length>0&&(0,K.jsxs)(h,{flexDirection:`column`,marginBottom:1,children:[(0,K.jsx)(h,{paddingLeft:2,children:(0,K.jsx)(s,{bold:!0,children:`Agent MCPs`})}),[...new Set(t.flatMap(e=>e.sourceAgents))].map(e=>(0,K.jsxs)(h,{flexDirection:`column`,marginTop:1,children:[(0,K.jsx)(h,{paddingLeft:2,children:(0,K.jsxs)(s,{dimColor:!0,children:[`@`,e]})}),t.filter(t=>t.sourceAgents.includes(e)).map(e=>j(e))]},e))]}),S.length>0&&(0,K.jsxs)(h,{flexDirection:`column`,marginBottom:1,children:[(0,K.jsxs)(h,{paddingLeft:2,children:[(0,K.jsx)(s,{bold:!0,children:C.label}),C.path&&(0,K.jsxs)(s,{dimColor:!0,children:[` (`,C.path,`)`]})]}),S.map(e=>A(e))]}),(0,K.jsxs)(h,{flexDirection:`column`,children:[k&&(0,K.jsx)(s,{dimColor:!0,children:O?`※ Error logs shown inline with --debug`:`※ Run claude --debug to see error logs`}),(0,K.jsxs)(s,{dimColor:!0,children:[(0,K.jsx)(i,{url:`https://code.claude.com/docs/en/mcp`,children:`https://code.claude.com/docs/en/mcp`}),` for help`]})]})]})}),(0,K.jsx)(h,{paddingX:1,children:(0,K.jsx)(s,{dimColor:!0,italic:!0,children:(0,K.jsxs)(u,{children:[(0,K.jsx)(l,{shortcut:`↑↓`,action:`navigate`}),(0,K.jsx)(l,{shortcut:`Enter`,action:`confirm`}),(0,K.jsx)(w,{action:`confirm:no`,context:`Confirmation`,fallback:`Esc`,description:`cancel`})]})})})]})}var G,K,q,ye=e((()=>{n(),G=t(a(),1),f(),ie(),O(),x(),y(),k(),ce(),K=g(),q=[`project`,`local`,`user`,`enterprise`]}));function be({serverName:e,onComplete:t}){let[n]=o(),i=E(),a=se(),[c,l]=(0,J.useState)(!0),[u,d]=(0,J.useState)(null);return(0,J.useEffect)(()=>{async function n(){try{if(!i.getState().mcp.clients.find(t=>t.name===e)){d(`MCP server "${e}" not found`),l(!1),t(`MCP server "${e}" not found`);return}switch((await a(e)).client.type){case`connected`:l(!1),t(`Successfully reconnected to ${e}`);break;case`needs-auth`:d(`${e} requires authentication`),l(!1),t(`${e} requires authentication. Use /mcp to authenticate.`);break;case`pending`:case`failed`:case`disabled`:d(`Failed to reconnect to ${e}`),l(!1),t(`Failed to reconnect to ${e}`);break}}catch(e){let n=e instanceof Error?e.message:String(e);d(n),l(!1),t(`Error: ${n}`)}}n()},[e,a,i,t]),c?(0,Y.jsxs)(h,{flexDirection:`column`,gap:1,padding:1,children:[(0,Y.jsxs)(s,{color:`text`,children:[`Reconnecting to `,(0,Y.jsx)(s,{bold:!0,children:e})]}),(0,Y.jsxs)(h,{children:[(0,Y.jsx)(te,{}),(0,Y.jsx)(s,{children:` Establishing connection to MCP server`})]})]}):u?(0,Y.jsxs)(h,{flexDirection:`column`,gap:1,padding:1,children:[(0,Y.jsxs)(h,{children:[(0,Y.jsxs)(s,{children:[m(`error`,n)(r.cross),` `]}),(0,Y.jsxs)(s,{color:`error`,children:[`Failed to reconnect to `,e]})]}),(0,Y.jsxs)(s,{dimColor:!0,children:[`Error: `,u]})]}):null}var J,Y,xe=e((()=>{n(),J=t(a(),1),f(),oe(),P(),N(),Y=g()}));function Se({onComplete:e}){let t=T(e=>e.mcp),n=T(e=>e.agentDefinitions),r=t.clients,[i,a]=X.useState({type:`list`}),[o,s]=X.useState([]),c=(0,X.useMemo)(()=>C(n.allAgents),[n.allAgents]),l=X.useMemo(()=>r.filter(e=>e.name!==`ide`).sort((e,t)=>e.name.localeCompare(t.name)),[r]);switch(X.useEffect(()=>{let e=!1;async function n(){let n=await Promise.all(l.map(async e=>{let n=e.config.scope,r=e.config.type===`sse`,i=e.config.type===`http`,a=e.config.type===`claudeai-proxy`,o;if(r||i){let n=await new A(e.name,e.config).tokens(),r=ne()!==null&&e.type===`connected`,i=e.type===`connected`&&F(t.tools,e.name).length>0;o=!!n||r||i}let s={name:e.name,client:e,scope:n};return a?{...s,transport:`claudeai-proxy`,isAuthenticated:!1,config:e.config}:r?{...s,transport:`sse`,isAuthenticated:o,config:e.config}:i?{...s,transport:`http`,isAuthenticated:o,config:e.config}:{...s,transport:`stdio`,config:e.config}}));e||s(n)}return n(),()=>{e=!0}},[l,t.tools]),(0,X.useEffect)(()=>{o.length===0&&l.length>0||o.length===0&&c.length===0&&e("No MCP servers configured. Please run /doctor if this is unexpected. Otherwise, run `claude mcp --help` or visit https://code.claude.com/docs/en/mcp to learn more.")},[o.length,l.length,c.length,e]),i.type){case`list`:return(0,Z.jsx)(ve,{servers:o,agentServers:c,onSelectServer:e=>a({type:`server-menu`,server:e}),onSelectAgentServer:e=>a({type:`agent-server-menu`,agentServer:e}),onComplete:e,defaultTab:i.defaultTab});case`server-menu`:{let n=F(t.tools,i.server.name),r=i.server.transport===`claudeai-proxy`?`claude.ai`:`Claude Code`;return i.server.transport===`stdio`?(0,Z.jsx)(me,{server:i.server,serverToolsCount:n.length,onViewTools:()=>a({type:`server-tools`,server:i.server}),onCancel:()=>a({type:`list`,defaultTab:r}),onComplete:e}):(0,Z.jsx)(de,{server:i.server,serverToolsCount:n.length,onViewTools:()=>a({type:`server-tools`,server:i.server}),onCancel:()=>a({type:`list`,defaultTab:r}),onComplete:e})}case`server-tools`:return(0,Z.jsx)(pe,{server:i.server,onSelectTool:(e,t)=>a({type:`server-tool-detail`,server:i.server,toolIndex:t}),onBack:()=>a({type:`server-menu`,server:i.server})});case`server-tool-detail`:{let e=F(t.tools,i.server.name)[i.toolIndex];return e?(0,Z.jsx)(ue,{tool:e,server:i.server,onBack:()=>a({type:`server-tools`,server:i.server})}):(a({type:`server-tools`,server:i.server}),null)}case`agent-server-menu`:return(0,Z.jsx)(ge,{agentServer:i.agentServer,onCancel:()=>a({type:`list`,defaultTab:`Agents`}),onComplete:e})}}var X,Z,Ce=e((()=>{X=t(a(),1),I(),O(),P(),re(),U(),ye(),B(),L(),z(),R(),Z=g()})),we=e((()=>{U(),ye(),xe(),B(),Ce(),L(),z(),R()}));function Te({action:e,target:t,onComplete:n}){let r=T(e=>e.mcp.clients),i=ae(),a=(0,Q.useRef)(!1);return(0,Q.useEffect)(()=>{if(a.current)return;a.current=!0;let o=e===`enable`,s=r.filter(e=>e.name!==`ide`),c=t===`all`?s.filter(e=>o?e.type===`disabled`:e.type!==`disabled`):s.filter(e=>e.name===t);if(c.length===0){n(t===`all`?`All MCP servers are already ${o?`enabled`:`disabled`}`:`MCP server "${t}" not found`);return}for(let e of c)i(e.name);n(t===`all`?`${o?`Enabled`:`Disabled`} ${c.length} MCP server(s)`:`MCP server "${t}" ${o?`enabled`:`disabled`}`)},[e,t,r,i,n]),null}async function Ee(e,t,n){if(n){let t=n.trim().split(/\s+/);if(t[0]===`no-redirect`)return(0,$.jsx)(Se,{onComplete:e});if(t[0]===`reconnect`&&t[1])return(0,$.jsx)(be,{serverName:t.slice(1).join(` `),onComplete:e});if(t[0]===`enable`||t[0]===`disable`)return(0,$.jsx)(Te,{action:t[0],target:t.length>1?t.slice(1).join(` `):`all`,onComplete:e})}return process.env.USER_TYPE===`ant`?(0,$.jsx)(he,{onComplete:e,args:`manage`,showMcpRedirectMessage:!0}):(0,$.jsx)(Se,{onComplete:e})}var Q,$;e((()=>{Q=t(a(),1),we(),xe(),oe(),P(),fe(),$=g()}))();export{Ee as call};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Dr as e,Pr as t}from"./paths-BBvuDQl9.js";t();export{e as getMainLoopModel};
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./chunk-DR8-3Aex.js";import{l as t,s as n,u as r}from"./envUtils-BWeoiL4Y.js";import{ai as i,ci as a,cr as o,dr as s}from"./paths-BBvuDQl9.js";import{d as c,s as l}from"./debug-UI3T040K.js";import{o as u,u as d}from"./proxy-CfZp-wce.js";import{AT as ee,Ko as f,Lo as p,NE as m,OT as h,PE as te,Wo as g,Xc as _,Yc as v,Zc as y,__ as b,_m as x,bo as S,co as C,g_ as ne,h_ as w,kT as T,pm as E,st as D,ut as O,v_ as k}from"./loadAgentsDir-DI1a76pd.js";import{Bn as A,Hn as re,Vn as j,i as ie,r as M,t as N}from"./prompt-CjFAtm3w.js";import{F as ae,I as P,L as F,P as I,R as L,Y as R}from"./rcDebugLog-CPKZCtR8.js";import{r as z,t as B}from"./store-DhI7Lcan.js";import{i as V,n as H,r as U,t as W}from"./openaiShared-D5lOejS1.js";import{randomUUID as G}from"crypto";function K(e){if(!e)return 0;let t=0,n=/(\d+(?:\.\d+)?)(ms|s|m|h|d)/g,r;for(;(r=n.exec(e))!==null;){let e=Number(r[1]);switch(r[2]){case`ms`:t+=e/1e3;break;case`s`:t+=e;break;case`m`:t+=e*60;break;case`h`:t+=e*3600;break;case`d`:t+=e*86400;break}}if(t===0){let n=Number(e);Number.isFinite(n)&&(t=n)}return t<=0?0:Math.floor(Date.now()/1e3)+t}function q(e,t){if(e===null||t===null)return null;let n=Number(e),r=Number(t);if(!Number.isFinite(n)||!Number.isFinite(r)||r<=0)return null;let i=Math.max(0,r-n);return Math.min(1,Math.max(0,i/r))}var J,oe=e((()=>{J={providerId:`openai`,parseHeaders(e){let t=[],n=q(e.get(`x-ratelimit-remaining-requests`),e.get(`x-ratelimit-limit-requests`));n!==null&&t.push({kind:`requests`,label:`RPM`,utilization:n,resetsAt:K(e.get(`x-ratelimit-reset-requests`))||void 0});let r=q(e.get(`x-ratelimit-remaining-tokens`),e.get(`x-ratelimit-limit-tokens`));return r!==null&&t.push({kind:`tokens`,label:`TPM`,utilization:r,resetsAt:K(e.get(`x-ratelimit-reset-tokens`))||void 0}),t}}}));function se(e){return async(...t)=>{let n=await e(...t);try{z(`openai`,J.parseHeaders(n.headers))}catch{}return n}}function ce(e){if(Y)return Y;let t=process.env.OPENAI_API_KEY||``,n=process.env.OPENAI_BASE_URL,r=se(e?.fetchOverride??globalThis.fetch),i=new V({apiKey:t,...n&&{baseURL:n},maxRetries:e?.maxRetries??0,timeout:parseInt(process.env.API_TIMEOUT_MS||`600000`,10),dangerouslyAllowBrowser:!0,...process.env.OPENAI_ORG_ID&&{organization:process.env.OPENAI_ORG_ID},...process.env.OPENAI_PROJECT_ID&&{project:process.env.OPENAI_PROJECT_ID},fetchOptions:u({forAnthropicAPI:!1}),fetch:r});return e?.fetchOverride||(Y=i),i}var Y,le=e((()=>{U(),oe(),B(),d(),Y=null}));function X(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
|
-
`):``}function ue(e){if(typeof e==`string`)return e;if(!Array.isArray(e))return X(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:X(e)}function de(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=X(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:X(e.content)});continue}if(i===`assistant`){let n=X(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:ue(e.content)})}return{input:t,instructions:n.length>0?n.join(`
|
|
3
|
-
|
|
4
|
-
`):void 0}}function fe(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 pe(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 me(e){let{input:t,instructions:n}=de(e.messages),r=fe(e.tools);return{model:e.model,stream:!0,store:!1,input:t,...n?{instructions:n}:{},...r.length>0?{tools:r}:{},...e.toolChoice?{tool_choice:pe(e.toolChoice)}:{},...e.reasoningEffort?{reasoning:{effort:e.reasoningEffort}}:{},parallel_tool_calls:!0}}async function*he(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(`
|
|
5
|
-
|
|
6
|
-
`);for(;a>=0;){let e=r.slice(0,a);r=r.slice(a+2);let t=e.split(/\r?\n/).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trimStart()).join(`
|
|
7
|
-
`);if(t&&t!==`[DONE]`){let e=JSON.parse(t);e&&typeof e==`object`&&(yield e)}a=r.indexOf(`
|
|
8
|
-
|
|
9
|
-
`)}}}function ge(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 _e(e){return e?.status===`incomplete`?`max_tokens`:`end_turn`}async function*ve(e,t){let n=`msg_${G().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:_e(e),stop_sequence:null},usage:ge(e)},yield{type:`message_stop`}}}}async function ye(e){let t=await h(),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:`claude-code-best`};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 he(i)}var be=e((()=>{T()}));function xe(e){if(t(process.env.OPENAI_ENABLE_THINKING))return!1;if(r(process.env.OPENAI_ENABLE_THINKING))return!0;let n=e.toLowerCase();return n.includes(`deepseek`)||n.includes(`mimo`)}function Se(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 Z(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 Ce=e((()=>{n()}));function Q(e){if(e===`low`)return`low`;if(e===`medium`)return`medium`;if(e===`high`)return`high`;if(e===`xhigh`||e===`max`)return`xhigh`;if(typeof e==`number`)return`high`}function we(e){let t=process.env.CLAUDE_CODE_EFFORT_LEVEL?.toLowerCase();if(!(t===`auto`||t===`unset`))return Q(t)??Q(e)??`medium`}function Te(e,t,n,r){if(!r||_())return e;let i=t.filter(e=>n.has(e.name)).map(N).sort().join(`
|
|
10
|
-
`);return i?[S({content:`<available-deferred-tools>\n${i}\n</available-deferred-tools>`,isMeta:!0}),...e]:e}function Ee(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&&c.push({message:{...t,content:g(l,r,i),usage:a,stop_reason:o,stop_sequence:null},requestId:void 0,type:`assistant`,uuid:G(),timestamp:new Date().toISOString()}),o===`max_tokens`&&c.push(C({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*De(e,t,n,r,a){try{let s=R(a.model),l=f(e,n),u=await y(a.model,n,a.getToolPermissionContext||(async()=>A()),a.agents||[],a.querySource),d=new Set;if(u)for(let e of n)ie(e)&&d.add(e.name);let p=n;u&&d.size>0&&(p=n.filter(e=>!!(!d.has(e.name)||re(e,`SearchExtraTools`))));let m=await Promise.all(p.map(e=>O(e,{getToolPermissionContext:a.getToolPermissionContext,tools:n,agents:a.agents,allowedAgentTypes:a.allowedAgentTypes,model:a.model,deferLoading:u&&d.has(e.name)}))),h=m.filter(e=>{let t=e;return t.type!==`advisor_20260301`&&t.type!==`computer_20250124`}),g=xe(s),_=L(Te(l.filter(Ee),n,d,u),t,{enableThinking:g}),v=F(h),x=P(a.toolChoice),S=we(a.effortValue);if(u){let e=p.filter(e=>d.has(e.name)).length;c(`[OpenAI] Tool search enabled: ${e}/${d.size} deferred tools included, total tools=${v.length}`)}else c(`[OpenAI] Tool search disabled, total tools=${v.length}`);let{upperLimit:C}=o(s),T=Se(C,a.maxOutputTokensOverride);c(`[OpenAI] Calling model=${s}, messages=${_.length}, tools=${v.length}, thinking=${g}`);let D=ee()?ve(await ye({request:me({model:s,messages:_,tools:v,toolChoice:x,reasoningEffort:S}),signal:r,fetchOverride:a.fetchOverride}),s):ae(await ce({maxRetries:0,fetchOverride:a.fetchOverride,source:a.querySource}).chat.completions.create(Z({model:s,messages:_,tools:v,toolChoice:x,enableThinking:g,maxTokens:T,temperatureOverride:a.temperatureOverride}),{signal:r}),s),k={},j=[],M,N=null,I={input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0},z=0,B=Date.now();for await(let e of D){switch(e.type){case`message_start`:M=e.message,z=Date.now()-B,e.message?.usage&&(I={...I,...e.message.usage});break;case`content_block_start`:{let t=e.index,n=e.content_block;n.type===`tool_use`?k[t]={...n,input:``}:n.type===`text`?k[t]={...n,text:``}:n.type===`thinking`?k[t]={...n,thinking:``,signature:``}:k[t]={...n};break}case`content_block_delta`:{let t=e.index,n=e.delta,r=k[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&&(I=H(I,t)),e.delta?.stop_reason!=null&&(N=e.delta.stop_reason);break}case`message_stop`:if(M){for(let e of $({partialMessage:M,contentBlocks:k,tools:n,agentId:a.agentId,usage:I,stopReason:N,maxTokens:T}))e.type===`assistant`&&j.push(e),yield e;M=null}I.input_tokens+I.output_tokens>0&&E(i(s,I),I,a.model);break}yield{type:`stream_event`,event:e,...e.type===`message_start`?{ttftMs:z}:void 0}}if(te(a.langfuseTrace??null,{model:s,provider:`openai`,input:w(_),output:ne(j),usage:{input_tokens:I.input_tokens,output_tokens:I.output_tokens,cache_creation_input_tokens:I.cache_creation_input_tokens,cache_read_input_tokens:I.cache_read_input_tokens},startTime:new Date(B),endTime:new Date,completionStartTime:z>0?new Date(B+z):void 0,tools:b(m),...g&&{thinking:{type:`enabled`}}}),M)for(let e of $({partialMessage:M,contentBlocks:k,tools:n,agentId:a.agentId,usage:I,stopReason:N,maxTokens:T}))yield e}catch(e){let t=e instanceof Error?e.message:String(e);c(`[OpenAI] Error: ${t}`,{level:`error`}),yield C({content:`API Error: ${t}`,apiError:`api_error`,error:e instanceof Error?e:Error(String(e))})}}e((()=>{le(),W(),I(),T(),be(),p(),D(),j(),l(),x(),a(),Ce(),m(),k(),s(),v(),M()}))();export{De as queryModelOpenAI};
|
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./chunk-DR8-3Aex.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,_,v,y,ee,b,te,x,S,ne,re,C=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 _(t,a,r,i):t===409?new v(t,a,r,i):t===422?new y(t,a,r,i):t===429?new ee(t,a,r,i):t>=500?new b(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{},_=class extends u{},v=class extends u{},y=class extends u{},ee=class extends u{},b=class extends u{},te=class extends l{constructor(){super(`Could not parse response content as the length limit was reached`)}},x=class extends l{constructor(){super(`Could not parse response content as the request was rejected by the content filter`)}},S=class extends Error{constructor(e){super(e)}},ne=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}},re=class extends l{constructor(e,t,n){super(e),this.provider=t,this.cause=n}}}));function ie(e){return typeof e==`object`?e??{}:{}}function ae(e){if(!e)return!0;for(let t in e)return!1;return!0}function oe(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function se(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var ce,le,w,ue,de,fe,pe=e((()=>{C(),ce=/^[a-z][a-z0-9+.-]*:/i,le=e=>ce.test(e),w=e=>(w=Array.isArray,w(e)),ue=w,de=(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},fe=e=>{try{return JSON.parse(e)}catch{return}}})),me,he=e((()=>{me=e=>new Promise(t=>setTimeout(t,e))})),ge,_e=e((()=>{ge=`6.34.0`}));function ve(){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 ye(){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 be,xe,Se,Ce,we,Te,Ee=e((()=>{_e(),be=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`,xe=()=>{let e=ve();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":ge,"X-Stainless-OS":Ce(Deno.build.os),"X-Stainless-Arch":Se(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":ge,"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":ge,"X-Stainless-OS":Ce(globalThis.process.platform??`unknown`),"X-Stainless-Arch":Se(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=ye();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":ge,"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":ge,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}},Se=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,Ce=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`),Te=()=>we??(we=xe())}));function De(){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 Oe(...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 ke(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return Oe({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function Ae(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 je(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 Me=e((()=>{})),Ne,Pe=e((()=>{Ne=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)})})),Fe,Ie,Le,Re=e((()=>{Fe=`RFC3986`,Ie=e=>String(e),Le={RFC1738:e=>String(e).replace(/%20/g,`+`),RFC3986:Ie}}));function ze(e){return!e||typeof e!=`object`?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function Be(e,t){if(w(e)){let n=[];for(let r=0;r<e.length;r+=1)n.push(t(e[r]));return n}return t(e)}var Ve,T,He,Ue,We=e((()=>{Re(),pe(),Ve=(e,t)=>(Ve=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Ve(e,t)),T=(()=>{let e=[];for(let t=0;t<256;++t)e.push(`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase());return e})(),He=1024,Ue=(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+=He){let t=a.length>=He?a.slice(e,e+He):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]=T[r];continue}if(r<2048){n[n.length]=T[192|r>>6]+T[128|r&63];continue}if(r<55296||r>=57344){n[n.length]=T[224|r>>12]+T[128|r>>6&63]+T[128|r&63];continue}e+=1,r=65536+((r&1023)<<10|t.charCodeAt(e)&1023),n[n.length]=T[240|r>>18]+T[128|r>>12&63]+T[128|r>>6&63]+T[128|r&63]}o+=n.join(``)}return o}}));function Ge(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`symbol`||typeof e==`bigint`}function Ke(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_){let v=e,y=_,ee=0,b=!1;for(;(y=y.get(Qe))!==void 0&&!b;){let t=y.get(e);if(ee+=1,t!==void 0){if(t===ee)throw RangeError(`Cyclic object value`);b=!0}y.get(Qe)===void 0&&(ee=0)}if(typeof l==`function`?v=l(t,v):v instanceof Date?v=f?.(v):n===`comma`&&w(v)&&(v=Be(v,function(e){return e instanceof Date?f?.(e):e})),v===null){if(a)return c&&!h?c(t,E.encoder,g,`key`,p):t;v=``}if(Ge(v)||ze(v)){if(c){let e=h?t:c(t,E.encoder,g,`key`,p);return[m?.(e)+`=`+m?.(c(v,E.encoder,g,`value`,p))]}return[m?.(t)+`=`+m?.(String(v))]}let te=[];if(v===void 0)return te;let x;if(n===`comma`&&w(v))h&&c&&(v=Be(v,c)),x=[{value:v.length>0?v.join(`,`)||null:void 0}];else if(w(l))x=l;else{let e=Object.keys(v);x=u?e.sort(u):e}let S=s?String(t).replace(/\./g,`%2E`):String(t),ne=r&&w(v)&&v.length===1?S+`[]`:S;if(i&&w(v)&&v.length===0)return ne+`[]`;for(let t=0;t<x.length;++t){let y=x[t],b=typeof y==`object`&&y.value!==void 0?y.value:v[y];if(o&&b===null)continue;let S=d&&s?y.replace(/\./g,`%2E`):y,re=w(v)?typeof n==`function`?n(ne,S):ne:ne+(d?`.`+S:`[`+S+`]`);_.set(e,ee);let C=new WeakMap;C.set(Qe,_),Xe(te,Ke(b,re,n,r,i,a,o,s,n===`comma`&&h&&w(v)?null:c,l,u,d,f,p,m,h,g,C))}return te}function qe(e=E){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||E.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=Fe;if(e.format!==void 0){if(!Ve(Le,e.format))throw TypeError(`Unknown format option provided.`);n=e.format}let r=Le[n],i=E.filter;(typeof e.filter==`function`||w(e.filter))&&(i=e.filter);let a;if(a=e.arrayFormat&&e.arrayFormat in Ye?e.arrayFormat:`indices`in e?e.indices?`indices`:`repeat`:E.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:E.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix==`boolean`?e.addQueryPrefix:E.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays==`boolean`?!!e.allowEmptyArrays:E.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel==`boolean`?e.charsetSentinel:E.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:e.delimiter===void 0?E.delimiter:e.delimiter,encode:typeof e.encode==`boolean`?e.encode:E.encode,encodeDotInKeys:typeof e.encodeDotInKeys==`boolean`?e.encodeDotInKeys:E.encodeDotInKeys,encoder:typeof e.encoder==`function`?e.encoder:E.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==`boolean`?e.encodeValuesOnly:E.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:typeof e.serializeDate==`function`?e.serializeDate:E.serializeDate,skipNulls:typeof e.skipNulls==`boolean`?e.skipNulls:E.skipNulls,sort:typeof e.sort==`function`?e.sort:null,strictNullHandling:typeof e.strictNullHandling==`boolean`?e.strictNullHandling:E.strictNullHandling}}function Je(e,t={}){let n=e,r=qe(t),i,a;typeof r.filter==`function`?(a=r.filter,n=a(``,n)):w(r.filter)&&(a=r.filter,i=a);let o=[];if(typeof n!=`object`||!n)return``;let s=Ye[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||Xe(o,Ke(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 Ye,Xe,Ze,E,Qe,$e=e((()=>{We(),Re(),pe(),Ye={brackets(e){return String(e)+`[]`},comma:`comma`,indices(e,t){return String(e)+`[`+t+`]`},repeat(e){return String(e)}},Xe=function(e,t){Array.prototype.push.apply(e,w(t)?t:[t])},E={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:`indices`,charset:`utf-8`,charsetSentinel:!1,delimiter:`&`,encode:!0,encodeDotInKeys:!1,encoder:Ue,encodeValuesOnly:!1,format:Fe,formatter:Ie,indices:!1,serializeDate(e){return(Ze??(Ze=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1},Qe={}}));function et(e){return Je(e,{arrayFormat:`brackets`})}var tt=e((()=>{$e()}));function nt(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 rt(e){let t;return(at??(t=new globalThis.TextEncoder,at=t.encode.bind(t)))(e)}function it(e){let t;return(ot??(t=new globalThis.TextDecoder,ot=t.decode.bind(t)))(e)}var at,ot,st=e((()=>{}));function ct(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 lt(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 D,O,ut,dt=e((()=>{r(),st(),ut=class{constructor(){D.set(this,void 0),O.set(this,void 0),t(this,D,new Uint8Array,`f`),t(this,O,null,`f`)}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==`string`?rt(e):e;t(this,D,nt([n(this,D,`f`),r]),`f`);let i=[],a;for(;(a=ct(n(this,D,`f`),n(this,O,`f`)))!=null;){if(a.carriage&&n(this,O,`f`)==null){t(this,O,a.index,`f`);continue}if(n(this,O,`f`)!=null&&(a.index!==n(this,O,`f`)+1||a.carriage)){i.push(it(n(this,D,`f`).subarray(0,n(this,O,`f`)-1))),t(this,D,n(this,D,`f`).subarray(n(this,O,`f`)),`f`),t(this,O,null,`f`);continue}let e=n(this,O,`f`)===null?a.preceding:a.preceding-1,r=it(n(this,D,`f`).subarray(0,e));i.push(r),t(this,D,n(this,D,`f`).subarray(a.index),`f`),t(this,O,null,`f`)}return i}flush(){return n(this,D,`f`).length?this.decode(`
|
|
2
|
-
`):[]}},D=new WeakMap,O=new WeakMap,ut.NEWLINE_CHARS=new Set([`
|
|
3
|
-
`,`\r`]),ut.NEWLINE_REGEXP=/\r\n|[\n\r]/g}));function ft(){}function pt(e,t,n){return!t||mt[e]>mt[n]?ft:t[e].bind(t)}function k(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return gt;let r=_t.get(t);if(r&&r[0]===n)return r[1];let i={error:pt(`error`,t,n),warn:pt(`warn`,t,n),info:pt(`info`,t,n),debug:pt(`debug`,t,n)};return _t.set(t,[n,i]),i}var mt,ht,gt,_t,A,vt=e((()=>{pe(),mt={off:0,error:200,warn:300,info:400,debug:500},ht=(e,t,n)=>{if(e){if(oe(mt,e))return e;k(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(mt))}`)}},gt={error:ft,warn:ft,info:ft,debug:ft},_t=new WeakMap,A=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()===`cookie`||e.toLowerCase()===`set-cookie`?`***`:t]))),`retryOfRequestLogID`in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e)}));async function*yt(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 wt,r=new ut,i=Ae(e.body);for await(let e of bt(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*bt(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`?rt(n):n,r=new Uint8Array(t.length+e.length);r.set(t),r.set(e,t.length),t=r;let i;for(;(i=lt(t))!==-1;)yield t.slice(0,i),t=t.slice(i)}t.length>0&&(yield t)}function xt(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.substring(0,n),t,e.substring(n+t.length)]}var St,Ct,wt,Tt=e((()=>{r(),C(),Me(),dt(),c(),st(),vt(),Ct=class e{constructor(e,n,r){this.iterator=e,St.set(this,void 0),this.controller=n,t(this,St,r,`f`)}static fromSSEResponse(t,n,r,i){let a=!1,s=r?k(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 yt(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 ut,n=Ae(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)}[(St=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,St,`f`)),new e(()=>a(r),this.controller,n(this,St,`f`))]}toReadableStream(){let e=this,t;return Oe({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=rt(JSON.stringify(n)+`
|
|
4
|
-
`);e.enqueue(i)}catch(t){e.error(t)}},async cancel(){await t.return?.()}})}},wt=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]=xt(e,`:`);return r.startsWith(` `)&&(r=r.substring(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}}}));async function Et(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(t.options.stream)return k(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):Ct.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:Dt(await n.json(),n):await n.text()})();return k(e).debug(`[${r}] response parsed`,A({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}function Dt(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 Ot=e((()=>{Tt(),vt()})),kt,At,jt=e((()=>{r(),Ot(),At=class e extends Promise{constructor(e,n,r=Et){super(e=>{e(null)}),this.responsePromise=n,this.parseResponse=r,kt.set(this,void 0),t(this,kt,e,`f`)}_thenUnwrap(t){return new e(n(this,kt,`f`),this.responsePromise,async(e,n)=>Dt(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,kt,`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)}},kt=new WeakMap})),Mt,Nt,Pt,Ft,j,It,M=e((()=>{r(),C(),Ot(),jt(),pe(),Nt=class{constructor(e,n,r,i){Mt.set(this,void 0),t(this,Mt,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,Mt,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Mt=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Pt=class extends At{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await Et(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},Ft=class extends Nt{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}},j=class extends Nt{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?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...ie(this.options.query),after:t}}:null}},It=class extends Nt{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?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...ie(this.options.query),after:e}}:null}}})),Lt,Rt,zt,Bt=e((()=>{Me(),C(),Lt={jwt:`urn:ietf:params:oauth:token-type:jwt`,id:`urn:ietf:params:oauth:token-type:id_token`},Rt=`urn:ietf:params:oauth:grant-type:token-exchange`,zt=class{constructor(e,t){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl=`https://auth.openai.com/oauth/token`,this.config=e,this.fetch=t??De()}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=await this.fetch(this.tokenExchangeUrl,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({grant_type:Rt,client_id:this.config.clientId,subject_token:e,subject_token_type:Lt[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId})});if(!t.ok){let e=await t.text(),n;try{n=JSON.parse(e)}catch{}throw t.status===400||t.status===401||t.status===403?new ne(t.status,n,t.headers):u.generate(t.status,n,`Token exchange failed with status ${t.status}`,t.headers)}let n=await t.json(),r=n.expires_in||3600,i=Date.now()+r*1e3;return this.cachedToken={token:n.access_token,expiresAt:i},n.access_token}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 Vt(e,t,n){return Wt(),new File(e,t??`unknown_file`,n)}function Ht(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 Ut(e){let t=typeof e==`function`?e:e.fetch,n=qt.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 qt.set(t,r),r}var Wt,Gt,Kt,N,qt,Jt,Yt,Xt,Zt,Qt,P=e((()=>{Me(),Wt=()=>{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`.":``))}},Gt=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,Kt=async(e,t)=>Zt(e.body)?{...e,body:await Jt(e.body,t)}:e,N=async(e,t)=>({...e,body:await Jt(e.body,t)}),qt=new WeakMap,Jt=async(e,t)=>{if(!await Ut(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])=>Qt(n,e,t))),n},Yt=e=>e instanceof Blob&&`name`in e,Xt=e=>typeof e==`object`&&!!e&&(e instanceof Response||Gt(e)||Yt(e)),Zt=e=>{if(Xt(e))return!0;if(Array.isArray(e))return e.some(Zt);if(e&&typeof e==`object`){for(let t in e)if(Zt(e[t]))return!0}return!1},Qt=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,Vt([await n.blob()],Ht(n)));else if(Gt(n))e.append(t,Vt([await new Response(ke(n)).blob()],Ht(n)));else if(Yt(n))e.append(t,n,Ht(n));else if(Array.isArray(n))await Promise.all(n.map(n=>Qt(e,t+`[]`,n)));else if(typeof n==`object`)await Promise.all(Object.entries(n).map(([n,r])=>Qt(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 $t(e,t,n){if(Wt(),e=await e,rn(e))return e instanceof File?e:Vt([await e.arrayBuffer()],e.name);if(an(e)){let r=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),Vt(await en(r),t,n)}let r=await en(e);if(t||(t=Ht(e)),!n?.type){let e=r.find(e=>typeof e==`object`&&`type`in e&&e.type);typeof e==`string`&&(n={...n,type:e})}return Vt(r,t,n)}async function en(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(nn(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(Gt(e))for await(let n of e)t.push(...await en(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${tn(e)}`)}return t}function tn(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var nn,rn,an,on=e((()=>{P(),nn=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`,rn=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&nn(e),an=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`})),sn=e((()=>{on()})),F,I=e((()=>{F=class{constructor(e){this._client=e}}}));function cn(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var ln,un,L,R=e((()=>{C(),ln=Object.freeze(Object.create(null)),un=(e=cn)=>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??ln)??ln)?.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},L=un(cn)})),dn,fn=e((()=>{I(),M(),R(),dn=class extends F{list(e,t={},n){return this._client.getAPIList(L`/chat/completions/${e}/messages`,j,{query:t,...n})}}})),z=e((()=>{C()}));function pn(e){return e!==void 0&&`function`in e&&e.function!==void 0}function mn(e){return e?.$brand===`auto-parseable-response-format`}function hn(e){return e?.$brand===`auto-parseable-tool`}function gn(e,t){return!t||!xn(t)?{...e,choices:e.choices.map(e=>(Sn(e.message.tool_calls),{...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}}))}:_n(e,t)}function _n(e,t){let n=e.choices.map(e=>{if(e.finish_reason===`length`)throw new te;if(e.finish_reason===`content_filter`)throw new x;return Sn(e.message.tool_calls),{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map(e=>yn(t,e))??void 0}:void 0,parsed:e.message.content&&!e.message.refusal?vn(t,e.message.content):null}}});return{...e,choices:n}}function vn(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 yn(e,t){let n=e.tools?.find(e=>pn(e)&&e.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:hn(n)?n.$parseRaw(t.function.arguments):n?.function.strict?JSON.parse(t.function.arguments):null}}}function bn(e,t){if(!e||!(`tools`in e)||!e.tools)return!1;let n=e.tools?.find(e=>pn(e)&&e.function?.name===t.function.name);return pn(n)&&(hn(n)||n?.function.strict||!1)}function xn(e){return mn(e.response_format)?!0:e.tools?.some(e=>hn(e)||e.type===`function`&&e.function.strict===!0)??!1}function Sn(e){for(let t of e||[])if(t.type!==`function`)throw new l(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}function Cn(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 wn=e((()=>{z()})),Tn,En,Dn=e((()=>{Tn=e=>e?.role===`assistant`,En=e=>e?.role===`tool`})),On,kn,An,jn,Mn,Nn,Pn,B,Fn,In,Ln,Rn,zn,Bn,Vn=e((()=>{r(),z(),Bn=class{constructor(){On.add(this),this.controller=new AbortController,kn.set(this,void 0),An.set(this,()=>{}),jn.set(this,()=>{}),Mn.set(this,void 0),Nn.set(this,()=>{}),Pn.set(this,()=>{}),B.set(this,{}),Fn.set(this,!1),In.set(this,!1),Ln.set(this,!1),Rn.set(this,!1),t(this,kn,new Promise((e,n)=>{t(this,An,e,`f`),t(this,jn,n,`f`)}),`f`),t(this,Mn,new Promise((e,n)=>{t(this,Nn,e,`f`),t(this,Pn,n,`f`)}),`f`),n(this,kn,`f`).catch(()=>{}),n(this,Mn,`f`).catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit(`end`)},n(this,On,`m`,zn).bind(this))},0)}_connected(){this.ended||(n(this,An,`f`).call(this),this._emit(`connect`))}get ended(){return n(this,Fn,`f`)}get errored(){return n(this,In,`f`)}get aborted(){return n(this,Ln,`f`)}abort(){this.controller.abort()}on(e,t){return(n(this,B,`f`)[e]||(n(this,B,`f`)[e]=[])).push({listener:t}),this}off(e,t){let r=n(this,B,`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,B,`f`)[e]||(n(this,B,`f`)[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((n,r)=>{t(this,Rn,!0,`f`),e!==`error`&&this.once(`error`,r),this.once(e,n)})}async done(){t(this,Rn,!0,`f`),await n(this,Mn,`f`)}_emit(e,...r){if(n(this,Fn,`f`))return;e===`end`&&(t(this,Fn,!0,`f`),n(this,Nn,`f`).call(this));let i=n(this,B,`f`)[e];if(i&&(n(this,B,`f`)[e]=i.filter(e=>!e.once),i.forEach(({listener:e})=>e(...r))),e===`abort`){let e=r[0];!n(this,Rn,`f`)&&!i?.length&&Promise.reject(e),n(this,jn,`f`).call(this,e),n(this,Pn,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=r[0];!n(this,Rn,`f`)&&!i?.length&&Promise.reject(e),n(this,jn,`f`).call(this,e),n(this,Pn,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){}},kn=new WeakMap,An=new WeakMap,jn=new WeakMap,Mn=new WeakMap,Nn=new WeakMap,Pn=new WeakMap,B=new WeakMap,Fn=new WeakMap,In=new WeakMap,Ln=new WeakMap,Rn=new WeakMap,On=new WeakSet,zn=function(e){if(t(this,In,!0,`f`),e instanceof Error&&e.name===`AbortError`&&(e=new d),e instanceof d)return t(this,Ln,!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 Hn(e){return typeof e.parse==`function`}var Un=e((()=>{})),V,Wn,Gn,Kn,qn,Jn,Yn,Xn,Zn,Qn,$n=e((()=>{r(),z(),wn(),Dn(),Vn(),Un(),Zn=10,Qn=class extends Bn{constructor(){super(...arguments),V.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(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),En(e)&&e.content)this._emit(`functionToolCallResult`,e.content);else if(Tn(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,V,`m`,Wn).call(this)}async finalMessage(){return await this.done(),n(this,V,`m`,Gn).call(this)}async finalFunctionToolCall(){return await this.done(),n(this,V,`m`,Kn).call(this)}async finalFunctionToolCallResult(){return await this.done(),n(this,V,`m`,qn).call(this)}async totalUsage(){return await this.done(),n(this,V,`m`,Jn).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit(`finalChatCompletion`,e);let t=n(this,V,`m`,Gn).call(this);t&&this._emit(`finalMessage`,t);let r=n(this,V,`m`,Wn).call(this);r&&this._emit(`finalContent`,r);let i=n(this,V,`m`,Kn).call(this);i&&this._emit(`finalFunctionToolCall`,i);let a=n(this,V,`m`,qn).call(this);a!=null&&this._emit(`finalFunctionToolCallResult`,a),this._chatCompletions.some(e=>e.usage)&&this._emit(`totalUsage`,n(this,V,`m`,Jn).call(this))}async _createChatCompletion(e,t,r){let i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener(`abort`,()=>this.controller.abort())),n(this,V,`m`,Yn).call(this,t);let a=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(_n(a,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){let i=`tool`,{tool_choice:a=`auto`,stream:o,...s}=t,c=typeof a!=`string`&&a.type===`function`&&a?.function?.name,{maxChatCompletions:u=Zn}=r||{},d=t.tools.map(e=>{if(hn(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}),f={};for(let e of d)e.type===`function`&&(f[e.function.name||e.function.function.name]=e.function);let p=`tools`in t?d.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);for(let t=0;t<u;++t){let t=(await this._createChatCompletion(e,{...s,tool_choice:a,tools:p,messages:[...this.messages]},r)).choices[0]?.message;if(!t)throw new l(`missing message in ChatCompletion response`);if(!t.tool_calls?.length)return;for(let e of t.tool_calls){if(e.type!==`function`)continue;let t=e.id,{name:r,arguments:a}=e.function,o=f[r];if(!o){let e=`Invalid tool_call: ${JSON.stringify(r)}. Available options are: ${Object.keys(f).map(e=>JSON.stringify(e)).join(`, `)}. Please try again`;this._addMessage({role:i,tool_call_id:t,content:e});continue}else if(c&&c!==r){let e=`Invalid tool_call: ${JSON.stringify(r)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:i,tool_call_id:t,content:e});continue}let s;try{s=Hn(o)?await o.parse(a):a}catch(e){let n=e instanceof Error?e.message:String(e);this._addMessage({role:i,tool_call_id:t,content:n});continue}let l=await o.function(s,this),u=n(this,V,`m`,Xn).call(this,l);if(this._addMessage({role:i,tool_call_id:t,content:u}),c)return}}}},V=new WeakSet,Wn=function(){return n(this,V,`m`,Gn).call(this).content??null},Gn=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(Tn(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new l(`stream ended without producing a ChatCompletionMessage with role=assistant`)},Kn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Tn(t)&&t?.tool_calls?.length)return t.tool_calls.filter(e=>e.type===`function`).at(-1)?.function}},qn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(En(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}},Jn=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},Yn=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.`)},Xn=function(e){return typeof e==`string`?e:e===void 0?`undefined`:JSON.stringify(e)}})),er,tr=e((()=>{$n(),Dn(),er=class e extends Qn{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,a)),i}_addMessage(e,t=!0){super._addMessage(e,t),Tn(e)&&e.content&&this._emit(`content`,e.content)}}}));function nr(e,t=H.ALL){if(typeof e!=`string`)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return vr(e.trim(),t)}var rr,ir,ar,or,sr,cr,lr,ur,dr,fr,pr,mr,hr,H,gr,_r,vr,yr,br=e((()=>{rr=1,ir=2,ar=4,or=8,sr=16,cr=32,lr=64,ur=128,dr=256,fr=ur|dr,pr=496,mr=ir|497,hr=ar|or,H={STR:rr,NUM:ir,ARR:ar,OBJ:or,NULL:sr,BOOL:cr,NAN:lr,INFINITY:ur,MINUS_INFINITY:dr,INF:fr,SPECIAL:pr,ATOM:mr,COLLECTION:hr,ALL:mr|hr},gr=class extends Error{},_r=class extends Error{},vr=(e,t)=>{let n=e.length,r=0,i=e=>{throw new gr(`${e} at position ${r}`)},a=e=>{throw new _r(`${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`||H.NULL&t&&n-r<4&&`null`.startsWith(e.substring(r))?(r+=4,null):e.substring(r,r+4)===`true`||H.BOOL&t&&n-r<4&&`true`.startsWith(e.substring(r))?(r+=4,!0):e.substring(r,r+5)===`false`||H.BOOL&t&&n-r<5&&`false`.startsWith(e.substring(r))?(r+=5,!1):e.substring(r,r+8)===`Infinity`||H.INFINITY&t&&n-r<8&&`Infinity`.startsWith(e.substring(r))?(r+=8,1/0):e.substring(r,r+9)===`-Infinity`||H.MINUS_INFINITY&t&&1<n-r&&n-r<9&&`-Infinity`.startsWith(e.substring(r))?(r+=9,-1/0):e.substring(r,r+3)===`NaN`||H.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:!1,r++;if(e.charAt(r)==`"`)try{return JSON.parse(e.substring(o,++r-Number(s)))}catch(e){a(String(e))}else if(H.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&&H.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(H.OBJ&t)return a;throw e}d(),e[r]===`,`&&r++}}catch{if(H.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(H.ARR&t)return n;i(`Expected ']' at end of array`)}return r++,n},u=()=>{if(r===0){e===`-`&&H.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e)}catch(n){if(H.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&&!(H.NUM&t)&&i(`Unterminated number literal`);try{return JSON.parse(e.substring(o,r))}catch{e.substring(o,r)===`-`&&H.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()},yr=e=>nr(e,H.ALL^H.NUM)})),xr=e((()=>{Tt()}));function Sr(e,t){let{id:n,choices:r,created:i,model:a,system_fingerprint:o,...s}=e;return gn({...s,id:n,choices:r.map(({message:t,finish_reason:n,index:r,logprobs:i,...a})=>{if(!n)throw new l(`missing finish_reason for choice ${r}`);let{content:o=null,function_call:s,tool_calls:c,...u}=t,d=t.role;if(!d)throw new l(`missing role for choice ${r}`);if(s){let{arguments:e,name:c}=s;if(e==null)throw new l(`missing function_call.arguments for choice ${r}`);if(!c)throw new l(`missing function_call.name for choice ${r}`);return{...a,message:{content:o,function_call:{arguments:e,name:c},role:d,refusal:t.refusal??null},finish_reason:n,index:r,logprobs:i}}return c?{...a,index:r,finish_reason:n,logprobs:i,message:{...u,role:d,content:o,refusal:t.refusal??null,tool_calls:c.map((t,n)=>{let{function:i,type:a,id:o,...s}=t,{arguments:c,name:u,...d}=i||{};if(o==null)throw new l(`missing choices[${r}].tool_calls[${n}].id\n${Cr(e)}`);if(a==null)throw new l(`missing choices[${r}].tool_calls[${n}].type\n${Cr(e)}`);if(u==null)throw new l(`missing choices[${r}].tool_calls[${n}].function.name\n${Cr(e)}`);if(c==null)throw new l(`missing choices[${r}].tool_calls[${n}].function.arguments\n${Cr(e)}`);return{...s,id:o,type:a,function:{...d,name:u,arguments:c}}})}}:{...a,message:{...u,content:o,role:d,refusal:t.refusal??null},finish_reason:n,index:r,logprobs:i}}),created:i,model:a,object:`chat.completion`,...o?{system_fingerprint:o}:{}},t)}function Cr(e){return JSON.stringify(e)}var U,W,wr,G,Tr,Er,Dr,Or,kr,Ar,jr,Mr,Nr,Pr=e((()=>{r(),br(),z(),wn(),xr(),$n(),Nr=class e extends Qn{constructor(e){super(),U.add(this),W.set(this,void 0),wr.set(this,void 0),G.set(this,void 0),t(this,W,e,`f`),t(this,wr,[],`f`)}get currentChatCompletionSnapshot(){return n(this,G,`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;let i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener(`abort`,()=>this.controller.abort())),n(this,U,`m`,Tr).call(this);let a=await e.chat.completions.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let e of a)n(this,U,`m`,Dr).call(this,e);if(a.controller.signal?.aborted)throw new d;return this._addChatCompletion(n(this,U,`m`,Ar).call(this))}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener(`abort`,()=>this.controller.abort())),n(this,U,`m`,Tr).call(this),this._connected();let i=Ct.fromReadableStream(e,this.controller),a;for await(let e of i)a&&a!==e.id&&this._addChatCompletion(n(this,U,`m`,Ar).call(this)),n(this,U,`m`,Dr).call(this,e),a=e.id;if(i.controller.signal?.aborted)throw new d;return this._addChatCompletion(n(this,U,`m`,Ar).call(this))}[(W=new WeakMap,wr=new WeakMap,G=new WeakMap,U=new WeakSet,Tr=function(){this.ended||t(this,G,void 0,`f`)},Er=function(e){let t=n(this,wr,`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,wr,`f`)[e.index]=t,t)},Dr=function(e){if(this.ended)return;let t=n(this,U,`m`,Mr).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,U,`m`,Er).call(this,e);e.finish_reason&&(n(this,U,`m`,kr).call(this,e),i.current_tool_call_index!=null&&n(this,U,`m`,Or).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,U,`m`,kr).call(this,e),i.current_tool_call_index!=null&&n(this,U,`m`,Or).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)}}},Or=function(e,t){if(n(this,U,`m`,Er).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,W,`f`)?.tools?.find(e=>pn(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:hn(e)?e.$parseRaw(r.function.arguments):e?.function.strict?JSON.parse(r.function.arguments):null})}else r.type},kr=function(e){let t=n(this,U,`m`,Er).call(this,e);if(e.message.content&&!t.content_done){t.content_done=!0;let r=n(this,U,`m`,jr).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}))},Ar=function(){if(this.ended)throw new l(`stream has ended, this shouldn't happen`);let e=n(this,G,`f`);if(!e)throw new l(`request ended without sending any chunks`);return t(this,G,void 0,`f`),t(this,wr,[],`f`),Sr(e,n(this,W,`f`))},jr=function(){let e=n(this,W,`f`)?.response_format;return mn(e)?e:null},Mr=function(e){var r,i,a,o;let s=n(this,G,`f`),{choices:c,...l}=e;s?Object.assign(s,l):s=t(this,G,{...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,W,`f`)&&xn(n(this,W,`f`)))){if(c===`length`)throw new te;if(c===`content_filter`)throw new x}if(Object.assign(e,d),!t)continue;let{content:f,refusal:p,function_call:m,role:h,tool_calls:g,..._}=t;if(Object.assign(e.message,_),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,U,`m`,jr).call(this)&&(e.message.parsed=yr(e.message.content))),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,bn(n(this,W,`f`),c)&&(c.function.parsed_arguments=yr(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 Ct(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}})),Fr,Ir=e((()=>{Pr(),Fr=class e extends Nr{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,a)),i}}})),Lr,Rr=e((()=>{I(),fn(),M(),R(),tr(),Ir(),Pr(),wn(),Un(),Lr=class extends F{constructor(){super(...arguments),this.messages=new dn(this._client)}create(e,t){return this._client.post(`/chat/completions`,{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(L`/chat/completions/${e}`,t)}update(e,t,n){return this._client.post(L`/chat/completions/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList(`/chat/completions`,j,{query:e,...t})}delete(e,t){return this._client.delete(L`/chat/completions/${e}`,t)}parse(e,t){return Cn(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":`chat.completions.parse`}})._thenUnwrap(t=>_n(t,e))}runTools(e,t){return e.stream?Fr.runTools(this._client,e,t):er.runTools(this._client,e,t)}stream(e,t){return Nr.createChatCompletion(this._client,e,t)}},Lr.Messages=dn})),zr,Br=e((()=>{I(),Rr(),zr=class extends F{constructor(){super(...arguments),this.completions=new Lr(this._client)}},zr.Completions=Lr})),Vr=e((()=>{Rr(),Rr(),fn()})),Hr=e((()=>{Br(),Vr()})),Ur=e((()=>{}));function*Wr(e){if(!e)return;if(Gr 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():ue(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=ue(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 Gr,K,q=e((()=>{pe(),Gr=Symbol(`brand.privateNullableHeaders`),K=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of Wr(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{[Gr]:!0,values:t,nulls:n}}})),Kr,qr=e((()=>{I(),q(),Kr=class extends F{create(e,t){return this._client.post(`/audio/speech`,{body:e,...t,headers:K([{Accept:`application/octet-stream`},t?.headers]),__binaryResponse:!0})}}})),Jr,Yr=e((()=>{I(),P(),Jr=class extends F{create(e,t){return this._client.post(`/audio/transcriptions`,N({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}})),Xr,Zr=e((()=>{I(),P(),Xr=class extends F{create(e,t){return this._client.post(`/audio/translations`,N({body:e,...t,__metadata:{model:e.model}},this._client))}}})),Qr,$r=e((()=>{I(),qr(),Yr(),Zr(),Qr=class extends F{constructor(){super(...arguments),this.transcriptions=new Jr(this._client),this.translations=new Xr(this._client),this.speech=new Kr(this._client)}},Qr.Transcriptions=Jr,Qr.Translations=Xr,Qr.Speech=Kr})),ei,ti=e((()=>{I(),M(),R(),ei=class extends F{create(e,t){return this._client.post(`/batches`,{body:e,...t})}retrieve(e,t){return this._client.get(L`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList(`/batches`,j,{query:e,...t})}cancel(e,t){return this._client.post(L`/batches/${e}/cancel`,t)}}})),ni,ri=e((()=>{I(),M(),q(),R(),ni=class extends F{create(e,t){return this._client.post(`/assistants`,{body:e,...t,headers:K([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}retrieve(e,t){return this._client.get(L`/assistants/${e}`,{...t,headers:K([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}update(e,t,n){return this._client.post(L`/assistants/${e}`,{body:t,...n,headers:K([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e={},t){return this._client.getAPIList(`/assistants`,j,{query:e,...t,headers:K([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}delete(e,t){return this._client.delete(L`/assistants/${e}`,{...t,headers:K([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}}})),ii,ai=e((()=>{I(),q(),ii=class extends F{create(e,t){return this._client.post(`/realtime/sessions`,{body:e,...t,headers:K([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}}})),oi,si=e((()=>{I(),q(),oi=class extends F{create(e,t){return this._client.post(`/realtime/transcription_sessions`,{body:e,...t,headers:K([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}}})),ci,li=e((()=>{I(),ai(),si(),ci=class extends F{constructor(){super(...arguments),this.sessions=new ii(this._client),this.transcriptionSessions=new oi(this._client)}},ci.Sessions=ii,ci.TranscriptionSessions=oi})),ui,di=e((()=>{I(),q(),R(),ui=class extends F{create(e,t){return this._client.post(`/chatkit/sessions`,{body:e,...t,headers:K([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}cancel(e,t){return this._client.post(L`/chatkit/sessions/${e}/cancel`,{...t,headers:K([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}}})),fi,pi=e((()=>{I(),M(),q(),R(),fi=class extends F{retrieve(e,t){return this._client.get(L`/chatkit/threads/${e}`,{...t,headers:K([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}list(e={},t){return this._client.getAPIList(`/chatkit/threads`,It,{query:e,...t,headers:K([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}delete(e,t){return this._client.delete(L`/chatkit/threads/${e}`,{...t,headers:K([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}listItems(e,t={},n){return this._client.getAPIList(L`/chatkit/threads/${e}/items`,It,{query:t,...n,headers:K([{"OpenAI-Beta":`chatkit_beta=v1`},n?.headers])})}}})),mi,hi=e((()=>{I(),di(),pi(),mi=class extends F{constructor(){super(...arguments),this.sessions=new ui(this._client),this.threads=new fi(this._client)}},mi.Sessions=ui,mi.Threads=fi})),gi,_i=e((()=>{I(),M(),q(),R(),gi=class extends F{create(e,t,n){return this._client.post(L`/threads/${e}/messages`,{body:t,...n,headers:K([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(L`/threads/${r}/messages/${e}`,{...n,headers:K([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(L`/threads/${r}/messages/${e}`,{body:i,...n,headers:K([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e,t={},n){return this._client.getAPIList(L`/threads/${e}/messages`,j,{query:t,...n,headers:K([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}delete(e,t,n){let{thread_id:r}=t;return this._client.delete(L`/threads/${r}/messages/${e}`,{...n,headers:K([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}}})),vi,yi=e((()=>{I(),M(),q(),R(),vi=class extends F{retrieve(e,t,n){let{thread_id:r,run_id:i,...a}=t;return this._client.get(L`/threads/${r}/runs/${i}/steps/${e}`,{query:a,...n,headers:K([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e,t,n){let{thread_id:r,...i}=t;return this._client.getAPIList(L`/threads/${r}/runs/${e}/steps`,j,{query:i,...n,headers:K([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}}})),bi,xi=e((()=>{bi=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))}}})),Si,Ci=e((()=>{Si=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()}})),wi=e((()=>{pe(),xi(),Ci(),vt(),a(),he(),tt()})),J,Ti,Ei,Y,Di,X,Oi,ki,Ai,ji,Z,Mi,Ni,Pi,Fi,Ii,Li,Ri,zi,Bi,Vi,Hi,Ui,Wi,Gi=e((()=>{r(),xr(),z(),Vn(),wi(),Wi=class extends Bn{constructor(){super(...arguments),J.add(this),Ei.set(this,[]),Y.set(this,{}),Di.set(this,{}),X.set(this,void 0),Oi.set(this,void 0),ki.set(this,void 0),Ai.set(this,void 0),ji.set(this,void 0),Z.set(this,void 0),Mi.set(this,void 0),Ni.set(this,void 0),Pi.set(this,void 0)}[(Ei=new WeakMap,Y=new WeakMap,Di=new WeakMap,X=new WeakMap,Oi=new WeakMap,ki=new WeakMap,Ai=new WeakMap,ji=new WeakMap,Z=new WeakMap,Mi=new WeakMap,Ni=new WeakMap,Pi=new WeakMap,J=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 Ti;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener(`abort`,()=>this.controller.abort())),this._connected();let i=Ct.fromReadableStream(e,this.controller);for await(let e of i)n(this,J,`m`,Fi).call(this,e);if(i.controller.signal?.aborted)throw new d;return this._addRun(n(this,J,`m`,Ii).call(this))}toReadableStream(){return new Ct(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,r){let i=new Ti;return i._run(()=>i._runToolAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createToolAssistantStream(e,t,r,i){let a=i?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener(`abort`,()=>this.controller.abort()));let o={...r,stream:!0},s=await e.submitToolOutputs(t,o,{...i,signal:this.controller.signal});this._connected();for await(let e of s)n(this,J,`m`,Fi).call(this,e);if(s.controller.signal?.aborted)throw new d;return this._addRun(n(this,J,`m`,Ii).call(this))}static createThreadAssistantStream(e,t,n){let r=new Ti;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 Ti;return i._run(()=>i._runAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}currentEvent(){return n(this,Mi,`f`)}currentRun(){return n(this,Ni,`f`)}currentMessageSnapshot(){return n(this,X,`f`)}currentRunStepSnapshot(){return n(this,Pi,`f`)}async finalRunSteps(){return await this.done(),Object.values(n(this,Y,`f`))}async finalMessages(){return await this.done(),Object.values(n(this,Di,`f`))}async finalRun(){if(await this.done(),!n(this,Oi,`f`))throw Error(`Final run was not received.`);return n(this,Oi,`f`)}async _createThreadAssistantStream(e,t,r){let i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener(`abort`,()=>this.controller.abort()));let a={...t,stream:!0},o=await e.createAndRun(a,{...r,signal:this.controller.signal});this._connected();for await(let e of o)n(this,J,`m`,Fi).call(this,e);if(o.controller.signal?.aborted)throw new d;return this._addRun(n(this,J,`m`,Ii).call(this))}async _createAssistantStream(e,t,r,i){let a=i?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener(`abort`,()=>this.controller.abort()));let o={...r,stream:!0},s=await e.create(t,o,{...i,signal:this.controller.signal});this._connected();for await(let e of s)n(this,J,`m`,Fi).call(this,e);if(s.controller.signal?.aborted)throw new d;return this._addRun(n(this,J,`m`,Ii).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(se(t)&&se(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(!se(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.push(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)}},Ti=Wi,Fi=function(e){if(!this.ended)switch(t(this,Mi,e,`f`),n(this,J,`m`,zi).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,J,`m`,Ui).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,J,`m`,Ri).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,J,`m`,Li).call(this,e);break;case`error`:throw Error(`Encountered an error event in event processing - errors should be processed earlier`);default:}},Ii=function(){if(this.ended)throw new l(`stream has ended, this shouldn't happen`);if(!n(this,Oi,`f`))throw Error(`Final run has not been received`);return n(this,Oi,`f`)},Li=function(e){let[r,i]=n(this,J,`m`,Vi).call(this,e,n(this,X,`f`));t(this,X,r,`f`),n(this,Di,`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,ki,`f`)){if(n(this,Ai,`f`))switch(n(this,Ai,`f`).type){case`text`:this._emit(`textDone`,n(this,Ai,`f`).text,n(this,X,`f`));break;case`image_file`:this._emit(`imageFileDone`,n(this,Ai,`f`).image_file,n(this,X,`f`));break}t(this,ki,i.index,`f`)}t(this,Ai,r.content[i.index],`f`)}break;case`thread.message.completed`:case`thread.message.incomplete`:if(n(this,ki,`f`)!==void 0){let t=e.data.content[n(this,ki,`f`)];if(t)switch(t.type){case`image_file`:this._emit(`imageFileDone`,t.image_file,n(this,X,`f`));break;case`text`:this._emit(`textDone`,t.text,n(this,X,`f`));break}}n(this,X,`f`)&&this._emit(`messageDone`,e.data),t(this,X,void 0,`f`)}},Ri=function(e){let r=n(this,J,`m`,Bi).call(this,e);switch(t(this,Pi,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,ji,`f`)?this._emit(`toolCallDelta`,e,r.step_details.tool_calls[e.index]):(n(this,Z,`f`)&&this._emit(`toolCallDone`,n(this,Z,`f`)),t(this,ji,e.index,`f`),t(this,Z,r.step_details.tool_calls[e.index],`f`),n(this,Z,`f`)&&this._emit(`toolCallCreated`,n(this,Z,`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,Pi,void 0,`f`),e.data.step_details.type==`tool_calls`&&n(this,Z,`f`)&&(this._emit(`toolCallDone`,n(this,Z,`f`)),t(this,Z,void 0,`f`)),this._emit(`runStepDone`,e.data,r);break;case`thread.run.step.in_progress`:break}},zi=function(e){n(this,Ei,`f`).push(e),this._emit(`event`,e)},Bi=function(e){switch(e.event){case`thread.run.step.created`:return n(this,Y,`f`)[e.data.id]=e.data,e.data;case`thread.run.step.delta`:let t=n(this,Y,`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=Ti.accumulateDelta(t,r.delta);n(this,Y,`f`)[e.data.id]=i}return n(this,Y,`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,Y,`f`)[e.data.id]=e.data;break}if(n(this,Y,`f`)[e.data.id])return n(this,Y,`f`)[e.data.id];throw Error(`No snapshot available`)},Vi=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,J,`m`,Hi).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`)},Hi=function(e,t){return Ti.accumulateDelta(t,e)},Ui=function(e){switch(t(this,Ni,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,Oi,e.data,`f`),n(this,Z,`f`)&&(this._emit(`toolCallDone`,n(this,Z,`f`)),t(this,Z,void 0,`f`));break;case`thread.run.cancelling`:break}}})),Ki,qi=e((()=>{I(),yi(),M(),q(),Gi(),he(),R(),Ki=class extends F{constructor(){super(...arguments),this.steps=new vi(this._client)}create(e,t,n){let{include:r,...i}=t;return this._client.post(L`/threads/${e}/runs`,{query:{include:r},body:i,...n,headers:K([{"OpenAI-Beta":`assistants=v2`},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(L`/threads/${r}/runs/${e}`,{...n,headers:K([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(L`/threads/${r}/runs/${e}`,{body:i,...n,headers:K([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e,t={},n){return this._client.getAPIList(L`/threads/${e}/runs`,j,{query:t,...n,headers:K([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}cancel(e,t,n){let{thread_id:r}=t;return this._client.post(L`/threads/${r}/runs/${e}/cancel`,{...n,headers:K([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}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 Wi.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){let r=K([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 me(e);break;case`requires_action`:case`incomplete`:case`cancelled`:case`completed`:case`failed`:case`expired`:return i}}}stream(e,t,n){return Wi.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){let{thread_id:r,...i}=t;return this._client.post(L`/threads/${r}/runs/${e}/submit_tool_outputs`,{body:i,...n,headers:K([{"OpenAI-Beta":`assistants=v2`},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!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 Wi.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}},Ki.Steps=vi})),Ji,Yi=e((()=>{I(),_i(),qi(),q(),Gi(),R(),Ji=class extends F{constructor(){super(...arguments),this.runs=new Ki(this._client),this.messages=new gi(this._client)}create(e={},t){return this._client.post(`/threads`,{body:e,...t,headers:K([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}retrieve(e,t){return this._client.get(L`/threads/${e}`,{...t,headers:K([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}update(e,t,n){return this._client.post(L`/threads/${e}`,{body:t,...n,headers:K([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}delete(e,t){return this._client.delete(L`/threads/${e}`,{...t,headers:K([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}createAndRun(e,t){return this._client.post(`/threads/runs`,{body:e,...t,headers:K([{"OpenAI-Beta":`assistants=v2`},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!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 Wi.createThreadAssistantStream(e,this._client.beta.threads,t)}},Ji.Runs=Ki,Ji.Messages=gi})),Xi,Zi=e((()=>{I(),ri(),li(),hi(),Yi(),Xi=class extends F{constructor(){super(...arguments),this.realtime=new ci(this._client),this.chatkit=new mi(this._client),this.assistants=new ni(this._client),this.threads=new Ji(this._client)}},Xi.Realtime=ci,Xi.ChatKit=mi,Xi.Assistants=ni,Xi.Threads=Ji})),Qi,$i=e((()=>{I(),Qi=class extends F{create(e,t){return this._client.post(`/completions`,{body:e,...t,stream:e.stream??!1})}}})),ea,ta=e((()=>{I(),q(),R(),ea=class extends F{retrieve(e,t,n){let{container_id:r}=t;return this._client.get(L`/containers/${r}/files/${e}/content`,{...n,headers:K([{Accept:`application/binary`},n?.headers]),__binaryResponse:!0})}}})),na,ra=e((()=>{I(),ta(),M(),q(),P(),R(),na=class extends F{constructor(){super(...arguments),this.content=new ea(this._client)}create(e,t,n){return this._client.post(L`/containers/${e}/files`,Kt({body:t,...n},this._client))}retrieve(e,t,n){let{container_id:r}=t;return this._client.get(L`/containers/${r}/files/${e}`,n)}list(e,t={},n){return this._client.getAPIList(L`/containers/${e}/files`,j,{query:t,...n})}delete(e,t,n){let{container_id:r}=t;return this._client.delete(L`/containers/${r}/files/${e}`,{...n,headers:K([{Accept:`*/*`},n?.headers])})}},na.Content=ea})),ia,aa=e((()=>{I(),ra(),M(),q(),R(),ia=class extends F{constructor(){super(...arguments),this.files=new na(this._client)}create(e,t){return this._client.post(`/containers`,{body:e,...t})}retrieve(e,t){return this._client.get(L`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList(`/containers`,j,{query:e,...t})}delete(e,t){return this._client.delete(L`/containers/${e}`,{...t,headers:K([{Accept:`*/*`},t?.headers])})}},ia.Files=na})),oa,sa=e((()=>{I(),M(),R(),oa=class extends F{create(e,t,n){let{include:r,...i}=t;return this._client.post(L`/conversations/${e}/items`,{query:{include:r},body:i,...n})}retrieve(e,t,n){let{conversation_id:r,...i}=t;return this._client.get(L`/conversations/${r}/items/${e}`,{query:i,...n})}list(e,t={},n){return this._client.getAPIList(L`/conversations/${e}/items`,It,{query:t,...n})}delete(e,t,n){let{conversation_id:r}=t;return this._client.delete(L`/conversations/${r}/items/${e}`,n)}}})),ca,la=e((()=>{I(),sa(),R(),ca=class extends F{constructor(){super(...arguments),this.items=new oa(this._client)}create(e={},t){return this._client.post(`/conversations`,{body:e,...t})}retrieve(e,t){return this._client.get(L`/conversations/${e}`,t)}update(e,t,n){return this._client.post(L`/conversations/${e}`,{body:t,...n})}delete(e,t){return this._client.delete(L`/conversations/${e}`,t)}},ca.Items=oa})),ua,da=e((()=>{I(),wi(),ua=class extends F{create(e,t){let n=!!e.encoding_format,r=n?e.encoding_format:`base64`;n&&k(this._client).debug(`embeddings/user defined encoding_format:`,e.encoding_format);let i=this._client.post(`/embeddings`,{body:{...e,encoding_format:r},...t});return n?i:(k(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=bi(t)}),e)))}}})),fa,pa=e((()=>{I(),M(),R(),fa=class extends F{retrieve(e,t,n){let{eval_id:r,run_id:i}=t;return this._client.get(L`/evals/${r}/runs/${i}/output_items/${e}`,n)}list(e,t,n){let{eval_id:r,...i}=t;return this._client.getAPIList(L`/evals/${r}/runs/${e}/output_items`,j,{query:i,...n})}}})),ma,ha=e((()=>{I(),pa(),M(),R(),ma=class extends F{constructor(){super(...arguments),this.outputItems=new fa(this._client)}create(e,t,n){return this._client.post(L`/evals/${e}/runs`,{body:t,...n})}retrieve(e,t,n){let{eval_id:r}=t;return this._client.get(L`/evals/${r}/runs/${e}`,n)}list(e,t={},n){return this._client.getAPIList(L`/evals/${e}/runs`,j,{query:t,...n})}delete(e,t,n){let{eval_id:r}=t;return this._client.delete(L`/evals/${r}/runs/${e}`,n)}cancel(e,t,n){let{eval_id:r}=t;return this._client.post(L`/evals/${r}/runs/${e}`,n)}},ma.OutputItems=fa})),ga,_a=e((()=>{I(),ha(),M(),R(),ga=class extends F{constructor(){super(...arguments),this.runs=new ma(this._client)}create(e,t){return this._client.post(`/evals`,{body:e,...t})}retrieve(e,t){return this._client.get(L`/evals/${e}`,t)}update(e,t,n){return this._client.post(L`/evals/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList(`/evals`,j,{query:e,...t})}delete(e,t){return this._client.delete(L`/evals/${e}`,t)}},ga.Runs=ma})),va,ya=e((()=>{I(),M(),q(),he(),z(),P(),R(),va=class extends F{create(e,t){return this._client.post(`/files`,N({body:e,...t},this._client))}retrieve(e,t){return this._client.get(L`/files/${e}`,t)}list(e={},t){return this._client.getAPIList(`/files`,j,{query:e,...t})}delete(e,t){return this._client.delete(L`/files/${e}`,t)}content(e,t){return this._client.get(L`/files/${e}/content`,{...t,headers:K([{Accept:`application/binary`},t?.headers]),__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 me(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}}})),ba,xa=e((()=>{I(),ba=class extends F{}})),Sa,Ca=e((()=>{I(),Sa=class extends F{run(e,t){return this._client.post(`/fine_tuning/alpha/graders/run`,{body:e,...t})}validate(e,t){return this._client.post(`/fine_tuning/alpha/graders/validate`,{body:e,...t})}}})),wa,Ta=e((()=>{I(),Ca(),wa=class extends F{constructor(){super(...arguments),this.graders=new Sa(this._client)}},wa.Graders=Sa})),Ea,Da=e((()=>{I(),M(),R(),Ea=class extends F{create(e,t,n){return this._client.getAPIList(L`/fine_tuning/checkpoints/${e}/permissions`,Ft,{body:t,method:`post`,...n})}retrieve(e,t={},n){return this._client.get(L`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n})}list(e,t={},n){return this._client.getAPIList(L`/fine_tuning/checkpoints/${e}/permissions`,It,{query:t,...n})}delete(e,t,n){let{fine_tuned_model_checkpoint:r}=t;return this._client.delete(L`/fine_tuning/checkpoints/${r}/permissions/${e}`,n)}}})),Oa,ka=e((()=>{I(),Da(),Oa=class extends F{constructor(){super(...arguments),this.permissions=new Ea(this._client)}},Oa.Permissions=Ea})),Aa,ja=e((()=>{I(),M(),R(),Aa=class extends F{list(e,t={},n){return this._client.getAPIList(L`/fine_tuning/jobs/${e}/checkpoints`,j,{query:t,...n})}}})),Ma,Na=e((()=>{I(),ja(),M(),R(),Ma=class extends F{constructor(){super(...arguments),this.checkpoints=new Aa(this._client)}create(e,t){return this._client.post(`/fine_tuning/jobs`,{body:e,...t})}retrieve(e,t){return this._client.get(L`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList(`/fine_tuning/jobs`,j,{query:e,...t})}cancel(e,t){return this._client.post(L`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},n){return this._client.getAPIList(L`/fine_tuning/jobs/${e}/events`,j,{query:t,...n})}pause(e,t){return this._client.post(L`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(L`/fine_tuning/jobs/${e}/resume`,t)}},Ma.Checkpoints=Aa})),Pa,Fa=e((()=>{I(),xa(),Ta(),ka(),Na(),Pa=class extends F{constructor(){super(...arguments),this.methods=new ba(this._client),this.jobs=new Ma(this._client),this.checkpoints=new Oa(this._client),this.alpha=new wa(this._client)}},Pa.Methods=ba,Pa.Jobs=Ma,Pa.Checkpoints=Oa,Pa.Alpha=wa})),Ia,La=e((()=>{I(),Ia=class extends F{}})),Ra,za=e((()=>{I(),La(),Ra=class extends F{constructor(){super(...arguments),this.graderModels=new Ia(this._client)}},Ra.GraderModels=Ia})),Ba,Va=e((()=>{I(),P(),Ba=class extends F{createVariation(e,t){return this._client.post(`/images/variations`,N({body:e,...t},this._client))}edit(e,t){return this._client.post(`/images/edits`,N({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post(`/images/generations`,{body:e,...t,stream:e.stream??!1})}}})),Ha,Ua=e((()=>{I(),M(),R(),Ha=class extends F{retrieve(e,t){return this._client.get(L`/models/${e}`,t)}list(e){return this._client.getAPIList(`/models`,Ft,e)}delete(e,t){return this._client.delete(L`/models/${e}`,t)}}})),Wa,Ga=e((()=>{I(),Wa=class extends F{create(e,t){return this._client.post(`/moderations`,{body:e,...t})}}})),Ka,qa=e((()=>{I(),q(),R(),Ka=class extends F{accept(e,t,n){return this._client.post(L`/realtime/calls/${e}/accept`,{body:t,...n,headers:K([{Accept:`*/*`},n?.headers])})}hangup(e,t){return this._client.post(L`/realtime/calls/${e}/hangup`,{...t,headers:K([{Accept:`*/*`},t?.headers])})}refer(e,t,n){return this._client.post(L`/realtime/calls/${e}/refer`,{body:t,...n,headers:K([{Accept:`*/*`},n?.headers])})}reject(e,t={},n){return this._client.post(L`/realtime/calls/${e}/reject`,{body:t,...n,headers:K([{Accept:`*/*`},n?.headers])})}}})),Ja,Ya=e((()=>{I(),Ja=class extends F{create(e,t){return this._client.post(`/realtime/client_secrets`,{body:e,...t})}}})),Xa,Za=e((()=>{I(),qa(),Ya(),Xa=class extends F{constructor(){super(...arguments),this.clientSecrets=new Ja(this._client),this.calls=new Ka(this._client)}},Xa.ClientSecrets=Ja,Xa.Calls=Ka}));function Qa(e,t){return!t||!to(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)}:$a(e,t)}function $a(e,t){let n=e.output.map(e=>{if(e.type===`function_call`)return{...e,parsed_arguments:io(t,e)};if(e.type===`message`){let n=e.content.map(e=>e.type===`output_text`?{...e,parsed:eo(t,e.text)}:e);return{...e,content:n}}return e}),r=Object.assign({},e,{output:n});return Object.getOwnPropertyDescriptor(e,`output_text`)||ao(r),Object.defineProperty(r,`output_parsed`,{enumerable:!0,get(){for(let e of r.output)if(e.type===`message`){for(let t of e.content)if(t.type===`output_text`&&t.parsed!==null)return t.parsed}return null}}),r}function eo(e,t){return e.text?.format?.type===`json_schema`?`$parseRaw`in e.text?.format?(e.text?.format).$parseRaw(t):JSON.parse(t):null}function to(e){return!!mn(e.text?.format)}function no(e){return e?.$brand===`auto-parseable-tool`}function ro(e,t){return e.find(e=>e.type===`function`&&e.name===t)}function io(e,t){let n=ro(e.tools??[],t.name);return{...t,...t,parsed_arguments:no(n)?n.$parseRaw(t.arguments):n?.strict?JSON.parse(t.arguments):null}}function ao(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 oo=e((()=>{z(),wn()}));function so(e,t){return Qa(e,t)}var co,lo,Q,uo,fo,po,mo,ho,go,_o=e((()=>{r(),z(),Vn(),oo(),go=class e extends Bn{constructor(e){super(),co.add(this),lo.set(this,void 0),Q.set(this,void 0),uo.set(this,void 0),t(this,lo,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){let i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener(`abort`,()=>this.controller.abort())),n(this,co,`m`,fo).call(this);let a,o=null;`response_id`in t?(a=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),o=t.starting_after??null):a=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(let e of a)n(this,co,`m`,po).call(this,e,o);if(a.controller.signal?.aborted)throw new d;return n(this,co,`m`,mo).call(this)}[(lo=new WeakMap,Q=new WeakMap,uo=new WeakMap,co=new WeakSet,fo=function(){this.ended||t(this,Q,void 0,`f`)},po=function(e,t){if(this.ended)return;let r=(e,n)=>{(t==null||n.sequence_number>t)&&this._emit(e,n)},i=n(this,co,`m`,ho).call(this,e);switch(r(`event`,e),e.type){case`response.output_text.delta`:{let t=i.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}`);r(`response.output_text.delta`,{...e,snapshot:n.text})}break}case`response.function_call_arguments.delta`:{let t=i.output[e.output_index];if(!t)throw new l(`missing output at index ${e.output_index}`);t.type===`function_call`&&r(`response.function_call_arguments.delta`,{...e,snapshot:t.arguments});break}default:r(e.type,e);break}},mo=function(){if(this.ended)throw new l(`stream has ended, this shouldn't happen`);let e=n(this,Q,`f`);if(!e)throw new l(`request ended without sending any events`);t(this,Q,void 0,`f`);let r=so(e,n(this,lo,`f`));return t(this,uo,r,`f`),r},ho=function(e){let r=n(this,Q,`f`);if(!r){if(e.type!==`response.created`)throw new l(`When snapshot hasn't been set yet, expected 'response.created' event, got ${e.type}`);return r=t(this,Q,e.response,`f`),r}switch(e.type){case`response.output_item.added`:r.output.push(e.item);break;case`response.content_part.added`:{let t=r.output[e.output_index];if(!t)throw new l(`missing output at index ${e.output_index}`);let n=t.type,i=e.part;n===`message`&&i.type!==`reasoning_text`?t.content.push(i):n===`reasoning`&&i.type===`reasoning_text`&&(t.content||(t.content=[]),t.content.push(i));break}case`response.output_text.delta`:{let t=r.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}`);n.text+=e.delta}break}case`response.function_call_arguments.delta`:{let t=r.output[e.output_index];if(!t)throw new l(`missing output at index ${e.output_index}`);t.type===`function_call`&&(t.arguments+=e.delta);break}case`response.reasoning_text.delta`:{let t=r.output[e.output_index];if(!t)throw new l(`missing output at index ${e.output_index}`);if(t.type===`reasoning`){let n=t.content?.[e.content_index];if(!n)throw new l(`missing content at index ${e.content_index}`);if(n.type!==`reasoning_text`)throw new l(`expected content to be 'reasoning_text', got ${n.type}`);n.text+=e.delta}break}case`response.completed`:t(this,Q,e.response,`f`);break}return 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,uo,`f`);if(!e)throw new l(`stream ended without producing a ChatCompletion`);return e}}})),vo,yo=e((()=>{I(),M(),R(),vo=class extends F{list(e,t={},n){return this._client.getAPIList(L`/responses/${e}/input_items`,j,{query:t,...n})}}})),bo,xo=e((()=>{I(),bo=class extends F{count(e={},t){return this._client.post(`/responses/input_tokens`,{body:e,...t})}}})),So,Co=e((()=>{oo(),_o(),I(),yo(),xo(),q(),R(),So=class extends F{constructor(){super(...arguments),this.inputItems=new vo(this._client),this.inputTokens=new bo(this._client)}create(e,t){return this._client.post(`/responses`,{body:e,...t,stream:e.stream??!1})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&ao(e),e))}retrieve(e,t={},n){return this._client.get(L`/responses/${e}`,{query:t,...n,stream:t?.stream??!1})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&ao(e),e))}delete(e,t){return this._client.delete(L`/responses/${e}`,{...t,headers:K([{Accept:`*/*`},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(t=>$a(t,e))}stream(e,t){return go.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(L`/responses/${e}/cancel`,t)}compact(e,t){return this._client.post(`/responses/compact`,{body:e,...t})}},So.InputItems=vo,So.InputTokens=bo})),wo,To=e((()=>{I(),q(),R(),wo=class extends F{retrieve(e,t){return this._client.get(L`/skills/${e}/content`,{...t,headers:K([{Accept:`application/binary`},t?.headers]),__binaryResponse:!0})}}})),Eo,Do=e((()=>{I(),q(),R(),Eo=class extends F{retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(L`/skills/${r}/versions/${e}/content`,{...n,headers:K([{Accept:`application/binary`},n?.headers]),__binaryResponse:!0})}}})),Oo,ko=e((()=>{I(),Do(),M(),P(),R(),Oo=class extends F{constructor(){super(...arguments),this.content=new Eo(this._client)}create(e,t={},n){return this._client.post(L`/skills/${e}/versions`,Kt({body:t,...n},this._client))}retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(L`/skills/${r}/versions/${e}`,n)}list(e,t={},n){return this._client.getAPIList(L`/skills/${e}/versions`,j,{query:t,...n})}delete(e,t,n){let{skill_id:r}=t;return this._client.delete(L`/skills/${r}/versions/${e}`,n)}},Oo.Content=Eo})),Ao,jo=e((()=>{I(),To(),ko(),M(),P(),R(),Ao=class extends F{constructor(){super(...arguments),this.content=new wo(this._client),this.versions=new Oo(this._client)}create(e={},t){return this._client.post(`/skills`,Kt({body:e,...t},this._client))}retrieve(e,t){return this._client.get(L`/skills/${e}`,t)}update(e,t,n){return this._client.post(L`/skills/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList(`/skills`,j,{query:e,...t})}delete(e,t){return this._client.delete(L`/skills/${e}`,t)}},Ao.Content=wo,Ao.Versions=Oo})),Mo,No=e((()=>{I(),P(),R(),Mo=class extends F{create(e,t,n){return this._client.post(L`/uploads/${e}/parts`,N({body:t,...n},this._client))}}})),Po,Fo=e((()=>{I(),No(),R(),Po=class extends F{constructor(){super(...arguments),this.parts=new Mo(this._client)}create(e,t){return this._client.post(`/uploads`,{body:e,...t})}cancel(e,t){return this._client.post(L`/uploads/${e}/cancel`,t)}complete(e,t,n){return this._client.post(L`/uploads/${e}/complete`,{body:t,...n})}},Po.Parts=Mo})),Io,Lo=e((()=>{Io=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}})),Ro,zo=e((()=>{I(),M(),q(),he(),Lo(),R(),Ro=class extends F{create(e,t,n){return this._client.post(L`/vector_stores/${e}/file_batches`,{body:t,...n,headers:K([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(L`/vector_stores/${r}/file_batches/${e}`,{...n,headers:K([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}cancel(e,t,n){let{vector_store_id:r}=t;return this._client.post(L`/vector_stores/${r}/file_batches/${e}/cancel`,{...n,headers:K([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}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(L`/vector_stores/${r}/file_batches/${e}/files`,j,{query:i,...n,headers:K([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}async poll(e,t,n){let r=K([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 me(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 Io(Array(a).fill(s).map(l)),await this.createAndPoll(e,{file_ids:c})}}})),Bo,Vo=e((()=>{I(),M(),q(),wi(),R(),Bo=class extends F{create(e,t,n){return this._client.post(L`/vector_stores/${e}/files`,{body:t,...n,headers:K([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(L`/vector_stores/${r}/files/${e}`,{...n,headers:K([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}update(e,t,n){let{vector_store_id:r,...i}=t;return this._client.post(L`/vector_stores/${r}/files/${e}`,{body:i,...n,headers:K([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e,t={},n){return this._client.getAPIList(L`/vector_stores/${e}/files`,j,{query:t,...n,headers:K([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}delete(e,t,n){let{vector_store_id:r}=t;return this._client.delete(L`/vector_stores/${r}/files/${e}`,{...n,headers:K([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}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=K([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 me(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(L`/vector_stores/${r}/files/${e}/content`,Ft,{...n,headers:K([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}}})),Ho,Uo=e((()=>{I(),zo(),Vo(),M(),q(),R(),Ho=class extends F{constructor(){super(...arguments),this.files=new Bo(this._client),this.fileBatches=new Ro(this._client)}create(e,t){return this._client.post(`/vector_stores`,{body:e,...t,headers:K([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}retrieve(e,t){return this._client.get(L`/vector_stores/${e}`,{...t,headers:K([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}update(e,t,n){return this._client.post(L`/vector_stores/${e}`,{body:t,...n,headers:K([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e={},t){return this._client.getAPIList(`/vector_stores`,j,{query:e,...t,headers:K([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}delete(e,t){return this._client.delete(L`/vector_stores/${e}`,{...t,headers:K([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}search(e,t,n){return this._client.getAPIList(L`/vector_stores/${e}/search`,Ft,{body:t,method:`post`,...n,headers:K([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}},Ho.Files=Bo,Ho.FileBatches=Ro})),Wo,Go=e((()=>{I(),M(),q(),P(),R(),Wo=class extends F{create(e,t){return this._client.post(`/videos`,N({body:e,...t},this._client))}retrieve(e,t){return this._client.get(L`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList(`/videos`,It,{query:e,...t})}delete(e,t){return this._client.delete(L`/videos/${e}`,t)}createCharacter(e,t){return this._client.post(`/videos/characters`,N({body:e,...t},this._client))}downloadContent(e,t={},n){return this._client.get(L`/videos/${e}/content`,{query:t,...n,headers:K([{Accept:`application/binary`},n?.headers]),__binaryResponse:!0})}edit(e,t){return this._client.post(`/videos/edits`,N({body:e,...t},this._client))}extend(e,t){return this._client.post(`/videos/extensions`,N({body:e,...t},this._client))}getCharacter(e,t){return this._client.get(L`/videos/characters/${e}`,t)}remix(e,t,n){return this._client.post(L`/videos/${e}/remix`,Kt({body:t,...n},this._client))}}})),Ko,qo,Jo,Yo,Xo=e((()=>{r(),z(),I(),q(),Yo=class extends F{constructor(){super(...arguments),Ko.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,Ko,`m`,qo).call(this,r);let a=K([t]).values,o=n(this,Ko,`m`,Jo).call(this,a,`webhook-signature`),s=n(this,Ko,`m`,Jo).call(this,a,`webhook-timestamp`),c=n(this,Ko,`m`,Jo).call(this,a,`webhook-id`),l=parseInt(s,10);if(isNaN(l))throw new S(`Invalid webhook timestamp format`);let u=Math.floor(Date.now()/1e3);if(u-l>i)throw new S(`Webhook timestamp is too old`);if(l>u+i)throw new S(`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 S(`The given webhook signature does not match the expected signature`)}},Ko=new WeakSet,qo=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`)},Jo=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}})),Zo=e((()=>{Xo()})),Qo=e((()=>{Zo()})),$o=e((()=>{Hr(),Ur(),$r(),ti(),Zi(),$i(),aa(),la(),da(),_a(),ya(),Fa(),za(),Va(),Ua(),Ga(),Za(),Co(),jo(),Fo(),Uo(),Go(),Qo()})),es,ts,ns,rs,is,$,as=e((()=>{r(),a(),pe(),he(),c(),Ee(),Me(),Pe(),tt(),_e(),C(),M(),Bt(),sn(),$o(),jt(),ti(),$i(),da(),ya(),Va(),Ua(),Ga(),Go(),$r(),Zi(),Br(),aa(),la(),_a(),Fa(),za(),Za(),Co(),jo(),Fo(),Uo(),Xo(),q(),Ci(),vt(),is=`workload-identity-auth`,$=class{constructor({baseURL:e=Si(`OPENAI_BASE_URL`),apiKey:n=Si(`OPENAI_API_KEY`),organization:r=Si(`OPENAI_ORG_ID`)??null,project:i=Si(`OPENAI_PROJECT_ID`)??null,webhookSecret:a=Si(`OPENAI_WEBHOOK_SECRET`)??null,workloadIdentity:o,...s}={}){if(es.add(this),ns.set(this,void 0),this.completions=new Qi(this),this.chat=new zr(this),this.embeddings=new ua(this),this.files=new va(this),this.images=new Ba(this),this.audio=new Qr(this),this.moderations=new Wa(this),this.models=new Ha(this),this.fineTuning=new Pa(this),this.graders=new Ra(this),this.vectorStores=new Ho(this),this.webhooks=new Yo(this),this.beta=new Xi(this),this.batches=new ei(this),this.uploads=new Po(this),this.responses=new So(this),this.realtime=new Xa(this),this.conversations=new ca(this),this.evals=new ga(this),this.containers=new ia(this),this.skills=new Ao(this),this.videos=new Wo(this),o){if(n&&n!==is)throw new l("The `apiKey` and `workloadIdentity` arguments are mutually exclusive; only one can be passed at a time.");n=is}else if(n===void 0)throw new l("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, or set the `OPENAI_API_KEY` environment variable.");let c={apiKey:n,organization:r,project:i,webhookSecret:a,workloadIdentity:o,...s,baseURL:e||`https://api.openai.com/v1`};if(!c.dangerouslyAllowBrowser&&be())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=c.baseURL,this.timeout=c.timeout??ts.DEFAULT_TIMEOUT,this.logger=c.logger??console;let u=`warn`;this.logLevel=u,this.logLevel=ht(c.logLevel,`ClientOptions.logLevel`,this)??ht(Si(`OPENAI_LOG`),`process.env['OPENAI_LOG']`,this)??u,this.fetchOptions=c.fetchOptions,this.maxRetries=c.maxRetries??2,this.fetch=c.fetch??De(),t(this,ns,Ne,`f`),this._options=c,o&&(this._workloadIdentityAuth=new zt(o,this.fetch)),this.apiKey=typeof n==`string`?n:`Missing Key`,this.organization=r,this.project=i,this.webhookSecret=a}withOptions(e){return new this.constructor({...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.apiKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return K([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return et(e)}getUserAgent(){return`${this.constructor.name}/JS ${ge}`}defaultIdempotencyKey(){return`stainless-node-retry-${i()}`}makeStatusError(e,t,n,r){return u.generate(e,t,n,r)}async _callApiKey(){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,es,`m`,rs).call(this)&&r||this.baseURL,a=le(e)?new URL(e):new URL(i+(i.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),o=this.defaultQuery(),s=Object.fromEntries(a.searchParams);return(!ae(o)||!ae(s))&&(t={...s,...o,...t}),typeof t==`object`&&t&&!Array.isArray(t)&&(a.search=this.stringifyQuery(t)),a.toString()}async prepareOptions(e){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 At(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});let u=`log_`+(Math.random()*(1<<24)|0).toString(16).padStart(6,`0`),m=n===void 0?``:`, retryOf: ${n}`,h=Date.now();if(k(this).debug(`[${u}] sending request`,A({retryOfRequestLogID:n,method:r.method,url:c,options:r,headers:a.headers})),r.signal?.aborted)throw new d;let g=new AbortController,_=await this.fetchWithAuth(c,a,l,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 k(this).info(`[${u}] connection ${i?`timed out`:`failed`} - ${e}`),k(this).debug(`[${u}] connection ${i?`timed out`:`failed`} (${e})`,A({retryOfRequestLogID:n,url:c,durationMs:v-h,message:_.message})),this.retryRequest(r,t,n??u);throw k(this).info(`[${u}] connection ${i?`timed out`:`failed`} - error; no more retries left`),k(this).debug(`[${u}] connection ${i?`timed out`:`failed`} (error; no more retries left)`,A({retryOfRequestLogID:n,url:c,durationMs:v-h,message:_.message})),_ instanceof ne||_ instanceof re?_:i?new p:new f({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&&!r.__metadata?.hasStreamingBody&&!r.__metadata?.workloadIdentityTokenRefreshed)return await je(_.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 je(_.body),k(this).info(`${y} - ${e}`),k(this).debug(`[${u}] response error (${e})`,A({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`;k(this).info(`${y} - ${i}`);let a=await _.text().catch(e=>s(e).message),o=fe(a),c=o?void 0:a;throw k(this).debug(`[${u}] response error (${i})`,A({retryOfRequestLogID:n,url:_.url,status:_.status,headers:_.headers,message:c,durationMs:Date.now()-h})),this.makeStatusError(_.status,o,c,_.headers)}return k(this).info(y),k(this).debug(`[${u}] response start`,A({retryOfRequestLogID:n,url:_.url,status:_.status,headers:_.headers,durationMs:v-h})),{response:_,options:r,controller:g,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 Pt(this,n,e)}async fetchWithAuth(e,t,n,r){if(this._workloadIdentityAuth){let e=t.headers,n=e.get(`Authorization`);if(!n||n===`Bearer ${is}`){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 me(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&&de(`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=K([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))}:{},...Te(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(a),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let r=K([t]),i=globalThis.ReadableStream!==void 0&&e instanceof globalThis.ReadableStream,a=!i&&(typeof e==`string`||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||globalThis.Blob!==void 0&&e instanceof globalThis.Blob||e instanceof URLSearchParams||e instanceof FormData);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e==`string`&&r.values.has(`content-type`)||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||i?{bodyHeaders:void 0,body:e,isStreamingBody:!a}:typeof e==`object`&&(Symbol.asyncIterator in e||Symbol.iterator in e&&`next`in e&&typeof e.next==`function`)?{bodyHeaders:void 0,body:ke(e),isStreamingBody:!0}:typeof e==`object`&&r.values.get(`content-type`)===`application/x-www-form-urlencoded`?{bodyHeaders:{"content-type":`application/x-www-form-urlencoded`},body:this.stringifyQuery(e),isStreamingBody:!1}:{...n(this,ns,`f`).call(this,{body:e,headers:r}),isStreamingBody:!1}}},ts=$,ns=new WeakMap,es=new WeakSet,rs=function(){return this.baseURL!==`https://api.openai.com/v1`},$.OpenAI=ts,$.DEFAULT_TIMEOUT=6e5,$.OpenAIError=l,$.APIError=u,$.APIConnectionError=f,$.APIConnectionTimeoutError=p,$.APIUserAbortError=d,$.NotFoundError=_,$.ConflictError=v,$.RateLimitError=ee,$.BadRequestError=m,$.AuthenticationError=h,$.InternalServerError=b,$.PermissionDeniedError=g,$.UnprocessableEntityError=y,$.InvalidWebhookSignatureError=S,$.toFile=$t,$.Completions=Qi,$.Chat=zr,$.Embeddings=ua,$.Files=va,$.Images=Ba,$.Audio=Qr,$.Moderations=Wa,$.Models=Ha,$.FineTuning=Pa,$.Graders=Ra,$.VectorStores=Ho,$.Webhooks=Yo,$.Beta=Xi,$.Batches=ei,$.Uploads=Po,$.Responses=So,$.Realtime=Xa,$.Conversations=ca,$.Evals=ga,$.Containers=ia,$.Skills=Ao,$.Videos=Wo})),os=e((()=>{z(),wi(),as()})),ss=e((()=>{as(),sn(),jt(),M(),C(),os()}));function cs(e,t){return{input_tokens:t.input_tokens??e.input_tokens,output_tokens:t.output_tokens??e.output_tokens,cache_creation_input_tokens:t.cache_creation_input_tokens!==void 0&&t.cache_creation_input_tokens>0?t.cache_creation_input_tokens:e.cache_creation_input_tokens,cache_read_input_tokens:t.cache_read_input_tokens!==void 0&&t.cache_read_input_tokens>0?t.cache_read_input_tokens:e.cache_read_input_tokens}}var ls=e((()=>{}));export{$ as i,cs as n,ss as r,ls as t};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{n as e,o as t}from"./chunk-DR8-3Aex.js";import{n,t as r}from"./figures-gfT9mM8P.js";import{F as i,In as a,J as o,Ln as s,Rn as c,Ut as l,_ as u,a as d,b as f,f as p,i as m,n as h,o as g,p as ee,r as te,t as _,tt as ne,x as v,xt as y}from"./src-Di342QoJ.js";import{t as b}from"./jsx-runtime-D-D469L8.js";import{cn as re,ot as x}from"./state-sIHsFpDu.js";import{Bo as S,Po as C,Ro as w,Vo as T,Xa as E,Xs as D,jo as O,nc as k,oo as A}from"./paths-BBvuDQl9.js";import{E as j,w as M}from"./debug-UI3T040K.js";import{Dx as N,H as ie,K as ae,Lo as P,Lw as oe,MS as se,Nx as ce,Ox as F,PS as le,Px as I,U as ue,V as de,W as fe,aD as pe,eD as me,hp as L,hu as R,iA as he,iD as z,jS as ge,mo as _e,mp as ve,mu as B,q as ye,tA as V}from"./loadAgentsDir-DI1a76pd.js";import{t as be}from"./useKeybinding-FsOnjW6T.js";import{l as xe,u as Se}from"./referral-DeDr9zAE.js";import{n as Ce,t as we}from"./AddWorkspaceDirectory-BYyM_V0q.js";import{t as Te}from"./SearchBox-DfOmUoaI.js";import{n as Ee,t as De}from"./useSearchInput-BV_azHiA.js";import{n as H,t as Oe}from"./shadowedRuleDetection-BBR3uEgx.js";import{n as ke,t as Ae}from"./autoModeDenials-Cp6VFdsm.js";function je({ruleValue:e}){switch(e.toolName){case B.name:return e.ruleContent?e.ruleContent.endsWith(`:*`)?(0,U.jsxs)(f,{dimColor:!0,children:[`Any Bash command starting with `,(0,U.jsx)(f,{bold:!0,children:e.ruleContent.slice(0,-2)})]}):(0,U.jsxs)(f,{dimColor:!0,children:[`The Bash command `,(0,U.jsx)(f,{bold:!0,children:e.ruleContent})]}):(0,U.jsx)(f,{dimColor:!0,children:`Any Bash command`});default:return e.ruleContent?null:(0,U.jsxs)(f,{dimColor:!0,children:[`Any use of the `,(0,U.jsx)(f,{bold:!0,children:e.toolName}),` tool`]})}}var U,Me=e((()=>{c(),_(),R(),U=b()}));function Ne(e){switch(e){case`localSettings`:return{label:`Project settings (local)`,description:`Saved in ${E(`localSettings`)}`,value:e};case`projectSettings`:return{label:`Project settings`,description:`Checked in at ${E(`projectSettings`)}`,value:e};case`userSettings`:return{label:`User settings`,description:`Saved in at ~/.claude/settings.json`,value:e}}}function Pe({onAddRules:e,onCancel:t,ruleValues:n,ruleBehavior:r,initialContext:i,setToolPermissionContext:a}){let o=D.map(Ne),s=(0,Fe.useCallback)(o=>{if(o===`cancel`){t();return}else if(D.includes(o)){let t=o,s=me(i,{type:`addRules`,rules:n,behavior:r,destination:t});pe({type:`addRules`,rules:n,behavior:r,destination:t}),a(s);let c=n.map(e=>({ruleValue:e,ruleBehavior:r,source:t})),l=Oe(s,{sandboxAutoAllowEnabled:V.isSandboxingEnabled()&&V.isAutoAllowBashIfSandboxedEnabled()}).filter(e=>n.some(t=>t.toolName===e.rule.ruleValue.toolName&&t.ruleContent===e.rule.ruleValue.ruleContent));e(c,l.length>0?l:void 0)}},[e,t,n,r,i,a]);return(0,W.jsxs)(p,{title:`Add ${r} permission ${C(n.length,`rule`)}`,onCancel:t,color:`permission`,children:[(0,W.jsx)(v,{flexDirection:`column`,paddingX:2,children:n.map(e=>(0,W.jsxs)(v,{flexDirection:`column`,children:[(0,W.jsx)(f,{bold:!0,children:T(e)}),(0,W.jsx)(je,{ruleValue:e})]},T(e)))}),(0,W.jsxs)(v,{flexDirection:`column`,marginY:1,children:[(0,W.jsx)(f,{children:n.length===1?`Where should this rule be saved?`:`Where should these rules be saved?`}),(0,W.jsx)(N,{options:o,onChange:s})]})]})}var Fe,W,Ie=e((()=>{c(),Fe=t(c(),1),F(),_(),z(),w(),H(),he(),k(),A(),O(),Me(),W=b()}));function Le({onCancel:e,onSubmit:t,ruleBehavior:n}){let[a,s]=(0,Re.useState)(``),[c,l]=(0,Re.useState)(0),u=Se();ne(`confirm:no`,e,{context:`Settings`});let{columns:d}=i(),p=d-6;return(0,G.jsxs)(G.Fragment,{children:[(0,G.jsxs)(v,{flexDirection:`column`,gap:1,borderStyle:`round`,paddingLeft:1,paddingRight:1,borderColor:`permission`,children:[(0,G.jsxs)(f,{bold:!0,color:`permission`,children:[`Add `,n,` permission rule`]}),(0,G.jsxs)(v,{flexDirection:`column`,children:[(0,G.jsxs)(f,{children:[`Permission rules are a tool name, optionally followed by a specifier in parentheses.`,(0,G.jsx)(o,{}),`e.g., `,(0,G.jsx)(f,{bold:!0,children:T({toolName:ve.name})}),(0,G.jsx)(f,{bold:!1,children:` or `}),(0,G.jsx)(f,{bold:!0,children:T({toolName:B.name,ruleContent:`ls:*`})})]}),(0,G.jsx)(v,{borderDimColor:!0,borderStyle:`round`,marginY:1,paddingLeft:1,children:(0,G.jsx)(ce,{showCursor:!0,value:a,onChange:s,onSubmit:e=>{let r=e.trim();r.length!==0&&t(S(r),n)},placeholder:`Enter permission rule${r.ellipsis}`,columns:p,cursorOffset:c,onChangeCursorOffset:l})})]})]}),(0,G.jsx)(v,{marginLeft:3,children:u.pending?(0,G.jsxs)(f,{dimColor:!0,children:[`Press `,u.keyName,` again to exit`]}):(0,G.jsx)(f,{dimColor:!0,children:`Enter to submit · Esc to cancel`})})]})}var Re,G,ze=e((()=>{n(),c(),Re=t(c(),1),I(),xe(),oe(),_(),be(),R(),L(),w(),G=b()}));function Be({onHeaderFocusChange:e,onStateChange:t}){let{headerFocused:n,focusHeader:r}=m();(0,K.useEffect)(()=>{e?.(n)},[n,e]);let[i]=(0,K.useState)(()=>Ae()),[a,o]=(0,K.useState)(()=>new Set),[s,c]=(0,K.useState)(()=>new Set),[l,u]=(0,K.useState)(0);(0,K.useEffect)(()=>{t({approved:a,retry:s,denials:i})},[a,s,i,t]);let d=(0,K.useCallback)(e=>{let t=Number(e);o(e=>{let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n})},[]),p=(0,K.useCallback)(e=>{u(Number(e))},[]);if(y((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,q.jsx)(f,{dimColor:!0,children:`No recent denials. Commands denied by the auto mode classifier will appear here.`});let h=i.map((e,t)=>{let n=a.has(t),r=s.has(t)?` (retry)`:``;return{label:(0,q.jsxs)(f,{children:[(0,q.jsx)(g,{status:n?`success`:`error`,withSpace:!0}),e.display,(0,q.jsx)(f,{dimColor:!0,children:r})]}),value:String(t)}});return(0,q.jsxs)(v,{flexDirection:`column`,children:[(0,q.jsx)(f,{children:`Commands recently denied by the auto mode classifier.`}),(0,q.jsx)(v,{marginTop:1,children:(0,q.jsx)(N,{options:h,onChange:d,onFocus:p,visibleOptionCount:Math.min(10,h.length),isDisabled:n,onUpFromFirstItem:r})})]})}var K,q,Ve=e((()=>{c(),K=t(c(),1),_(),ke(),F(),q=b()}));function He({directoryPath:e,onRemove:t,onCancel:n,permissionContext:r,setPermissionContext:i}){let a=(0,J.useCallback)(()=>{i(me(r,{type:`removeDirectories`,directories:[e],destination:`session`})),t()},[e,r,i,t]),o=(0,J.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)(v,{marginX:2,flexDirection:`column`,children:(0,Y.jsx)(f,{bold:!0,children:e})}),(0,Y.jsx)(f,{children:`Claude Code will no longer have access to files in this directory.`}),(0,Y.jsx)(N,{onChange:o,onCancel:n,options:[{label:`Yes`,value:`yes`},{label:`No`,value:`no`}]})]})}var J,Y,Ue=e((()=>{c(),J=t(c(),1),F(),_(),z(),Y=b()}));function We({onExit:e,toolPermissionContext:t,onRequestAddDirectory:n,onRequestRemoveDirectory:i,onHeaderFocusChange:a}){let{headerFocused:o,focusHeader:s}=m();(0,X.useEffect)(()=>{a?.(o)},[o,a]);let c=Ge.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&&t.isDeletable&&i(t.path)},[c,n,i]),u=(0,X.useCallback)(()=>e(`Workspace dialog dismissed`,{display:`system`}),[e]),d=Ge.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)(v,{flexDirection:`column`,marginBottom:1,children:[(0,Z.jsxs)(v,{flexDirection:`row`,marginTop:1,marginLeft:2,gap:1,children:[(0,Z.jsx)(f,{children:`- ${x()}`}),(0,Z.jsx)(f,{dimColor:!0,children:`(Original working directory)`})]}),(0,Z.jsx)(N,{options:d,onChange:l,onCancel:u,visibleOptionCount:Math.min(10,d.length),onUpFromFirstItem:s,isDisabled:o})]})}var Ge,X,Z,Ke=e((()=>{n(),Ge=t(c(),1),X=t(c(),1),re(),F(),_(),Z=b()}));function qe({rule:e}){return(0,$.jsx)(f,{dimColor:!0,children:`From ${ye(e.source)}`})}function Je(e){switch(e){case`allow`:return`allowed`;case`deny`:return`denied`;case`ask`:return`ask`}}function Ye({rule:e,onDelete:t,onCancel:n}){let r=Se();ne(`confirm:no`,n,{context:`Confirmation`});let i=(0,$.jsxs)(v,{flexDirection:`column`,marginX:2,children:[(0,$.jsx)(f,{bold:!0,children:T(e.ruleValue)}),(0,$.jsx)(je,{ruleValue:e.ruleValue}),(0,$.jsx)(qe,{rule:e})]}),a=(0,$.jsx)(v,{marginLeft:3,children:r.pending?(0,$.jsxs)(f,{dimColor:!0,children:[`Press `,r.keyName,` again to exit`]}):(0,$.jsx)(f,{dimColor:!0,children:`Esc to cancel`})});return e.source===`policySettings`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(v,{flexDirection:`column`,gap:1,borderStyle:`round`,paddingLeft:1,paddingRight:1,borderColor:`permission`,children:[(0,$.jsx)(f,{bold:!0,color:`permission`,children:`Rule details`}),i,(0,$.jsxs)(f,{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)(v,{flexDirection:`column`,gap:1,borderStyle:`round`,paddingLeft:1,paddingRight:1,borderColor:`error`,children:[(0,$.jsxs)(f,{bold:!0,color:`error`,children:[`Delete `,Je(e.ruleBehavior),` tool?`]}),i,(0,$.jsx)(f,{children:`Are you sure you want to delete this permission rule?`}),(0,$.jsx)(N,{onChange:e=>e===`yes`?t():n(),onCancel:n,options:[{label:`Yes`,value:`yes`},{label:`No`,value:`no`}]})]}),a]})}function Xe(e){let{options:t,searchQuery:n,isSearchMode:r,isFocused:i,onSelect:a,onCancel:o,lastFocusedRuleKey:s,cursorOffset:c,onHeaderFocusChange:l}=e,f=d(),{headerFocused:p,focusHeader:h,blurHeader:g}=m();return(0,Q.useEffect)(()=>{r&&p&&g()},[r,p,g]),(0,Q.useEffect)(()=>{l?.(p)},[p,l]),(0,$.jsxs)(v,{flexDirection:`column`,children:[(0,$.jsx)(v,{marginBottom:1,flexDirection:`column`,children:(0,$.jsx)(u,{query:n,isFocused:r&&!p,isTerminalFocused:i,width:f,cursorOffset:c})}),(0,$.jsx)(N,{options:t,onChange:a,onCancel:o,visibleOptionCount:Math.min(10,t.length),isDisabled:r||p,defaultFocusValue:s,onUpFromFirstItem:h})]})}function Ze({tab:e,getRulesOptions:t,handleToolSelect:n,...r}){return(0,$.jsxs)(v,{flexDirection:`column`,flexShrink:e===`allow`?0:void 0,children:[(0,$.jsx)(f,{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)(Xe,{options:t(e,r.searchQuery).options,onSelect:t=>n(t,e),...r})]})}function Qe({onExit:e,initialTab:t,onRetryDenials:n}){let i=Ae().length>0,o=t??(i?`recent`:`allow`),[s,c]=(0,Q.useState)([]),u=se(e=>e.toolPermissionContext),d=le(),p=l(),m=(0,Q.useRef)({approved:new Set,retry:new Set,denials:[]}),g=(0,Q.useCallback)(e=>{m.current=e},[]),[_,y]=(0,Q.useState)(),[b,re]=(0,Q.useState)(),[x,S]=(0,Q.useState)(null),[C,w]=(0,Q.useState)(null),[E,D]=(0,Q.useState)(!1),[O,k]=(0,Q.useState)(null),[A,M]=(0,Q.useState)(!1),[N,ae]=(0,Q.useState)(!0),P=(0,Q.useCallback)(e=>{ae(e)},[]),oe=(0,Q.useMemo)(()=>{let e=new Map;return ie(u).forEach(t=>{e.set(j(t),t)}),e},[u]),ce=(0,Q.useMemo)(()=>{let e=new Map;return fe(u).forEach(t=>{e.set(j(t),t)}),e},[u]),F=(0,Q.useMemo)(()=>{let e=new Map;return ue(u).forEach(t=>{e.set(j(t),t)}),e},[u]),I=(0,Q.useCallback)((e,t=``)=>{let n=(()=>{switch(e){case`allow`:return oe;case`deny`:return ce;case`ask`:return F;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=T(r.ruleValue).toLowerCase(),t=T(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=T(r.ruleValue);if(t&&!n.toLowerCase().includes(o))continue;i.push({label:n,value:e})}}return{options:i,rulesByKey:n}},[oe,ce,F]),L=Se(),R=!_&&!x&&!C&&!E&&!O,{query:he,setQuery:z,cursorOffset:ge}=Ee({isActive:R&&A,onExit:()=>{M(!1)}}),_e=(0,Q.useCallback)(e=>{R&&(A||e.ctrl||e.meta||(e.key===`/`?(e.preventDefault(),M(!0),z(``)):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),z(e.key))))},[R,A,z]),ve=(0,Q.useCallback)((e,t)=>{let{rulesByKey:n}=I(t);if(e===`add-new-rule`){S(t);return}else{y(n.get(e));return}},[I]),B=(0,Q.useCallback)(()=>{S(null)},[]),ye=(0,Q.useCallback)((e,t)=>{w({ruleValue:e,ruleBehavior:t}),S(null)},[]),V=(0,Q.useCallback)((e,t)=>{w(null);for(let t of e)c(e=>[...e,`Added ${t.ruleBehavior} rule ${a.bold(T(t.ruleValue))}`]);if(t&&t.length>0)for(let e of t){let t=e.shadowType===`deny`?`blocked`:`shadowed`;c(n=>[...n,a.yellow(`${r.warning} Warning: ${T(e.rule.ruleValue)} is ${t}`),a.dim(` ${e.reason}`),a.dim(` Fix: ${e.fix}`)])}},[]),be=(0,Q.useCallback)(()=>{w(null)},[]),xe=(0,Q.useCallback)(()=>D(!0),[]),Ce=(0,Q.useCallback)(e=>k(e),[]),Te=(0,Q.useCallback)(()=>{let t=m.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 o=r(t.approved);o.length>0||s.length>0?e([...o.length>0?[`Approved ${o.map(e=>a.bold(e.display)).join(`, `)}`]:[],...s].join(`
|
|
3
|
-
`)):e(`Permissions dialog dismissed`,{display:`system`})},[s,e,n]);ne(`confirm:no`,Te,{context:`Settings`,isActive:R&&!A});let De=()=>{if(!_)return;let{options:e}=I(_.ruleBehavior),t=j(_),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])),re(i),de({rule:_,initialContext:u,setToolPermissionContext(e){d(t=>({...t,toolPermissionContext:e}))}}),c(e=>[...e,`Deleted ${_.ruleBehavior} rule ${a.bold(T(_.ruleValue))}`]),y(void 0)};if(_)return(0,$.jsx)(Ye,{rule:_,onDelete:De,onCancel:()=>y(void 0)});if(x&&x!==`workspace`&&x!==`recent`)return(0,$.jsx)(Le,{onCancel:B,onSubmit:ye,ruleBehavior:x});if(C)return(0,$.jsx)(Pe,{onAddRules:V,onCancel:be,ruleValues:[C.ruleValue],ruleBehavior:C.ruleBehavior,initialContext:u,setToolPermissionContext:e=>{d(t=>({...t,toolPermissionContext:e}))}});if(E)return(0,$.jsx)(we,{onAddDirectory:(e,t)=>{let n={type:`addDirectories`,directories:[e],destination:t?`localSettings`:`session`},r=me(u,n);d(e=>({...e,toolPermissionContext:r})),t&&pe(n),c(n=>[...n,`Added directory ${a.bold(e)} to workspace${t?` and saved to local settings`:` for this session`}`]),D(!1)},onCancel:()=>D(!1),permissionContext:u});if(O)return(0,$.jsx)(He,{directoryPath:O,onRemove:()=>{c(e=>[...e,`Removed directory ${a.bold(O)} from workspace`]),k(null)},onCancel:()=>k(null),permissionContext:u,setPermissionContext:e=>{d(t=>({...t,toolPermissionContext:e}))}});let H={searchQuery:he,isSearchMode:A,isFocused:p,onCancel:Te,lastFocusedRuleKey:b,cursorOffset:ge,getRulesOptions:I,handleToolSelect:ve,onHeaderFocusChange:P};return(0,$.jsx)(v,{flexDirection:`column`,onKeyDown:_e,children:(0,$.jsxs)(ee,{color:`permission`,children:[(0,$.jsxs)(te,{title:`Permissions:`,color:`permission`,defaultTab:o,hidden:!!_||!!x||!!C||E||!!O,initialHeaderFocused:!i,navFromContent:!A,children:[(0,$.jsx)(h,{id:`recent`,title:`Recently denied`,children:(0,$.jsx)(Be,{onHeaderFocusChange:P,onStateChange:g})}),(0,$.jsx)(h,{id:`allow`,title:`Allow`,children:(0,$.jsx)(Ze,{tab:`allow`,...H})}),(0,$.jsx)(h,{id:`ask`,title:`Ask`,children:(0,$.jsx)(Ze,{tab:`ask`,...H})}),(0,$.jsx)(h,{id:`deny`,title:`Deny`,children:(0,$.jsx)(Ze,{tab:`deny`,...H})}),(0,$.jsx)(h,{id:`workspace`,title:`Workspace`,children:(0,$.jsxs)(v,{flexDirection:`column`,children:[(0,$.jsx)(f,{children:`Claude Code can read files in the workspace, and make edits when auto-accept edits is on.`}),(0,$.jsx)(We,{onExit:e,toolPermissionContext:u,onRequestAddDirectory:xe,onRequestRemoveDirectory:Ce,onHeaderFocusChange:P})]})})]}),(0,$.jsx)(v,{marginTop:1,paddingLeft:1,children:(0,$.jsx)(f,{dimColor:!0,children:L.pending?(0,$.jsxs)($.Fragment,{children:[`Press `,L.keyName,` again to exit`]}):N?(0,$.jsx)($.Fragment,{children:`←/→ tab switch · ↓ return · Esc cancel`}):A?(0,$.jsx)($.Fragment,{children:`Type to filter · Enter/↓ select · ↑ tabs · Esc clear`}):i&&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,$,$e=e((()=>{s(),n(),c(),Q=t(c(),1),ge(),z(),F(),xe(),De(),_(),be(),ke(),w(),ae(),M(),Te(),Ie(),Ce(),Me(),ze(),Ve(),Ue(),Ke(),$=b()})),et,tt;e((()=>{$e(),P(),et=b(),tt=async(e,t)=>(0,et.jsx)(Qe,{onExit:e,onRetryDenials:e=>{t.setMessages(t=>[...t,_e(e)])}})}))();export{tt as call};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{n as e,t}from"./pluginStartupCheck-BW2fjg2P.js";e();export{t as getPluginEditableScopes};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Ba as e,Ka as t,Ra as n}from"./loadAgentsDir-DI1a76pd.js";n();export{e as isPolicyAllowed,t as waitForPolicyLimitsToLoad};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{n as e,t}from"./poorMode-DzYT47KW.js";t();export{e as isPoorModeActive};
|