claude-code-best 2.6.6 → 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-Bb6crGWh.js → AddWorkspaceDirectory-YmrkKVv2.js} +1 -1
- package/dist/chunks/{App-CW0Y4ceR.js → App-IAjCdPUn.js} +1 -1
- package/dist/chunks/ApproveApiKey-CAvlRKLr.js +1 -0
- package/dist/chunks/{ApproveApiKey-9rkwQfgT.js → ApproveApiKey-DhsT69v7.js} +1 -1
- package/dist/chunks/{AssistantSessionChooser-XzXZZdiH.js → AssistantSessionChooser-DCUVNGfn.js} +1 -1
- package/dist/chunks/BackgroundTasksDialog-Di_gH2TW.js +2 -0
- package/dist/chunks/{BypassPermissionsModeDialog-DlLWAKw2.js → BypassPermissionsModeDialog-BeZqE75e.js} +1 -1
- package/dist/chunks/{ClaudeInChromeOnboarding-CjGydpBk.js → ClaudeInChromeOnboarding-CZHktpPE.js} +1 -1
- package/dist/chunks/{ClaudeMdExternalIncludesDialog-B04cjDwX.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-CFBUqcCf.js → DesktopHandoff-C8_CDNft.js} +1 -1
- package/dist/chunks/{DevChannelsDialog-ByTf41du.js → DevChannelsDialog-DkGWCFpL.js} +1 -1
- package/dist/chunks/{DiffDialog-CY-8kw_Q.js → DiffDialog-93P95op8.js} +2 -2
- package/dist/chunks/Doctor-CheDaF3O.js +1 -0
- package/dist/chunks/Doctor-Zd0UaR5d.js +3 -0
- package/dist/chunks/{ExitFlow-BlON8IgH.js → ExitFlow-4edARxmd.js} +2 -2
- package/dist/chunks/{Feedback-CSeD3k4M.js → Feedback-CZY-BikO.js} +2 -2
- package/dist/chunks/Grove-CbcR0CsI.js +1 -0
- package/dist/chunks/{Grove-Tp_UtIMg.js → Grove-TYf1glGP.js} +1 -1
- package/dist/chunks/{HybridTransport-CAko699F.js → HybridTransport-BNexuwcN.js} +1 -1
- package/dist/chunks/{ITermBackend-5P3WJumD.js → ITermBackend-DuomVpsD.js} +1 -1
- package/dist/chunks/{InvalidConfigDialog-CVcdra9v.js → InvalidConfigDialog-Byury3Zx.js} +1 -1
- package/dist/chunks/{InvalidSettingsDialog-CfLdbmSI.js → InvalidSettingsDialog-B8_0AvWo.js} +1 -1
- package/dist/chunks/{MCPConnectionManager-BK_3uwQj.js → MCPConnectionManager-xL_wQCda.js} +1 -1
- package/dist/chunks/{McpParsingWarnings-BOj-T8F3.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-C06Mxlf-.js → Onboarding-XWhelEBr.js} +1 -1
- package/dist/chunks/{OverageCreditUpsell-abcPm3PB.js → OverageCreditUpsell-BvPz1jLU.js} +1 -1
- package/dist/chunks/PluginSettings-D1YHfrE1.js +17 -0
- package/dist/chunks/{PromptInputFooterSuggestions-ihnbjU0K.js → PromptInputFooterSuggestions-rqUoa9Ch.js} +1 -1
- package/dist/chunks/{PromptInputHelpMenu-CMm8z7Gk.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-CBFcgD4r.js → REPL-D2p-vgct.js} +34 -34
- package/dist/chunks/{RemoteCallout-Cy6lH-CZ.js → RemoteCallout-CCIWIrd-.js} +1 -1
- package/dist/chunks/{RemoteSessionManager-C7iGd5Og.js → RemoteSessionManager-Dx81p5dH.js} +2 -2
- package/dist/chunks/ResumeConversation-73r3Zh5P.js +1 -0
- package/dist/chunks/{SSETransport-B5xlXeAN.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-iih9eFpM.js → SentryErrorBoundary-z8tMb-zO.js} +1 -1
- package/dist/chunks/Settings-D9qdaMe5.js +2 -0
- package/dist/chunks/{TeleportProgress-BX-uLwuL.js → TeleportProgress-CPXN7u3Z.js} +1 -1
- package/dist/chunks/{TeleportRepoMismatchDialog-D8oPPTWd.js → TeleportRepoMismatchDialog-CiyXjTxq.js} +1 -1
- package/dist/chunks/{TeleportResumeWrapper-B_CvNDbr.js → TeleportResumeWrapper-Dao8ktHk.js} +1 -1
- package/dist/chunks/{ThemePicker-BG1ykSpX.js → ThemePicker-CFYFNnPp.js} +1 -1
- package/dist/chunks/{TmuxBackend-CnMCWNS4.js → TmuxBackend-B5DBBugq.js} +1 -1
- package/dist/chunks/{TrustDialog-Z_maAYj8.js → TrustDialog-DtIXHMR_.js} +1 -1
- package/dist/chunks/{ValidationErrorsList-C9swVkZ-.js → ValidationErrorsList-BK0wOS55.js} +1 -1
- package/dist/chunks/{WelcomeV2-Au_5ddlT.js → WelcomeV2-BjUbi9vp.js} +1 -1
- package/dist/chunks/{WindowsTerminalBackend-CGxaYH74.js → WindowsTerminalBackend-DFLLlAOp.js} +1 -1
- package/dist/chunks/{add-dir-Cm9u56YX.js → add-dir-JoVgNFOk.js} +1 -1
- package/dist/chunks/{agentDisplay-Bi_bEyEn.js → agentDisplay-B3RjWR-3.js} +1 -1
- package/dist/chunks/{agents-CMF9fLzV.js → agents-BUyLUAIu.js} +7 -7
- package/dist/chunks/{agents-CbjR7hNr.js → agents-UqS5PhD2.js} +1 -1
- package/dist/chunks/{ant-Bu1Gs4WJ.js → ant-Bq1wIvnP.js} +1 -1
- package/dist/chunks/{api-D_t0nHsS.js → api-O4eHGLTY.js} +1 -1
- package/dist/chunks/api-kAjsowcb.js +1 -0
- package/dist/chunks/{assistant-C_pfWe2a.js → assistant-CMIbt3Ir.js} +1 -1
- package/dist/chunks/{assistant-EA-MHNQ-.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-D7PZvVPf.js → auth-D3SKo0wT.js} +1 -1
- package/dist/chunks/{autoMode-B8iO05xy.js → autoMode-BIVJlkBM.js} +1 -1
- package/dist/chunks/{autonomy-dQVtSiCJ.js → autonomy-BYi6z9LD.js} +1 -1
- package/dist/chunks/{autonomy-CaLvE5N6.js → autonomy-Mi7Fkq1J.js} +12 -12
- package/dist/chunks/{autonomyPanel-DSswVlCF.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-C7pM8Sjh.js → branch-BC-K45fw.js} +1 -1
- package/dist/chunks/{bridge-CTYdzSWg.js → bridge-DBteRzgS.js} +2 -2
- package/dist/chunks/{bridgeConfig-Df6uyp3q.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-A-_xJ94c.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-DPVLAIzl.js → bridgeMessaging-CqXQzew4.js} +1 -1
- package/dist/chunks/{btw-CqgjLlFN.js → btw-DBtPlEWc.js} +1 -1
- package/dist/chunks/{buddy-DCGBAqF2.js → buddy-BYwTgNnf.js} +1 -1
- package/dist/chunks/{bypassPermissionsKillswitch-CK0jeZTW.js → bypassPermissionsKillswitch-DkYLp9m0.js} +1 -1
- package/dist/chunks/caches-B-GiT9hm.js +1 -0
- package/dist/chunks/{caches-CdVW8fYV.js → caches-DGW9ovtw.js} +2 -2
- package/dist/chunks/{ccrClient-B_3AmY7K.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-BbDQdLZC.js → channelNotification-n7Avue-9.js} +1 -1
- package/dist/chunks/{chrome-CGyqsCkL.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-e0kkanVT.js → commitAttribution-q7SEukgl.js} +1 -1
- package/dist/chunks/{compact-Dh9RewNA.js → compact-DiY1w7pT.js} +3 -3
- package/dist/chunks/{companion-DVFacTUw.js → companion-D18UNnC7.js} +1 -1
- package/dist/chunks/{config-CkSmYDJY.js → config-CSHnElBp.js} +1 -1
- package/dist/chunks/{config-DwiVCSrY.js → config-D3QKcEKz.js} +1 -1
- package/dist/chunks/{context-B8VDDHTv.js → context-DnyYrN2X.js} +1 -1
- package/dist/chunks/context-noninteractive-0YpW67KZ.js +1 -0
- package/dist/chunks/{context-noninteractive-IZfWniex.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-CIjrYoFa.js → copy-CHGX-YpC.js} +2 -2
- package/dist/chunks/{createSSHSession-ArNlbIZB.js → createSSHSession-Bf-8h3Sw.js} +1 -1
- package/dist/chunks/createSession-BYf27ahD.js +1 -0
- package/dist/chunks/{createSession-CBheIT_G.js → createSession-rRZIkjl3.js} +1 -1
- package/dist/chunks/{cronJitterConfig-DcMGWOa-.js → cronJitterConfig-DmBBJDTf.js} +3 -3
- package/dist/chunks/{crossProjectResume-Z-aR2q-d.js → crossProjectResume-BQxLBpDD.js} +3 -3
- package/dist/chunks/{datadog-BK8eJz8B.js → datadog-Bb65d6yd.js} +1 -1
- package/dist/chunks/datadog-NnzM1Mu3.js +1 -0
- package/dist/chunks/{desktop-B9vWJeRu.js → desktop-DiCA6RUU.js} +1 -1
- package/dist/chunks/{diff-BTV7_Dca.js → diff-BvLQ-t8P.js} +1 -1
- package/dist/chunks/{doctor-Dpbh0aRz.js → doctor-bmTXLycZ.js} +1 -1
- package/dist/chunks/{effort-Czlwa5qF.js → effort-CSTwkB2B.js} +2 -2
- package/dist/chunks/{entry-CdfuWjKu.js → entry-BUwwv2dM.js} +4 -4
- package/dist/chunks/{envLessBridgeConfig-BAFYaZ0E.js → envLessBridgeConfig-DJJKeDBT.js} +1 -1
- package/dist/chunks/envLessBridgeConfig-Dq02Vvx1.js +1 -0
- package/dist/chunks/{exit-DzOm62Dn.js → exit-eirVuF-n.js} +1 -1
- package/dist/chunks/{export-DHOR3z3Z.js → export-CcJD8r8U.js} +1 -1
- package/dist/chunks/{exportRenderer-CiNXeNr9.js → exportRenderer-DtezFcml.js} +1 -1
- package/dist/chunks/{extra-usage-DIYR_3ZR.js → extra-usage-CBcgeIcJ.js} +1 -1
- package/dist/chunks/extra-usage-DhB0NElh.js +1 -0
- package/dist/chunks/{extra-usage-core-C3uM9bOP.js → extra-usage-core-DWM0Q56J.js} +1 -1
- package/dist/chunks/{extra-usage-noninteractive-Ctz9TfY8.js → extra-usage-noninteractive-BvJEi4WX.js} +1 -1
- package/dist/chunks/{extraUsage-CBwIvl73.js → extraUsage-CWde-Mi0.js} +1 -1
- package/dist/chunks/extractMemories-wcRNh_jz.js +1 -0
- package/dist/chunks/{fast-BpBwjbSD.js → fast-DQyJ7c7s.js} +1 -1
- package/dist/chunks/fast-ukzN3wl2.js +1 -0
- package/dist/chunks/{feedback-BkVnsZVx.js → feedback-BzBBKT2y.js} +1 -1
- package/dist/chunks/{firstPartyEventLogger-BCzGkdpd.js → firstPartyEventLogger-BOHIpp-w.js} +1 -1
- package/dist/chunks/{flushGate-CQsnMw8g.js → flushGate-DeCDhkKp.js} +1 -1
- package/dist/chunks/{gates-CxWIWtmd.js → gates-CAVdjC23.js} +1 -1
- package/dist/chunks/gates-CB_pFChT.js +1 -0
- package/dist/chunks/{gemini-BbV8D2SS.js → gemini-CFrOUVS4.js} +1 -1
- package/dist/chunks/{generateRecap-B3j2nUgh.js → generateRecap-Bcp5DiiO.js} +1 -1
- package/dist/chunks/{generateSessionName-aGnXSNgN.js → generateSessionName-DeFGkHct.js} +1 -1
- package/dist/chunks/{githubRepoPathMapping-DCJLSTLl.js → githubRepoPathMapping-B07Wb07_.js} +1 -1
- package/dist/chunks/grok-DtidcVWD.js +1 -0
- package/dist/chunks/{growthbook-prtWhMRg.js → growthbook-gLwBDK-r.js} +1 -1
- package/dist/chunks/{heapdump-Czm-2XiG.js → heapdump-BxQYlnPR.js} +1 -1
- package/dist/chunks/{help-CSAFsN0-.js → help-Bi0sABuv.js} +1 -1
- package/dist/chunks/hooks-BTBhK9sh.js +1 -0
- package/dist/chunks/{hooks-DkbOP-bI.js → hooks-Cc_DxF9N.js} +2 -2
- package/dist/chunks/{hostAdapter-BcdDPVTj.js → hostAdapter-D9_d4gU0.js} +1 -1
- package/dist/chunks/{ide-BXERRFZF.js → ide-3wDIOoZF.js} +2 -2
- package/dist/chunks/inboundAttachments-DBaPmCTv.js +1 -0
- package/dist/chunks/{inboundAttachments-7rXrAtkb.js → inboundAttachments-DPMETKd6.js} +1 -1
- package/dist/chunks/initReplBridge-BWP41EGm.js +1 -0
- package/dist/chunks/{insights-DrvqJgF8.js → insights-w7qM4YyA.js} +5 -5
- package/dist/chunks/{install-BGnxwO00.js → install-N2FgArWv.js} +1 -1
- package/dist/chunks/{install-github-app-CIpBHlr9.js → install-github-app-By39Zi78.js} +2 -2
- package/dist/chunks/{install-slack-app-By4Lh7ww.js → install-slack-app-CVwZphU-.js} +1 -1
- package/dist/chunks/{instrumentation-D9y7Ph_R.js → instrumentation-BkLEupDC.js} +3 -3
- package/dist/chunks/{job-BPVIMW_P.js → job-CgBE27O7.js} +1 -1
- package/dist/chunks/{keybindings-Ce6AHMLI.js → keybindings-DHXJzU3E.js} +2 -2
- package/dist/chunks/{lang-DfDG_fSa.js → lang-DLneRt1b.js} +1 -1
- package/dist/chunks/{language-yGoDFP3X.js → language-BVAzlrRz.js} +1 -1
- package/dist/chunks/language-ZBygqv6V.js +1 -0
- package/dist/chunks/{launchAgentsPlatform-DT01xZM7.js → launchAgentsPlatform-CtfK0qPa.js} +1 -1
- package/dist/chunks/{launchAutofixPr-DrYd7WVf.js → launchAutofixPr-CQBv0rQ0.js} +3 -3
- package/dist/chunks/{launchLocalMemory-Bt3tMYVJ.js → launchLocalMemory-BNE09TKr.js} +2 -2
- package/dist/chunks/{launchLocalVault-jyRHEa_Y.js → launchLocalVault-Dw_NJUnd.js} +3 -3
- package/dist/chunks/{launchMemoryStores-cmXnLAF5.js → launchMemoryStores-CRRB6Z5A.js} +1 -1
- package/dist/chunks/{launchOnboarding-BPTNFftb.js → launchOnboarding-nMAF5iv7.js} +1 -1
- package/dist/chunks/{launchSchedule-141GqGC8.js → launchSchedule-Akq1AmK8.js} +1 -1
- package/dist/chunks/{launchSkillStore-Bz0lok_o.js → launchSkillStore-Zwtasj13.js} +1 -1
- package/dist/chunks/{launchTeleport-BMquJxIq.js → launchTeleport-BzlIYyll.js} +3 -3
- package/dist/chunks/{launchVault-Bsuwqad6.js → launchVault-BevXlxJB.js} +1 -1
- package/dist/chunks/{loadAgentsDir-D7kapZB5.js → loadAgentsDir-DF6FgRn-.js} +810 -791
- 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-r1_G8kfV.js → localSearch-v4itMlCM.js} +1 -1
- package/dist/chunks/{login-7MvpaOkt.js → login-CKodBzyZ.js} +1 -1
- package/dist/chunks/login-CTIVwgFU.js +1 -0
- package/dist/chunks/{logoV2Utils-DjThKW15.js → logoV2Utils-VebeEs7Y.js} +1 -1
- package/dist/chunks/logout-B3MyP8fk.js +1 -0
- package/dist/chunks/{magicDocs-Dy72LHIj.js → magicDocs-uX5n3NKh.js} +2 -2
- package/dist/chunks/{main-CF6Im-LV.js → main-Cd_i0ZPo.js} +48 -48
- package/dist/chunks/{mappers-CkMESMy7.js → mappers-CPL2ni36.js} +1 -1
- package/dist/chunks/{mcp-BTgHgOhR.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-BueM5fWI.js → mcpServer-CPJo2eKm.js} +1 -1
- package/dist/chunks/{mcpServer-Dqm2PQQx.js → mcpServer-CTuPkyD6.js} +1 -1
- package/dist/chunks/{memory-BNZmqma1.js → memory-enMuKEnU.js} +1 -1
- package/dist/chunks/{model-DOw7wIKQ.js → model-4f3U2YMu.js} +1 -1
- package/dist/chunks/model-BsHyPvD0.js +1 -0
- package/dist/chunks/{onChangeAppState-Cb9_yIuW.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-BrN7dk3d.js → overageCreditGrant-CCkJVN9k.js} +1 -1
- package/dist/chunks/{passes-vgcY8_l8.js → passes-O0VEQz1a.js} +1 -1
- package/dist/chunks/{paths-1ngPRtu3.js → paths-o5iA-EnQ.js} +6 -6
- package/dist/chunks/permissions-BtYQvivG.js +3 -0
- package/dist/chunks/{pipeTransport-KU8psPDI.js → pipeTransport-BEfqa7Uh.js} +1 -1
- package/dist/chunks/{plan-5NVPuxp6.js → plan-Jw4GjVL0.js} +1 -1
- package/dist/chunks/{plugin-t8jMqdsY.js → plugin-DZq0voFR.js} +1 -1
- package/dist/chunks/{pluginAutoupdate-CAa4KLro.js → pluginAutoupdate-D19vNoOp.js} +1 -1
- package/dist/chunks/{pluginBlocklist-BG2LkLq1.js → pluginBlocklist-DeX8I4dK.js} +1 -1
- package/dist/chunks/{pluginCliCommands-vqAtVibb.js → pluginCliCommands-CMgqxOaT.js} +1 -1
- package/dist/chunks/{pluginFlagging-BFCtv3kY.js → pluginFlagging-DFLE5fkh.js} +1 -1
- package/dist/chunks/{pluginOperations-C9XP-mko.js → pluginOperations-BTz69m3_.js} +2 -2
- package/dist/chunks/{pluginStartupCheck-RRcAbKfx.js → pluginStartupCheck-CWWKwD5F.js} +1 -1
- package/dist/chunks/pluginStartupCheck-Non969kz.js +1 -0
- package/dist/chunks/plugins-BPUnAc0r.js +4 -0
- package/dist/chunks/policyLimits-D6dpS-CU.js +1 -0
- package/dist/chunks/{pollConfig-DTYIJ8lQ.js → pollConfig-DyHumJli.js} +1 -1
- package/dist/chunks/{poor-Dw5dMZpM.js → poor-CHHZIPDW.js} +1 -1
- package/dist/chunks/{poorMode-CsGLI_hm.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-P2r-kg2i.js → privacy-settings-DR0_P3JF.js} +1 -1
- package/dist/chunks/{processBashCommand-a8W8aTRu.js → processBashCommand-CkqKsBSD.js} +1 -1
- 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-BBg3jtfc.js → prompt-DiHksuOs.js} +1 -1
- package/dist/chunks/{promptEditor-CvaugNTt.js → promptEditor-B3S5E5Q7.js} +2 -2
- package/dist/chunks/{protocolHandler-DxBaHlaD.js → protocolHandler-D1XT2l3j.js} +1 -1
- package/dist/chunks/{rate-limit-options-Df_sgE0b.js → rate-limit-options-DHh1ksB5.js} +1 -1
- package/dist/chunks/{rcDebugLog-CPGWJbI4.js → rcDebugLog-BNojB_eB.js} +1 -1
- package/dist/chunks/{referral-BKeCKnOJ.js → referral-BADm5sBf.js} +1 -1
- package/dist/chunks/refresh-D48fjYJ4.js +1 -0
- package/dist/chunks/{registerProtocol-DLuRm0mf.js → registerProtocol-Dzmi6VC4.js} +1 -1
- package/dist/chunks/{registry-DVSgtCq5.js → registry-CEu_N3dS.js} +1 -1
- package/dist/chunks/{release-notes-CZcf8zB7.js → release-notes-Dr61jYDO.js} +1 -1
- package/dist/chunks/{releaseNotes-CvfZb3fZ.js → releaseNotes-5SV7C5aV.js} +2 -2
- package/dist/chunks/{reload-plugins-pSlDLk3b.js → reload-plugins-BxuE-21F.js} +1 -1
- package/dist/chunks/{remote-env-BH89NuwC.js → remote-env-BaQjT5em.js} +1 -1
- package/dist/chunks/{remoteBridgeCore-CrXlWEL1.js → remoteBridgeCore-B8MjcW6f.js} +1 -1
- package/dist/chunks/{remoteControlServer-BSOnq4yY.js → remoteControlServer-BvoNcg9D.js} +2 -2
- package/dist/chunks/{rename-DNGvNQm2.js → rename-B3q0tgmd.js} +1 -1
- package/dist/chunks/{resume-6UL38yL3.js → resume-BSGOqus7.js} +2 -2
- package/dist/chunks/{runtimeObserver-Cp-DN8fP.js → runtimeObserver-Bb6wSUMJ.js} +1 -1
- package/dist/chunks/{runtimeObserver-BhvHeiwD.js → runtimeObserver-BbwUiToa.js} +4 -4
- package/dist/chunks/sandbox-adapter-Cr6f6gjf.js +1 -0
- package/dist/chunks/{sandbox-toggle-D19YbI5G.js → sandbox-toggle-L7YPKXba.js} +1 -1
- package/dist/chunks/searchExtraTools-DRVIhwVJ.js +1 -0
- package/dist/chunks/{sentry-BZmpC-iI.js → sentry-DG3ru8XE.js} +1 -1
- package/dist/chunks/{session-lLpGqp0B.js → session-B5wA2K9M.js} +1 -1
- package/dist/chunks/{sessionDiscovery-BX3fjgzD.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-CujNIWks.js → sessionObserver-CsDT2GnB.js} +1 -1
- package/dist/chunks/sessionStorage-BUuPrnU0.js +1 -0
- package/dist/chunks/{sessionTitle-QxXslbJY.js → sessionTitle-CxmvZO71.js} +2 -2
- package/dist/chunks/{sessionTracing-DognYcDf.js → sessionTracing-Cy5dAplG.js} +1 -1
- package/dist/chunks/{settingsSync-DEPET5O1.js → settingsSync-54E8xV8N.js} +1 -1
- package/dist/chunks/setup-B5CMpp0c.js +2 -0
- package/dist/chunks/{setup-C6G0lasE.js → setup-GJtdESQj.js} +1 -1
- package/dist/chunks/{setup-BUBUidOg.js → setup-KWELOokh.js} +1 -1
- package/dist/chunks/{shadowedRuleDetection-CQayPrmM.js → shadowedRuleDetection-C4NGjljb.js} +1 -1
- package/dist/chunks/{sideQuestion-B9EE1vTM.js → sideQuestion-DBrzdgkl.js} +1 -1
- package/dist/chunks/{sink-Cugto5We.js → sink-BKc24wdw.js} +1 -1
- package/dist/chunks/sink-DG0SNHP7.js +1 -0
- package/dist/chunks/{sinks-B9A94oIj.js → sinks-BTS1DWM4.js} +2 -2
- package/dist/chunks/sinks-Cbp-8X1S.js +1 -0
- package/dist/chunks/{skill-learning-CroDcatu.js → skill-learning-C5NrosiL.js} +1 -1
- package/dist/chunks/skillChangeDetector-NJrEtU47.js +1 -0
- package/dist/chunks/{skillGapStore-91Mb3xDY.js → skillGapStore-D1rkePoo.js} +2 -2
- package/dist/chunks/{skillGapStore-LKwap3o4.js → skillGapStore-uXpRqLGG.js} +1 -1
- package/dist/chunks/{skillGenerator-B9GM0LHk.js → skillGenerator-Deog7yBO.js} +2 -2
- package/dist/chunks/{skillLearning-DbOOqb6b.js → skillLearning-BHjRTDJw.js} +1 -1
- package/dist/chunks/skillLearning-By7jxHSI.js +1 -0
- package/dist/chunks/{skillPanel-rIIYgnBE.js → skillPanel-Bx63GX9w.js} +3 -3
- package/dist/chunks/{skillSearchPanel-xAL-6uJF.js → skillSearchPanel-CM5EZGkH.js} +4 -4
- package/dist/chunks/{skills-Doe47wxK.js → skills-JvC7Ms0P.js} +1 -1
- package/dist/chunks/{sprites-D11F3i1M.js → sprites-YBiqlYch.js} +1 -1
- package/dist/chunks/{stats-WNUyieG-.js → stats-BJMKNvVK.js} +1 -1
- package/dist/chunks/{status-CjBS9SkF.js → status-DAJ28yxZ.js} +1 -1
- package/dist/chunks/{statusNoticeHelpers-cnI4TiGw.js → statusNoticeHelpers-B7nbsqLz.js} +1 -1
- package/dist/chunks/{tag-Gfb8vTAR.js → tag-B4y7cBqH.js} +2 -2
- package/dist/chunks/{tasks-BwX1rzOD.js → tasks-CSye58Ap.js} +1 -1
- package/dist/chunks/{teamHelpers-DEgaCpta.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-Dyukgtp9.js → teammateModeSnapshot-DXc2vyo2.js} +1 -1
- package/dist/chunks/teleport-NN6zSxxe.js +1 -0
- package/dist/chunks/{templateJobs-DQXuFnkl.js → templateJobs-DAVqqU0g.js} +1 -1
- package/dist/chunks/{terminalSetup-bSbq4LE7.js → terminalSetup-DqL65XR2.js} +1 -1
- package/dist/chunks/{terminalSetup-CTEIn08j.js → terminalSetup-jZKBoPTc.js} +1 -1
- package/dist/chunks/{theme-DazaKPy8.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-D4h-QqVP.js → toolEventObserver-CtApZXry.js} +1 -1
- package/dist/chunks/{toolEventObserver-Dfvv2trb.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-rdvUkS1W.js → trustedDevice-Bxn7WW5C.js} +1 -1
- package/dist/chunks/{trustedDevice-CQ9PK-8m.js → trustedDevice-DsgCQRsJ.js} +1 -1
- package/dist/chunks/{ultrareviewCommand-Zf9hO4wr.js → ultrareviewCommand-BfuSrdXz.js} +2 -2
- package/dist/chunks/undercover-B-R6dhHB.js +1 -0
- package/dist/chunks/{undercover-DLyKv5TE.js → undercover-CM8zTx5g.js} +1 -1
- package/dist/chunks/{updateCCB-7WQRz9lW.js → updateCCB-DTArxdyR.js} +1 -1
- package/dist/chunks/upgrade-CCrHxXrm.js +1 -0
- package/dist/chunks/{upgrade-ByIumMQe.js → upgrade-CEd1Jxw_.js} +1 -1
- package/dist/chunks/{upload-CvOMbA9_.js → upload-DNo3bZLc.js} +1 -1
- package/dist/chunks/{usage-C_d-Z-eb.js → usage-DEwRsc7E.js} +1 -1
- package/dist/chunks/{usage-DE4PSQiF.js → usage-X4-qec8g.js} +1 -1
- package/dist/chunks/{useMainLoopModel-Os8Ao8-x.js → useMainLoopModel-2A9HV1H3.js} +1 -1
- package/dist/chunks/{useManagePlugins-BYBubfHU.js → useManagePlugins-D9MBag8O.js} +1 -1
- package/dist/chunks/{useMergedTools-BJAn2i-F.js → useMergedTools-DCYrP_YE.js} +1 -1
- package/dist/chunks/{useSearchInput-CF77X2OV.js → useSearchInput-CepwLBvi.js} +1 -1
- package/dist/chunks/useSettingsErrors-C8ffWXbY.js +1 -0
- package/dist/chunks/{useVoice-DwzMN0fq.js → useVoice-vHZVaTAN.js} +1 -1
- package/dist/chunks/{util-DD30Y4o8.js → util-B13MVSse.js} +1 -1
- package/dist/chunks/utils-C-vk0zpl.js +1 -0
- package/dist/chunks/validatePlugin-Cf_toBOJ.js +1 -0
- package/dist/chunks/{vim-zc9EiMil.js → vim-6p7eiRPG.js} +1 -1
- package/dist/chunks/{voice-BRhZt4jW.js → voice-Bvc_BxoI.js} +2 -2
- package/dist/chunks/{voiceModeEnabled-168-1Ocs.js → voiceModeEnabled-BPbOh6jd.js} +1 -1
- package/dist/chunks/voiceModeEnabled-JSBux8GA.js +1 -0
- package/dist/chunks/{voiceStreamSTT-B80UegKG.js → voiceStreamSTT-CzCUhap3.js} +1 -1
- package/dist/chunks/voiceStreamSTT-D9ER6Ml3.js +1 -0
- package/dist/chunks/{workerRegistry-s8nnpmUO.js → workerRegistry-DCtC-WN3.js} +1 -1
- package/dist/chunks/worktree-Dv0mPuy_.js +1 -0
- package/dist/chunks/{xml-DTMvLcPg.js → xml-CqxiCY4v.js} +1 -1
- package/dist/cli.js +1 -1
- package/package.json +1 -1
- package/dist/chunks/ApproveApiKey-BhMr2Y5F.js +0 -1
- package/dist/chunks/BackgroundTasksDialog-BL_dfbZP.js +0 -2
- package/dist/chunks/ClaudeMdExternalIncludesDialog-DPki55Xa.js +0 -1
- package/dist/chunks/ConsoleOAuthFlow-D_j1NebK.js +0 -1
- package/dist/chunks/Doctor-2D5Wz58o.js +0 -1
- package/dist/chunks/Doctor-CDez_u_U.js +0 -3
- package/dist/chunks/Grove-Dwu_0zRw.js +0 -1
- package/dist/chunks/MessageSelector-BRkxpO1O.js +0 -3
- package/dist/chunks/Messages-wyMyMP7U.js +0 -11
- package/dist/chunks/PluginSettings-DGpIVGvV.js +0 -17
- package/dist/chunks/QueryEngine-I3Bqzbiz.js +0 -1
- package/dist/chunks/REPL-BxAsVlx3.js +0 -1
- package/dist/chunks/ResumeConversation-AdLtgdVB.js +0 -1
- package/dist/chunks/SearchExtraToolsTool-BJ8Nx_Nu.js +0 -1
- package/dist/chunks/SentryErrorBoundary-Bs7mtkPb.js +0 -1
- package/dist/chunks/Settings-PioHwsvg.js +0 -2
- package/dist/chunks/api-CFNGoLoL.js +0 -1
- package/dist/chunks/assistant-BLd4y2FJ.js +0 -1
- package/dist/chunks/auth-DGfZCD_B.js +0 -1
- package/dist/chunks/backgroundHousekeeping-Ckj8W3RO.js +0 -1
- package/dist/chunks/backgroundHousekeeping-D2_Uopt7.js +0 -17
- package/dist/chunks/bridgeConfig-7c07tJm9.js +0 -1
- package/dist/chunks/bridgeEnabled-Z2S8lk0l.js +0 -1
- package/dist/chunks/bridgeMain-B7FZpvo0.js +0 -68
- package/dist/chunks/bridgeMain-C5UxF8ST.js +0 -1
- package/dist/chunks/caches-Dt52PedI.js +0 -1
- package/dist/chunks/changeDetector-uO9CBvut.js +0 -1
- package/dist/chunks/channelNotification-DzTzUrCe.js +0 -1
- package/dist/chunks/clear-B_cVk64B.js +0 -1
- package/dist/chunks/client-BcqXgcrx.js +0 -1
- package/dist/chunks/color-DEXUx7gE.js +0 -1
- package/dist/chunks/commands-BX0_wEGw.js +0 -1
- package/dist/chunks/commitAttribution-CSVDcgTO.js +0 -1
- package/dist/chunks/context-noninteractive-SBxqQ3iu.js +0 -1
- package/dist/chunks/conversation-CQBl9Yy2.js +0 -1
- package/dist/chunks/conversation-DVZplNag.js +0 -1
- package/dist/chunks/createSession-DfEQy2dZ.js +0 -1
- package/dist/chunks/datadog-Uj6FjEuU.js +0 -1
- package/dist/chunks/envLessBridgeConfig-DOO9eX07.js +0 -1
- package/dist/chunks/extra-usage-CJcyfVCt.js +0 -1
- package/dist/chunks/extractMemories-C3SU-Osb.js +0 -1
- package/dist/chunks/fast-7iinMwk-.js +0 -1
- package/dist/chunks/gates-qgzva-fO.js +0 -1
- package/dist/chunks/grok-C4QFXJnR.js +0 -1
- package/dist/chunks/hooks-Ch2vPE8u.js +0 -1
- package/dist/chunks/inboundAttachments-C0rkLl2x.js +0 -1
- package/dist/chunks/initReplBridge-tXqkba08.js +0 -1
- package/dist/chunks/language-B1yHC1d6.js +0 -1
- package/dist/chunks/loadAgentsDir-DxPE2bIO.js +0 -1
- package/dist/chunks/loadPluginHooks-CL5aGDrb.js +0 -1
- package/dist/chunks/localSearch-iozuZZhZ.js +0 -1
- package/dist/chunks/login-Dxza_KNT.js +0 -1
- package/dist/chunks/logout-BeGQR78E.js +0 -1
- package/dist/chunks/mcp-UJZ22IDJ.js +0 -6
- package/dist/chunks/mcp-fHf8Uc7h.js +0 -1
- package/dist/chunks/model-D3g2QdU-.js +0 -1
- package/dist/chunks/openai-Bvo0Gcec.js +0 -10
- package/dist/chunks/openaiShared-D5lOejS1.js +0 -16
- package/dist/chunks/permissions-BDbIjTT6.js +0 -3
- package/dist/chunks/pluginStartupCheck-DZp0wnXP.js +0 -1
- package/dist/chunks/plugins-0SyID4Kx.js +0 -4
- package/dist/chunks/policyLimits-Cmmzuv-E.js +0 -1
- package/dist/chunks/poorMode-D_hB-rDf.js +0 -1
- package/dist/chunks/print-Ct8N4PYT.js +0 -39
- package/dist/chunks/processSlashCommand-BaUdUg3T.js +0 -6
- package/dist/chunks/prompt-B1Qy8mi4.js +0 -1
- package/dist/chunks/prompt-D4kWWEZC.js +0 -1
- package/dist/chunks/refresh-Cjv4jA6L.js +0 -1
- package/dist/chunks/sandbox-adapter-DGVtPPD0.js +0 -1
- package/dist/chunks/searchExtraTools-DXWkpOIg.js +0 -1
- package/dist/chunks/sessionFileAccessHooks-BeuS4m7a.js +0 -1
- package/dist/chunks/sessionMemory-LMOQk90c.js +0 -1
- package/dist/chunks/sessionMemory-UpILj5ww.js +0 -1
- package/dist/chunks/sessionMemoryUtils-DE7AezA0.js +0 -1
- package/dist/chunks/sessionObserver-HqvTXhs9.js +0 -1
- package/dist/chunks/sessionStorage-BN56DAAd.js +0 -1
- package/dist/chunks/setup-BZMVuIIx.js +0 -2
- package/dist/chunks/sink-BRrEbL6h.js +0 -1
- package/dist/chunks/sinks-CKaSBvU8.js +0 -1
- package/dist/chunks/skillChangeDetector-DnyEQqe6.js +0 -1
- package/dist/chunks/skillLearning-D6latSKi.js +0 -1
- package/dist/chunks/teamHelpers-EJxTXoTV.js +0 -1
- package/dist/chunks/teammateModeSnapshot-BgUQ4Phz.js +0 -1
- package/dist/chunks/teleport-B4p8XlAv.js +0 -1
- package/dist/chunks/thinkback-BOfZP_QG.js +0 -1
- package/dist/chunks/thinkback-CxWZV2Oz.js +0 -1
- package/dist/chunks/thinkback-play-CHe1x2Hc.js +0 -1
- package/dist/chunks/toolPool-BHChMuLr.js +0 -1
- package/dist/chunks/toolPool-C5K43w4_.js +0 -1
- package/dist/chunks/undercover-DNS9V_JT.js +0 -1
- package/dist/chunks/upgrade-bK4x32Ma.js +0 -1
- package/dist/chunks/useSettingsErrors-DD7fQ-fU.js +0 -1
- package/dist/chunks/utils-D44M8obg.js +0 -1
- package/dist/chunks/validatePlugin-DpHiJRsT.js +0 -1
- package/dist/chunks/voiceModeEnabled-CTT25yFj.js +0 -1
- package/dist/chunks/voiceStreamSTT-BpYhKo2H.js +0 -1
- package/dist/chunks/worktree-CkB4jLXK.js +0 -1
|
@@ -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-1ngPRtu3.js";import{E as j,w as M}from"./debug-UI3T040K.js";import{Ax as N,Fx as ie,H as ae,IS as oe,Ix as P,K as se,Lo as ce,NS as le,PS as ue,U as de,V as fe,W as pe,hp as F,hu as I,kx as L,mo as me,mp as R,mu as z,nD as he,oA as ge,oD as B,q as _e,rA as ve,sD as ye,zw as be}from"./loadAgentsDir-D7kapZB5.js";import{t as xe}from"./useKeybinding-FsOnjW6T.js";import{l as Se,u as Ce}from"./referral-BKeCKnOJ.js";import{n as we,t as Te}from"./AddWorkspaceDirectory-Bb6crGWh.js";import{t as Ee}from"./SearchBox-DfOmUoaI.js";import{n as De,t as Oe}from"./useSearchInput-CF77X2OV.js";import{n as V,t as ke}from"./shadowedRuleDetection-CQayPrmM.js";import{n as Ae,t as je}from"./autoModeDenials-Cp6VFdsm.js";function Me({ruleValue:e}){switch(e.toolName){case z.name:return e.ruleContent?e.ruleContent.endsWith(`:*`)?(0,H.jsxs)(f,{dimColor:!0,children:[`Any Bash command starting with `,(0,H.jsx)(f,{bold:!0,children:e.ruleContent.slice(0,-2)})]}):(0,H.jsxs)(f,{dimColor:!0,children:[`The Bash command `,(0,H.jsx)(f,{bold:!0,children:e.ruleContent})]}):(0,H.jsx)(f,{dimColor:!0,children:`Any Bash command`});default:return e.ruleContent?null:(0,H.jsxs)(f,{dimColor:!0,children:[`Any use of the `,(0,H.jsx)(f,{bold:!0,children:e.toolName}),` tool`]})}}var H,Ne=e((()=>{c(),_(),I(),H=b()}));function Pe(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 Fe({onAddRules:e,onCancel:t,ruleValues:n,ruleBehavior:r,initialContext:i,setToolPermissionContext:a}){let o=D.map(Pe),s=(0,Ie.useCallback)(o=>{if(o===`cancel`){t();return}else if(D.includes(o)){let t=o,s=he(i,{type:`addRules`,rules:n,behavior:r,destination:t});ye({type:`addRules`,rules:n,behavior:r,destination:t}),a(s);let c=n.map(e=>({ruleValue:e,ruleBehavior:r,source:t})),l=ke(s,{sandboxAutoAllowEnabled:ve.isSandboxingEnabled()&&ve.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,U.jsxs)(p,{title:`Add ${r} permission ${C(n.length,`rule`)}`,onCancel:t,color:`permission`,children:[(0,U.jsx)(v,{flexDirection:`column`,paddingX:2,children:n.map(e=>(0,U.jsxs)(v,{flexDirection:`column`,children:[(0,U.jsx)(f,{bold:!0,children:T(e)}),(0,U.jsx)(Me,{ruleValue:e})]},T(e)))}),(0,U.jsxs)(v,{flexDirection:`column`,marginY:1,children:[(0,U.jsx)(f,{children:n.length===1?`Where should this rule be saved?`:`Where should these rules be saved?`}),(0,U.jsx)(L,{options:o,onChange:s})]})]})}var Ie,U,Le=e((()=>{c(),Ie=t(c(),1),N(),_(),B(),w(),V(),ge(),k(),A(),O(),Ne(),U=b()}));function Re({onCancel:e,onSubmit:t,ruleBehavior:n}){let[a,s]=(0,ze.useState)(``),[c,l]=(0,ze.useState)(0),u=Ce();ne(`confirm:no`,e,{context:`Settings`});let{columns:d}=i(),p=d-6;return(0,W.jsxs)(W.Fragment,{children:[(0,W.jsxs)(v,{flexDirection:`column`,gap:1,borderStyle:`round`,paddingLeft:1,paddingRight:1,borderColor:`permission`,children:[(0,W.jsxs)(f,{bold:!0,color:`permission`,children:[`Add `,n,` permission rule`]}),(0,W.jsxs)(v,{flexDirection:`column`,children:[(0,W.jsxs)(f,{children:[`Permission rules are a tool name, optionally followed by a specifier in parentheses.`,(0,W.jsx)(o,{}),`e.g., `,(0,W.jsx)(f,{bold:!0,children:T({toolName:R.name})}),(0,W.jsx)(f,{bold:!1,children:` or `}),(0,W.jsx)(f,{bold:!0,children:T({toolName:z.name,ruleContent:`ls:*`})})]}),(0,W.jsx)(v,{borderDimColor:!0,borderStyle:`round`,marginY:1,paddingLeft:1,children:(0,W.jsx)(ie,{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,W.jsx)(v,{marginLeft:3,children:u.pending?(0,W.jsxs)(f,{dimColor:!0,children:[`Press `,u.keyName,` again to exit`]}):(0,W.jsx)(f,{dimColor:!0,children:`Enter to submit · Esc to cancel`})})]})}var ze,W,Be=e((()=>{n(),c(),ze=t(c(),1),P(),Se(),be(),_(),xe(),I(),F(),w(),W=b()}));function Ve({onHeaderFocusChange:e,onStateChange:t}){let{headerFocused:n,focusHeader:r}=m();(0,G.useEffect)(()=>{e?.(n)},[n,e]);let[i]=(0,G.useState)(()=>je()),[a,o]=(0,G.useState)(()=>new Set),[s,c]=(0,G.useState)(()=>new Set),[l,u]=(0,G.useState)(0);(0,G.useEffect)(()=>{t({approved:a,retry:s,denials:i})},[a,s,i,t]);let d=(0,G.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,G.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,K.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,K.jsxs)(f,{children:[(0,K.jsx)(g,{status:n?`success`:`error`,withSpace:!0}),e.display,(0,K.jsx)(f,{dimColor:!0,children:r})]}),value:String(t)}});return(0,K.jsxs)(v,{flexDirection:`column`,children:[(0,K.jsx)(f,{children:`Commands recently denied by the auto mode classifier.`}),(0,K.jsx)(v,{marginTop:1,children:(0,K.jsx)(L,{options:h,onChange:d,onFocus:p,visibleOptionCount:Math.min(10,h.length),isDisabled:n,onUpFromFirstItem:r})})]})}var G,K,He=e((()=>{c(),G=t(c(),1),_(),Ae(),N(),K=b()}));function Ue({directoryPath:e,onRemove:t,onCancel:n,permissionContext:r,setPermissionContext:i}){let a=(0,q.useCallback)(()=>{i(he(r,{type:`removeDirectories`,directories:[e],destination:`session`})),t()},[e,r,i,t]),o=(0,q.useCallback)(e=>{e===`yes`?a():n()},[a,n]);return(0,J.jsxs)(p,{title:`Remove directory from workspace?`,onCancel:n,color:`error`,children:[(0,J.jsx)(v,{marginX:2,flexDirection:`column`,children:(0,J.jsx)(f,{bold:!0,children:e})}),(0,J.jsx)(f,{children:`Claude Code will no longer have access to files in this directory.`}),(0,J.jsx)(L,{onChange:o,onCancel:n,options:[{label:`Yes`,value:`yes`},{label:`No`,value:`no`}]})]})}var q,J,We=e((()=>{c(),q=t(c(),1),N(),_(),B(),J=b()}));function Ge({onExit:e,toolPermissionContext:t,onRequestAddDirectory:n,onRequestRemoveDirectory:i,onHeaderFocusChange:a}){let{headerFocused:o,focusHeader:s}=m();(0,Y.useEffect)(()=>{a?.(o)},[o,a]);let c=Ke.useMemo(()=>Array.from(t.additionalWorkingDirectories.keys()).map(e=>({path:e,isCurrent:!1,isDeletable:!0})),[t.additionalWorkingDirectories]),l=(0,Y.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,Y.useCallback)(()=>e(`Workspace dialog dismissed`,{display:`system`}),[e]),d=Ke.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,X.jsxs)(v,{flexDirection:`column`,marginBottom:1,children:[(0,X.jsxs)(v,{flexDirection:`row`,marginTop:1,marginLeft:2,gap:1,children:[(0,X.jsx)(f,{children:`- ${x()}`}),(0,X.jsx)(f,{dimColor:!0,children:`(Original working directory)`})]}),(0,X.jsx)(L,{options:d,onChange:l,onCancel:u,visibleOptionCount:Math.min(10,d.length),onUpFromFirstItem:s,isDisabled:o})]})}var Ke,Y,X,qe=e((()=>{n(),Ke=t(c(),1),Y=t(c(),1),re(),N(),_(),X=b()}));function Je({rule:e}){return(0,$.jsx)(f,{dimColor:!0,children:`From ${_e(e.source)}`})}function Ye(e){switch(e){case`allow`:return`allowed`;case`deny`:return`denied`;case`ask`:return`ask`}}function Xe({rule:e,onDelete:t,onCancel:n}){let r=Ce();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)(Me,{ruleValue:e.ruleValue}),(0,$.jsx)(Je,{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 `,Ye(e.ruleBehavior),` tool?`]}),i,(0,$.jsx)(f,{children:`Are you sure you want to delete this permission rule?`}),(0,$.jsx)(L,{onChange:e=>e===`yes`?t():n(),onCancel:n,options:[{label:`Yes`,value:`yes`},{label:`No`,value:`no`}]})]}),a]})}function Ze(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)(L,{options:t,onChange:a,onCancel:o,visibleOptionCount:Math.min(10,t.length),isDisabled:r||p,defaultFocusValue:s,onUpFromFirstItem:h})]})}function Z({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)(Ze,{options:t(e,r.searchQuery).options,onSelect:t=>n(t,e),...r})]})}function Qe({onExit:e,initialTab:t,onRetryDenials:n}){let i=je().length>0,o=t??(i?`recent`:`allow`),[s,c]=(0,Q.useState)([]),u=ue(e=>e.toolPermissionContext),d=oe(),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,ie]=(0,Q.useState)(!0),P=(0,Q.useCallback)(e=>{ie(e)},[]),se=(0,Q.useMemo)(()=>{let e=new Map;return ae(u).forEach(t=>{e.set(j(t),t)}),e},[u]),ce=(0,Q.useMemo)(()=>{let e=new Map;return pe(u).forEach(t=>{e.set(j(t),t)}),e},[u]),le=(0,Q.useMemo)(()=>{let e=new Map;return de(u).forEach(t=>{e.set(j(t),t)}),e},[u]),F=(0,Q.useCallback)((e,t=``)=>{let n=(()=>{switch(e){case`allow`:return se;case`deny`:return ce;case`ask`:return le;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}},[se,ce,le]),I=Ce(),L=!_&&!x&&!C&&!E&&!O,{query:me,setQuery:R,cursorOffset:z}=De({isActive:L&&A,onExit:()=>{M(!1)}}),ge=(0,Q.useCallback)(e=>{L&&(A||e.ctrl||e.meta||(e.key===`/`?(e.preventDefault(),M(!0),R(``)):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),R(e.key))))},[L,A,R]),B=(0,Q.useCallback)((e,t)=>{let{rulesByKey:n}=F(t);if(e===`add-new-rule`){S(t);return}else{y(n.get(e));return}},[F]),_e=(0,Q.useCallback)(()=>{S(null)},[]),ve=(0,Q.useCallback)((e,t)=>{w({ruleValue:e,ruleBehavior:t}),S(null)},[]),be=(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}`)])}},[]),xe=(0,Q.useCallback)(()=>{w(null)},[]),Se=(0,Q.useCallback)(()=>D(!0),[]),we=(0,Q.useCallback)(e=>k(e),[]),Ee=(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`,Ee,{context:`Settings`,isActive:L&&!A});let Oe=()=>{if(!_)return;let{options:e}=F(_.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),fe({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)(Xe,{rule:_,onDelete:Oe,onCancel:()=>y(void 0)});if(x&&x!==`workspace`&&x!==`recent`)return(0,$.jsx)(Re,{onCancel:_e,onSubmit:ve,ruleBehavior:x});if(C)return(0,$.jsx)(Fe,{onAddRules:be,onCancel:xe,ruleValues:[C.ruleValue],ruleBehavior:C.ruleBehavior,initialContext:u,setToolPermissionContext:e=>{d(t=>({...t,toolPermissionContext:e}))}});if(E)return(0,$.jsx)(Te,{onAddDirectory:(e,t)=>{let n={type:`addDirectories`,directories:[e],destination:t?`localSettings`:`session`},r=he(u,n);d(e=>({...e,toolPermissionContext:r})),t&&ye(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)(Ue,{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 V={searchQuery:me,isSearchMode:A,isFocused:p,onCancel:Ee,lastFocusedRuleKey:b,cursorOffset:z,getRulesOptions:F,handleToolSelect:B,onHeaderFocusChange:P};return(0,$.jsx)(v,{flexDirection:`column`,onKeyDown:ge,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)(Ve,{onHeaderFocusChange:P,onStateChange:g})}),(0,$.jsx)(h,{id:`allow`,title:`Allow`,children:(0,$.jsx)(Z,{tab:`allow`,...V})}),(0,$.jsx)(h,{id:`ask`,title:`Ask`,children:(0,$.jsx)(Z,{tab:`ask`,...V})}),(0,$.jsx)(h,{id:`deny`,title:`Deny`,children:(0,$.jsx)(Z,{tab:`deny`,...V})}),(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)(Ge,{onExit:e,toolPermissionContext:u,onRequestAddDirectory:Se,onRequestRemoveDirectory:we,onHeaderFocusChange:P})]})})]}),(0,$.jsx)(v,{marginTop:1,paddingLeft:1,children:(0,$.jsx)(f,{dimColor:!0,children:I.pending?(0,$.jsxs)($.Fragment,{children:[`Press `,I.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),le(),B(),N(),Se(),Oe(),_(),xe(),Ae(),w(),se(),M(),Ee(),Le(),we(),Ne(),Be(),He(),We(),qe(),$=b()})),et,tt;e((()=>{$e(),ce(),et=b(),tt=async(e,t)=>(0,et.jsx)(Qe,{onExit:e,onRetryDenials:e=>{t.setMessages(t=>[...t,me(e)])}})}))();export{tt as call};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{n as e,t}from"./pluginStartupCheck-RRcAbKfx.js";e();export{t as getPluginEditableScopes};
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import{n as e,t}from"./figures-gfT9mM8P.js";import{Or as n,cn as r}from"./state-sIHsFpDu.js";import{Po as i,jo as a}from"./paths-1ngPRtu3.js";import{E as o,L as s,V as c,w as l}from"./debug-UI3T040K.js";import{n as u,r as d}from"./analytics-DqMQntaB.js";import{o as f,s as p}from"./log-CzsijfHZ.js";import{$s as m,As as h,Es as g,Ew as _,FA as v,Fs as y,Gs as b,Hs as x,IA as S,Ms as C,Tw as w,Vs as T,Ws as ee,Ys as te,ac as ne,fs as E,lc as D,ps as O,qs as k,sc as A,uc as j}from"./loadAgentsDir-D7kapZB5.js";import{i as M,o as N,s as P}from"./xml-DTMvLcPg.js";import{n as F,t as I}from"./exit-_obETqBv.js";import{n as L,t as R}from"./pluginOperations-C9XP-mko.js";import{a as z,i as B,n as V,o as H,r as U,t as W}from"./pluginCliCommands-vqAtVibb.js";import{a as re,c as G,i as K,n as q,r as J,s as Y,t as X}from"./validatePlugin-DpHiJRsT.js";import{basename as ie,dirname as Z}from"path";e(),r(),u(),S(),c(),f(),j(),G(),g(),ne(),T(),w(),K(),M(),E(),X(),l(),a();function Q(e,n){p(e),I(`${t.cross} Failed to ${n}: ${s(e)}`)}function $(e){e.errors.length>0&&(console.log(`${t.cross} Found ${e.errors.length} ${i(e.errors.length,`error`)}:\n`),e.errors.forEach(e=>{console.log(` ${t.pointer} ${e.path}: ${e.message}`)}),console.log(``)),e.warnings.length>0&&(console.log(`${t.warning} Found ${e.warnings.length} ${i(e.warnings.length,`warning`)}:\n`),e.warnings.forEach(e=>{console.log(` ${t.pointer} ${e.path}: ${e.message}`)}),console.log(``))}async function ae(e,r){r.cowork&&n(!0);try{let n=await q(e);console.log(`Validating ${n.fileType} manifest: ${n.filePath}\n`),$(n);let r=[];if(n.fileType===`plugin`){let e=Z(n.filePath);if(ie(e)===`.claude-plugin`){r=await J(Z(e));for(let e of r)console.log(`Validating ${e.fileType}: ${e.filePath}\n`),$(e)}}let i=n.success&&r.every(e=>e.success),a=n.warnings.length>0||r.some(e=>e.warnings.length>0);i?F(a?`${t.tick} Validation passed with warnings`:`${t.tick} Validation passed`):(console.log(`${t.cross} Validation failed`),process.exit(1))}catch(e){p(e),console.error(`${t.cross} Unexpected error during validation: ${s(e)}`),process.exit(2)}}async function oe(e){e.cowork&&n(!0),d(`tengu_plugin_list_command`,{});let r=C(),{getPluginEditableScopes:i}=await import(`./pluginStartupCheck-DZp0wnXP.js`),a=i(),s=Object.keys(r.plugins),{enabled:c,disabled:l,errors:u}=await O(),f=[...c,...l],p=f.filter(e=>e.source.endsWith(`@inline`)),g=u.filter(e=>e.source.endsWith(`@inline`)||e.source.startsWith(`inline[`));if(e.json){let t=new Map(f.map(e=>[e.source,e])),n=[];for(let e of s.sort()){let i=r.plugins[e];if(!i||i.length===0)continue;let o=N(e).name,s=u.filter(t=>t.source===e||`plugin`in t&&t.plugin===o).map(v);for(let r of i){let i=t.get(e),o;if(i){let e=i.mcpServers||await _(i);e&&Object.keys(e).length>0&&(o=e)}n.push({id:e,version:r.version||`unknown`,scope:r.scope,enabled:a.has(e),installPath:r.installPath,installedAt:r.installedAt,lastUpdated:r.lastUpdated,projectPath:r.projectPath,mcpServers:o,errors:s.length>0?s:void 0})}}for(let e of p){let t=e.mcpServers||await _(e),r=g.filter(t=>t.source===e.source||`plugin`in t&&t.plugin===e.name).map(v);n.push({id:e.source,version:e.manifest.version??`unknown`,scope:`session`,enabled:e.enabled!==!1,installPath:e.path,mcpServers:t&&Object.keys(t).length>0?t:void 0,errors:r.length>0?r:void 0})}for(let e of g.filter(e=>e.source.startsWith(`inline[`)))n.push({id:e.source,version:`unknown`,scope:`session`,enabled:!1,installPath:`path`in e?e.path:``,errors:[v(e)]});if(e.available){let e=[];try{let[t,n]=await Promise.all([x(),Y()]),{marketplaces:r}=await A(t);for(let{name:t,data:i}of r)if(i)for(let r of i.plugins){let i=m(r.name,t);h(i)||e.push({pluginId:i,name:r.name,description:r.description,marketplaceName:t,version:r.version,source:r.source,installCount:n?.get(i)})}}catch{}F(o({installed:n,available:e},null,2))}else F(o(n,null,2))}s.length===0&&p.length===0&&g.length===0&&F("No plugins installed. Use `claude plugin install` to install a plugin."),s.length>0&&console.log(`Installed plugins:
|
|
2
|
-
`);for(let e of s.sort()){let n=r.plugins[e];if(!n||n.length===0)continue;let i=N(e).name,o=u.filter(t=>t.source===e||`plugin`in t&&t.plugin===i);for(let r of n){let n=a.has(e),i=o.length>0?`${t.cross} failed to load`:n?`${t.tick} enabled`:`${t.cross} disabled`,s=r.version||`unknown`,c=r.scope;console.log(` ${t.pointer} ${e}`),console.log(` Version: ${s}`),console.log(` Scope: ${c}`),console.log(` Status: ${i}`);for(let e of o)console.log(` Error: ${v(e)}`);console.log(``)}}if(p.length>0||g.length>0){console.log(`Session-only plugins (--plugin-dir):
|
|
3
|
-
`);for(let e of p){let n=g.filter(t=>t.source===e.source||`plugin`in t&&t.plugin===e.name),r=n.length>0?`${t.cross} loaded with errors`:`${t.tick} loaded`;console.log(` ${t.pointer} ${e.source}`),console.log(` Version: ${e.manifest.version??`unknown`}`),console.log(` Path: ${e.path}`),console.log(` Status: ${r}`);for(let e of n)console.log(` Error: ${v(e)}`);console.log(``)}for(let e of g.filter(e=>e.source.startsWith(`inline[`)))console.log(` ${t.pointer} ${e.source}: ${t.cross} ${v(e)}\n`)}F()}async function se(e,r){r.cowork&&n(!0);try{let n=await re(e);n||I(`${t.cross} Invalid marketplace source format. Try: owner/repo, https://..., or ./path`),`error`in n&&I(`${t.cross} ${n.error}`);let i=r.scope??`user`;i!==`user`&&i!==`project`&&i!==`local`&&I(`${t.cross} Invalid scope '${i}'. Use: user, project, or local`);let a=P(i),o=n;r.sparse&&r.sparse.length>0&&(o.source===`github`||o.source===`git`?o={...o,sparsePaths:r.sparse}:I(`${t.cross} --sparse is only supported for github and git marketplace sources (got: ${o.source})`)),console.log(`Adding marketplace...`);let{name:s,alreadyMaterialized:c,resolvedSource:l}=await y(o,e=>{console.log(e)});te(s,{source:l},a),D();let u=o.source;o.source===`github`&&(u=o.repo),d(`tengu_marketplace_added`,{source_type:u}),F(c?`${t.tick} Marketplace '${s}' already on disk — declared in ${i} settings`:`${t.tick} Successfully added marketplace: ${s} (declared in ${i} settings)`)}catch(e){Q(e,`add marketplace`)}}async function ce(e){e.cowork&&n(!0);try{let n=await x(),r=Object.keys(n);e.json&&F(o(r.sort().map(e=>{let t=n[e],r=t?.source;return{name:e,source:r?.source,...r?.source===`github`&&{repo:r.repo},...r?.source===`git`&&{url:r.url},...r?.source===`url`&&{url:r.url},...r?.source===`directory`&&{path:r.path},...r?.source===`file`&&{path:r.path},installLocation:t?.installLocation}}),null,2)),r.length===0&&F(`No marketplaces configured`),console.log(`Configured marketplaces:
|
|
4
|
-
`),r.forEach(e=>{let r=n[e];if(console.log(` ${t.pointer} ${e}`),r?.source){let e=r.source;e.source===`github`?console.log(` Source: GitHub (${e.repo})`):e.source===`git`?console.log(` Source: Git (${e.url})`):e.source===`url`?console.log(` Source: URL (${e.url})`):e.source===`directory`?console.log(` Source: Directory (${e.path})`):e.source===`file`&&console.log(` Source: File (${e.path})`)}console.log(``)}),F()}catch(e){Q(e,`list marketplaces`)}}async function le(e,r){r.cowork&&n(!0);try{await k(e),D(),d(`tengu_marketplace_removed`,{marketplace_name:e}),F(`${t.tick} Successfully removed marketplace: ${e}`)}catch(e){Q(e,`remove marketplace`)}}async function ue(e,r){r.cowork&&n(!0);try{if(e)console.log(`Updating marketplace: ${e}...`),await b(e,e=>{console.log(e)}),D(),d(`tengu_marketplace_updated`,{marketplace_name:e}),F(`${t.tick} Successfully updated marketplace: ${e}`);else{let e=await x(),n=Object.keys(e);n.length===0&&F(`No marketplaces configured`),console.log(`Updating ${n.length} marketplace(s)...`),await ee(),D(),d(`tengu_marketplace_updated_all`,{count:n.length}),F(`${t.tick} Successfully updated ${n.length} marketplace(s)`)}}catch(e){Q(e,`update marketplace(s)`)}}async function de(e,t){t.cowork&&n(!0);let r=t.scope||`user`;t.cowork&&r!==`user`&&I(`--cowork can only be used with user scope`),R.includes(r)||I(`Invalid scope: ${r}. Must be one of: ${R.join(`, `)}.`);let{name:i,marketplace:a}=N(e);d(`tengu_plugin_install_command`,{_PROTO_plugin_name:i,...a&&{_PROTO_marketplace_name:a},scope:r}),await B(e,r)}async function fe(e,t){t.cowork&&n(!0);let r=t.scope||`user`;t.cowork&&r!==`user`&&I(`--cowork can only be used with user scope`),R.includes(r)||I(`Invalid scope: ${r}. Must be one of: ${R.join(`, `)}.`);let{name:i,marketplace:a}=N(e);d(`tengu_plugin_uninstall_command`,{_PROTO_plugin_name:i,...a&&{_PROTO_marketplace_name:a},scope:r}),await z(e,r,t.keepData)}async function pe(e,t){t.cowork&&n(!0);let r;t.scope&&(R.includes(t.scope)||I(`Invalid scope "${t.scope}". Valid scopes: ${R.join(`, `)}`),r=t.scope),t.cowork&&r!==void 0&&r!==`user`&&I(`--cowork can only be used with user scope`),t.cowork&&r===void 0&&(r=`user`);let{name:i,marketplace:a}=N(e);d(`tengu_plugin_enable_command`,{_PROTO_plugin_name:i,...a&&{_PROTO_marketplace_name:a},scope:r??`auto`}),await U(e,r)}async function me(e,t){if(t.all&&e&&I(`Cannot use --all with a specific plugin`),!t.all&&!e&&I(`Please specify a plugin name or use --all to disable all plugins`),t.cowork&&n(!0),t.all){t.scope&&I(`Cannot use --scope with --all`),d(`tengu_plugin_disable_command`,{}),await W();return}let r;t.scope&&(R.includes(t.scope)||I(`Invalid scope "${t.scope}". Valid scopes: ${R.join(`, `)}`),r=t.scope),t.cowork&&r!==void 0&&r!==`user`&&I(`--cowork can only be used with user scope`),t.cowork&&r===void 0&&(r=`user`);let{name:i,marketplace:a}=N(e);d(`tengu_plugin_disable_command`,{_PROTO_plugin_name:i,...a&&{_PROTO_marketplace_name:a},scope:r??`auto`}),await V(e,r)}async function he(e,t){t.cowork&&n(!0);let{name:r,marketplace:i}=N(e);d(`tengu_plugin_update_command`,{_PROTO_plugin_name:r,...i&&{_PROTO_marketplace_name:i}});let a=`user`;t.scope&&(L.includes(t.scope)||I(`Invalid scope "${t.scope}". Valid scopes: ${L.join(`, `)}`),a=t.scope),t.cowork&&a!==`user`&&I(`--cowork can only be used with user scope`),await H(e,a)}export{se as marketplaceAddHandler,ce as marketplaceListHandler,le as marketplaceRemoveHandler,ue as marketplaceUpdateHandler,me as pluginDisableHandler,pe as pluginEnableHandler,de as pluginInstallHandler,oe as pluginListHandler,fe as pluginUninstallHandler,he as pluginUpdateHandler,ae as pluginValidateHandler};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Ba as e,Ka as t,Ra as n}from"./loadAgentsDir-D7kapZB5.js";n();export{e as isPolicyAllowed,t as waitForPolicyLimitsToLoad};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{n as e,t}from"./poorMode-CsGLI_hm.js";t();export{e as isPoorModeActive};
|
|
@@ -1,39 +0,0 @@
|
|
|
1
|
-
import{a as e}from"./chunk-DR8-3Aex.js";import{c as t,l as n,s as r,u as i}from"./envUtils-BWeoiL4Y.js";import{n as a,t as o}from"./defineProperty-80gRi2ZW.js";import{B as s,b as c,v as l}from"./server-DzOdtq8A.js";import{Ct as u,F as d,In as f,R as p,Tn as m,Vn as h,_n as g,_r as ee,cn as _,jr as te,ln as v,nr as y,tr as b,tt as x,y as S}from"./state-sIHsFpDu.js";import{Aa as C,Br as w,Bt as ne,C as re,Cr as ie,Dr as ae,El as T,Et as oe,Fa as se,Ki as ce,Ma as E,Ml as le,Na as ue,Ot as D,Pr as O,Rr as de,S as fe,Si as pe,Tl as me,Xn as he,Xo as k,Yn as A,_ as ge,a as _e,bl as ve,c as ye,jl as be,kt as xe,ls as Se,ms as Ce,no as j,on as we,oo as Te,pi as Ee,qi as De,ss as Oe,to as ke,vi as M,xi as Ae,xs as N,yi as je,yl as Me}from"./paths-1ngPRtu3.js";import{E as P,K as Ne,L as F,T as Pe,V as Fe,X as Ie,Y as Le,c as Re,d as I,h as ze,p as Be,s as L,w as R}from"./debug-UI3T040K.js";import{n as Ve,r as z}from"./analytics-DqMQntaB.js";import{n as He,t as Ue}from"./cwd--iizewsn.js";import{i as We,n as B,o as V}from"./process-DMKLUQIO.js";import{F as Ge,I as Ke,P as H}from"./git-CN3qtTb_.js";import{J as qe,K as Je,c as Ye,et as U,i as Xe,o as Ze,s as W}from"./log-CzsijfHZ.js";import{i as Qe,n as $e}from"./path-C4kbwvSH.js";import{s as et,u as tt}from"./types-Csi32ZXh.js";import{C as nt,c as rt,d as it,l as at,m as ot,s as st,x as G}from"./teammate-DMYOtLTK.js";import{n as ct,t as lt}from"./sleep-8Eb9j_Ly.js";import{$A as ut,$E as dt,$r as ft,AO as pt,Ar as mt,BD as ht,BE as gt,BT as _t,Ba as vt,CC as yt,CO as bt,Cn as xt,D as St,DE as Ct,Di as wt,Dv as Tt,Dx as Et,EC as Dt,Ei as Ot,Ev as kt,F as At,FD as jt,Fc as Mt,G as Nt,Gi as Pt,Hi as Ft,ID as It,I_ as Lt,Ic as Rt,Is as zt,JE as Bt,JT as K,Jv as Vt,K as Ht,Ks as Ut,LD as Wt,LS as Gt,L_ as Kt,Lo as qt,Ls as Jt,MD as Yt,Ml as Xt,ND as Zt,NT as Qt,Nc as $t,Ny as en,O as tn,Of as nn,Or as rn,Ox as an,PD as on,Pc as sn,Py as cn,QC as ln,QD as un,QE as dn,Qv as fn,RD as pn,RS as mn,RT as hn,Ra as gn,S as _n,Sx as vn,TD as yn,TT as bn,Tv as xn,Tx as Sn,UD as Cn,UT as wn,Uh as Tn,Us as En,Uu as Dn,VD as On,VE as kn,Vs as An,Vt as jn,WA as Mn,WD as Nn,WT as Pn,Wu as Fn,XT as In,Xi as Ln,Xv as Rn,YC as zn,YD as Bn,YE as Vn,YT as Hn,ZE as Un,Zh as Wn,Zv as Gn,_E as Kn,_O as qn,_c as Jn,_v as Yn,aj as Xn,as as Zn,au as Qn,aw as $n,bE as er,bO as tr,bb as nr,bc as rr,bv as ir,cC as ar,cE as or,cO as sr,cs as cr,cw as lr,db as ur,di as dr,dw as fr,eg as pr,fc as mr,fi as hr,fj as gr,fs as _r,fw as vr,gO as yr,gc as br,gi as xr,gw as Sr,gx as Cr,hO as wr,hc as Tr,hi as Er,ip as Dr,ir as Or,jD as q,jl as kr,kE as Ar,kO as jr,kf as Mr,kr as Nr,lC as Pr,lE as Fr,lO as Ir,la as Lr,lr as Rr,mA as zr,mc as Br,ms as Vr,nj as Hr,nu as Ur,ny as Wr,o as Gr,oA as Kr,oC as qr,os as Jr,ow as Yr,p as Xr,pc as Zr,po as Qr,qE as $r,qT as ei,qu as ti,rA as ni,rp as ri,ru as ii,ry as ai,s as oi,sE as si,sb as ci,tg as li,tj as ui,u as di,uE as fi,uO as J,uj as pi,vA as mi,vE as hi,vc as gi,vi as _i,vx as vi,w as yi,wC as bi,wD as xi,wT as Si,wn as Ci,wv as wi,x as Ti,xE as Ei,xc as Di,xv as Oi,yb as ki,yc as Ai,yn as ji,yx as Mi,zC as Ni,zD as Pi,zi as Fi}from"./loadAgentsDir-D7kapZB5.js";import{F as Ii,Hn as Li,Ht as Ri,M as zi,Nt as Bi,Pt as Vi,Vn as Hi,_t as Ui,pn as Wi,vt as Gi,xn as Ki}from"./prompt-BBg3jtfc.js";import{i as qi,o as Ji}from"./xml-DTMvLcPg.js";import{a as Yi,o as Xi,s as Zi}from"./fileStateCache-C7-TxF8G.js";import{A as Qi,C as $i,D as ea,N as ta,O as na,P as ra,Z as ia,_ as aa,d as oa,g as sa,h as ca,m as la,u as ua,v as da,y as fa}from"./rcDebugLog-CPGWJbI4.js";import{c as pa,l as ma}from"./commitAttribution-e0kkanVT.js";import{P as ha,V as ga,a as _a,d as va}from"./teamHelpers-DEgaCpta.js";import{t as ya}from"./pollConfig-DTYIJ8lQ.js";import{r as ba}from"./inboundAttachments-7rXrAtkb.js";import{i as xa,n as Sa,s as Ca}from"./mappers-CkMESMy7.js";import{n as wa,r as Ta}from"./sessionTitle-QxXslbJY.js";import{n as Ea,t as Da}from"./ccrClient-B_3AmY7K.js";import{n as Oa,t as ka}from"./HybridTransport-CAko699F.js";import{n as Aa,t as ja}from"./SSETransport-B5xlXeAN.js";import{t as Ma}from"./pluginBlocklist-BG2LkLq1.js";import{c as Na,d as Pa,f as Fa,l as Ia,o as La,r as Ra,s as za,u as Ba}from"./channelNotification-BbDQdLZC.js";import{t as Va}from"./onChangeAppState-Cb9_yIuW.js";import{t as Ha}from"./settingsSync-DEPET5O1.js";import{a as Ua,c as Wa,d as Ga,f as Ka,l as qa,m as Ja,o as Ya,p as Xa,r as Za,t as Qa}from"./cronJitterConfig-DcMGWOa-.js";import{i as $a,n as eo}from"./toolPool-BHChMuLr.js";import{n as to,r as no}from"./QueryEngine-I3Bqzbiz.js";import{n as ro,r as io}from"./sideQuestion-B9EE1vTM.js";import{n as ao,r as oo}from"./context-noninteractive-IZfWniex.js";import{a as so,o as co,t as lo}from"./skillChangeDetector-DnyEQqe6.js";import{n as uo,t as fo}from"./refresh-Cjv4jA6L.js";import{dirname as po,join as mo}from"path";import{PassThrough as ho}from"stream";import{randomUUID as Y}from"crypto";import{readFile as go,stat as _o}from"fs/promises";import{URL as vo}from"url";import{cwd as X}from"process";a(),_(),He(),Le(),Fe(),R(),ze(),B(),L(),H(),U(),Ze(),Qe(),et(),G(),N(),Te(),se(),E(),De(),O(),A(),lt(),we(),at(),fe(),_e(),Hi(),Ki(),zr(),Kr(),qn(),jt(),yn(),kn(),ta(),hi(),ha(),Hn(),Qt(),na(),Lt(),oa(),Mt(),sn(),Jr(),qt(),Ln(),mt(),Ci(),ji(),Ha(),r(),Aa();function yo(e,t={},n,r){if(i(process.env.CLAUDE_CODE_USE_CCR_V2)){let i=new vo(e.href);return i.protocol===`wss:`?i.protocol=`https:`:i.protocol===`ws:`&&(i.protocol=`http:`),i.pathname=i.pathname.replace(/\/$/,``)+`/worker/events/stream`,new ja(i,t,n,r)}if(e.protocol===`ws:`||e.protocol===`wss:`)return i(process.env.CLAUDE_CODE_POST_FOR_SESSION_INGRESS_V2)?new ka(e,t,n,r):new Oa(e,t,n,r);throw Error(`Unsupported protocol: ${e.protocol}`)}r(),Aa();var bo=class extends Ga{constructor(e,t,n){let r=new ho({encoding:`utf8`});super(r,n),o(this,`url`,void 0),o(this,`transport`,void 0),o(this,`inputStream`,void 0),o(this,`isBridge`,!1),o(this,`isDebug`,!1),o(this,`ccrClient`,null),o(this,`keepAliveTimer`,null),this.inputStream=r,this.url=new vo(e);let a={},s=ea();s?a.Authorization=`Bearer ${s}`:I(`[remote-io] No session ingress token available`,{level:`error`});let c=process.env.CLAUDE_CODE_ENVIRONMENT_RUNNER_VERSION;if(c&&(a[`x-environment-runner-version`]=c),this.transport=yo(this.url,a,u(),()=>{let e={},t=ea();t&&(e.Authorization=`Bearer ${t}`);let n=process.env.CLAUDE_CODE_ENVIRONMENT_RUNNER_VERSION;return n&&(e[`x-environment-runner-version`]=n),e}),this.isBridge=process.env.CLAUDE_CODE_ENVIRONMENT_KIND===`bridge`,this.isDebug=Re(),this.transport.setOnData(e=>{this.inputStream.write(e),this.isBridge&&this.isDebug&&V(e.endsWith(`
|
|
2
|
-
`)?e:e+`
|
|
3
|
-
`)}),this.transport.setOnClose(()=>{this.inputStream.end()}),i(process.env.CLAUDE_CODE_USE_CCR_V2)){if(!(this.transport instanceof ja))throw Error(`CCR v2 requires SSETransport; check getTransportForUrl`);this.ccrClient=new Da(this.transport,this.url);let e=this.ccrClient.initialize();this.restoredWorkerState=e.catch(()=>null),e.catch(e=>{Ge(`error`,`cli_worker_lifecycle_init_failed`,{reason:e instanceof Ea?e.reason:`unknown`}),W(Error(`CCRClient initialization failed: ${F(e)}`)),ei(1,`other`)}),Ie(async()=>this.ccrClient?.close()),wt((e,t,n)=>this.ccrClient.writeInternalEvent(e,t,n)),Ot(()=>this.ccrClient.readInternalEvents(),()=>this.ccrClient.readSubagentInternalEvents());let t={started:`processing`,completed:`processed`};Wt((e,n)=>{this.ccrClient?.reportDelivery(e,t[n])}),da((e,t)=>{this.ccrClient?.reportState(e,t)}),aa(e=>{this.ccrClient?.reportMetadata(e)},{replayCurrent:!0})}this.transport.connect();let l=ya().session_keepalive_interval_v2_ms;if(this.isBridge&&l>0&&(this.keepAliveTimer=setInterval(()=>{I(`[remote-io] keep_alive sent`),this.write({type:`keep_alive`}).catch(e=>{I(`[remote-io] keep_alive write failed: ${F(e)}`)})},l),this.keepAliveTimer.unref?.()),Ie(async()=>this.close()),t){let e=this.inputStream;(async()=>{for await(let n of t)e.write(String(n).replace(/\n$/,``)+`
|
|
4
|
-
`)})()}}flushInternalEvents(){return this.ccrClient?.flushInternalEvents()??Promise.resolve()}get internalEventsPending(){return this.ccrClient?.internalEventsPending??0}async write(e){this.ccrClient?await this.ccrClient.writeEvent(e):await this.transport.write(e),this.isBridge&&(e.type===`control_request`||this.isDebug)&&V(Ka(e)+`
|
|
5
|
-
`)}close(){this.keepAliveTimer&&(clearInterval(this.keepAliveTimer),this.keepAliveTimer=null),this.transport.close(),this.inputStream.end()}};Wi(),k(),Ri(),Vi(),[...Bi],Le(),L();var xo=`[stdout-guard]`,So=!1,Z=``,Co=null;function wo(e){if(e.length===0)return!0;try{return JSON.parse(e),!0}catch{return!1}}function To(){So||(So=!0,Co=process.stdout.write.bind(process.stdout),process.stdout.write=function(e,t,n){let r=typeof e==`string`?e:Buffer.from(e).toString(`utf-8`);Z+=r;let i,a=!0;for(;(i=Z.indexOf(`
|
|
6
|
-
`))!==-1;){let e=Z.slice(0,i);Z=Z.slice(i+1),wo(e)?a=Co(e+`
|
|
7
|
-
`):(process.stderr.write(`${xo} ${e}\n`),I(`streamJsonStdoutGuard diverted non-JSON stdout line: ${e.slice(0,200)}`))}let o=typeof t==`function`?t:n;return o&&queueMicrotask(()=>o()),a},Ie(async()=>{Z.length>0&&(Co&&wo(Z)?Co(Z+`
|
|
8
|
-
`):process.stderr.write(`${xo} ${Z}\n`),Z=``),Co&&(process.stdout.write=Co,Co=null),So=!1}))}Me(),Se(),pi(),ut(),qi(),Gi(),Xi(),ra(),dn(),Ar(),fr(),ln(),ai(),wi(),ir(),ti(),Ai(),An(),_r(),Ht(),Gr(),Ba(),Na(),eo(),Yn(),Fe(),Ze(),na(),Vt(),L(),Hn();function Eo(e){let t=process.env.CLAUDE_CODE_EXIT_AFTER_STOP_DELAY,n=t?parseInt(t,10):null,r=n&&!isNaN(n)&&n>0,i=null,a=0;return{start(){i&&(clearTimeout(i),i=null),r&&(a=Date.now(),i=setTimeout(()=>{let t=Date.now()-a;e()&&t>=n&&(I(`Exiting after ${n}ms of idle time`),K())},n))},stop(){i&&(clearTimeout(i),i=null)}}}be(),me(),M(),jr(),$r(),or(),bn(),mn(),ki(),ur(),Xt(),gn(),yi(),Ta(),ro();function Do(e){if(e.toLowerCase().endsWith(`.jsonl`))return{sessionId:Y(),ingressUrl:null,isUrl:!1,jsonlFile:e,isJsonlFile:!0};if(Kt(e))return{sessionId:e,ingressUrl:null,isUrl:!1,jsonlFile:null,isJsonlFile:!1};try{let t=new URL(e);return{sessionId:Y(),ingressUrl:t.href,isUrl:!0,jsonlFile:null,isJsonlFile:!1}}catch{}return null}s(),D(),Bn(),On(),Zt(),ma(),wn(),yt(),qr(),Sn(),Mr(),Ur(),Sa(),oo(),L();async function Oo(){try{let e=await go(br(),`utf-8`),t=Ce().safeParse(Pe(e));return t.success?t.data:(I(`Invalid known_marketplaces.json in zip cache: ${t.error.message}`,{level:`error`}),{})}catch{return{}}}async function ko(e){await mr(br(),P(e,null,2))}async function Ao(e,t){let n=Tr();if(!n)return;let r=await jo(t);r!==null&&await mr(mo(n,Br(e)),r)}async function jo(e){let t=[mo(e,`.claude-plugin`,`marketplace.json`),mo(e,`marketplace.json`),e];for(let e of t)try{return await go(e,`utf-8`)}catch{}return null}async function Mo(){let e=await En();for(let[t,n]of Object.entries(e))if(n.installLocation)try{await Ao(t,n.installLocation)}catch(e){I(`Failed to save marketplace JSON for ${t}: ${e}`)}await ko({...await Oo(),...e})}Ve(),Le(),L(),H(),Ze(),An(),Ai();async function No(){let e=Di();I(`installPluginsForHeadless: starting${e?` (zip cache mode)`:``}`);let t=await Ut();t&&(zt(),cr(`headlessPluginInstall: seed marketplaces registered`)),e&&(await Be().mkdir(Jn()),await Be().mkdir(gi()));let n=Object.keys(Jt()).length,r={marketplaces_installed:0,delisted_count:0},i=t;try{if(n===0)I(`installPluginsForHeadless: no marketplaces declared`);else{let t=await Ke(`headless_marketplace_reconcile`,()=>Wa({skip:e?(e,t)=>!rr(t):void 0,onProgress:e=>{e.type===`installed`?I(`installPluginsForHeadless: installed marketplace ${e.name}`):e.type===`failed`&&I(`installPluginsForHeadless: failed to install marketplace ${e.name}: ${e.error}`)}}),e=>({installed_count:e.installed.length,updated_count:e.updated.length,failed_count:e.failed.length,skipped_count:e.skipped.length}));t.skipped.length>0&&I(`installPluginsForHeadless: skipped ${t.skipped.length} marketplace(s) unsupported by zip cache: ${t.skipped.join(`, `)}`);let n=t.installed.length+t.updated.length;n>0&&(zt(),cr(`headlessPluginInstall: marketplaces reconciled`),i=!0),r.marketplaces_installed=n}e&&await Mo();let t=await Ma();return r.delisted_count=t.length,t.length>0&&(i=!0),i&&cr(`headlessPluginInstall: plugins changed`),e&&Ie(Zr),i}catch(e){return W(e),!1}finally{z(`tengu_headless_plugin_install`,r)}}Ve(),L(),H(),jt(),oa(),Ze(),B(),Lt(),Hn(),Le(),He(),_(),mt(),qt(),R(),r(),fo(),_r(),Tn(),_a(),Ei(),en(),ri(),Fe();var Q=(fi(),e(Fr)),$=(fa(),e($i)),Po=(Ya(),e(Ua)),Fo=(Za(),e(Qa)),Io=(zi(),e(Ii)),Lo=`<system-reminder>
|
|
9
|
-
You are running in non-interactive mode and cannot return a response to the user until your team is shut down.
|
|
10
|
-
|
|
11
|
-
You MUST shut down your team before preparing your final response:
|
|
12
|
-
1. Use requestShutdown to ask each team member to shut down gracefully
|
|
13
|
-
2. Wait for shutdown approvals
|
|
14
|
-
3. Use the cleanup operation to clean up the team
|
|
15
|
-
4. Only then provide your final response to the user
|
|
16
|
-
|
|
17
|
-
The user cannot receive your response until the team is completely shut down.
|
|
18
|
-
</system-reminder>
|
|
19
|
-
|
|
20
|
-
Shut down your team and prepare your final response for the user.`,Ro=1e4,zo=new Set,Bo=[];function Vo(e){if(zo.has(e))return!1;if(zo.add(e),Bo.push(e),Bo.length>Ro){let e=Bo.splice(0,Bo.length-Ro);for(let t of e)zo.delete(t)}return!0}function Ho(e){return typeof e==`string`?[{type:`text`,text:e}]:e}function Uo(e){return e.length===1?e[0]:e.every(e=>typeof e==`string`)?e.join(`
|
|
21
|
-
`):e.flatMap(Ho)}function Wo(e,t){return t!==void 0&&t.mode===`prompt`&&t.workload===e.workload&&t.isMeta===e.isMeta}async function Go(e,t,n,r,a,o,s,c){if(process.env.USER_TYPE===`ant`&&i(process.env.CLAUDE_CODE_EXIT_AFTER_FIRST_RENDER)&&(process.stderr.write(`\nStartup time: ${Math.round(process.uptime()*1e3)}ms\n`),process.exit(0)),mi.subscribe(e=>{Gt(e,n),Ae()&&n(e=>{let t=e.settings,n=t.fastMode===!0&&!t.fastModePerSessionOptIn;return{...e,fastMode:n}})}),$&&!$.isProactiveActive()&&i(process.env.CLAUDE_CODE_PROACTIVE)&&$.activateProactive(`command`),typeof Bun<`u`&&setInterval(()=>{process.memoryUsage.rss()>350*1024*1024?Bun.gc(!0):Bun.gc(!1)},1e3).unref(),Yt(),q(`runHeadless_entry`),await Pn()&&await _t(),q(`after_grove_check`),re(),c.resumeSessionAt&&!c.resume){process.stderr.write(`Error: --resume-session-at requires --resume
|
|
22
|
-
`),K(1);return}if(c.rewindFiles&&!c.resume){process.stderr.write(`Error: --rewind-files requires --resume
|
|
23
|
-
`),K(1);return}if(c.rewindFiles&&e){process.stderr.write(`Error: --rewind-files is a standalone operation and cannot be used with a prompt
|
|
24
|
-
`),K(1);return}let l=rs(e,c);c.outputFormat===`stream-json`&&To();let d=ni.getSandboxUnavailableReason();if(d){if(ni.isSandboxRequired()){process.stderr.write(`\nError: sandbox required but unavailable: ${d}\n sandbox.failIfUnavailable is set — refusing to start without a working sandbox.\n\n`),K(1);return}process.stderr.write(`\n⚠ Sandbox disabled: ${d}\n Commands will run WITHOUT sandboxing. Network and filesystem restrictions will NOT be enforced.\n\n`)}else if(ni.isSandboxingEnabled())try{await ni.initialize(l.createSandboxAskCallback())}catch(e){process.stderr.write(`\n❌ Sandbox Error: ${F(e)}\n`),K(1,`other`);return}c.outputFormat===`stream-json`&&c.verbose&&Rt(e=>{let t=(()=>{switch(e.type){case`started`:return{type:`system`,subtype:`hook_started`,hook_id:e.hookId,hook_name:e.hookName,hook_event:e.hookEvent,uuid:Y(),session_id:u()};case`progress`:return{type:`system`,subtype:`hook_progress`,hook_id:e.hookId,hook_name:e.hookName,hook_event:e.hookEvent,stdout:e.stdout,stderr:e.stderr,output:e.output,uuid:Y(),session_id:u()};case`response`:return{type:`system`,subtype:`hook_response`,hook_id:e.hookId,hook_name:e.hookName,hook_event:e.hookEvent,output:e.output,stdout:e.stdout,stderr:e.stderr,exit_code:e.exitCode,outcome:e.outcome,uuid:Y(),session_id:u()}}})();l.write(t)}),c.setupTrigger&&await kt(c.setupTrigger),q(`before_loadInitialMessages`);let f=t(),{messages:p,turnInterruptionState:m,agentSetting:h}=await ns(n,{continue:c.continue,teleport:c.teleport,resume:c.resume,resumeSessionAt:c.resumeSessionAt,forkSession:c.forkSession,outputFormat:c.outputFormat,sessionStartHooksPromise:c.sessionStartHooksPromise,restoredWorkerState:l.restoredWorkerState}),g=Tt();if(g&&l.prependUserMessage(g),!c.agent&&!x()&&h){let{agentDefinition:e}=so(h,void 0,{activeAgents:s,allAgents:s});if(e){if(n(t=>({...t,agent:e.agentType})),!c.systemPrompt&&!oi(e)){let t=e.getSystemPrompt();t&&(c.systemPrompt=t)}Er(e.agentType)}}if(p.length===0&&process.exitCode!==void 0)return;if(c.rewindFiles){let e=p.find(e=>e.uuid===c.rewindFiles);if(!e||e.type!==`user`){process.stderr.write(`Error: --rewind-files requires a user message UUID, but ${c.rewindFiles} is not a user message in this session\n`),K(1);return}let r=t(),i=await Xo(c.rewindFiles,r,n,!1);if(!i.canRewind){process.stderr.write(`Error: ${i.error||`Unexpected error`}\n`),K(1);return}process.stdout.write(`Files rewound to state at message ${c.rewindFiles}\n`),K(0);return}let ee=typeof c.resume==`string`&&(!!Kt(c.resume)||c.resume.endsWith(`.jsonl`)),_=!!c.sdkUrl;if(!e&&!ee&&!_){process.stderr.write(`Error: Input must be provided either through stdin or as a prompt argument when using --print
|
|
25
|
-
`),K(1);return}if(c.outputFormat===`stream-json`&&!c.verbose){process.stderr.write(`Error: When using --print, --output-format=stream-json requires --verbose
|
|
26
|
-
`),K(1);return}let te=Fn(f.mcp.tools,f.toolPermissionContext),v=[...a,...te],y=Jo(c.sdkUrl?`stdio`:c.permissionPromptToolName,l,()=>t().mcp.tools,e=>{n(e=>({...e,attribution:{...e.attribution,permissionPromptCount:e.attribution.permissionPromptCount+1}})),ca(`requires_action`,e)});c.permissionPromptToolName&&(v=v.filter(e=>!Li(e,c.permissionPromptToolName))),We(),q(`after_loadInitialMessages`),await C(),q(`after_modelStrings`);let b=c.outputFormat===`json`&&c.verbose,S=[],w;q(`before_runHeadlessStreaming`);for await(let e of Ko(l,f.mcp.clients,[...r,...f.mcp.commands],v,p,y,o,t,n,s,c,m))c.outputFormat===`stream-json`&&c.verbose&&await l.write(e),e.type!==`control_response`&&e.type!==`control_request`&&e.type!==`control_cancel_request`&&!(e.type===`system`&&(e.subtype===`session_state_changed`||e.subtype===`task_notification`||e.subtype===`task_started`||e.subtype===`task_progress`||e.subtype===`post_turn_summary`))&&e.type!==`stream_event`&&e.type!==`keep_alive`&&e.type!==`streamlined_text`&&e.type!==`streamlined_tool_use_summary`&&e.type!==`prompt_suggestion`&&(b&&S.push(e),w=e);switch(c.outputFormat){case`json`:if(!w||w.type!==`result`)throw Error(`No messages returned`);if(c.verbose){V(P(S)+`
|
|
27
|
-
`);break}V(P(w)+`
|
|
28
|
-
`);break;case`stream-json`:break;default:if(!w||w.type!==`result`)throw Error(`No messages returned`);switch(w.subtype){case`success`:V(w.result.endsWith(`
|
|
29
|
-
`)?w.result:w.result+`
|
|
30
|
-
`);break;case`error_during_execution`:V(`Execution error`);break;case`error_max_turns`:V(`Error: Reached max turns (${c.maxTurns}).\nTip: Increase the limit with --max-turns or continue in a new session.`);break;case`error_max_budget_usd`:V(`Error: Exceeded USD budget ($${c.maxBudgetUsd}).\nTip: Increase the limit with --max-budget-usd or start a new session to continue.`);break;case`error_max_structured_output_retries`:V(`Error: Failed to provide valid structured output after maximum retries.
|
|
31
|
-
Tip: Simplify your schema or check if the output format matches the expected structure.`)}}if(on(),ye())try{let{drainPendingExtraction:e}=await import(`./extractMemories-C3SU-Osb.js`);await e()}catch{}K(w?.type===`result`&&w?.is_error?1:0)}function Ko(e,r,a,o,s,m,h,g,_,te,v,y){let x=!1,S,C=!1,re=!1,se=null,E,D=e.outbound;process.on(`SIGINT`,()=>{Ge(`info`,`shutdown_signal`,{signal:`SIGINT`}),E&&!E.signal.aborted&&E.abort(),ei(0)}),Ie(async()=>{let t={};for(let e of er(g()))cn(e)&&(t[e.type]=(t[e.type]??0)+1);Ge(`info`,`run_state_at_shutdown`,{run_active:x,run_phase:S,worker_status:ua(),internal_events_pending:e.internalEventsPending,bg_tasks:t})}),sa(e=>{(e===`default`||e===`acceptEdits`||e===`bypassPermissions`||e===`plan`||e===`auto`||e===`dontAsk`)&&D.enqueue({type:`system`,subtype:`status`,status:null,permissionMode:e,uuid:Y(),session_id:u()})});let O={abortController:null,inflightPromise:null,lastEmitted:null,pendingSuggestion:null,pendingLastEmittedEntry:null},fe;v.enableAuthStatus&&(fe=ce.getInstance().subscribe(e=>{D.enqueue({type:`auth_status`,isAuthenticating:e.isAuthenticating,output:e.output,error:e.error,uuid:Y(),session_id:u()})}));let me=e=>{let t=Ca(e);t&&D.enqueue({type:`rate_limit_event`,rate_limit_info:t,uuid:Y(),session_id:u()})};pt.add(me);let k=s,A=Ct(s,X(),100),_e=Yi(100),ye=process.env.CLAUDE_CODE_RESUME_INTERRUPTED_TURN;y&&y.kind!==`none`&&ye&&(I(`[print.ts] Auto-resuming interrupted turn (kind: ${y.kind})`),ts(k,y.message),J({mode:`prompt`,value:y.message.message.content,uuid:Y()}));let be=nn().map(e=>{let t=e.value===null?`default`:e.value,n=t===`default`?ie():w(t),r=ui(n),i=gr(n),a=pe(e.value),o=he(n);return{name:t,value:t,displayName:e.label,description:e.description,...r&&{supportsEffort:!0,supportedEffortLevels:Hr(n)?[...Mn]:Mn.filter(e=>e!==`max`)},...i&&{supportsAdaptiveThinking:!0},...a&&{supportsFastMode:!0},...o&&{supportsAutoMode:!0}}}),Se=v.userSpecifiedModel;function Ce(e,t){let n=Qr(e,de(t));k.push(...n);for(let e of n)typeof e.message.content==`string`&&e.message.content.includes(`<local-command-stdout>`)&&D.enqueue({type:`user`,content:e.message.content,message:e.message,session_id:u(),parent_tool_use_id:null,uuid:e.uuid,timestamp:e.timestamp,isReplay:!0})}let j=[],we=[],Te=new Set;function Ee(t){for(let n of t){if(n.type!==`connected`||Te.has(n.name)||n.config.type===`sdk`)continue;let t=n.name;try{n.client.setRequestHandler(l,async(n,r)=>{Ye(t,`Elicitation request received in print mode: ${P(n)}`);let i=n.params.mode===`url`?`url`:`form`;z(`tengu_mcp_elicitation_shown`,{mode:i});let a=await ar(t,n.params,r.signal);if(a)return Ye(t,`Elicitation resolved by hook: ${P(a)}`),z(`tengu_mcp_elicitation_response`,{mode:i,action:a.action}),a;let o=`url`in n.params?n.params.url:void 0,s=`requestedSchema`in n.params?n.params.requestedSchema:void 0,c=`elicitationId`in n.params?n.params.elicitationId:void 0,l=await Pr(t,await e.handleElicitation(t,n.params.message,s,r.signal,i,o,c),r.signal,i,c);return z(`tengu_mcp_elicitation_response`,{mode:i,action:l.action}),l}),n.client.setNotificationHandler(c,e=>{let{elicitationId:n}=e.params;Ye(t,`Elicitation completion notification: ${n}`),jn({message:`MCP server "${t}" confirmed elicitation ${n} complete`,notificationType:`elicitation_complete`}),D.enqueue({type:`system`,subtype:`elicitation_complete`,mcp_server_name:t,elicitation_id:n,uuid:Y(),session_id:u()})}),Te.add(t)}catch{}}}async function De(){let t=new Set(Object.keys(h)),n=new Set(j.map(e=>e.name)),r=Array.from(t).some(e=>!n.has(e)),i=Array.from(n).some(e=>!t.has(e)),a=j.some(e=>e.type===`pending`),o=j.some(e=>e.type===`failed`);if(r||i||a||o){for(let e of j)t.has(e.name)||e.type===`connected`&&await e.cleanup();let r=await an(h,(t,n)=>e.sendMcpMessage(t,n));j=r.clients,we=r.tools;let i=nt([...n,...t]);_(e=>({...e,mcp:{...e.mcp,tools:[...e.mcp.tools.filter(e=>!i.some(t=>e.name.startsWith(Oe(t)))),...we]}})),dt(j)}}De();let M={clients:[],tools:[],configs:{}},Ae=e=>{let t=Dn(e.toolPermissionContext,e.mcp.tools),n=ve($a([...o,...we,...M.tools],t,e.toolPermissionContext.mode),`name`);v.permissionPromptToolName&&(n=n.filter(e=>!Li(e,v.permissionPromptToolName)));let r=p();if(r&&!v.jsonSchema){let e=Ui(r);`tool`in e&&(n=[...n,e.tool])}return n},N=null,je=0;function Me(){if(!N)return;let e=Math.min(je,k.length),t=k.slice(e).filter(e=>e.type===`user`||e.type===`assistant`);je=k.length,t.length>0&&N.writeMessages(t)}let Pe=Promise.resolve({response:{added:[],removed:[],errors:{}},sdkServersChanged:!1});function Fe(e){let t=async()=>{let t=new Set(j.map(e=>e.name)),n=await os(e,{configs:h,clients:j,tools:we},M,_);for(let e of Object.keys(h))delete h[e];if(Object.assign(h,n.newSdkState.configs),j=n.newSdkState.clients,we=n.newSdkState.tools,M=n.newDynamicState,n.sdkServersChanged){let e=new Set(j.map(e=>e.name)),n=nt([...t,...e]);_(e=>({...e,mcp:{...e.mcp,tools:[...e.mcp.tools.filter(e=>!n.some(t=>e.name.startsWith(Oe(t)))),...we]}}))}return{response:n.response,sdkServersChanged:n.sdkServersChanged}};return Pe=Pe.then(t,t),Pe}function Le(){let e=g(),t=e.mcp.clients,n=ve([...e.mcp.tools,...M.tools],`name`),r=new Set([...t.map(e=>e.name),...j.map(e=>e.name)]);return[...t,...j,...M.clients.filter(e=>!r.has(e.name))].map(e=>{let t;if(e.config.type===`sse`||e.config.type===`http`)t={type:e.config.type,url:e.config.url,headers:e.config.headers,oauth:e.config.oauth};else if(e.config.type===`claudeai-proxy`)t={type:`claudeai-proxy`,url:e.config.url,id:e.config.id};else if(e.config.type===`stdio`||e.config.type===void 0){let n=e.config;t={type:`stdio`,command:n.command,args:n.args}}let r=e.type===`connected`?zn(n,e.name).map(e=>({name:e.mcpInfo?.toolName??e.name,annotations:{readOnly:e.isReadOnly({})||void 0,destructive:e.isDestructive?.({})||void 0,openWorld:e.isOpenWorld?.({})||void 0}})):void 0,i;if(e.type===`connected`&&e.capabilities.experimental){let t={...e.capabilities.experimental};t[`claude/channel`]&&(!Fa()||!Pa(e.config.pluginSource))&&delete t[`claude/channel`],Object.keys(t).length>0&&(i={experimental:t})}return{name:e.name,status:e.type,serverInfo:e.type===`connected`?e.serverInfo:void 0,error:e.type===`failed`?e.error:void 0,config:t,scope:e.config.scope,tools:r,capabilities:i}})}async function Re(){try{await Promise.all([Promise.resolve(),Ke(`headless_managed_settings_wait`,()=>hn())]),await No()&&await He()}catch(e){W(e)}}let ze=null;t()||(i(process.env.CLAUDE_CODE_SYNC_PLUGIN_INSTALL)?ze=Re():Re());let Be=Eo(()=>!x),L=a,R=te;async function Ve(){let{agentDefinitions:e}=await uo(_);L=await Pt(X());let t=R.filter(e=>e.source===`flagSettings`);R=[...e.allAgents,...t]}async function He(){let{servers:e}=await Yr(),t={};for(let[n,r]of Object.entries(e)){let e=r.type;(e===void 0||e===`stdio`||e===`sse`||e===`http`||e===`sdk`)&&(t[n]=r)}for(let[e,n]of Object.entries(h))n.type===`sdk`&&!(e in t)&&(t[e]=n);let{response:n,sdkServersChanged:r}=await Fe(t);r&&De(),I(`Headless MCP refresh: added=${n.added.length}, removed=${n.removed.length}`)}let Ue=lo.subscribe(()=>{Fi(),Pt(X()).then(e=>{L=e})}),We=()=>{setTimeout(()=>{!$?.isProactiveActive()||$.isProactivePaused()||C||(async()=>{let e=await Nn({basePrompt:`<${qe}>${new Date().toLocaleTimeString()}</${qe}>`,currentDir:X(),shouldCreate:()=>!C});if(C){await pn({commands:e});return}for(let t of e)J({...t,uuid:Y()});B()})().catch(e=>{W(e),I(`[Proactive] failed to create headless tick: ${e}`,{level:`error`})})},0)};bt(()=>{E&&wr(`now`).length>0&&E.abort(`interrupt`)});let B=async()=>{if(x)return;if(x=!0,S=void 0,ca(`running`),Be.stop(),q(`run_entry`),await De(),q(`after_updateSdkMcp`),ze){let e=parseInt(process.env.CLAUDE_CODE_SYNC_PLUGIN_INSTALL_TIMEOUT_MS||``,10);if(e>0){let t=ct(e).then(()=>`timeout`);await Promise.race([ze,t])===`timeout`&&(W(Error(`CLAUDE_CODE_SYNC_PLUGIN_INSTALL: plugin installation timed out after ${e}ms`)),z(`tengu_sync_plugin_install_timeout`,{timeout_ms:e}))}else await ze;ze=null,await Ve();let{setupPluginHookHotReload:t}=await import(`./loadPluginHooks-CL5aGDrb.js`);t()}let t=e=>e.agentId===void 0;try{let r,i=!1,a=async()=>{for(;r=sr(t);){if(r.mode!==`prompt`&&r.mode!==`orphaned-permission`&&r.mode!==`task-notification`)throw Error(`only prompt commands are supported in streaming mode`);let i=[r];if(r.mode===`prompt`)for(;Wo(r,tr(t));)i.push(sr(t));let a=await Pi(i);if(i=a.attachmentCommands,i.length===0)continue;r=i[0],r.mode===`prompt`&&i.length>1&&(r={...r,value:Uo(i.map(e=>e.value)),uuid:i.findLast(e=>e.uuid)?.uuid??r.uuid});let o=i.map(e=>e.uuid).filter(e=>e!==void 0);if(v.replayUserMessages&&i.length>1)for(let e of i)e.uuid&&e.uuid!==r.uuid&&D.enqueue({type:`user`,content:e.value,message:{role:`user`,content:e.value},session_id:u(),parent_tool_use_id:null,uuid:e.uuid,isReplay:!0});let s=g(),c=[...s.mcp.clients,...j,...M.clients];Ee(c);for(let e of c)$o(e);let l=Ae(s);for(let e of o)It(e,`started`);if(r.mode===`task-notification`){let e=typeof r.value==`string`?r.value:``,t=e.match(/<task-id>([^<]+)<\/task-id>/),n=e.match(/<tool-use-id>([^<]+)<\/tool-use-id>/),i=e.match(/<output-file>([^<]+)<\/output-file>/),a=e.match(/<status>([^<]+)<\/status>/),o=e.match(/<summary>([^<]+)<\/summary>/),s=e=>e===`completed`||e===`failed`||e===`stopped`||e===`killed`,c=a?.[1],l=s(c)?c===`killed`?`stopped`:c:`completed`,d=e.match(/<usage>([\s\S]*?)<\/usage>/)?.[1]??``,f=d.match(/<total_tokens>(\d+)<\/total_tokens>/),p=d.match(/<tool_uses>(\d+)<\/tool_uses>/),m=d.match(/<duration_ms>(\d+)<\/duration_ms>/);a&&D.enqueue({type:`system`,subtype:`task_notification`,task_id:t?.[1]??``,tool_use_id:n?.[1],status:l,output_file:i?.[1]??``,summary:o?.[1]??``,usage:f&&p?{total_tokens:parseInt(f[1],10),tool_uses:parseInt(p[1],10),duration_ms:m?parseInt(m[1],10):0}:void 0,session_id:u(),uuid:Y()})}let d=r.value,f=a.claimedCommands;if(e instanceof bo&&r.mode===`prompt`&&z(`tengu_bridge_message_received`,{is_repl:!1}),O.abortController?.abort(),O.abortController=null,O.pendingSuggestion=null,O.pendingLastEmittedEntry=null,O.lastEmitted&&r.mode===`prompt`){let e=typeof d==`string`?d:d.find(e=>e.type===`text`)?.text;typeof e==`string`&&Bt(O.lastEmitted.text,e,O.lastEmitted.emittedAt,O.lastEmitted.promptId,O.lastEmitted.generationRequestId),O.lastEmitted=null}E=xi(),q(`before_ask`),Qn();let h=r,ee=!1;try{if(await xe(h.workload??v.workload,async()=>{for await(let t of to({commands:ve([...L,...s.mcp.commands],`name`),prompt:d,promptUuid:h.uuid,isMeta:h.isMeta,cwd:X(),tools:l,verbose:v.verbose,mcpClients:c,thinkingConfig:v.thinkingConfig,maxTurns:v.maxTurns,maxBudgetUsd:v.maxBudgetUsd,taskBudget:v.taskBudget,canUseTool:m,userSpecifiedModel:Se,fallbackModel:v.fallbackModel,jsonSchema:p()??v.jsonSchema,mutableMessages:k,getReadFileCache:()=>_e.size===0?A:Zi(A,_e),setReadFileCache:e=>{A=e;for(let[e,t]of _e.entries()){let n=A.get(e);(!n||t.timestamp>n.timestamp)&&A.set(e,t)}_e.clear()},customSystemPrompt:v.systemPrompt,appendSystemPrompt:v.appendSystemPrompt,getAppState:g,setAppState:_,abortController:E,replayUserMessages:v.replayUserMessages,includePartialMessages:v.includePartialMessages,handleElicitation:(t,n,r)=>e.handleElicitation(t,n.message,void 0,r,n.mode,n.url,`elicitationId`in n?n.elicitationId:void 0),agents:R,orphanedPermission:h.orphanedPermission,setSDKStatus:e=>{D.enqueue({type:`system`,subtype:`status`,status:e,session_id:u(),uuid:Y()})}}))if(Me(),t.type===`result`){ee=!!t.is_error;for(let e of Qi())D.enqueue(e);er(g()).some(e=>(e.type===`local_agent`||e.type===`local_workflow`)&&cn(e))?se=t:(se=null,D.enqueue(t))}else{for(let e of Qi())D.enqueue(e);D.enqueue(t)}}),ee)await ht({commands:f,outcome:{type:`failed`,message:`ask() returned an error result`},currentDir:X(),priority:`later`,workload:h.workload??v.workload});else{let e=await ht({commands:f,outcome:{type:`completed`},currentDir:X(),priority:`later`,workload:h.workload??v.workload});for(let t of e)J({...t,uuid:Y()})}}catch(e){throw await ht({commands:f,outcome:{type:`failed`,error:e},currentDir:X(),priority:`later`,workload:h.workload??v.workload}),e}for(let e of o)It(e,`completed`);if(Me(),N?.sendResult(),v.promptSuggestions&&!n(process.env.CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION)){O.abortController?.abort();let e=new AbortController;O.abortController=e;let t=kr();if(!t)Vn(`sdk_no_params`,void 0,void 0,`sdk`);else{let n={promise:null};n.promise=(async()=>{try{let n=await Un(e,k,g,t,`sdk`);if(!n||e.signal.aborted)return;let r={type:`prompt_suggestion`,suggestion:n.suggestion,uuid:Y(),session_id:u()},i={text:n.suggestion,emittedAt:Date.now(),promptId:n.promptId,generationRequestId:n.generationRequestId};se?(O.pendingSuggestion=r,O.pendingLastEmittedEntry={text:i.text,promptId:i.promptId,generationRequestId:i.generationRequestId}):(O.lastEmitted=i,D.enqueue(r))}catch(e){if(e instanceof Error&&(e.name===`AbortError`||e.name===`APIUserAbortError`)){Vn(`aborted`,void 0,void 0,`sdk`);return}W(Ne(e))}finally{O.inflightPromise===n.promise&&(O.inflightPromise=null)}})(),O.inflightPromise=n.promise}}on(),ii(),Yt()}};do{for(let e of Qi())D.enqueue(e);S=`draining_commands`,await a(),i=!1;{let e=er(g()).some(e=>cn(e)&&e.type!==`in_process_teammate`),n=tr(t)!==void 0;(e||n)&&(i=!0,n||(S=`waiting_for_agents`,await ct(100)))}}while(i);se&&(D.enqueue(se),se=null,O.pendingSuggestion&&(D.enqueue(O.pendingSuggestion),O.pendingLastEmittedEntry&&(O.lastEmitted={...O.pendingLastEmittedEntry,emittedAt:Date.now()},O.pendingLastEmittedEntry=null),O.pendingSuggestion=null))}catch(t){try{await e.write({type:`result`,subtype:`error_during_execution`,duration_ms:0,duration_api_ms:0,is_error:!0,num_turns:0,stop_reason:null,session_id:u(),total_cost_usd:0,usage:ia,modelUsage:{},permission_denials:[],uuid:Y(),errors:[F(t),...Xe().map(e=>e.error)]})}catch{}O.abortController?.abort(),K(1);return}finally{if(S=`finally_flush`,await e.flushInternalEvents(),S=`finally_post_flush`,!In()){ca(`idle`);for(let e of Qi())D.enqueue(e)}x=!1,Be.start()}if($?.isProactiveActive()&&!$.isProactivePaused()&&tr(t)===void 0&&!C){We();return}if(tr(t)!==void 0){B();return}{let e=g().teamContext;if(e&&it(e)){let e=`team-lead`;for(;;){let t=g();if(!(st(t)||t.teamContext&&Object.keys(t.teamContext.teammates).length>0)){I(`[print.ts] No more active teammates, stopping poll`);break}let n=await li(e,t.teamContext?.teamName);if(n.length>0){I(`[print.ts] Team-lead found ${n.length} unread messages`),await pr(e,t.teamContext?.teamName);let r=t.teamContext?.teamName;for(let e of n){let n=Wn(e.text);if(n&&r){let e=n.from;I(`[print.ts] Processing shutdown_approved from ${e}`);let i=t.teamContext?.teammates?Object.entries(t.teamContext.teammates).find(([,t])=>t.name===e)?.[0]:void 0;i&&(va(r,{agentId:i,name:e}),I(`[print.ts] Removed ${e} from team file`),await ga(r,i,e,`shutdown`),_(e=>{if(!e.teamContext?.teammates||!(i in e.teamContext.teammates))return e;let{[i]:t,...n}=e.teamContext.teammates;return{...e,teamContext:{...e.teamContext,teammates:n}}}))}}J({mode:`prompt`,value:n.map(e=>`<${Je} teammate_id="${e.from}"${e.color?` color="${e.color}"`:``}>\n${e.text}\n</${Je}>`).join(`
|
|
32
|
-
|
|
33
|
-
`),uuid:Y()}),B();return}if(C&&!re){re=!0,I(`[print.ts] Input closed with active teammates, injecting shutdown prompt`),J({mode:`prompt`,value:Lo,uuid:Y()}),B();return}await ct(500)}}}C&&(await(async()=>{let e=g();rt(e)&&await ot(_,e);let t=g(),n=t.teamContext;return n&&Object.keys(n.teammates).length>0||st(t)})()?(J({mode:`prompt`,value:Lo,uuid:Y()}),B()):(O.inflightPromise&&await Promise.race([O.inflightPromise,ct(5e3)]),O.abortController?.abort(),O.abortController=null,await $t(),Ue(),fe?.(),pt.delete(me),D.done()))},V=null;if(Io.isKairosCronEnabled()){let e=e=>{C||(async()=>{let t=await Cn({basePrompt:e.basePrompt,trigger:`scheduled-task`,currentDir:X(),sourceId:e.sourceId,sourceLabel:e.sourceLabel,workload:oe,shouldCreate:()=>!C});if(t){if(C){await pn({commands:[t]});return}await e.onSuccess(t)}})().catch(t=>{W(t),I(`[ScheduledTasks] failed to enqueue headless task${e.logSuffix}: ${t}`,{level:`error`})})},t=e=>{J({...e,uuid:Y()}),B()};V=Po.createCronScheduler({onFire:n=>{e({basePrompt:n,sourceId:n,sourceLabel:n,logSuffix:``,onSuccess:t})},onFireTask:n=>{if(n.agentId){e({basePrompt:n.prompt,sourceId:n.id,sourceLabel:n.prompt,logSuffix:` ${n.id}`,onSuccess:async e=>{await un(e.autonomy.runId,`No teammate runtime available for scheduled task owner ${n.agentId} in headless mode.`,e.autonomy.rootDir)}});return}e({basePrompt:n.prompt,sourceId:n.id,sourceLabel:n.prompt,logSuffix:` ${n.id}`,onSuccess:t})},isLoading:()=>x||C,getJitterConfig:Fo?.getCronJitterConfig,isKilled:()=>!Io?.isKairosCronEnabled()}),V.start()}let H=function(e,t){D.enqueue({type:`control_response`,response:{subtype:`success`,request_id:e.request_id,response:t}})},U=function(e,t){D.enqueue({type:`control_response`,response:{subtype:`error`,request_id:e.request_id,error:t}})},Ze=new Set;e.setUnexpectedResponseCallback(async e=>{await is({message:e,setAppState:_,handledToolUseIds:Ze,onEnqueued:()=>{B()}})});let Qe=new Map,et=new Map,tt=new Set,at=new Map,G=null;return(async()=>{let t=!1;Ge(`info`,`cli_message_loop_started`);for await(let n of e.structuredInput){let i=`uuid`in n?n.uuid:void 0;if(i&&n.type!==`user`&&n.type!==`control_response`&&It(i,`completed`),n.type===`control_request`){let i=n,o=i.request;if(i.request.subtype===`interrupt`)_(e=>({...e,attribution:{...e.attribution,escapeCount:e.attribution.escapeCount+1}})),E&&E.abort(),O.abortController?.abort(),O.abortController=null,O.lastEmitted=null,O.pendingSuggestion=null,H(i);else if(o.subtype===`end_session`){I(`[print.ts] end_session received, reason=${o.reason??`unspecified`}`),E&&E.abort(),O.abortController?.abort(),O.abortController=null,O.lastEmitted=null,O.pendingSuggestion=null,H(i);break}else if(i.request.subtype===`initialize`){if(i.request.sdkMcpServers&&i.request.sdkMcpServers.length>0)for(let e of i.request.sdkMcpServers)h[e]={type:`sdk`,name:e};await Yo(i.request,i.request_id,t,D,a,be,e,!!v.enableAuthStatus,v,te,g),i.request.promptSuggestions&&_(e=>e.promptSuggestionEnabled?e:{...e,promptSuggestionEnabled:!0}),i.request.agentProgressSummaries&&ge(`tengu_slate_prism`,!0)&&ee(!0),t=!0,yr()&&B()}else if(i.request.subtype===`set_permission_mode`){let e=i.request;_(t=>({...t,toolPermissionContext:Zo(e,i.request_id,t.toolPermissionContext,D),isUltraplanMode:e.ultraplan??t.isUltraplanMode}))}else if(i.request.subtype===`set_model`){let e=i.request.model??`default`,t=e===`default`?ie():e;Se=t,b(t),la({model:t}),Ce(e,t),H(i)}else if(i.request.subtype===`set_max_thinking_tokens`)i.request.max_thinking_tokens===null?v.thinkingConfig=void 0:i.request.max_thinking_tokens===0?v.thinkingConfig={type:`disabled`}:v.thinkingConfig={type:`enabled`,budgetTokens:i.request.max_thinking_tokens},H(i);else if(i.request.subtype===`mcp_status`)H(i,{mcpServers:Le()});else if(i.request.subtype===`get_context_usage`)try{let e=g();H(i,{...await ao({messages:k,getAppState:g,options:{mainLoopModel:ae(),tools:Ae(e),agentDefinitions:e.agentDefinitions,customSystemPrompt:v.systemPrompt,appendSystemPrompt:v.appendSystemPrompt}})})}catch(e){U(i,F(e))}else if(i.request.subtype===`mcp_message`){let e=i.request,t=j.find(t=>t.name===e.server_name);t&&t.type===`connected`&&t.client?.transport?.onmessage&&t.client.transport.onmessage(e.message),H(i)}else if(i.request.subtype===`rewind_files`){let e=g(),t=await Xo(i.request.user_message_id,e,_,i.request.dry_run??!1);t.canRewind||i.request.dry_run?H(i,t):U(i,t.error??`Unexpected error`)}else if(i.request.subtype===`cancel_async_message`){let e=i.request.message_uuid;H(i,{cancelled:Ir(t=>t.uuid===e).length>0})}else if(i.request.subtype===`seed_read_state`){try{let e=$e(i.request.path),t=Math.floor((await _o(e)).mtimeMs);if(t<=i.request.mtime){let n=await go(e,`utf-8`),r=(n.charCodeAt(0)===65279?n.slice(1):n).replaceAll(`\r
|
|
34
|
-
`,`
|
|
35
|
-
`);_e.set(e,{content:r,timestamp:t,offset:void 0,limit:void 0})}}catch{}H(i)}else if(i.request.subtype===`mcp_set_servers`){let{response:e,sdkServersChanged:t}=await Fe(i.request.servers);H(i,e),t&&De()}else if(i.request.subtype===`reload_plugins`)try{let e=await uo(_),t=R.filter(e=>e.source===`flagSettings`);R=[...e.agentDefinitions.allAgents,...t];let n=[],[r,a,o]=await Promise.allSettled([Pt(X()),He(),Vr()]);r.status===`fulfilled`?L=r.value:W(r.reason),a.status===`rejected`&&W(a.reason),o.status===`fulfilled`?n=o.value.enabled.map(e=>({name:e.name,path:e.path,source:e.source})):W(o.reason),H(i,{commands:L.filter(e=>e.userInvocable!==!1).map(e=>({name:Lr(e),description:Ft(e),argumentHint:e.argumentHint||``})),agents:R.map(e=>({name:e.agentType,description:e.whenToUse,model:e.model===`inherit`?void 0:e.model})),plugins:n,mcpServers:Le(),error_count:e.error_count})}catch(e){U(i,F(e))}else if(i.request.subtype===`mcp_reconnect`){let e=g(),{serverName:t}=i.request;Te.delete(t);let n=lr(t)??r.find(e=>e.name===t)?.config??j.find(e=>e.name===t)?.config??M.clients.find(e=>e.name===t)?.config??e.mcp.clients.find(e=>e.name===t)?.config??null;if(!n)U(i,`Server not found: ${t}`);else{let e=await Et(t,n),r=Oe(t);_(n=>({...n,mcp:{...n.mcp,clients:n.mcp.clients.map(n=>n.name===t?e.client:n),tools:[...T(n.mcp.tools,e=>e.name?.startsWith(r)),...e.tools],commands:[...T(n.mcp.commands,e=>Ni(e,t)),...e.commands],resources:e.resources&&e.resources.length>0?{...n.mcp.resources,[t]:e.resources}:le(n.mcp.resources,t)}})),M={...M,clients:[...M.clients.filter(e=>e.name!==t),e.client],tools:[...M.tools.filter(e=>!e.name?.startsWith(r)),...e.tools]},e.client.type===`connected`?(Ee([e.client]),$o(e.client),H(i)):U(i,e.client.type===`failed`?e.client.error??`Connection failed`:`Server status: ${e.client.type}`)}}else if(i.request.subtype===`mcp_toggle`){let e=g(),{serverName:t,enabled:n}=i.request;Te.delete(t);let a=lr(t)??r.find(e=>e.name===t)?.config??j.find(e=>e.name===t)?.config??M.clients.find(e=>e.name===t)?.config??e.mcp.clients.find(e=>e.name===t)?.config??null;if(!a)U(i,`Server not found: ${t}`);else if(n){Sr(t,!0);let e=await Et(t,a),n=Oe(t);_(r=>({...r,mcp:{...r.mcp,clients:r.mcp.clients.map(n=>n.name===t?e.client:n),tools:[...T(r.mcp.tools,e=>e.name?.startsWith(n)),...e.tools],commands:[...T(r.mcp.commands,e=>Ni(e,t)),...e.commands],resources:e.resources&&e.resources.length>0?{...r.mcp.resources,[t]:e.resources}:le(r.mcp.resources,t)}})),e.client.type===`connected`?(Ee([e.client]),$o(e.client),H(i)):U(i,e.client.type===`failed`?e.client.error??`Connection failed`:`Server status: ${e.client.type}`)}else{Sr(t,!1);let n=[...r,...j,...M.clients,...e.mcp.clients].find(e=>e.name===t);n&&n.type===`connected`&&await vi(t,a);let o=Oe(t);_(e=>({...e,mcp:{...e.mcp,clients:e.mcp.clients.map(e=>e.name===t?{name:t,type:`disabled`,config:a}:e),tools:T(e.mcp.tools,e=>e.name?.startsWith(o)),commands:T(e.mcp.commands,e=>Ni(e,t)),resources:le(e.mcp.resources,t)}})),H(i)}}else if(o.subtype===`channel_enable`){let e=g();Qo(i.request_id,o.serverName,[...e.mcp.clients,...j,...M.clients],D)}else if(o.subtype===`mcp_authenticate`){let e=o.serverName,t=g(),n=lr(e)??r.find(t=>t.name===e)?.config??t.mcp.clients.find(t=>t.name===e)?.config??null;if(!n)U(i,`Server not found: ${e}`);else if(n.type!==`sse`&&n.type!==`http`)U(i,`Server type "${n.type}" does not support OAuth authentication`);else try{Qe.get(e)?.abort();let t=new AbortController;Qe.set(e,t);let r,a=new Promise(e=>{r=e}),o=bi(e,n,e=>r(e),t.signal,{skipBrowserOpen:!0,onWaitingForCallback:t=>{et.set(e,t)}}),s=await Promise.race([a,o.then(()=>null)]);s?H(i,{authUrl:s,requiresUserAction:!0}):H(i,{requiresUserAction:!1}),at.set(e,o),o.then(async()=>{if(vr(e)||tt.has(e))return;let t=await Et(e,n),r=Oe(e);_(n=>({...n,mcp:{...n.mcp,clients:n.mcp.clients.map(n=>n.name===e?t.client:n),tools:[...T(n.mcp.tools,e=>e.name?.startsWith(r)),...t.tools],commands:[...T(n.mcp.commands,t=>Ni(t,e)),...t.commands],resources:t.resources&&t.resources.length>0?{...n.mcp.resources,[e]:t.resources}:le(n.mcp.resources,e)}})),M={...M,clients:[...M.clients.filter(t=>t.name!==e),t.client],tools:[...M.tools.filter(e=>!e.name?.startsWith(r)),...t.tools]}}).catch(t=>{I(`MCP OAuth failed for ${e}: ${t}`,{level:`error`})}).finally(()=>{Qe.get(e)===t&&(Qe.delete(e),et.delete(e),tt.delete(e),at.delete(e))})}catch(e){U(i,F(e))}}else if(o.subtype===`mcp_oauth_callback_url`){let e=o.serverName,t=o.callbackUrl,n=et.get(e);if(n){let r=!1;try{let e=new URL(t);r=e.searchParams.has(`code`)||e.searchParams.has(`error`)}catch{}if(!r)U(i,`Invalid callback URL: missing authorization code. Please paste the full redirect URL including the code parameter.`);else{tt.add(e),n(t);let r=at.get(e);if(r)try{await r,H(i)}catch(e){U(i,e instanceof Error?e.message:`OAuth authentication failed`)}else H(i)}}else U(i,`No active OAuth flow for server: ${e}`)}else if(o.subtype===`claude_authenticate`){let e=o.loginWithClaudeAi;G?.service.cleanup(),z(`tengu_oauth_flow_start`,{loginWithClaudeAi:e??!0});let t=new Si,n,r=new Promise(e=>{n=e}),a=t.startOAuthFlow(async(e,t)=>{n({manualUrl:e,automaticUrl:t})},{loginWithClaudeAi:e??!0,skipBrowserOpen:!0}).then(async t=>{await nr(t),z(`tengu_oauth_success`,{loginWithClaudeAi:e??!0})}).finally(()=>{t.cleanup(),G?.service===t&&(G=null)});G={service:t,flow:a},a.catch(e=>I(`claude_authenticate flow ended: ${e}`,{level:`info`}));try{let{manualUrl:e,automaticUrl:t}=await Promise.race([r,a.then(()=>{throw Error(`OAuth flow completed without producing auth URLs`)})]);H(i,{manualUrl:e,automaticUrl:t})}catch(e){U(i,F(e))}}else if(o.subtype===`claude_oauth_callback`||o.subtype===`claude_oauth_wait_for_completion`)if(!G)U(i,`No active claude_authenticate flow`);else{o.subtype===`claude_oauth_callback`&&G.service.handleManualAuthCodeInput({authorizationCode:o.authorizationCode,state:o.state});let{flow:e}=G;e.then(()=>{let e=ne();H(i,{account:{email:e?.email,organization:e?.organization,subscriptionType:e?.subscription,tokenSource:e?.tokenSource,apiKeySource:e?.apiKeySource,apiProvider:ue()}})},e=>U(i,F(e)))}else if(o.subtype===`mcp_clear_auth`){let e=o.serverName,t=g(),n=lr(e)??r.find(t=>t.name===e)?.config??t.mcp.clients.find(t=>t.name===e)?.config??null;if(!n)U(i,`Server not found: ${e}`);else if(n.type!==`sse`&&n.type!==`http`)U(i,`Cannot clear auth for server type "${n.type}"`);else{await Dt(e,n);let t=await Et(e,n),r=Oe(e);_(n=>({...n,mcp:{...n.mcp,clients:n.mcp.clients.map(n=>n.name===e?t.client:n),tools:[...T(n.mcp.tools,e=>e.name?.startsWith(r)),...t.tools],commands:[...T(n.mcp.commands,t=>Ni(t,e)),...t.commands],resources:t.resources&&t.resources.length>0?{...n.mcp.resources,[e]:t.resources}:le(n.mcp.resources,e)}})),H(i,{})}}else if(i.request.subtype===`apply_flag_settings`){let e=ae(),t=d()??{},n=i.request.settings,r={...t,...n};for(let e of Object.keys(r))r[e]===null&&delete r[e];f(r),mi.notifyChange(`flagSettings`),`model`in n&&(n.model==null?b(void 0):b(String(n.model)));let a=ae();if(a!==e){Se=a;let e=n.model?String(n.model):`default`;la({model:a}),Ce(e,a)}H(i)}else if(i.request.subtype===`get_settings`){let e=g(),t=ae(),n=ui(t)?Xn(t,e.effortValue):void 0;H(i,{...ke(),applied:{model:t,effort:typeof n==`string`?n:null}})}else if(i.request.subtype===`stop_task`){let{task_id:e}=i.request;try{await Dr(e,{getAppState:g,setAppState:_}),H(i,{})}catch(e){U(i,F(e))}}else if(o.subtype===`generate_session_title`){let e=o.description,t=o.persist,n=(E&&!E.signal.aborted?E:xi()).signal;(async()=>{try{let r=await wa(e,n);if(r&&t)try{xr(u(),r)}catch(e){W(e)}H(i,{title:r})}catch(e){U(i,F(e))}})()}else if(o.subtype===`side_question`){let e=o.question;(async()=>{try{let t=kr();H(i,{response:(await io({question:e,cacheSafeParams:t?{...t,toolUseContext:{...t.toolUseContext,abortController:xi()}}:await no({tools:Ae(g()),commands:L,mcpClients:[...g().mcp.clients,...j,...M.clients],messages:k,readFileState:A,getAppState:g,setAppState:_,customSystemPrompt:v.systemPrompt,appendSystemPrompt:v.appendSystemPrompt,thinkingConfig:v.thinkingConfig,agents:R})})).response})}catch(e){U(i,F(e))}})()}else if(i.request.subtype===`set_proactive`)i.request.enabled?$.isProactiveActive()||($.activateProactive(`command`),We()):$.deactivateProactive(),H(i);else if(o.subtype===`remote_control`)if(o.enabled)if(N)H(i,{session_url:si(N.bridgeSessionId,N.sessionIngressUrl),connect_url:ci(N.environmentId,N.sessionIngressUrl),environment_id:N.environmentId});else{let t;try{let{initReplBridge:n}=await import(`./initReplBridge-tXqkba08.js`),r=await n({onInboundMessage(e){let t=qa(e);if(!t)return;let{content:n,uuid:r}=t;J({value:n,mode:`prompt`,uuid:r,skipSlashCommands:!0}),B()},onPermissionResponse(t){e.injectControlResponse(t)},onInterrupt(){E?.abort()},onSetModel(e){let t=e===`default`?ie():e;Se=t,b(t)},onSetMaxThinkingTokens(e){e===null?v.thinkingConfig=void 0:e===0?v.thinkingConfig={type:`disabled`}:v.thinkingConfig={type:`enabled`,budgetTokens:e}},onStateChange(e,n){e===`failed`&&(t=n),I(`[bridge:sdk] State change: ${e}${n?` — ${n}`:``}`),D.enqueue({type:`system`,subtype:`bridge_state`,state:e,detail:n,uuid:Y(),session_id:u()})},initialMessages:k.length>0?k:void 0});r?(N=r,je=k.length,e.setOnControlRequestSent(e=>{r.sendControlRequest(e)}),e.setOnControlRequestResolved(e=>{r.sendControlCancelRequest(e)}),H(i,{session_url:si(r.bridgeSessionId,r.sessionIngressUrl),connect_url:ci(r.environmentId,r.sessionIngressUrl),environment_id:r.environmentId})):U(i,t??`Remote Control initialization failed`)}catch(e){U(i,F(e))}}else N&&(e.setOnControlRequestSent(void 0),e.setOnControlRequestResolved(void 0),await N.teardown(),N=null),H(i);else U(i,`Unsupported control request subtype: ${i.request.subtype}`);continue}else if(n.type===`control_response`){v.replayUserMessages&&D.enqueue(n);continue}else if(n.type===`keep_alive`)continue;else if(n.type===`update_environment_variables`)continue;else if(n.type===`assistant`||n.type===`system`){let e=xa([n]);k.push(...e),n.type===`assistant`&&v.replayUserMessages&&D.enqueue(n);continue}if(n.type!==`user`)continue;let o=n;if(t=!0,o.uuid){let e=u(),t=await Or(e,o.uuid);if(t||zo.has(o.uuid)){I(`Skipping duplicate user message: ${o.uuid}`),v.replayUserMessages&&(I(`Sending acknowledgment for duplicate user message: ${o.uuid}`),D.enqueue({type:`user`,content:o.message?.content??``,message:o.message,session_id:e,parent_tool_use_id:null,uuid:o.uuid,timestamp:o.timestamp,isReplay:!0})),t&&It(o.uuid,`completed`);continue}Vo(o.uuid)}J({mode:`prompt`,value:await ba(o,o.message.content),uuid:o.uuid,priority:o.priority}),_(e=>({...e,attribution:pa(e.attribution,e=>{ft(e).catch(e=>{I(`Attribution: Failed to save snapshot: ${e}`)})})})),B()}C=!0,V?.stop(),x||(O.inflightPromise&&await Promise.race([O.inflightPromise,ct(5e3)]),O.abortController?.abort(),O.abortController=null,await $t(),Ue(),fe?.(),pt.delete(me),D.done())})(),D}function qo(e){let t=async(n,r,i,a,o,s)=>{let c=s??await Nt(n,r,i,a,o);if(c.behavior===`allow`||c.behavior===`deny`)return c;let{signal:l,cleanup:u}=xt(i.abortController.signal);if(l.aborted)return u(),{behavior:`deny`,message:`Permission prompt was aborted.`,decisionReason:{type:`permissionPromptTool`,permissionPromptToolName:n.name,toolResult:void 0}};let d=new Promise(e=>{l.addEventListener(`abort`,()=>e(`aborted`),{once:!0})}),f=e.call({tool_name:n.name,input:r,tool_use_id:o},i,t,a),p=await Promise.race([f,d]);if(u(),p===`aborted`||l.aborted)return{behavior:`deny`,message:`Permission prompt was aborted.`,decisionReason:{type:`permissionPromptTool`,permissionPromptToolName:n.name,toolResult:void 0}};let m=p,h=e.mapToolResultToToolResultBlockParam(m.data,`1`);if(!h.content||!Array.isArray(h.content)||!h.content[0]||h.content[0].type!==`text`||typeof h.content[0].text!=`string`)throw Error(`Permission prompt tool returned an invalid result. Expected a single text block param with type="text" and a string text value.`);return Ja(Xa().parse(tt(h.content[0].text)),e,r,i)};return t}function Jo(e,t,n,r){if(e===`stdio`)return t.createCanUseTool(r);if(!e)return async(e,t,n,r,i,a)=>a??await Nt(e,t,n,r,i);let i=null;return async(t,r,a,o,s,c)=>{if(!i){let t=n(),r=t.find(t=>Li(t,e));if(!r){let n=`Error: MCP tool ${e} (passed via --permission-prompt-tool) not found. Available MCP tools: ${t.map(e=>e.name).join(`, `)||`none`}`;throw process.stderr.write(`${n}\n`),K(1),Error(n)}if(!r.inputJSONSchema){let t=`Error: tool ${e} (passed via --permission-prompt-tool) must be an MCP tool`;throw process.stderr.write(`${t}\n`),K(1),Error(t)}i=qo(r)}return i(t,r,a,o,s,c)}}async function Yo(e,t,n,r,i,a,o,s,c,l,d){if(n){r.enqueue({type:`control_response`,response:{subtype:`error`,error:`Already initialized`,request_id:t,pending_permission_requests:o.getPendingPermissionRequests()}});return}if(e.systemPrompt!==void 0&&(c.systemPrompt=e.systemPrompt),e.appendSystemPrompt!==void 0&&(c.appendSystemPrompt=e.appendSystemPrompt),e.promptSuggestions!==void 0&&(c.promptSuggestions=e.promptSuggestions),e.agents){let t=Xr(e.agents,`flagSettings`);l.push(...t)}if(c.agent){let e=x()===c.agent,t=l.find(e=>e.agentType===c.agent);if(t&&!e){if(y(t.agentType),!c.systemPrompt&&!oi(t)){let e=t.getSystemPrompt();e&&(c.systemPrompt=e)}!c.userSpecifiedModel&&t.model&&t.model!==`inherit`&&b(w(t.model)),t.initialPrompt&&o.prependUserMessage(t.initialPrompt)}else t?.initialPrompt&&o.prependUserMessage(t.initialPrompt)}let f=j()?.outputStyle||`default`,p=await Zn(Ue()),m=ne();if(e.hooks){let t={};for(let[n,r]of Object.entries(e.hooks))t[n]=r.map(e=>{let t=e.hookCallbackIds.map(t=>o.createHookCallback(t,e.timeout));return{matcher:e.matcher,hooks:t}});g(t)}e.jsonSchema&&h(e.jsonSchema);let ee={commands:i.filter(e=>e.userInvocable!==!1).map(e=>({name:Lr(e),description:Ft(e),argumentHint:e.argumentHint||``})),agents:l.map(e=>({name:e.agentType,description:e.whenToUse,model:e.model===`inherit`?void 0:e.model})),output_style:f,available_output_styles:Object.keys(p),models:a,account:{email:m?.email,organization:m?.organization,subscriptionType:m?.subscription,tokenSource:m?.tokenSource,apiKeySource:m?.apiKeySource,apiProvider:ue()},pid:process.pid};if(Ae()&&je()){let e=d();ee.fast_mode_state=Ee(c.userSpecifiedModel??null,e.fastMode)}if(r.enqueue({type:`control_response`,response:{subtype:`success`,request_id:t,response:ee}}),s){let e=ce.getInstance().getStatus();e&&r.enqueue({type:`auth_status`,isAuthenticating:e.isAuthenticating,output:e.output,error:e.error,uuid:Y(),session_id:u()})}}async function Xo(e,t,n,r){if(!Gn())return{canRewind:!1,error:`File rewinding is not enabled.`,filesChanged:[]};if(!Rn(t.fileHistory,e))return{canRewind:!1,error:`No file checkpoint found for this message.`,filesChanged:[]};if(r){let n=await fn(t.fileHistory,e);return{canRewind:!0,filesChanged:n?.filesChanged??[],insertions:n?.insertions,deletions:n?.deletions}}try{await Wr(e=>n(t=>({...t,fileHistory:e(t.fileHistory)})),e)}catch(e){return{canRewind:!1,error:`Failed to rewind: ${F(e)}`,filesChanged:[]}}return{canRewind:!0,filesChanged:[]}}function Zo(e,t,n,r){if(e.mode===`bypassPermissions`){if(tn())return r.enqueue({type:`control_response`,response:{subtype:`error`,request_id:t,error:`Cannot set permission mode to bypassPermissions because it is disabled by settings or configuration`}}),n;if(!n.isBypassPermissionsModeAvailable)return r.enqueue({type:`control_response`,response:{subtype:`error`,request_id:t,error:`Cannot set permission mode to bypassPermissions because the session was not launched with --dangerously-skip-permissions`}}),n}if(e.mode===`auto`&&!St()){let e=_n();return r.enqueue({type:`control_response`,response:{subtype:`error`,request_id:t,error:e?`Cannot set permission mode to auto: ${Ti(e)}`:`Cannot set permission mode to auto`}}),n}return r.enqueue({type:`control_response`,response:{subtype:`success`,request_id:t,response:{mode:e.mode}}}),{...At(n.mode,e.mode,n),mode:e.mode}}function Qo(e,t,n,r){let i=t=>r.enqueue({type:`control_response`,response:{subtype:`error`,request_id:e,error:t}}),a=n.find(e=>e.name===t&&e.type===`connected`);if(!a||a.type!==`connected`)return i(`server ${t} is not connected`);let o=a.config.pluginSource,s=o?Ji(o):void 0;if(!s?.marketplace)return i(`server ${t} is not plugin-sourced; channel_enable requires a marketplace plugin`);let c={kind:`plugin`,name:s.name,marketplace:s.marketplace},l=S(),u=l.some(e=>e.kind===`plugin`&&e.name===c.name&&e.marketplace===c.marketplace);u||m([...l,c]);let d=za(t,a.capabilities,o);if(d.action===`skip`)return u||m(l),i(d.reason);let f=`${c.name}@${c.marketplace}`;Ye(t,`Channel notifications registered`),z(`tengu_mcp_channel_enable`,{plugin:f}),a.client.setNotificationHandler(Ra(),async e=>{let{content:n,meta:r}=e.params;Ye(t,`notifications/claude/channel: ${n.slice(0,80)}`),z(`tengu_mcp_channel_message`,{content_length:n.length,meta_key_count:Object.keys(r??{}).length,entry_kind:`plugin`,is_dev:!1,plugin:f}),J({mode:`prompt`,value:Ia(t,n,r),priority:`next`,isMeta:!0,origin:{kind:`channel`,server:t},skipSlashCommands:!0})}),r.enqueue({type:`control_response`,response:{subtype:`success`,request_id:e,response:void 0}})}function $o(e){if(e.type!==`connected`||za(e.name,e.capabilities,e.config.pluginSource).action!==`register`)return;let t=La(e.name,S()),n=t?.kind===`plugin`?`${t.name}@${t.marketplace}`:void 0;Ye(e.name,`Channel notifications re-registered after reconnect`),e.client.setNotificationHandler(Ra(),async r=>{let{content:i,meta:a}=r.params;Ye(e.name,`notifications/claude/channel: ${i.slice(0,80)}`),z(`tengu_mcp_channel_message`,{content_length:i.length,meta_key_count:Object.keys(a??{}).length,entry_kind:t?.kind,is_dev:t?.dev??!1,plugin:n}),J({mode:`prompt`,value:Ia(e.name,i,a),priority:`next`,isMeta:!0,origin:{kind:`channel`,server:e.name},skipSlashCommands:!0})})}function es(e,t){if(t===`stream-json`){let t={type:`result`,subtype:`error_during_execution`,duration_ms:0,duration_api_ms:0,is_error:!0,num_turns:0,stop_reason:null,session_id:u(),total_cost_usd:0,usage:ia,modelUsage:{},permission_denials:[],uuid:Y(),errors:[e]};process.stdout.write(P(t)+`
|
|
36
|
-
`)}else process.stderr.write(e+`
|
|
37
|
-
`)}function ts(e,t){let n=e.findIndex(e=>e.uuid===t.uuid);n!==-1&&e.splice(n,2)}async function ns(t,n){let r=!v();if(n.continue)try{z(`tengu_continue_print`,{});let i=await Oi(void 0,void 0);if(i){if(Q){let n=Q.matchSessionMode(i.mode);if(n){process.stderr.write(n+`
|
|
38
|
-
`);let{getAgentDefinitionsWithOverrides:r,getActiveAgentsFromList:i}=(Gr(),e(di));r.cache.clear?.();let a=await r(Ue());t(e=>({...e,agentDefinitions:{...a,allAgents:a.allAgents,activeAgents:i(a.allAgents)}}))}}return n.forkSession||i.sessionId&&(te(Kn(i.sessionId),i.fullPath?po(i.fullPath):null),r&&await dr()),co(i,t),hr(n.forkSession?{...i,worktreeSession:void 0}:i),Q&&_i(Q.isCoordinatorMode()?`coordinator`:`normal`),{messages:i.messages,turnInterruptionState:i.turnInterruptionState,agentSetting:i.agentSetting}}}catch(e){return W(e),K(1),{messages:[]}}if(n.teleport)try{if(!vt(`allow_remote_sessions`))throw Error(`Remote sessions are disabled by your organization's policy.`);if(z(`tengu_teleport_print`,{}),typeof n.teleport!=`string`)throw Error(`No session ID provided for teleport`);let{checkOutTeleportedSessionBranch:e,processMessagesForTeleportResume:t,teleportResumeCodeSession:r,validateGitState:i}=await import(`./teleport-B4p8XlAv.js`);await i();let a=await r(n.teleport),{branchError:o}=await e(a.branch);return{messages:t(a.log,o)}}catch(e){return W(e),K(1),{messages:[]}}if(n.resume)try{z(`tengu_resume_print`,{});let a=Do(typeof n.resume==`string`?n.resume:``);if(!a){let e=`Error: --resume requires a valid session ID when used with --print. Usage: claude -p --resume <session-id>`;return typeof n.resume==`string`&&(e+=`. Session IDs must be in UUID format (e.g., 550e8400-e29b-41d4-a716-446655440000). Provided value "${n.resume}" is not a valid UUID`),es(e,n.outputFormat),K(1),{messages:[]}}if(i(process.env.CLAUDE_CODE_USE_CCR_V2)){let[,e]=await Promise.all([rn(a.sessionId),n.restoredWorkerState]);e&&(t(Va(e)),typeof e.model==`string`&&b(e.model))}else a.isUrl&&a.ingressUrl&&i(process.env.ENABLE_SESSION_PERSISTENCE)&&await Nr(a.sessionId,a.ingressUrl);let o=await Oi(a.sessionId,a.jsonlFile||void 0);if(!o||o.messages.length===0)return a.isUrl||i(process.env.CLAUDE_CODE_USE_CCR_V2)?{messages:await(n.sessionStartHooksPromise??xn(`startup`))}:(es(`No conversation found with session ID: ${a.sessionId}`,n.outputFormat),K(1),{messages:[]});if(n.resumeSessionAt){let e=o.messages.findIndex(e=>e.uuid===n.resumeSessionAt);if(e<0)return es(`No message found with message.uuid of: ${n.resumeSessionAt}`,n.outputFormat),K(1),{messages:[]};o.messages=e>=0?o.messages.slice(0,e+1):[]}if(Q){let n=Q.matchSessionMode(o.mode);if(n){process.stderr.write(n+`
|
|
39
|
-
`);let{getAgentDefinitionsWithOverrides:r,getActiveAgentsFromList:i}=(Gr(),e(di));r.cache.clear?.();let a=await r(Ue());t(e=>({...e,agentDefinitions:{...a,allAgents:a.allAgents,activeAgents:i(a.allAgents)}}))}}return!n.forkSession&&o.sessionId&&(te(Kn(o.sessionId),o.fullPath?po(o.fullPath):null),r&&await dr()),co(o,t),hr(n.forkSession?{...o,worktreeSession:void 0}:o),Q&&_i(Q.isCoordinatorMode()?`coordinator`:`normal`),{messages:o.messages,turnInterruptionState:o.turnInterruptionState,agentSetting:o.agentSetting}}catch(e){return W(e),es(e instanceof Error?`Failed to resume session: ${e.message}`:`Failed to resume session with --print mode`,n.outputFormat),K(1),{messages:[]}}return{messages:await(n.sessionStartHooksPromise??xn(`startup`))}}function rs(e,t){let n;return n=typeof e==`string`?e.trim()===``?gt([]):gt([P({type:`user`,content:e,uuid:``,session_id:``,message:{role:`user`,content:e},parent_tool_use_id:null})]):e,t.sdkUrl?new bo(t.sdkUrl,n,t.replayUserMessages):new Ga(n,t.replayUserMessages)}async function is({message:e,setAppState:t,onEnqueued:n,handledToolUseIds:r}){let i=e.response;if(i?.subtype===`success`&&i.response?.toolUseID&&typeof i.response.toolUseID==`string`){let e=i.response,t=e.toolUseID;if(!t)return!1;if(I(`handleOrphanedPermissionResponse: received orphaned control_response for toolUseID=${t} request_id=${i.request_id}`),r.has(t))return I(`handleOrphanedPermissionResponse: skipping duplicate orphaned permission for toolUseID=${t} (already handled)`),!1;let a=await Rr(t);return a?(r.add(t),I(`handleOrphanedPermissionResponse: enqueuing orphaned permission for toolUseID=${t} messageID=${a.message.id}`),J({mode:`orphaned-permission`,value:[],orphanedPermission:{permissionResult:e,assistantMessage:a}}),n?.(),!0):(I(`handleOrphanedPermissionResponse: no unresolved tool_use found for toolUseID=${t} (already resolved in transcript)`),!1)}return!1}function as(e){return{...e,scope:`dynamic`}}async function os(e,t,n,r){let{allowed:i,blocked:a}=$n(e),o={};for(let e of a)o[e]=`Blocked by enterprise policy (allowedMcpServers/deniedMcpServers)`;let s={},c={};for(let[e,t]of Object.entries(i))t.type===`sdk`?s[e]=t:c[e]=t;let l=new Set(Object.keys(t.configs)),u=new Set(Object.keys(s)),d=[],f=[],p={...t.configs},m=[...t.clients],h=[...t.tools];for(let e of l)if(!u.has(e)){let t=m.find(t=>t.name===e);t&&t.type===`connected`&&await t.cleanup(),m=m.filter(t=>t.name!==e);let n=`mcp__${e}__`;h=h.filter(e=>!e.name.startsWith(n)),delete p[e],f.push(e)}for(let[e,t]of Object.entries(s))if(!l.has(e)){p[e]=t;let n={type:`pending`,name:e,config:{...t,scope:`dynamic`}};m=[...m,n],d.push(e)}let g=await ss(c,n,r);return{response:{added:[...d,...g.response.added],removed:[...f,...g.response.removed],errors:{...o,...g.response.errors}},newSdkState:{configs:p,clients:m,tools:h},newDynamicState:g.newState,sdkServersChanged:d.length>0||f.length>0}}async function ss(e,t,n){let r=new Set(Object.keys(t.configs)),i=new Set(Object.keys(e)),a=[...r].filter(e=>!i.has(e)),o=[...i].filter(e=>!r.has(e)),s=[...r].filter(e=>i.has(e)).filter(n=>{let r=t.configs[n],i=e[n];return!r||!i?!0:!Cr(r,as(i))}),c=[],l=[],u={},d=[...t.clients],f=[...t.tools];for(let e of[...a,...s]){let n=d.find(t=>t.name===e),r=t.configs[e];if(n&&r){if(n.type===`connected`)try{await n.cleanup()}catch(e){W(e)}await vi(e,r)}let i=`mcp__${e}__`;f=f.filter(e=>!e.name.startsWith(i)),d=d.filter(t=>t.name!==e),a.includes(e)&&c.push(e)}for(let t of[...o,...s]){let n=e[t];if(!n)continue;let r=as(n);if(n.type===`sdk`){l.push(t);continue}try{let e=await Mi(t,r);if(d.push(e),e.type===`connected`){let t=await vn(e);f.push(...t)}else e.type===`failed`&&(u[t]=e.error||`Connection failed`);l.push(t)}catch(e){let n=Ne(e);u[t]=n.message,W(n)}}let p={};for(let t of i){let n=e[t];n&&(p[t]=as(n))}let m={clients:d,tools:f,configs:p};return n(e=>{let n=new Set([...Object.keys(t.configs),...Object.keys(p)]),r=e.mcp.tools.filter(e=>{for(let t of n)if(e.name.startsWith(`mcp__${t}__`))return!1;return!0}),i=e.mcp.clients.filter(e=>!n.has(e.name));return{...e,mcp:{...e.mcp,tools:[...r,...f],clients:[...i,...d]}}}),{response:{added:l,removed:c,errors:u},newState:m}}export{Go as runHeadless};
|