@readmagic/workmate 0.0.15 → 0.0.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (273) hide show
  1. package/dist/chunks/{AddWorkspaceDirectory-DcVnvL_u.js → AddWorkspaceDirectory-DAtfMH4o.js} +1 -1
  2. package/dist/chunks/{AgentsMdExternalIncludesDialog-D6DopTxc.js → AgentsMdExternalIncludesDialog-BTYgjY5c.js} +1 -1
  3. package/dist/chunks/AgentsMdExternalIncludesDialog-C6VH6JG6.js +1 -0
  4. package/dist/chunks/{App-BoI5EJry.js → App-HF0bvxi_.js} +1 -1
  5. package/dist/chunks/ApproveApiKey-B7mKgSqY.js +1 -0
  6. package/dist/chunks/{ApproveApiKey-BjlQDcMx.js → ApproveApiKey-BBFLw2B7.js} +1 -1
  7. package/dist/chunks/{BackgroundTasksDialog-ClSMkcGp.js → BackgroundTasksDialog-Coc0ecUd.js} +1 -1
  8. package/dist/chunks/{BypassPermissionsModeDialog-KCZv-PXl.js → BypassPermissionsModeDialog--Gx9ARd4.js} +1 -1
  9. package/dist/chunks/{DiffDialog-BGBkuVIn.js → DiffDialog-tlINuFS1.js} +1 -1
  10. package/dist/chunks/Doctor-BJf49FWX.js +1 -0
  11. package/dist/chunks/{Doctor-CI04juFO.js → Doctor-Wh7z6CnF.js} +2 -2
  12. package/dist/chunks/ExitFlow-B1zHTqQt.js +2 -0
  13. package/dist/chunks/{Grove-B-M3DWD3.js → Grove-1Kf7xxIV.js} +1 -1
  14. package/dist/chunks/{HybridTransport-n5jji6SI.js → HybridTransport-DWqWUZCH.js} +1 -1
  15. package/dist/chunks/{InvalidConfigDialog-By-j6fHE.js → InvalidConfigDialog-OZPFQSnC.js} +1 -1
  16. package/dist/chunks/{InvalidSettingsDialog-C_reeMzL.js → InvalidSettingsDialog-BNCm-eyC.js} +1 -1
  17. package/dist/chunks/MCPConnectionManager-7H84oi5n.js +1 -0
  18. package/dist/chunks/{MCPToolListView-jw0tITfc.js → MCPToolListView-CVgtg3Iq.js} +1 -1
  19. package/dist/chunks/{McpParsingWarnings-BeZ3Bn8N.js → McpParsingWarnings-CN8f449l.js} +1 -1
  20. package/dist/chunks/{MessageSelector-Ci6N-gCw.js → MessageSelector-B9j6zZ5w.js} +1 -1
  21. package/dist/chunks/Messages-yz1m39eI.js +10 -0
  22. package/dist/chunks/{Onboarding-DDkVEq-G.js → Onboarding-bFbgae8m.js} +1 -1
  23. package/dist/chunks/{PromptInputFooterSuggestions-BlhZuQ5F.js → PromptInputFooterSuggestions-CE_yVun1.js} +1 -1
  24. package/dist/chunks/PromptInputHelpMenu-TPWuGwAy.js +1 -0
  25. package/dist/chunks/QueryEngine-CRobcENE.js +1 -0
  26. package/dist/chunks/REPL-BhCC0JP6.js +1 -0
  27. package/dist/chunks/REPL-C33mMf_q.js +128 -0
  28. package/dist/chunks/{RemoteSessionManager-mWVrdNfS.js → RemoteSessionManager-BjVD918g.js} +2 -2
  29. package/dist/chunks/{ResumeConversation-BzTn_1jS.js → ResumeConversation-CXd8d8po.js} +1 -1
  30. package/dist/chunks/{SSETransport-D86IVNn1.js → SSETransport-BSilVN9e.js} +1 -1
  31. package/dist/chunks/SearchExtraToolsTool-DoiCI2uJ.js +1 -0
  32. package/dist/chunks/Settings-ClcLl0C1.js +2 -0
  33. package/dist/chunks/{TeleportProgress-CW8mLRy2.js → TeleportProgress-DonJUoPc.js} +1 -1
  34. package/dist/chunks/{TeleportRepoMismatchDialog-DZD32R-l.js → TeleportRepoMismatchDialog-ByOuSVVz.js} +1 -1
  35. package/dist/chunks/{TeleportResumeWrapper-BhuUE1aq.js → TeleportResumeWrapper-BBtELwF1.js} +1 -1
  36. package/dist/chunks/{ThemePicker-ByQZgIbH.js → ThemePicker-1QQJFOEv.js} +1 -1
  37. package/dist/chunks/{TrustDialog-BzwibD_8.js → TrustDialog-DwJ9L_u4.js} +1 -1
  38. package/dist/chunks/{add-dir-BQ-ljgk6.js → add-dir-DOKdPFT2.js} +1 -1
  39. package/dist/chunks/{agentDisplay-tRprY4gB.js → agentDisplay-TX1bh-lX.js} +1 -1
  40. package/dist/chunks/{agents-Dq4BCf0H.js → agents-C58tRxpi.js} +1 -1
  41. package/dist/chunks/{agents-DMyQUXwl.js → agents-CbRjX9Pj.js} +6 -6
  42. package/dist/chunks/{allErrors-CQWZ6BPw.js → allErrors-DRiW7i6Y.js} +1 -1
  43. package/dist/chunks/api-C8uOHD-v.js +1 -0
  44. package/dist/chunks/{api-ClAyS7cQ.js → api-CazVavfB.js} +1 -1
  45. package/dist/chunks/auth-BL238vgr.js +1 -0
  46. package/dist/chunks/auth-CfrCl9BZ.js +10 -0
  47. package/dist/chunks/auth-D3GkU6d7.js +1 -0
  48. package/dist/chunks/{backgroundHousekeeping-rzQFJiND.js → backgroundHousekeeping-CPLlaWcV.js} +2 -2
  49. package/dist/chunks/backgroundHousekeeping-Du2tN2WE.js +1 -0
  50. package/dist/chunks/{branch-BWbCrXBJ.js → branch-pAa0oBaj.js} +1 -1
  51. package/dist/chunks/{bridgeConfig-CPHAyzdg.js → bridgeConfig-DnFfCpGd.js} +1 -1
  52. package/dist/chunks/bridgeConfig-joBqeK0j.js +1 -0
  53. package/dist/chunks/{bridgeMessaging-vR7uQXB9.js → bridgeMessaging-B_hnuUHb.js} +1 -1
  54. package/dist/chunks/{bridgeStatusUtil-CHTx7XwJ.js → bridgeStatusUtil-Dwz4YHNA.js} +1 -1
  55. package/dist/chunks/{btw-IGcgP-Qq.js → btw-CkVkYeRr.js} +1 -1
  56. package/dist/chunks/{caches-FP8mGB4k.js → caches-BLQUkrIG.js} +1 -1
  57. package/dist/chunks/caches-DsFl83sh.js +1 -0
  58. package/dist/chunks/{ccrClient--8aPutWE.js → ccrClient-AfdUbWzY.js} +1 -1
  59. package/dist/chunks/{clear-CF-FZwpe.js → clear-Ac3qYi_-.js} +1 -1
  60. package/dist/chunks/client-BX0r6K3I.js +1 -0
  61. package/dist/chunks/client-Bb2eZnuq.js +1 -0
  62. package/dist/chunks/client-DNEVh6Wu.js +1 -0
  63. package/dist/chunks/client-Pap_HyZZ.js +1 -0
  64. package/dist/chunks/client-zhozU2ws.js +1 -0
  65. package/dist/chunks/commands-BKLsl6gK.js +1 -0
  66. package/dist/chunks/{compact-BrJGpEFZ.js → compact-CXuDr5qM.js} +1 -1
  67. package/dist/chunks/config-DrY1SvhQ.js +1 -0
  68. package/dist/chunks/{context-DADnwl4t.js → context-C2plOqH4.js} +1 -1
  69. package/dist/chunks/context-noninteractive-DpVlZ-wP.js +1 -0
  70. package/dist/chunks/{context-noninteractive-kACWzgS1.js → context-noninteractive-fVQtwEkw.js} +1 -1
  71. package/dist/chunks/conversation-C0yysXds.js +1 -0
  72. package/dist/chunks/{conversation-C8w1DtXk.js → conversation-DQpS6nvg.js} +1 -1
  73. package/dist/chunks/{createSSHSession-B71Plec6.js → createSSHSession-CfyFuJMH.js} +1 -1
  74. package/dist/chunks/createSession-CmBawnsh.js +1 -0
  75. package/dist/chunks/{createSession-BJeDECzt.js → createSession-qk9C66lK.js} +1 -1
  76. package/dist/chunks/{crossProjectResume-B1I6YzXr.js → crossProjectResume-DY1ZBO5P.js} +1 -1
  77. package/dist/chunks/{datadog-C9uqPA6N.js → datadog-Cr0VKbct.js} +1 -1
  78. package/dist/chunks/{diff-CzChvQyK.js → diff-BNjcCXDr.js} +1 -1
  79. package/dist/chunks/doctor-BkCtT7H1.js +1 -0
  80. package/dist/chunks/{entry-BoL8sy1Y.js → entry-o9IZPS4g.js} +2 -2
  81. package/dist/chunks/{esm-DtcV71xh.js → esm-BI3tFLyy.js} +1 -1
  82. package/dist/chunks/exit-Dlyj7nY8.js +1 -0
  83. package/dist/chunks/extraUsage-5Ueiyw6W.js +1 -0
  84. package/dist/chunks/extractMemories-DnTBWFOW.js +1 -0
  85. package/dist/chunks/fast-B3fRp1xO.js +1 -0
  86. package/dist/chunks/fast-ClOKONyD.js +1 -0
  87. package/dist/chunks/fetchModelList-B8KG79EK.js +1 -0
  88. package/dist/chunks/fetchModelList-gh_jFYai.js +1 -0
  89. package/dist/chunks/{fileSuggestions-DU7gmksK.js → fileSuggestions-DK7W8kLF.js} +1 -1
  90. package/dist/chunks/{firstPartyEventLogger-7pAyUdbp.js → firstPartyEventLogger-BMnXb9cv.js} +2 -2
  91. package/dist/chunks/firstPartyEventLogger-YYOb8aIo.js +1 -0
  92. package/dist/chunks/{flushGate-4DfYr-Ru.js → flushGate-n4kK6H1U.js} +1 -1
  93. package/dist/chunks/{gemini-Cll4fVQn.js → gemini-C8-QHnsC.js} +1 -1
  94. package/dist/chunks/{generateSessionName-BgGMwpps.js → generateSessionName-C8DnAVaa.js} +1 -1
  95. package/dist/chunks/{goal-D4E2WQVn.js → goal-DMmzlZOF.js} +1 -1
  96. package/dist/chunks/grok-LLjpAwP_.js +1 -0
  97. package/dist/chunks/{grove-Bck1zFaD.js → grove-CQBCzeHf.js} +1 -1
  98. package/dist/chunks/{help-DJp61Job.js → help-JH7WzjZP.js} +1 -1
  99. package/dist/chunks/hooks-COhKt_pF.js +1 -0
  100. package/dist/chunks/{hooks-CJ17byYD.js → hooks-DD2jpRfx.js} +1 -1
  101. package/dist/chunks/initReplBridge-BDaN0hpY.js +1 -0
  102. package/dist/chunks/{install-Dd5fw0cA.js → install-CD4or0vj.js} +1 -1
  103. package/dist/chunks/{instrumentation-jsPu6qqs.js → instrumentation-n-otwpYf.js} +4 -4
  104. package/dist/chunks/{job-BHhkQbvu.js → job-B-pEWgXI.js} +1 -1
  105. package/dist/chunks/keybindings-qed9q9tx.js +1 -0
  106. package/dist/chunks/{launchLocalMemory-DsaijVcO.js → launchLocalMemory-cBovdGMT.js} +1 -1
  107. package/dist/chunks/{launchOnboarding-DHOylaqn.js → launchOnboarding-B__wtt7p.js} +1 -1
  108. package/dist/chunks/{loadAgentsDir-CwEfQDOw.js → loadAgentsDir-PPiD2Mfq.js} +569 -569
  109. package/dist/chunks/loadAgentsDir-qvqrTVuS.js +1 -0
  110. package/dist/chunks/{loadPluginHooks-C-Yk5KlI.js → loadPluginHooks-DUCuU3_8.js} +1 -1
  111. package/dist/chunks/localSearch-CDk_stXJ.js +1 -0
  112. package/dist/chunks/{localSearch-BEnlgSB7.js → localSearch-Cvs9WfoX.js} +1 -1
  113. package/dist/chunks/{logoV2Utils-DG9GwFjl.js → logoV2Utils-Bkj74dtY.js} +1 -1
  114. package/dist/chunks/{magicDocs-qGHR3Cqh.js → magicDocs-3U6peChg.js} +2 -2
  115. package/dist/chunks/{main-CBVQ8bRm.js → main-DkjxhBIC.js} +26 -26
  116. package/dist/chunks/{managedEnv-3MbOWrVs.js → managedEnv-BUrzwaD3.js} +1 -1
  117. package/dist/chunks/managedEnv-XOUMOtEF.js +1 -0
  118. package/dist/chunks/{mappers-CdY45PDA.js → mappers-ZGgwqDOK.js} +1 -1
  119. package/dist/chunks/{mcp-DvY_FibT.js → mcp-COZxwgJZ.js} +3 -3
  120. package/dist/chunks/{mcp-DI8pGrqi.js → mcp-CdyNeNzh.js} +1 -1
  121. package/dist/chunks/{mcp-BA8XQ6h1.js → mcp-CysOyBIn.js} +1 -1
  122. package/dist/chunks/{memory-C2U7CCmM.js → memory-B5h2TTSS.js} +1 -1
  123. package/dist/chunks/{mode-ByV6NqmB.js → mode-D3yY1fdK.js} +1 -1
  124. package/dist/chunks/model-Bz4JHoU0.js +1 -0
  125. package/dist/chunks/model-g6XBcNAG.js +1 -0
  126. package/dist/chunks/{model-CeG-iOKF.js → model-sviY1inu.js} +1 -1
  127. package/dist/chunks/modelOptions-DYQqTLPi.js +1 -0
  128. package/dist/chunks/{nativeInstaller-CXFD8LDV.js → nativeInstaller-N1xiUpCP.js} +1 -1
  129. package/dist/chunks/{omit-B65XeX8r.js → omit-BOILu8jW.js} +1 -1
  130. package/dist/chunks/{onChangeAppState-EtUxsgYz.js → onChangeAppState-COFFZAXb.js} +1 -1
  131. package/dist/chunks/{openai-Dx5mvMjY.js → openai-BHM5kEFo.js} +2 -2
  132. package/dist/chunks/openai-CR3CcjCE.js +17 -0
  133. package/dist/chunks/{partition-8vZDG3rY.js → partition-C1SFDk_L.js} +1 -1
  134. package/dist/chunks/{permissions-CJUBfBTr.js → permissions-uy_NFbfy.js} +2 -2
  135. package/dist/chunks/{pidLock-tjm2n1Nd.js → pidLock-DuMVSwnN.js} +2 -2
  136. package/dist/chunks/{plan-eFur8bdH.js → plan-DF9YSB5M.js} +1 -1
  137. package/dist/chunks/{plugin-fYLRLdOY.js → plugin-GRPzqgTr.js} +1 -1
  138. package/dist/chunks/{pluginAutoupdate-B4w7SSYc.js → pluginAutoupdate-AMD-FvKB.js} +1 -1
  139. package/dist/chunks/{pluginBlocklist-CMwb7gmY.js → pluginBlocklist-DNxkAxH6.js} +1 -1
  140. package/dist/chunks/{pluginCliCommands-3YCj7Y3Q.js → pluginCliCommands-BFoR1ZXx.js} +1 -1
  141. package/dist/chunks/{pluginFlagging-srvq9H7p.js → pluginFlagging-CW2IZWSI.js} +1 -1
  142. package/dist/chunks/{pluginOperations-C7BCR7pw.js → pluginOperations-DlWE0idP.js} +1 -1
  143. package/dist/chunks/{pluginStartupCheck-BLc0U7W7.js → pluginStartupCheck-AQGV0DCS.js} +1 -1
  144. package/dist/chunks/pluginStartupCheck-DWpquqxx.js +1 -0
  145. package/dist/chunks/{plugins-CPtmmDDi.js → plugins-CwUSTE4E.js} +1 -1
  146. package/dist/chunks/print-9wR_ijrL.js +14 -0
  147. package/dist/chunks/{processBashCommand-C9-FonuX.js → processBashCommand-Deqwq1IE.js} +1 -1
  148. package/dist/chunks/{processSlashCommand-Bi8_1MRC.js → processSlashCommand-U9LJ4Keq.js} +2 -2
  149. package/dist/chunks/prompt-BBeDQXIs.js +1 -0
  150. package/dist/chunks/{prompt-Bm2EEG4F.js → prompt-CQmEvnKN.js} +1 -1
  151. package/dist/chunks/prompt-CXhdqgB7.js +1 -0
  152. package/dist/chunks/{promptEditor-DQ9fpdQD.js → promptEditor-Bf72KNF-.js} +1 -1
  153. package/dist/chunks/{reconciler-DgQ4y1Vn.js → reconciler-Css9bs07.js} +1 -1
  154. package/dist/chunks/{refresh-CayVRWUY.js → refresh-B87z39Zs.js} +1 -1
  155. package/dist/chunks/{reload-plugins-6xcH3dLg.js → reload-plugins-BpmUIkfm.js} +1 -1
  156. package/dist/chunks/{remoteBridgeCore-BnZYGaMH.js → remoteBridgeCore-BCLIIygk.js} +1 -1
  157. package/dist/chunks/{remoteManagedSettings-CfFmrRze.js → remoteManagedSettings-Ahgn2e80.js} +1 -1
  158. package/dist/chunks/{rename-mDtCTbnD.js → rename-BUt3PliQ.js} +1 -1
  159. package/dist/chunks/{resume-DRvz4QFs.js → resume-uZI9p_FE.js} +1 -1
  160. package/dist/chunks/{runtimeObserver-Ba6SM-sI.js → runtimeObserver-AKOWfdZ_.js} +1 -1
  161. package/dist/chunks/{runtimeObserver-Dt5sGJVb.js → runtimeObserver-By59MZKJ.js} +2 -2
  162. package/dist/chunks/sandbox-adapter-D4Uho1vF.js +1 -0
  163. package/dist/chunks/{sandbox-toggle-DKcw3SbO.js → sandbox-toggle-BdvylnWS.js} +1 -1
  164. package/dist/chunks/searchExtraTools-BHMkqGBf.js +1 -0
  165. package/dist/chunks/{session-COVyD8UU.js → session-Tm2-rzBY.js} +1 -1
  166. package/dist/chunks/sessionFileAccessHooks-BaWZ8sqn.js +1 -0
  167. package/dist/chunks/{sessionObserver-iAgSetlC.js → sessionObserver-BAr8AWeL.js} +1 -1
  168. package/dist/chunks/sessionObserver-KB1UL_n2.js +1 -0
  169. package/dist/chunks/{sessionState-zhvcDpb2.js → sessionState-BTFowSpR.js} +2 -2
  170. package/dist/chunks/sessionStorage-D6nlmaI-.js +1 -0
  171. package/dist/chunks/{sessionTitle-QPRly1tZ.js → sessionTitle-SCqmSDYM.js} +1 -1
  172. package/dist/chunks/{sessionTracing-C4uqAdud.js → sessionTracing-CvY4udYI.js} +1 -1
  173. package/dist/chunks/{settingsSync-BGo6dHJo.js → settingsSync-nxeaGM2-.js} +1 -1
  174. package/dist/chunks/setup-D4FPeBnM.js +3 -0
  175. package/dist/chunks/{shadowedRuleDetection-CzRAzcC1.js → shadowedRuleDetection-Co8m1q1D.js} +1 -1
  176. package/dist/chunks/{sideQuestion-oIYrx5ar.js → sideQuestion-4TJYn-Az.js} +1 -1
  177. package/dist/chunks/{sinks-Bje3hCkR.js → sinks-Bb2i50kz.js} +1 -1
  178. package/dist/chunks/sinks-D1opmy_x.js +1 -0
  179. package/dist/chunks/skillChangeDetector-BU9AFG0i.js +1 -0
  180. package/dist/chunks/{skillGapStore-CJjt3IW7.js → skillGapStore-BcVP3ZUb.js} +2 -2
  181. package/dist/chunks/{skillLifecycle-BsgH84vl.js → skillLifecycle-CG2XmS8f.js} +2 -2
  182. package/dist/chunks/{skillSearchPanel-CneXymsb.js → skillSearchPanel-DOJmUBXB.js} +4 -4
  183. package/dist/chunks/{skills-DZRBy7vT.js → skills-DIgCWvzX.js} +1 -1
  184. package/dist/chunks/{status-BP_R8051.js → status-Ber2xOXc.js} +2 -2
  185. package/dist/chunks/status-CVcXPoOZ.js +1 -0
  186. package/dist/chunks/{statusNoticeHelpers-ODrnrLAZ.js → statusNoticeHelpers-CYkrPUpN.js} +1 -1
  187. package/dist/chunks/{switcher-BkGOeIzI.js → switcher-BIP3rbQn.js} +1 -1
  188. package/dist/chunks/switcher-zbG6T9dN.js +1 -0
  189. package/dist/chunks/syncCache-AMQMQ_HR.js +1 -0
  190. package/dist/chunks/{tasks-CIUuwrX4.js → tasks-BKERIO4G.js} +1 -1
  191. package/dist/chunks/{teleport-IzyDplC7.js → teleport-DOXbf2sQ.js} +1 -1
  192. package/dist/chunks/{templateJobs-De57J461.js → templateJobs-dg2F45ZJ.js} +1 -1
  193. package/dist/chunks/{theme-Nwii7354.js → theme-BGxytGjA.js} +1 -1
  194. package/dist/chunks/{toolEventObserver-Cq-uBb0-.js → toolEventObserver-CJhg_p3P.js} +1 -1
  195. package/dist/chunks/toolPool-C0d7Bznl.js +1 -0
  196. package/dist/chunks/{trustedDevice-DWZxDUxS.js → trustedDevice-BtXHXu-T.js} +1 -1
  197. package/dist/chunks/trustedDevice-hw3iq84W.js +1 -0
  198. package/dist/chunks/{useExitOnCtrlCDWithKeybindings-D48aDPG9.js → useExitOnCtrlCDWithKeybindings-C9orgrub.js} +1 -1
  199. package/dist/chunks/useMainLoopModel-BigVcn2T.js +1 -0
  200. package/dist/chunks/{useManagePlugins-EqoQELMT.js → useManagePlugins-Bt-DYAnX.js} +1 -1
  201. package/dist/chunks/{useMergedTools-BJ4L9QSK.js → useMergedTools-CZeQBdky.js} +1 -1
  202. package/dist/chunks/{useSearchInput-DkVER3cm.js → useSearchInput-DdKrVHJS.js} +1 -1
  203. package/dist/chunks/{useSettingsErrors-D3MlQ1GF.js → useSettingsErrors-BR9Wws7D.js} +1 -1
  204. package/dist/chunks/{userAgent-aoe_xVAb.js → userAgent-DUt0q-Vl.js} +1 -1
  205. package/dist/chunks/{util-g-5UX5gH.js → util-h-Hmdke_.js} +1 -1
  206. package/dist/chunks/{validatePlugin-CSE8zjZn.js → validatePlugin-mWVKNtJa.js} +1 -1
  207. package/dist/chunks/{workerRegistry-DGwy0YHB.js → workerRegistry-dlfqtySm.js} +2 -2
  208. package/dist/chunks/worktree-IxcFe7g-.js +1 -0
  209. package/dist/cli.js +1 -1
  210. package/package.json +1 -1
  211. package/dist/chunks/AgentsMdExternalIncludesDialog-0Qdg3Rh7.js +0 -1
  212. package/dist/chunks/ApproveApiKey-PWFcscjY.js +0 -1
  213. package/dist/chunks/Doctor-DCrqcW68.js +0 -1
  214. package/dist/chunks/ExitFlow-qrCDVA9i.js +0 -2
  215. package/dist/chunks/MCPConnectionManager-BNG7iSlw.js +0 -1
  216. package/dist/chunks/Messages-D6CRTH2m.js +0 -10
  217. package/dist/chunks/PromptInputHelpMenu-kKyPIMau.js +0 -1
  218. package/dist/chunks/QueryEngine-DXpS0Ytq.js +0 -1
  219. package/dist/chunks/REPL-D1BCm7cR.js +0 -128
  220. package/dist/chunks/REPL-JQgCrSEv.js +0 -1
  221. package/dist/chunks/SearchExtraToolsTool-BXIja1MR.js +0 -1
  222. package/dist/chunks/Settings-D_i8HzEW.js +0 -2
  223. package/dist/chunks/api-CpD5jeKe.js +0 -1
  224. package/dist/chunks/auth-CWAvPfX7.js +0 -10
  225. package/dist/chunks/auth-DG5bkWDc.js +0 -1
  226. package/dist/chunks/auth-DuHfQBuH.js +0 -1
  227. package/dist/chunks/backgroundHousekeeping-kf_v7Vfr.js +0 -1
  228. package/dist/chunks/bridgeConfig-CABsoOum.js +0 -1
  229. package/dist/chunks/caches-Dj1YhqrG.js +0 -1
  230. package/dist/chunks/client-B7WkO81L.js +0 -17
  231. package/dist/chunks/client-BCzhAEd0.js +0 -1
  232. package/dist/chunks/client-BU7upHOb.js +0 -1
  233. package/dist/chunks/commands-Cr1p7OPH.js +0 -1
  234. package/dist/chunks/config-BohF3_IV.js +0 -1
  235. package/dist/chunks/context-noninteractive-BAbzwNxu.js +0 -1
  236. package/dist/chunks/conversation-Ds7zRD0x.js +0 -1
  237. package/dist/chunks/createSession-Bozo4Bu8.js +0 -1
  238. package/dist/chunks/doctor-DdvdGkNX.js +0 -1
  239. package/dist/chunks/exit-Af27f74w.js +0 -1
  240. package/dist/chunks/extraUsage-DsFwXMAj.js +0 -1
  241. package/dist/chunks/extractMemories-B1KbTMY0.js +0 -1
  242. package/dist/chunks/fast-BGU8p2uY.js +0 -1
  243. package/dist/chunks/fast-CuUjONVV.js +0 -1
  244. package/dist/chunks/firstPartyEventLogger-sMeCTEUW.js +0 -1
  245. package/dist/chunks/grok-HF1PHxXb.js +0 -1
  246. package/dist/chunks/hooks-CjR3Eq0Z.js +0 -1
  247. package/dist/chunks/initReplBridge-D09JEKHt.js +0 -1
  248. package/dist/chunks/keybindings-Ch5lzNB8.js +0 -1
  249. package/dist/chunks/loadAgentsDir-8FioUEwX.js +0 -1
  250. package/dist/chunks/localSearch-LcgRjjl3.js +0 -1
  251. package/dist/chunks/managedEnv-B4YV3A_y.js +0 -1
  252. package/dist/chunks/model-C73ETGu9.js +0 -1
  253. package/dist/chunks/model-CVG_RRTy.js +0 -1
  254. package/dist/chunks/modelOptions-A5jrCUBp.js +0 -1
  255. package/dist/chunks/pluginStartupCheck-nzVDPI1k.js +0 -1
  256. package/dist/chunks/print-BCud0ukQ.js +0 -14
  257. package/dist/chunks/prompt-CX_v9F3s.js +0 -1
  258. package/dist/chunks/prompt-V0WQJrkO2.js +0 -1
  259. package/dist/chunks/sandbox-adapter-Cmrd6tBj.js +0 -1
  260. package/dist/chunks/searchExtraTools-DIgC0CFB.js +0 -1
  261. package/dist/chunks/sessionFileAccessHooks-yAPDTrbm.js +0 -1
  262. package/dist/chunks/sessionObserver-BizdPx8P.js +0 -1
  263. package/dist/chunks/sessionStorage-LMY409Ji.js +0 -1
  264. package/dist/chunks/setup-Bjw5VS6x.js +0 -3
  265. package/dist/chunks/sinks-FaljTZ-c.js +0 -1
  266. package/dist/chunks/skillChangeDetector-v6mAYzXX.js +0 -1
  267. package/dist/chunks/status-CZYD3NGb.js +0 -1
  268. package/dist/chunks/switcher-DwKN9daN.js +0 -1
  269. package/dist/chunks/syncCache-CpmpvjfC.js +0 -1
  270. package/dist/chunks/toolPool-BBU4ll_p.js +0 -1
  271. package/dist/chunks/trustedDevice-BKzkA7fq.js +0 -1
  272. package/dist/chunks/useMainLoopModel-89eUU13X.js +0 -1
  273. package/dist/chunks/worktree-jjuORs7p.js +0 -1
@@ -1 +0,0 @@
1
- import{hn as e,mn as t,qt as n,sn as r}from"./loadAgentsDir-CwEfQDOw.js";e();export{n as executeSessionEndHooks,r as getSessionEndHookTimeoutMs,t as hasWorktreeCreateHook};
@@ -1 +0,0 @@
1
- import{l as e,o as t,u as n}from"./envUtils-DcaKZlRU.js";import{Da as r,La as i,Va as a,aE as o,af as s,br as c,hc as l,iE as u,ka as d,lf as f,rf as p,rr as m,yc as h}from"./loadAgentsDir-CwEfQDOw.js";import{Wt as g,et as _,pt as v}from"./state-BPFYBqm1.js";import{P as y,R as b,c as x,i as S,nt as ee,tt as C}from"./debug-BQj6h99Q.js";import{c as te,h as ne,y as re}from"./config-BSkuQZNf.js";import{O as w,i as ie,k as T,m as E,u as D}from"./git-DplvjXEY.js";import{g as O,m as k}from"./log-BlJ7CcKG.js";import{n as A,r as j}from"./analytics-DJobLaWP.js";import{Bt as ae,It as M,Nr as oe,Ot as se,Pr as N,_n as P,mt as F,vn as I}from"./model-CeG-iOKF.js";import{C as L,c as ce,n as R,w as le}from"./sessionState-zhvcDpb2.js";import{a as ue,i as de,r as fe,t as z}from"./sessionIdCompat-Dgp6PW_1.js";import{a as B,i as pe,n as V,o as me,t as H}from"./bridgeConfig-CPHAyzdg.js";import{a as U,o as W,r as G,s as K}from"./debugUtils-B86DM1Sp.js";import{a as q,i as J,n as he,t as Y}from"./createSession-BJeDECzt.js";import{n as ge,o as X}from"./mappers-CdY45PDA.js";import{n as _e,r as Z,t as Q}from"./sessionTitle-QPRly1tZ.js";import{a as ve,d as ye,f as be,i as xe,l as Se,n as Ce,o as we,r as Te,t as Ee,u as De}from"./bridgeMessaging-vR7uQXB9.js";import{i as Oe,n as ke,r as Ae,t as je}from"./flushGate-4DfYr-Ru.js";import{n as Me,t as Ne}from"./pollConfig-BgpfHQPJ.js";import{n as Pe,t as Fe}from"./rcDebugLog-DSchf3Hs.js";import{a as Ie,i as Le,n as $,o as Re,r as ze,t as Be}from"./capacityWake-LRiPhPeM.js";import{a as Ve,n as He,r as Ue,t as We}from"./workSecret-BUd8cQ6-.js";import{i as Ge}from"./trustedDevice-DWZxDUxS.js";import{t as Ke}from"./HybridTransport-n5jji6SI.js";import{hostname as qe}from"os";import{randomUUID as Je}from"crypto";g(),k(),E(),ne(),N(),ae(),o(),p(),i(),c(),B(),J(),ge(),Z(),S(),Fe(),w(),A(),C(),z(),l(),L(),R(),t(),W(),b(),P();var Ye=2e3,Xe=6e4,Ze=900*1e3,Qe=0;async function $e(t){let{dir:r,machineName:i,branch:a,gitRepoUrl:o,title:s,baseUrl:c,sessionIngressUrl:l,workerType:u,getAccessToken:d,createSession:f,archiveSession:p,getCurrentTitle:m=()=>s,toSDKMessages:g=()=>{throw Error(`BridgeCoreParams.toSDKMessages not provided. Pass it if you use writeMessages() or initialMessages — daemon callers that only use writeSdkMessages() never hit this path.`)},onAuth401:_,getPollIntervalConfig:v=()=>Me,initialHistoryCap:b=200,initialMessages:S,previouslyFlushedUUIDs:C,onInboundMessage:te,onPermissionResponse:ne,onInterrupt:re,onSetModel:w,onSetMaxThinkingTokens:ie,onSetPermissionMode:E,onStateChange:D,onUserMessage:O,perpetual:k,initialSSESequenceNum:A=0}=t,ae=++Qe,{writeBridgePointer:M,clearBridgePointer:oe,readBridgePointer:se}=await import(`./bridgePointer-CiHy2tTN.js`),N=k?await se(r):null,P=N?.source===`repl`?N:null;x(`[bridge:repl] initBridgeCore #${ae} starting (initialMessages=${S?.length??0}${P?` perpetual prior=env:${P.environmentId}`:``})`);let F=ze({baseUrl:c,getAccessToken:d,runnerVersion:`0.0.15`,onDebug:x,onAuth401:_,getTrustedDeviceToken:Ge}),I={dir:r,machineName:i,branch:a,gitRepoUrl:o,maxSessions:1,spawnMode:`single-session`,verbose:!1,sandbox:!1,bridgeId:Je(),workerType:u,environmentId:Je(),reuseEnvironmentId:P?.environmentId,apiBaseUrl:c,sessionIngressUrl:l},L,R;try{let e=await F.registerBridgeEnvironment(I);L=e.environment_id,R=e.environment_secret}catch(e){return K(`registration_failed`,`[bridge:repl] Environment registration failed: ${y(e)}`),P&&await oe(r),D?.(`failed`,y(e)),null}x(`[bridge:repl] Environment registered: ${L}`),T(`info`,`bridge_repl_env_registered`),j(`tengu_bridge_repl_env_registered`,{});async function fe(e,t){if(L!==e)return x(`[bridge:repl] Env mismatch (requested ${e}, got ${L}) — cannot reconnect in place`),!1;let n=ue(t),r=n===t?[t]:[t,n];for(let e of r)try{return await F.reconnectSession(L,e),x(`[bridge:repl] Reconnected session ${e} in place on env ${L}`),!0}catch(t){x(`[bridge:repl] reconnectSession(${e}) failed: ${y(t)}`)}return x(`[bridge:repl] reconnectSession exhausted — falling through to fresh session`),!1}let z=P?await fe(P.environmentId,P.sessionId):!1;P&&!z&&await oe(r);let B;if(z&&P){if(B=P.sessionId,x(`[bridge:repl] Perpetual session reused: ${B}`),S&&C)for(let e of S)C.add(e.uuid)}else{let e=await f({environmentId:L,title:s,gitRepoUrl:o,branch:a,signal:AbortSignal.timeout(15e3)});if(!e)return x(`[bridge:repl] Session creation failed, deregistering environment`),j(`tengu_bridge_repl_session_failed`,{}),await F.deregisterEnvironment(L).catch(()=>{}),D?.(`failed`,`Session creation failed`),null;B=e,x(`[bridge:repl] Session created: ${B}`)}await M(r,{sessionId:B,environmentId:L,source:`repl`}),T(`info`,`bridge_repl_session_created`),j(`tengu_bridge_repl_started`,{has_initial_messages:!!(S&&S.length>0),inProtectedNamespace:n()});let pe=new Set;if(S)for(let e of S)pe.add(e.uuid);let V=new Ee(2e3);for(let e of pe)V.add(e);let me=new Ee(2e3),H=new AbortController,U=null;ce(e=>{H.signal.aborted||U?.reportMetadata(e)},{replayCurrent:!0});let W=0,G=z?A:0,q=null,J=null,he=Be(H.signal),Y=he.wake,ge=he.signal,X=new je,_e=!O,Z=0,Q=null;async function ye(){if(Q)return Q;Q=be();try{return await Q}finally{Q=null}}async function be(){if(Z++,Pe(`doReconnect: attempt=${Z}/3 envId=${L} sessionId=${B} workId=${q}`),W++,x(`[bridge:repl] Reconnecting after env lost (attempt ${Z}/3)`),Z>3)return x(`[bridge:repl] Environment reconnect limit reached (3), giving up`),!1;if(U){let e=U.getLastSequenceNum();e>G&&(G=e),U.close(),U=null}if(Y(),X.drop(),q){let e=q;if(await F.stopWork(L,e,!1).catch(()=>{}),q!==e)return x(`[bridge:repl] Poll loop recovered during stopWork await — deferring to it`),Z=0,!0;q=null,J=null}if(H.signal.aborted)return x(`[bridge:repl] Reconnect aborted by teardown`),!1;let e=L;I.reuseEnvironmentId=e;try{let e=await F.registerBridgeEnvironment(I);L=e.environment_id,R=e.environment_secret}catch(e){return I.reuseEnvironmentId=void 0,x(`[bridge:repl] Environment re-registration failed: ${y(e)}`),!1}if(I.reuseEnvironmentId=void 0,x(`[bridge:repl] Re-registered: requested=${e} got=${L}`),H.signal.aborted)return x(`[bridge:repl] Reconnect aborted after env registration, cleaning up`),await F.deregisterEnvironment(L).catch(()=>{}),!1;if(U!==null)return x(`[bridge:repl] Poll loop recovered during registerBridgeEnvironment await — deferring to it`),Z=0,!0;if(await fe(e,B))return j(`tengu_bridge_repl_reconnected_in_place`,{}),Z=0,!0;if(L!==e&&j(`tengu_bridge_repl_env_expired_fresh_session`,{}),await p(B),H.signal.aborted)return x(`[bridge:repl] Reconnect aborted after archive, cleaning up`),await F.deregisterEnvironment(L).catch(()=>{}),!1;let t=m(),n=await f({environmentId:L,title:t,gitRepoUrl:o,branch:a,signal:AbortSignal.timeout(15e3)});return n?H.signal.aborted?(x(`[bridge:repl] Reconnect aborted after session creation, cleaning up`),await p(n),!1):(B=n,h(de(n)).catch(()=>{}),G=0,me.clear(),_e=!O,x(`[bridge:repl] Re-created session: ${B}`),await M(r,{sessionId:B,environmentId:L,source:`repl`}),C?.clear(),Z=0,!0):(x(`[bridge:repl] Session creation failed during reconnection`),!1)}function Se(){return d()}function De(){let e=X.end();if(e.length===0)return;if(!U){x(`[bridge:repl] Cannot drain ${e.length} pending message(s): no transport`);return}for(let t of e)V.add(t.uuid);let t=g(e).map(e=>({...e,session_id:B}));x(`[bridge:repl] Drained ${e.length} pending message(s) after flush`),U.writeBatch(t)}let Oe=null;function Ne(){Oe?.()}function Fe(e){if(Pe(`handleTransportPermanentClose: code=${e} transport=${U?`exists`:`null`} pollAborted=${H.signal.aborted}`),x(`[bridge:repl] Transport permanently closed: code=${e}`),j(`tengu_bridge_repl_ws_closed`,{code:e}),U){let e=U.getLastSequenceNum();e>G&&(G=e),U=null}Y();let t=X.drop();if(t>0&&x(`[bridge:repl] Dropping ${t} pending message(s) on transport close (code=${e})`,{level:`warn`}),e===1e3){D?.(`failed`,`session ended`),H.abort(),Ne();return}D?.(`reconnecting`,`Remote Control connection lost (code ${e})`),x(`[bridge:repl] Transport reconnect budget exhausted (code=${e}), attempting env reconnect`),ye().then(t=>{t||H.signal.aborted||(x(`[bridge:repl] reconnectEnvironmentWithSession resolved false — tearing down`),j(`tengu_bridge_repl_reconnect_failed`,{close_code:e}),D?.(`failed`,`reconnection failed`),Ne())})}et({api:F,getCredentials:()=>({environmentId:L,environmentSecret:R}),signal:H.signal,getPollIntervalConfig:v,onStateChange:D,getWsState:()=>U?.getStateLabel()??`null`,isAtCapacity:()=>U!==null,capacitySignal:ge,onFatalError:Ne,getHeartbeatInfo:()=>!q||!J?null:{environmentId:L,workId:q,sessionToken:J},onHeartbeatFatal:e=>{if(x(`[bridge:repl] heartbeatWork fatal (status=${e.status}) — tearing down work item for fast re-dispatch`),U){let e=U.getLastSequenceNum();e>G&&(G=e),U.close(),U=null}X.drop(),q&&F.stopWork(L,q,!1).catch(e=>{x(`[bridge:repl] stopWork after heartbeat fatal: ${y(e)}`)}),q=null,J=null,Y(),D?.(`reconnecting`,`Work item lease expired, fetching fresh token`)},async onEnvironmentLost(){return await ye()?{environmentId:L,environmentSecret:R}:null},onWorkReceived:(t,n,i,a)=>{if(U?.isConnectedStatus()&&x(`[bridge:repl] Work received while transport connected, replacing with fresh token (workId=${i})`),x(`[bridge:repl] Work received: workId=${i} workSessionId=${t} currentSessionId=${B} match=${Ve(t,B)}`),M(r,{sessionId:B,environmentId:L,source:`repl`}),!Ve(t,B)){x(`[bridge:repl] Rejecting foreign session: expected=${B} got=${t}`);return}q=i,J=n;let o=a||e(process.env.CLAUDE_BRIDGE_USE_CCR_V2),s;if(!o){if(s=Se(),!s){x(`[bridge:repl] No OAuth token available for session ingress, skipping work`);return}le(s)}if(j(`tengu_bridge_repl_work_received`,{}),U){let e=U;U=null;let t=e.getLastSequenceNum();t>G&&(G=t),e.close()}X.deactivate();let u=e=>xe(e,{transport:U,sessionId:B,onInterrupt:re,onSetModel:w,onSetMaxThinkingTokens:ie,onSetPermissionMode:E}),d=!1,f=e=>{U=e,e.setOnConnect(()=>{if(U===e){if(x(`[bridge:repl] Ingress transport connected`),j(`tengu_bridge_repl_ws_connected`,{}),!o){let e=Se();e&&le(e)}if(Re=!1,!d&&S&&S.length>0){d=!0;let t=b,n=S.filter(e=>ve(e)&&!C?.has(e.uuid)),r=t>0&&n.length>t?n.slice(-t):n;r.length<n.length&&(x(`[bridge:repl] Capped initial flush: ${n.length} -> ${r.length} (cap=${t})`),j(`tengu_bridge_repl_history_capped`,{eligible_count:n.length,capped_count:r.length}));let i=g(r);if(i.length>0){x(`[bridge:repl] Flushing ${i.length} initial message(s) via transport`);let t=i.map(e=>({...e,session_id:B})),n=e.droppedBatchCount;e.writeBatch(t).then(()=>{if(e.droppedBatchCount>n){x(`[bridge:repl] Initial flush dropped ${e.droppedBatchCount-n} batch(es) — not marking ${i.length} UUID(s) as flushed`);return}if(C)for(let e of i)e.uuid&&C.add(e.uuid)}).catch(e=>x(`[bridge:repl] Initial flush failed: ${e}`)).finally(()=>{U===e&&(De(),D?.(`connected`))})}else De(),D?.(`connected`)}else X.active||D?.(`connected`)}}),e.setOnData(e=>{try{let t=JSON.parse(e);Pe(`ingress: type=${t.type}${t.type===`control_request`?` subtype=${t.request?.subtype} request_id=${t.request_id}`:``}${t.type===`control_response`?` subtype=${t.response?.subtype} request_id=${t.response?.request_id}`:``}${t.type===`user`?` uuid=${t.uuid}`:``}${t.type===`keep_alive`?``:` len=${e.length}`}`)}catch{Pe(`ingress (non-JSON): ${String(e).slice(0,200)}`)}Te(e,V,me,te,ne,u)}),e.setOnClose(t=>{U===e&&(Pe(`transport onClose: code=${t} connected=${e.isConnectedStatus()} state=${e.getStateLabel()} seq=${e.getLastSequenceNum()}`),Fe(t))}),!d&&S&&S.length>0&&X.start(),e.connect()};if(W++,o){let e=We(c,t),r=W;x(`[bridge:repl] CCR v2: sessionUrl=${e} session=${t} gen=${r}`),Ae({sessionUrl:e,ingressToken:n,sessionId:t,initialSequenceNum:G}).then(e=>{if(H.signal.aborted){e.close();return}if(r!==W){x(`[bridge:repl] CCR v2: discarding stale handshake gen=${r} current=${W}`),e.close();return}f(e)},e=>{x(`[bridge:repl] CCR v2: createV2ReplTransport failed: ${y(e)}`,{level:`error`}),j(`tengu_bridge_repl_ccr_v2_init_failed`,{}),r===W&&(q&&(F.stopWork(L,q,!1).catch(e=>{x(`[bridge:repl] stopWork after v2 init failure: ${y(e)}`)}),q=null,J=null),Y())})}else{let e=He(l,t);x(`[bridge:repl] Ingress URL: ${e}`),x(`[bridge:repl] Creating HybridTransport: session=${t}`);let n=s??``;f(ke(new Ke(new URL(e),{Authorization:`Bearer ${n}`,"anthropic-version":`2023-06-01`},t,()=>({Authorization:`Bearer ${Se()??n}`,"anthropic-version":`2023-06-01`}),{maxConsecutiveFailures:50,isBridge:!0,onBatchDropped:()=>{D?.(`reconnecting`,`Lost sync with Remote Control — events could not be delivered`),Y()}})))}}});let Ie=k?setInterval(()=>{Q||M(r,{sessionId:B,environmentId:L,source:`repl`})},60*6e4):null;Ie?.unref?.();let Le=v().session_keepalive_interval_v2_ms,$=Le>0?setInterval(()=>{U&&(x(`[bridge:repl] keep_alive sent`),U.write({type:`keep_alive`}).catch(e=>{x(`[bridge:repl] keep_alive write failed: ${y(e)}`)}))},Le):null;$?.unref?.();let Re=!1;Oe=async()=>{if(Re){x(`[bridge:repl] Teardown already in progress, skipping duplicate call env=${L} session=${B}`);return}Re=!0;let e=Date.now();if(x(`[bridge:repl] Teardown starting: env=${L} session=${B} workId=${q??`none`} transportState=${U?.getStateLabel()??`null`}`),Ie!==null&&clearInterval(Ie),$!==null&&clearInterval($),H.abort(),x(`[bridge:repl] Teardown: poll loop aborted`),U){let e=U.getLastSequenceNum();e>G&&(G=e)}if(k){U=null,X.drop(),await M(r,{sessionId:B,environmentId:L,source:`repl`}),x(`[bridge:repl] Teardown (perpetual): leaving env=${L} session=${B} alive on server, duration=${Date.now()-e}ms`);return}let t=U;if(U=null,X.drop(),t){let e={...we(B),session_id:B};t.write(e)}let n=q?F.stopWork(L,q,!0).then(()=>{x(`[bridge:repl] Teardown: stopWork completed`)}).catch(e=>{x(`[bridge:repl] Teardown stopWork failed: ${y(e)}`)}):Promise.resolve();await Promise.all([n,p(B)]),t?.close(),x(`[bridge:repl] Teardown: transport closed`),await F.deregisterEnvironment(L).catch(e=>{x(`[bridge:repl] Teardown deregister failed: ${y(e)}`)}),await oe(r),x(`[bridge:repl] Teardown complete: env=${L} duration=${Date.now()-e}ms`)};let Ue=ee(()=>Oe?.());return x(`[bridge:repl] Ready: env=${L} session=${B}`),D?.(`ready`),{get bridgeSessionId(){return B},get environmentId(){return L},getSSESequenceNum(){let e=U?.getLastSequenceNum()??0;return Math.max(G,e)},sessionIngressUrl:l,writeMessages(e){let t=e.filter(e=>ve(e)&&!pe.has(e.uuid)&&!V.has(e.uuid));if(t.length===0)return;if(!_e)for(let e of t){let t=Ce(e);if(t!==void 0&&O?.(t,B)){_e=!0;break}}if(X.enqueue(...t)){x(`[bridge:repl] Queued ${t.length} message(s) during initial flush`);return}if(!U){let e=t.map(e=>e.type).join(`,`);x(`[bridge:repl] Transport not configured, dropping ${t.length} message(s) [${e}] for session=${B}`,{level:`warn`});return}for(let e of t)V.add(e.uuid);x(`[bridge:repl] Sending ${t.length} message(s) via transport`);let n=g(t).map(e=>({...e,session_id:B}));U.writeBatch(n)},writeSdkMessages(e){let t=e.filter(e=>!e.uuid||!V.has(e.uuid));if(t.length===0)return;if(!U){x(`[bridge:repl] Transport not configured, dropping ${t.length} SDK message(s) for session=${B}`,{level:`warn`});return}for(let e of t)e.uuid&&V.add(e.uuid);let n=t.map(e=>({...e,session_id:B}));U.writeBatch(n)},sendControlRequest(e){if(!U){x(`[bridge:repl] Transport not configured, skipping control_request`);return}let t={...e,session_id:B};U.write(t),x(`[bridge:repl] Sent control_request request_id=${e.request_id}`)},sendControlResponse(e){if(!U){x(`[bridge:repl] Transport not configured, skipping control_response`);return}let t={...e,session_id:B};U.write(t),x(`[bridge:repl] Sent control_response`)},sendControlCancelRequest(e){if(!U){x(`[bridge:repl] Transport not configured, skipping control_cancel_request`);return}let t={type:`control_cancel_request`,request_id:e,session_id:B};U.write(t),x(`[bridge:repl] Sent control_cancel_request request_id=${e}`)},sendResult(){if(!U){x(`[bridge:repl] sendResult: skipping, transport not configured session=${B}`);return}U.reportState(`idle`);let e={...we(B),session_id:B};U.write(e),x(`[bridge:repl] Sent result for session=${B}`)},async teardown(){Ue(),await Oe?.(),x(`[bridge:repl] Torn down`),j(`tengu_bridge_repl_teardown`,{})}}}async function et({api:e,getCredentials:t,signal:n,onStateChange:r,onWorkReceived:i,onEnvironmentLost:a,getWsState:o,isAtCapacity:s,capacitySignal:c,onFatalError:l,getPollIntervalConfig:u=()=>Me,getHeartbeatInfo:d,onHeartbeatFatal:f}){x(`[bridge:repl] Starting work poll loop for env=${t().environmentId}`);let p=0,m=null,h=null,g=0,_=!1;for(;!n.aborted;){let{environmentId:v,environmentSecret:b}=t(),S=u();try{let t=await e.pollForWork(v,b,n,S.reclaim_older_than_ms);if(g=0,p>0&&(x(`[bridge:repl] Poll recovered after ${p} consecutive error(s)`),p=0,m=null,h=null,r?.(`ready`)),!t){let t=_;if(_=!1,s?.()&&c&&!t){let t=S.poll_interval_ms_at_capacity;if(S.non_exclusive_heartbeat_interval_ms>0&&d){j(`tengu_bridge_heartbeat_mode_entered`,{heartbeat_interval_ms:S.non_exclusive_heartbeat_interval_ms});let r=t>0?Date.now()+t:null,i=!1,a=0;for(;!n.aborted&&s()&&(r===null||Date.now()<r);){let t=u();if(t.non_exclusive_heartbeat_interval_ms<=0)break;let n=d();if(!n)break;let r=c();try{await e.heartbeatWork(n.environmentId,n.workId,n.sessionToken)}catch(e){if(x(`[bridge:repl:heartbeat] Failed: ${y(e)}`),e instanceof $){r.cleanup(),j(`tengu_bridge_heartbeat_error`,{status:e.status,error_type:e.status===401||e.status===403?`auth_failed`:`fatal`}),f?(f(e),x(`[bridge:repl:heartbeat] Fatal (status=${e.status}), work state cleared — fast-polling for re-dispatch`)):i=!0;break}}a++,await I(t.non_exclusive_heartbeat_interval_ms,r.signal),r.cleanup()}let o=i?`error`:n.aborted?`shutdown`:s()?r!==null&&Date.now()>=r?`poll_due`:`config_disabled`:`capacity_changed`;if(j(`tengu_bridge_heartbeat_mode_exited`,{reason:o,heartbeat_cycles:a}),!i){o===`poll_due`&&x(`[bridge:repl] Heartbeat poll_due after ${a} cycles — falling through to pollForWork`);continue}}let r=t>0?t:S.non_exclusive_heartbeat_interval_ms;if(r>0){let e=c(),t=Date.now();await I(r,e.signal),e.cleanup();let n=Date.now()-t-r;n>6e4&&(x(`[bridge:repl] At-capacity sleep overran by ${Math.round(n/1e3)}s — process suspension detected, forcing one fast-poll cycle`),j(`tengu_bridge_repl_suspension_detected`,{overrun_ms:n}),_=!0)}}else await I(S.poll_interval_ms_not_at_capacity,n);continue}let a;try{a=Ue(t.secret)}catch(n){x(`[bridge:repl] Failed to decode work secret: ${y(n)}`),j(`tengu_bridge_repl_work_secret_failed`,{}),await e.stopWork(v,t.id,!1).catch(()=>{});continue}x(`[bridge:repl] Acknowledging workId=${t.id}`);try{await e.acknowledgeWork(v,t.id,a.session_ingress_token)}catch(e){x(`[bridge:repl] Acknowledge failed workId=${t.id}: ${y(e)}`)}if(t.data.type===`healthcheck`){x(`[bridge:repl] Healthcheck received`);continue}if(t.data.type===`session`){let e=t.data.id;try{Re(e,`session_id`)}catch{x(`[bridge:repl] Invalid session_id in work: ${e}`);continue}i(e,a.session_ingress_token,t.id,a.use_code_sessions===!0),x(`[bridge:repl] Work accepted, continuing poll loop`)}}catch(i){if(n.aborted)break;if(i instanceof $&&i.status===404&&a){let e=t().environmentId;if(v!==e){x(`[bridge:repl] Stale poll error for old env=${v}, current env=${e} — skipping onEnvironmentLost`),p=0,m=null;continue}if(g++,x(`[bridge:repl] Environment deleted, attempting re-registration (attempt ${g}/3)`),j(`tengu_bridge_repl_env_lost`,{attempt:g}),g>3){x(`[bridge:repl] Environment re-registration limit reached (3), giving up`),r?.(`failed`,`Environment deleted and re-registration limit reached`),l?.();break}r?.(`reconnecting`,`environment lost, recreating session`);let i=await a();if(n.aborted)break;if(i){p=0,m=null,r?.(`ready`),x(`[bridge:repl] Re-registered environment: ${i.environmentId}`);continue}r?.(`failed`,`Environment deleted and re-registration failed`),l?.();break}if(i instanceof $){let e=Le(i.errorType),t=Ie(i);x(`[bridge:repl] Fatal poll error: ${i.message} (status=${i.status}, type=${i.errorType??`unknown`})${t?` (suppressed)`:``}`),j(`tengu_bridge_repl_fatal_error`,{status:i.status,error_type:i.errorType}),T(e?`info`:`error`,`bridge_repl_fatal_error`,{status:i.status,error_type:i.errorType}),t||r?.(`failed`,e?`session expired · /remote-control to reconnect`:i.message),l?.();break}let s=Date.now();h!==null&&s-h>6e4*2&&(x(`[bridge:repl] Detected system sleep (${Math.round((s-h)/1e3)}s gap), resetting poll error budget`),T(`info`,`bridge_repl_poll_sleep_detected`,{gapMs:s-h}),p=0,m=null),h=s,p++,m===null&&(m=s);let c=s-m,f=U(i),_=G(i),y=o?.()??`unknown`;if(x(`[bridge:repl] Poll error (attempt ${p}, elapsed ${Math.round(c/1e3)}s, ws=${y}): ${_}`),j(`tengu_bridge_repl_poll_error`,{status:f,consecutiveErrors:p,elapsedMs:c}),p===1&&r?.(`reconnecting`,_),c>=9e5){x(`[bridge:repl] Poll failures exceeded ${Ze/1e3}s (${p} errors), giving up`),T(`info`,`bridge_repl_poll_give_up`),j(`tengu_bridge_repl_poll_give_up`,{consecutiveErrors:p,elapsedMs:c,lastStatus:f}),r?.(`failed`,`connection to server lost`);break}let b=Math.min(Ye*2**(p-1),Xe);if(u().non_exclusive_heartbeat_interval_ms>0){let t=d?.();if(t)try{await e.heartbeatWork(t.environmentId,t.workId,t.sessionToken)}catch{}}await I(b,n)}}x(`[bridge:repl] Work poll loop ended (aborted=${n.aborted}) env=${t().environmentId}`)}S(),b(),W(),z();async function tt(e){let{onInboundMessage:t,onPermissionResponse:n,onInterrupt:i,onSetModel:o,onSetMaxThinkingTokens:c,onSetPermissionMode:l,onStateChange:p,initialMessages:h,getMessages:g,previouslyFlushedUUIDs:b,initialName:S,perpetual:ee,outboundOnly:C,tags:ne}=e??{};if(fe(ye),!await De())return K(`not_enabled`,`[bridge:repl] Skipping: bridge not enabled`),null;if(!H())return K(`no_oauth`,`[bridge:repl] Skipping: no OAuth tokens`),p?.(`failed`,`authentication required`),null;if(await f(),!s(`allow_remote_control`))return K(`policy_denied`,`[bridge:repl] Skipping: allow_remote_control policy not allowed`),p?.(`failed`,`disabled by your organization's policy`),null;if(!pe()){let e=te();if(e.bridgeOauthDeadExpiresAt!=null&&(e.bridgeOauthDeadFailCount??0)>=3&&se()?.expiresAt===e.bridgeOauthDeadExpiresAt)return x(`[bridge:repl] Skipping: cross-process backoff (dead token seen ${e.bridgeOauthDeadFailCount} times)`),null;await F();let t=se();if(t&&t.expiresAt!==null&&t.expiresAt<=Date.now()){K(`oauth_expired_unrefreshable`,`[bridge:repl] Skipping: OAuth token expired and refresh failed (re-login required)`),p?.(`failed`,`authentication required`);let e=t.expiresAt;return re(t=>({...t,bridgeOauthDeadExpiresAt:e,bridgeOauthDeadFailCount:t.bridgeOauthDeadExpiresAt===e?(t.bridgeOauthDeadFailCount??0)+1:1})),null}}let w=V(),T=`remote-control-${u()}`,E=!1,O=!1;if(S)T=S,E=!0,O=!0;else{let e=v(),t=e?m(e):void 0;if(t)T=t,E=!0,O=!0;else if(h&&h.length>0)for(let e=h.length-1;e>=0;e--){let t=h[e];if(t.type!==`user`||t.isMeta||t.toolUseResult||t.isCompactSummary||t.origin&&t.origin.kind!==`human`||a(t))continue;let n=r(t.message.content);if(!n)continue;let i=rt(n);if(i){T=i,E=!0;break}}}let k=0,A,j=0,ae=(e,t,n)=>{E=!0,T=e,x(`[bridge:repl] derived title from message ${n}: ${e}`),q(t,e,{baseUrl:w,getAccessToken:H}).catch(()=>{})},N=(e,t)=>{let n=++j,r=k;_e(e,AbortSignal.timeout(15e3)).then(e=>{e&&n===j&&A===t&&!m(v())&&ae(e,t,r)})},P=(e,t)=>{if(O||m(v()))return!0;if(A!==void 0&&A!==t&&(k=0),A=t,k++,k===1&&!E){let n=rt(e);n&&ae(n,t,k),N(e,t)}else if(k===3){let n=g?.(),r=n?Q(d(n)):e;N(r,t)}return k>=3},I=me()?`self-hosted`:await oe();if(!I)return K(`no_org_uuid`,`[bridge:repl] Skipping: no org UUID`),p?.(`failed`,`/login`),null;if(be()&&!ee){let e=await Oe();if(e)return K(`version_too_old`,`[bridge:repl] Skipping: ${e}`,!0),p?.(`failed`,"run `claude update` to upgrade"),null;x(`[bridge:repl] Using env-less bridge path (tengu_bridge_repl_v2)`);let{initEnvLessBridgeCore:r}=await import(`./remoteBridgeCore-BnZYGaMH.js`);return r({baseUrl:w,orgUUID:I,title:T,getAccessToken:H,onAuth401:M,toSDKMessages:X,initialHistoryCap:200,initialMessages:h,onInboundMessage:t,onUserMessage:P,onPermissionResponse:n,onInterrupt:i,onSetModel:o,onSetMaxThinkingTokens:c,onSetPermissionMode:l,onStateChange:p,outboundOnly:C,tags:ne})}let L=Se();if(L)return K(`version_too_old`,`[bridge:repl] Skipping: ${L}`),p?.(`failed`,"run `claude update` to upgrade"),null;let ce=await ie(),R=await D(),le=process.env.CLAUDE_BRIDGE_SESSION_INGRESS_URL||w;return $e({dir:_(),machineName:qe(),branch:ce,gitRepoUrl:R,title:T,baseUrl:w,sessionIngressUrl:le,workerType:`claude_code`,getAccessToken:H,createSession:e=>he({...e,events:[],baseUrl:w,getAccessToken:H}),archiveSession:e=>Y(e,{baseUrl:w,getAccessToken:H,timeoutMs:1500}).catch(e=>{x(`[bridge:repl] archiveBridgeSession threw: ${y(e)}`,{level:`error`})}),getCurrentTitle:()=>m(v())??T,onUserMessage:P,toSDKMessages:X,onAuth401:M,getPollIntervalConfig:Ne,initialHistoryCap:200,initialMessages:h,previouslyFlushedUUIDs:b,onInboundMessage:t,onPermissionResponse:n,onInterrupt:i,onSetModel:o,onSetMaxThinkingTokens:c,onSetPermissionMode:l,onStateChange:p,perpetual:ee})}var nt=50;function rt(e){let t=O(e),n=(/^(.*?[.!?])\s/.exec(t)?.[1]??t).replace(/\s+/g,` `).trim();if(n)return n.length>nt?`${n.slice(0,nt-1)}\u2026`:n}export{tt as initReplBridge};
@@ -1 +0,0 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{GT as t,IT as n,KT as r,LT as i,RT as a,UT as o,VT as s,WT as c}from"./loadAgentsDir-CwEfQDOw.js";import{C as l,F as u,R as d,x as f}from"./debug-BQj6h99Q.js";import{r as p,t as m}from"./promptEditor-DQ9fpdQD.js";import{dirname as h}from"path";import{mkdir as g,writeFile as _}from"fs/promises";function v(e){let t=new Set(s.map(e=>c(e.key)));return e.map(e=>{let n={};for(let[r,i]of Object.entries(e.bindings))t.has(c(r))||(n[r]=i);return{context:e.context,bindings:n}}).filter(e=>Object.keys(e.bindings).length>0)}function y(){return`${l({$schema:`https://www.schemastore.org/claude-code-keybindings.json`,$docs:`https://code.workmate.com/docs/en/keybindings`,bindings:v(t)},null,2)}\n`}var b=e((()=>{f(),r(),o()}));async function x(){if(!a())return{type:`text`,value:`Keybinding customization is not enabled. This feature is currently in preview.`};let e=n(),t=!1;await g(h(e),{recursive:!0});try{await _(e,y(),{encoding:`utf-8`,flag:`wx`})}catch(e){if(u(e)===`EEXIST`)t=!0;else throw e}let r=await m(e);return r.error?{type:`text`,value:`${t?`Opened`:`Created`} ${e}. Could not open in editor: ${r.error}`}:{type:`text`,value:t?`Opened ${e} in your editor.`:`Created ${e} with template. Opened in your editor.`}}e((()=>{i(),b(),d(),p()}))();export{x as call};
@@ -1 +0,0 @@
1
- import{o as e,t}from"./loadAgentsDir-CwEfQDOw.js";e();export{t as clearAgentDefinitionsCache};
@@ -1 +0,0 @@
1
- import{a as e,o as t,s as n,t as r}from"./localSearch-BEnlgSB7.js";t();export{r as clearSkillIndexCache,e as getSkillIndex,n as searchSkills};
@@ -1 +0,0 @@
1
- import{r as e,t}from"./managedEnv-3MbOWrVs.js";e();export{t as applyConfigEnvironmentVariables};
@@ -1 +0,0 @@
1
- import{n as e,o as t}from"./rolldown-runtime-DaDcL9Zw.js";import{$h as n,Kw as r,Xh as i,Zh as a,bp as o,qw as s,xp as c,yp as l}from"./loadAgentsDir-CwEfQDOw.js";import{ai as u,di as d,fi as f}from"./src-DL3w8VPk2.js";import{t as p}from"./jsx-runtime-Bb4Xn-E0.js";import{D as m,E as h,q as g}from"./log-BlJ7CcKG.js";import{n as _,r as v}from"./analytics-DJobLaWP.js";import{F as y,K as b,M as x,N as S,P as C,_ as w,b as T,et as E,it as D,rt as O,s as k,tt as A,w as j}from"./model-CeG-iOKF.js";import{i as M,n as N,r as P,t as F}from"./extraUsage-DsFwXMAj.js";function I({onDone:e}){let t=a(e=>e.mainLoopModel),r=a(e=>e.mainLoopModelForSession),i=a(e=>e.fastMode),o=n();function s(){v(`tengu_model_command_menu`,{action:`cancel`});let n=H(t);e(`Kept model as ${d.bold(n)}`,{display:`system`})}function c(n){v(`tengu_model_command_menu`,{action:n,from_model:t,to_model:n}),o(e=>({...e,mainLoopModel:n,mainLoopModelForSession:null}));let r=`Set model to ${d.bold(H(n))}`,a;O()&&(b(),!D(n)&&i?(o(e=>({...e,fastMode:!1})),a=!1):D(n)&&A()&&i&&(r+=` · Fast mode ON`,a=!0)),N(n,a===!0,T())&&(r+=` · Billed as extra usage`),a===!1&&(r+=` · Fast mode OFF`),e(r)}return(0,W.jsx)(P,{initial:t,sessionModel:r,onSelect:c,onCancel:s,isStandaloneCommand:!0,showFastModeNotice:O()&&i&&D(t)&&A()})}function L({args:e,onDone:t}){let r=a(e=>e.fastMode),i=n(),o=e==="default"?null:e;return U.useEffect(()=>{async function e(){if(o&&!S(o)){t(`Model '${o}' is not available. Your organization restricts model selection.`,{display:`system`});return}if(o&&z(o)){t(`Opus 4.7 with 1M context is not available for your account. Learn more: https://code.workmate.com/docs/en/model-config#extended-context-with-1m`,{display:`system`});return}if(o&&B(o)){t(`Sonnet 4.6 with 1M context is not available for your account. Learn more: https://code.workmate.com/docs/en/model-config#extended-context-with-1m`,{display:`system`});return}if(!o){n(null);return}if(R(o)){n(o);return}try{let{valid:e,error:r}=await s(o);e?n(o):t(r||`Model '${o}' not found`,{display:`system`})}catch(e){t(`Failed to validate model: ${e.message}`,{display:`system`})}}function n(e){i(t=>({...t,mainLoopModel:e,mainLoopModelForSession:null}));let n=`Set model to ${d.bold(H(e))}`,a;O()&&(b(),!D(e)&&r?(i(e=>({...e,fastMode:!1})),a=!1):D(e)&&r&&(n+=` · Fast mode ON`,a=!0)),N(e,a===!0,T())&&(n+=` · Billed as extra usage`),a===!1&&(n+=` · Fast mode OFF`),t(n)}e()},[o,t,i]),null}function R(e){return C.includes(e.toLowerCase().trim())}function z(e){let t=e.toLowerCase();return!l()&&!T()&&t.includes(`opus`)&&t.includes(`[1m]`)}function B(e){let t=e.toLowerCase();return!o()&&(t.includes(`sonnet[1m]`)||t.includes(`sonnet-4-6[1m]`))}function V({onDone:e}){let t=a(e=>e.mainLoopModel),n=a(e=>e.mainLoopModelForSession),r=H(t);return e(n?`Current model: ${d.bold(H(n))} (session override from plan mode)\nBase model: ${r}`:`Current model: ${r}`),null}function H(e){let t=j(e??k());return e===null?`${t} (default)`:t}var U,W,G;e((()=>{f(),U=t(u(),1),M(),g(),_(),i(),F(),E(),y(),c(),w(),x(),r(),W=p(),G=async(e,t,n)=>{if(n=n?.trim()||``,m.includes(n))return v(`tengu_model_command_inline_help`,{args:n}),(0,W.jsx)(V,{onDone:e});if(h.includes(n)){e(`Run /model to open the model selection menu, or /model [modelName] to set the model.`,{display:`system`});return}return n?(v(`tengu_model_command_inline`,{args:n}),(0,W.jsx)(L,{args:n,onDone:e})):(0,W.jsx)(I,{onDone:e})}}))();export{G as call};
@@ -1 +0,0 @@
1
- import{_ as e,u as t}from"./model-CeG-iOKF.js";e();export{t as getMainLoopModel};
@@ -1 +0,0 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{bp as t,xp as n,yp as r}from"./loadAgentsDir-CwEfQDOw.js";import{F as i,Wt as a}from"./state-BPFYBqm1.js";import{f as o,g as ee}from"./settings-CvhsRFaT.js";import{c as te,h as ne}from"./config-BSkuQZNf.js";import{A as s,Bt as c,Gn as l,Gr as u,Gt as d,H as f,I as p,Kn as m,Kr as h,L as g,M as _,N as v,O as y,R as b,W as re,Xt as ie,_ as ae,a as x,b as S,c as oe,d as C,en as w,f as T,g as E,i as D,ii as O,j as k,k as A,l as j,oi as M,r as N,s as P,w as F}from"./model-CeG-iOKF.js";function I(e=!1){if(d())return{value:null,label:`Default (recommended)`,description:D(e)};let t=O()!==`firstParty`;return{value:null,label:`Default (recommended)`,description:`Use the default model (currently ${F(P())})${t?``:` · ${f(b)}`}`}}function L(){let e=O()!==`firstParty`,t=O(),n=t===`openai`?process.env.OPENAI_DEFAULT_SONNET_MODEL:t===`gemini`?process.env.GEMINI_DEFAULT_SONNET_MODEL:process.env.ANTHROPIC_DEFAULT_SONNET_MODEL;if(e&&n){let e=l(n),r=t===`openai`?process.env.OPENAI_DEFAULT_SONNET_MODEL_NAME:t===`gemini`?process.env.GEMINI_DEFAULT_SONNET_MODEL_NAME:process.env.ANTHROPIC_DEFAULT_SONNET_MODEL_NAME,i=t===`openai`?process.env.OPENAI_DEFAULT_SONNET_MODEL_DESCRIPTION:t===`gemini`?process.env.GEMINI_DEFAULT_SONNET_MODEL_DESCRIPTION:process.env.ANTHROPIC_DEFAULT_SONNET_MODEL_DESCRIPTION;return{value:`sonnet`,label:r??n,description:i??`Custom Sonnet model${e?` (1M context)`:``}`,descriptionForModel:`${i??`Custom Sonnet model${e?` with 1M context`:``}`} (${n})`}}}function R(){let e=O()!==`firstParty`;return{value:e?u().sonnet46:`sonnet`,label:`Sonnet`,description:`Sonnet 4.6 · Best for everyday tasks${e?``:` · ${f(b)}`}`,descriptionForModel:`Sonnet 4.6 - best for everyday tasks. Generally recommended for most coding tasks`}}function se(){let e=O()!==`firstParty`,t=O(),n=t===`openai`?process.env.OPENAI_DEFAULT_OPUS_MODEL:t===`gemini`?process.env.GEMINI_DEFAULT_OPUS_MODEL:process.env.ANTHROPIC_DEFAULT_OPUS_MODEL;if(e&&n){let e=l(n),r=t===`openai`?process.env.OPENAI_DEFAULT_OPUS_MODEL_NAME:t===`gemini`?process.env.GEMINI_DEFAULT_OPUS_MODEL_NAME:process.env.ANTHROPIC_DEFAULT_OPUS_MODEL_NAME,i=t===`openai`?process.env.OPENAI_DEFAULT_OPUS_MODEL_DESCRIPTION:t===`gemini`?process.env.GEMINI_DEFAULT_OPUS_MODEL_DESCRIPTION:process.env.ANTHROPIC_DEFAULT_OPUS_MODEL_DESCRIPTION;return{value:`opus`,label:r??n,description:i??`Custom Opus model${e?` (1M context)`:``}`,descriptionForModel:`${i??`Custom Opus model${e?` with 1M context`:``}`} (${n})`}}}function z(e=!1){return{value:O()===`firstParty`?`opus`:u().opus47,label:`Opus 4.7`,description:`Opus 4.7 · Most capable for complex work${T(e)}`,descriptionForModel:`Opus 4.7 - most capable for complex work`}}function B(){let e=O()!==`firstParty`;return{value:e?`${u().sonnet46}[1m]`:`sonnet[1m]`,label:`Sonnet (1M context)`,description:`Sonnet 4.6 for long sessions${e?``:` · ${f(b)}`}`,descriptionForModel:`Sonnet 4.6 with 1M context window - for long sessions with large codebases`}}function V(e=!1){return{value:O()===`firstParty`?`opus[1m]`:`${u().opus47}[1m]`,label:`Opus 4.7 (1M context)`,description:`Opus 4.7 with 1M context${T(e)}`,descriptionForModel:`Opus 4.7 with 1M context window - for long sessions with large codebases`}}function H(e=!1){return{value:`${u().opus46}[1m]`,label:`Opus 4.6 (1M context)`,description:`Opus 4.6 with 1M context${T(e)}`,descriptionForModel:`Opus 4.6 with 1M context window - for long sessions with large codebases`}}function U(){let e=O()!==`firstParty`,t=O(),n=t===`openai`?process.env.OPENAI_DEFAULT_HAIKU_MODEL:t===`gemini`?process.env.GEMINI_DEFAULT_HAIKU_MODEL:process.env.ANTHROPIC_DEFAULT_HAIKU_MODEL;if(e&&n){let e=t===`openai`?process.env.OPENAI_DEFAULT_HAIKU_MODEL_NAME:t===`gemini`?process.env.GEMINI_DEFAULT_HAIKU_MODEL_NAME:process.env.ANTHROPIC_DEFAULT_HAIKU_MODEL_NAME,r=t===`openai`?process.env.OPENAI_DEFAULT_HAIKU_MODEL_DESCRIPTION:t===`gemini`?process.env.GEMINI_DEFAULT_HAIKU_MODEL_DESCRIPTION:process.env.ANTHROPIC_DEFAULT_HAIKU_MODEL_DESCRIPTION;return{value:`haiku`,label:e??n,description:r??`Custom Haiku model`,descriptionForModel:`${r??`Custom Haiku model`} (${n})`}}}function W(){return{value:`haiku`,label:`Haiku`,description:`Haiku 4.5 · Fastest for quick answers${O()===`firstParty`?` · ${f(g)}`:``}`,descriptionForModel:`Haiku 4.5 - fastest for quick answers. Lower cost but less capable than Sonnet 4.6.`}}function G(){return{value:`haiku`,label:`Haiku`,description:`Haiku 3.5 for simple tasks${O()===`firstParty`?` · ${f(p)}`:``}`,descriptionForModel:`Haiku 3.5 - faster and lower cost, but less capable than Sonnet. Use for simple tasks.`}}function K(){return x()===u().haiku45?W():G()}function q(e=!1){return{value:`opus`,label:`Opus 4.7`,description:`Opus 4.7 · Most capable for complex work${e?T(!0):``}`}}function J(){let e=O()!==`firstParty`;return{value:`sonnet[1m]`,label:`Sonnet (1M context)`,description:`Sonnet 4.6 with 1M context${d()?` · Billed as extra usage`:``}${e?``:` · ${f(b)}`}`}}function ce(e=!1){return{value:`opus[1m]`,label:`Opus 4.7 (1M context)`,description:`Opus 4.7 with 1M context${d()?` · Billed as extra usage`:``}${T(e)}`}}function Y(e=!1){let t=O()!==`firstParty`;return{value:t?`${u().opus47}[1m]`:`opus[1m]`,label:`Opus 4.7 (1M context)`,description:`Opus 4.7 with 1M context · Most capable for complex work${!t&&e?T(e):``}`,descriptionForModel:`Opus 4.7 with 1M context - most capable for complex work`}}function le(){return{value:`opusplan`,label:`Opus Plan Mode`,description:`Use Opus 4.7 in plan mode, Sonnet 4.6 otherwise`}}function ue(){return[{value:null,label:`Default (recommended)`,description:`Use the default ChatGPT Codex model (currently ${y})`,descriptionForModel:`Default ChatGPT Codex model (currently ${y})`},...A.map(e=>({value:e.value,label:e.label,description:e.description,descriptionForModel:`${e.description} (${e.value})`}))]}function de(e=!1){if(O()===`openai`&&k())return ue();if(d()){if(ie()||w()){let n=[I(e)];return n.push(H(e)),n.push(Q),t()&&n.push(J()),n.push($),n}let n=[I(e)];return S()?n.push(Y(e)):(n.push(q(e)),r()&&n.push(ce(e))),n.push(H(e)),t()&&n.push(J()),n.push($),n}if(O()===`firstParty`){let n=[I(e)];return S()?n.push(Y(e)):(n.push(z(e)),r()&&n.push(V(e))),n.push(H(e)),t()&&n.push(B()),n.push(W()),n}let n=[I(e)],i=L();i===void 0?(n.push(R()),t()&&n.push(B())):n.push(i);let a=se();a===void 0?(n.push(V(e)),n.push(H(e))):n.push(a);let o=U();return o===void 0?n.push(K()):n.push(o),n}function fe(e){let t=N(e);if(t.includes(`claude-sonnet-4-6`)||t.includes(`claude-sonnet-4-5`)||t.includes(`claude-sonnet-4-`)||t.includes(`claude-3-7-sonnet`)||t.includes(`claude-3-5-sonnet`)){let e=C(j());if(e)return{alias:`Sonnet`,currentVersionName:e}}if(t.includes(`claude-opus-4`)){let e=C(oe());if(e)return{alias:`Opus`,currentVersionName:e}}if(t.includes(`claude-haiku`)||t.includes(`claude-3-5-haiku`)){let e=C(x());if(e)return{alias:`Haiku`,currentVersionName:e}}return null}function X(e){let t=C(e);if(!t)return null;let n=fe(e);return n?t===n.currentVersionName?{value:e,label:t,description:e}:{value:e,label:t,description:`Newer version available · select ${n.alias} for ${n.currentVersionName}`}:{value:e,label:t,description:e}}function pe(e=!1){let t=de(e),n=process.env.ANTHROPIC_CUSTOM_MODEL_OPTION;n&&!t.some(e=>e.value===n)&&t.push({value:n,label:process.env.ANTHROPIC_CUSTOM_MODEL_OPTION_NAME??n,description:process.env.ANTHROPIC_CUSTOM_MODEL_OPTION_DESCRIPTION??`Custom model (${n})`});for(let e of te().additionalModelOptionsCache??[])t.some(t=>t.value===e.value)||t.push(e);let r=null,a=E(),o=i();if(a==null?o!==null&&(r=o):r=a,r===null||t.some(e=>e.value===r))return Z(t);if(r===`opusplan`)return Z([...t,le()]);if(r===`opus`&&O()===`firstParty`)return Z([...t,q(e)]);if(r===`opus[1m]`&&O()===`firstParty`)return Z([...t,Y(e)]);{let e=X(r);return e?t.push(e):t.push({value:r,label:r,description:`Custom model`}),Z(t)}}function Z(e){return(o()||{}).availableModels?e.filter(e=>e.value===null||e.value!==null&&v(e.value)):e}var Q,$,me=e((()=>{a(),c(),h(),re(),ee(),n(),M(),_(),ae(),m(),ne(),s(),Q={value:`sonnet`,label:`Sonnet`,description:`Sonnet 4.6 · Best for everyday tasks`},$={value:`haiku`,label:`Haiku`,description:`Haiku 4.5 · Fastest for quick answers`}}));export{me as n,pe as t};
@@ -1 +0,0 @@
1
- import{n as e,t}from"./pluginStartupCheck-BLc0U7W7.js";e();export{t as getPluginEditableScopes};
@@ -1,14 +0,0 @@
1
- import{c as e,i as t,l as n,o as r,s as i}from"./envUtils-DcaKZlRU.js";import{n as a,t as o}from"./defineProperty-C-QyHrDq.js";import{n as s,t as c}from"./axios-DaWTGg7G.js";import{$d as l,$l as u,$y as d,A as f,Ai as p,Ax as m,B as h,Bb as g,Bc as ee,Bg as _,Bt as te,C as ne,Cn as re,Cx as v,Di as y,Fb as b,Fc as x,Gg as ie,Gs as ae,Gv as oe,Hc as se,If as S,Ig as ce,Io as le,Ix as ue,Jb as de,Jn as fe,Jv as pe,KS as me,Kv as he,La as C,Lb as ge,Lc as _e,Lf as ve,Lg as ye,Li as be,Lv as xe,Lx as Se,Mi as Ce,Mo as w,Ms as we,Mx as Te,Nb as Ee,Ns as T,Ob as De,Pb as Oe,Pc as ke,Ps as Ae,Qd as E,Qn as je,Qy as Me,Rb as Ne,Rc as Pe,Ro as Fe,Rv as Ie,ST as D,Sb as Le,Sn as Re,Tb as ze,Th as Be,Tu as O,Uc as Ve,Ug as He,Ur as Ue,V as We,Vc as Ge,Vg as Ke,Vo as qe,Vt as Je,Vx as Ye,Wc as k,Xp as A,Xv as Xe,Yb as Ze,Yv as Qe,Zb as $e,Zd as et,Zp as tt,_T as nt,__ as rt,_i as it,_m as at,aT as ot,af as st,ai as ct,b as lt,bg as ut,bm as dt,bn as ft,br as pt,bx as mt,cT as ht,cc as gt,co as _t,cs as vt,dS as yt,dm as bt,ds as xt,eb as St,ec as Ct,ef as wt,eg as Tt,eu as Et,f as Dt,fS as Ot,fT as kt,fm as At,fs as jt,g_ as Mt,ga as Nt,gi as Pt,gm as Ft,gs as It,h_ as Lt,hg as Rt,hm as zt,hn as Bt,hs as Vt,ic as Ht,ii as Ut,io as Wt,jS as Gt,jb as Kt,jo as qt,js as Jt,jx as Yt,kS as Xt,lc as Zt,lp as Qt,ls as $t,ly as en,m_ as tn,mg as nn,mm as rn,ms as an,nc as on,ni as sn,no as cn,nw as ln,ny as un,o as dn,oE as fn,oy as pn,pT as mn,pg as hn,pm as gn,ps as _n,qc as vn,qg as yn,qs as bn,rf as xn,rw as Sn,ry as Cn,s as wn,sp as Tn,ss as En,tc as Dn,tg as On,ti as kn,to as An,ty as jn,um as Mn,uo as Nn,us as Pn,ux as Fn,v as In,vT as Ln,vm as Rn,vr as zn,w as Bn,wb as Vn,wh as Hn,wm as Un,wn as Wn,wu as Gn,xT as Kn,xm as qn,xn as Jn,xu as Yn,y as Xn,yg as Zn,ym as Qn,yn as $n,yr as er,zb as tr,zi as nr}from"./loadAgentsDir-CwEfQDOw.js";import{A as j,C as M,M as N,O as P,b as F,f as rr,g as ir,j as I,l as L,m as R,p as z,u as ar,w as B,y as or}from"./external-CEp-aPkt.js";import{i as V,n as H,r as sr,t as cr}from"./lazySchema-B4D4qJVE.js";import{$t as lr,Gt as ur,M as dr,Mn as fr,Nn as pr,P as mr,Wt as hr,Y as gr,hn as _r,or as vr,pt as U,qn as yr,yn as br}from"./state-BPFYBqm1.js";import{n as xr,t as Sr}from"./cwd-Besi3Os3.js";import{C as Cr,E as wr,P as W,R as Tr,S as Er,U as Dr,a as Or,c as G,f as kr,i as Ar,nt as jr,tt as Mr,u as Nr,x as Pr}from"./debug-BQj6h99Q.js";import{Bn as Fr,G as Ir,Rn as Lr,cr as Rr,d as zr,dt as Br,f as Vr,g as Hr,it as Ur,nt as Wr,or as Gr,vt as Kr}from"./settings-CvhsRFaT.js";import{F as qr,M as Jr}from"./config-BSkuQZNf.js";import{i as Yr,n as Xr,o as K}from"./process-gEbdy6uY.js";import{A as Zr,O as Qr,k as $r}from"./git-DplvjXEY.js";import{H as ei,c as ti,i as ni,o as ri,q as ii,s as q}from"./log-BlJ7CcKG.js";import{s as ai,u as oi}from"./types-BomO8WUz.js";import{n as si,r as J}from"./analytics-DJobLaWP.js";import{Bt as ci,C as li,Kr as ui,Mn as di,Wr as fi,Y as pi,_ as mi,_n as hi,_r as gi,bt as _i,et as vi,gr as yi,ii as bi,it as xi,jn as Si,ni as Ci,o as wi,oi as Ti,ri as Ei,rt as Di,tt as Oi,u as ki,vn as Ai,x as ji}from"./model-CeG-iOKF.js";import{_t as Mi,at as Ni,it as Pi,nn as Fi,vt as Ii,xn as Li,yn as Ri,yt as zi}from"./prompt-Bm2EEG4F.js";import{C as Bi,S as Vi,T as Hi,_ as Ui,a as Wi,at as Gi,b as Ki,c as qi,ct as Ji,et as Yi,l as Xi,n as Zi,nt as Qi,o as $i,rt as ea,s as ta,st as na,t as ra}from"./sessionState-zhvcDpb2.js";import{n as ia,t as aa}from"./omit-B65XeX8r.js";import{a as oa,n as sa,t as ca}from"./bridgeConfig-CPHAyzdg.js";import{i as la,n as ua,s as da}from"./mappers-CdY45PDA.js";import{n as fa,r as pa}from"./sessionTitle-QPRly1tZ.js";import{t as ma}from"./pollConfig-BgpfHQPJ.js";import{t as ha}from"./controlMessageCompat-IFu4Gc1y.js";import{n as ga,t as _a}from"./ccrClient--8aPutWE.js";import{n as va,t as ya}from"./HybridTransport-n5jji6SI.js";import{n as ba,t as xa}from"./SSETransport-D86IVNn1.js";import{a as Sa,n as Ca}from"./grove-Bck1zFaD.js";import{o as wa}from"./remoteManagedSettings-CfFmrRze.js";import{i as Ta,r as Ea}from"./auth-CWAvPfX7.js";import{t as Da}from"./pluginBlocklist-CMwb7gmY.js";import{t as Oa}from"./settingsSync-BGo6dHJo.js";import{n as ka,t as Aa}from"./toolPool-BBU4ll_p.js";import{t as ja}from"./onChangeAppState-EtUxsgYz.js";import{n as Ma,r as Na}from"./QueryEngine-DXpS0Ytq.js";import{r as Pa}from"./bridgeStatusUtil-CHTx7XwJ.js";import{n as Fa,r as Ia}from"./sideQuestion-oIYrx5ar.js";import{n as La,r as Ra}from"./context-noninteractive-kACWzgS1.js";import{n as za,t as Ba}from"./modelOptions-A5jrCUBp.js";import{a as Va,o as Ha,t as Ua}from"./skillChangeDetector-v6mAYzXX.js";import{n as Wa}from"./reconciler-DgQ4y1Vn.js";import{n as Ga,t as Ka}from"./refresh-CayVRWUY.js";import{basename as qa,dirname as Ja,join as Ya}from"path";import{PassThrough as Xa}from"stream";import{randomUUID as Y}from"crypto";import{mkdir as Za,readFile as Qa,stat as $a,writeFile as eo}from"fs/promises";import{URL as to}from"url";import{cwd as X}from"process";r(),a(),c(),hr(),Mr(),Tr(),Pr(),kr(),Xr(),Ar(),Qr(),ii(),ri(),Lr(),ai(),Hr(),Ti(),ui(),gi(),Si(),hi(),ci(),mi(),Oa(),sr(),cr();var no=H(()=>B({inputTokens:M(),outputTokens:M(),cacheReadInputTokens:M(),cacheCreationInputTokens:M(),webSearchRequests:M(),costUSD:M(),contextWindow:M(),maxOutputTokens:M()})),ro=H(()=>F(`json_schema`));H(()=>B({type:ro()}));var io=H(()=>B({type:F(`json_schema`),schema:P(j(),N())}));H(()=>io());var ao=H(()=>L([`user`,`project`,`org`,`temporary`,`oauth`]));H(()=>L([`local`,`user`,`project`]).describe(`Config scope for settings.`)),H(()=>F(`context-1m-2025-08-07`));var oo=H(()=>B({type:F(`adaptive`)}).describe(`Work Mate decides when and how much to think (Opus 4.6+).`)),so=H(()=>B({type:F(`enabled`),budgetTokens:M().optional()}).describe(`Fixed thinking token budget (older models)`)),co=H(()=>B({type:F(`disabled`)}).describe(`No extended thinking`));H(()=>I([oo(),so(),co()]).describe(`Controls Work Mate's thinking/reasoning behavior. When set, takes precedence over the deprecated maxThinkingTokens.`));var lo=H(()=>B({type:F(`stdio`).optional(),command:j(),args:z(j()).optional(),env:P(j(),j()).optional()})),uo=H(()=>B({type:F(`sse`),url:j(),headers:P(j(),j()).optional()})),fo=H(()=>B({type:F(`http`),url:j(),headers:P(j(),j()).optional()})),po=H(()=>B({type:F(`sdk`),name:j()})),mo=H(()=>I([lo(),uo(),fo(),po()])),ho=H(()=>B({type:F(`claudeai-proxy`),url:j(),id:j()})),go=H(()=>I([mo(),ho()])),_o=H(()=>B({name:j().describe(`Server name as configured`),status:L([`connected`,`failed`,`needs-auth`,`pending`,`disabled`]).describe(`Current connection status`),serverInfo:B({name:j(),version:j()}).optional().describe(`Server information (available when connected)`),error:j().optional().describe(`Error message (available when status is 'failed')`),config:go().optional().describe(`Server configuration (includes URL for HTTP/SSE servers)`),scope:j().optional().describe(`Configuration scope (e.g., project, user, local, claudeai, managed)`),tools:z(B({name:j(),description:j().optional(),annotations:B({readOnly:R().optional(),destructive:R().optional(),openWorld:R().optional()}).optional()})).optional().describe(`Tools provided by this server (available when connected)`),capabilities:B({experimental:P(j(),N()).optional()}).optional().describe(`@internal Server capabilities (available when connected). experimental['claude/channel'] is only present if the server's plugin is on the approved channels allowlist — use its presence to decide whether to show an Enable-channel prompt.`)}).describe(`Status information for an MCP server connection.`));H(()=>B({added:z(j()).describe(`Names of servers that were added`),removed:z(j()).describe(`Names of servers that were removed`),errors:P(j(),j()).describe(`Map of server names to error messages for servers that failed to connect`)}).describe(`Result of a setMcpServers operation.`));var vo=H(()=>L([`userSettings`,`projectSettings`,`localSettings`,`session`,`cliArg`])),yo=H(()=>L([`allow`,`deny`,`ask`])),bo=H(()=>B({toolName:j(),ruleContent:j().optional()})),xo=H(()=>ir(`type`,[B({type:F(`addRules`),rules:z(bo()),behavior:yo(),destination:vo()}),B({type:F(`replaceRules`),rules:z(bo()),behavior:yo(),destination:vo()}),B({type:F(`removeRules`),rules:z(bo()),behavior:yo(),destination:vo()}),B({type:F(`setMode`),mode:or(()=>Co()),destination:vo()}),B({type:F(`addDirectories`),directories:z(j()),destination:vo()}),B({type:F(`removeDirectories`),directories:z(j()),destination:vo()})])),So=H(()=>L([`user_temporary`,`user_permanent`,`user_reject`]).describe(`Classification of this permission decision for telemetry. SDK hosts that prompt users (desktop apps, IDEs) should set this to reflect what actually happened: user_temporary for allow-once, user_permanent for always-allow (both the click and later cache hits), user_reject for deny. If unset, the CLI infers conservatively (temporary for allow, reject for deny). The vocabulary matches tool_decision OTel events (monitoring-usage docs).`));H(()=>I([B({behavior:F(`allow`),updatedInput:P(j(),N()).optional(),updatedPermissions:z(xo()).optional(),toolUseID:j().optional(),decisionClassification:So().optional()}),B({behavior:F(`deny`),message:j(),interrupt:R().optional(),toolUseID:j().optional(),decisionClassification:So().optional()})]));var Co=H(()=>L([`default`,`acceptEdits`,`bypassPermissions`,`plan`,`dontAsk`,`auto`]).describe(`Permission mode for controlling how tool executions are handled. 'default' - Standard behavior, prompts for dangerous operations. 'acceptEdits' - Auto-accept file edit operations. 'bypassPermissions' - Bypass all permission checks (requires allowDangerouslySkipPermissions). 'plan' - Planning mode, no actual tool execution. 'dontAsk' - Don't prompt for permissions, deny if not pre-approved. 'auto' - Automatic mode (transcript classifier).`)),wo=`PreToolUse.PostToolUse.PostToolUseFailure.Notification.UserPromptSubmit.SessionStart.SessionEnd.Stop.StopFailure.SubagentStart.SubagentStop.PreCompact.PostCompact.PermissionRequest.PermissionDenied.Setup.TeammateIdle.TaskCreated.TaskCompleted.Elicitation.ElicitationResult.ConfigChange.WorktreeCreate.WorktreeRemove.InstructionsLoaded.CwdChanged.FileChanged`.split(`.`),To=H(()=>L(wo)),Z=H(()=>B({session_id:j(),transcript_path:j(),cwd:j(),permission_mode:j().optional(),agent_id:j().optional().describe(`Subagent identifier. Present only when the hook fires from within a subagent (e.g., a tool called by an AgentTool worker). Absent for the main thread, even in --agent sessions. Use this field (not agent_type) to distinguish subagent calls from main-thread calls.`),agent_type:j().optional().describe(`Agent type name (e.g., "general-purpose", "code-reviewer"). Present when the hook fires from within a subagent (alongside agent_id), or on the main thread of a session started with --agent (without agent_id).`)})),Eo=H(()=>Z().and(B({hook_event_name:F(`PreToolUse`),tool_name:j(),tool_input:N(),tool_use_id:j()}))),Do=H(()=>Z().and(B({hook_event_name:F(`PermissionRequest`),tool_name:j(),tool_input:N(),permission_suggestions:z(xo()).optional()}))),Oo=H(()=>Z().and(B({hook_event_name:F(`PostToolUse`),tool_name:j(),tool_input:N(),tool_response:N(),tool_use_id:j()}))),ko=H(()=>Z().and(B({hook_event_name:F(`PostToolUseFailure`),tool_name:j(),tool_input:N(),tool_use_id:j(),error:j(),is_interrupt:R().optional()}))),Ao=H(()=>Z().and(B({hook_event_name:F(`PermissionDenied`),tool_name:j(),tool_input:N(),tool_use_id:j(),reason:j()}))),jo=H(()=>Z().and(B({hook_event_name:F(`Notification`),message:j(),title:j().optional(),notification_type:j()}))),Mo=H(()=>Z().and(B({hook_event_name:F(`UserPromptSubmit`),prompt:j()}))),No=H(()=>Z().and(B({hook_event_name:F(`SessionStart`),source:L([`startup`,`resume`,`clear`,`compact`]),agent_type:j().optional(),model:j().optional()}))),Po=H(()=>Z().and(B({hook_event_name:F(`Setup`),trigger:L([`init`,`maintenance`])}))),Fo=H(()=>Z().and(B({hook_event_name:F(`Stop`),stop_hook_active:R(),last_assistant_message:j().optional().describe(`Text content of the last assistant message before stopping. Avoids the need to read and parse the transcript file.`)}))),Io=H(()=>Z().and(B({hook_event_name:F(`StopFailure`),error:Ns(),error_details:j().optional(),last_assistant_message:j().optional()}))),Lo=H(()=>Z().and(B({hook_event_name:F(`SubagentStart`),agent_id:j(),agent_type:j()}))),Ro=H(()=>Z().and(B({hook_event_name:F(`SubagentStop`),stop_hook_active:R(),agent_id:j(),agent_transcript_path:j(),agent_type:j(),last_assistant_message:j().optional().describe(`Text content of the last assistant message before stopping. Avoids the need to read and parse the transcript file.`)}))),zo=H(()=>Z().and(B({hook_event_name:F(`PreCompact`),trigger:L([`manual`,`auto`]),custom_instructions:j().nullable()}))),Bo=H(()=>Z().and(B({hook_event_name:F(`PostCompact`),trigger:L([`manual`,`auto`]),compact_summary:j().describe(`The conversation summary produced by compaction`)}))),Vo=H(()=>Z().and(B({hook_event_name:F(`TeammateIdle`),teammate_name:j(),team_name:j()}))),Ho=H(()=>Z().and(B({hook_event_name:F(`TaskCreated`),task_id:j(),task_subject:j(),task_description:j().optional(),teammate_name:j().optional(),team_name:j().optional()}))),Uo=H(()=>Z().and(B({hook_event_name:F(`TaskCompleted`),task_id:j(),task_subject:j(),task_description:j().optional(),teammate_name:j().optional(),team_name:j().optional()}))),Wo=H(()=>Z().and(B({hook_event_name:F(`Elicitation`),mcp_server_name:j(),message:j(),mode:L([`form`,`url`]).optional(),url:j().optional(),elicitation_id:j().optional(),requested_schema:P(j(),N()).optional()})).describe(`Hook input for the Elicitation event. Fired when an MCP server requests user input. Hooks can auto-respond (accept/decline) instead of showing the dialog.`)),Go=H(()=>Z().and(B({hook_event_name:F(`ElicitationResult`),mcp_server_name:j(),elicitation_id:j().optional(),mode:L([`form`,`url`]).optional(),action:L([`accept`,`decline`,`cancel`]),content:P(j(),N()).optional()})).describe(`Hook input for the ElicitationResult event. Fired after the user responds to an MCP elicitation. Hooks can observe or override the response before it is sent to the server.`)),Ko=[`user_settings`,`project_settings`,`local_settings`,`policy_settings`,`skills`],qo=H(()=>Z().and(B({hook_event_name:F(`ConfigChange`),source:L(Ko),file_path:j().optional()}))),Jo=[`session_start`,`nested_traversal`,`path_glob_match`,`include`,`compact`],Yo=[`User`,`Project`,`Local`,`Managed`],Xo=H(()=>Z().and(B({hook_event_name:F(`InstructionsLoaded`),file_path:j(),memory_type:L(Yo),load_reason:L(Jo),globs:z(j()).optional(),trigger_file_path:j().optional(),parent_file_path:j().optional()}))),Zo=H(()=>Z().and(B({hook_event_name:F(`WorktreeCreate`),name:j()}))),Qo=H(()=>Z().and(B({hook_event_name:F(`WorktreeRemove`),worktree_path:j()}))),$o=H(()=>Z().and(B({hook_event_name:F(`CwdChanged`),old_cwd:j(),new_cwd:j()}))),es=H(()=>Z().and(B({hook_event_name:F(`FileChanged`),file_path:j(),event:L([`change`,`add`,`unlink`])}))),ts=[`clear`,`resume`,`logout`,`prompt_input_exit`,`other`,`bypass_permissions_disabled`],ns=H(()=>L(ts)),rs=H(()=>Z().and(B({hook_event_name:F(`SessionEnd`),reason:ns()}))),is=H(()=>I([Eo(),Oo(),ko(),Ao(),jo(),Mo(),No(),rs(),Fo(),Io(),Lo(),Ro(),zo(),Bo(),Do(),Po(),Vo(),Ho(),Uo(),Wo(),Go(),qo(),Xo(),Zo(),Qo(),$o(),es()])),as=H(()=>B({async:F(!0),asyncTimeout:M().optional()})),os=H(()=>B({hookEventName:F(`PreToolUse`),permissionDecision:yo().optional(),permissionDecisionReason:j().optional(),updatedInput:P(j(),N()).optional(),additionalContext:j().optional()})),ss=H(()=>B({hookEventName:F(`UserPromptSubmit`),additionalContext:j().optional()})),cs=H(()=>B({hookEventName:F(`SessionStart`),additionalContext:j().optional(),initialUserMessage:j().optional(),watchPaths:z(j()).optional()})),ls=H(()=>B({hookEventName:F(`Setup`),additionalContext:j().optional()})),us=H(()=>B({hookEventName:F(`SubagentStart`),additionalContext:j().optional()})),ds=H(()=>B({hookEventName:F(`PostToolUse`),additionalContext:j().optional(),updatedMCPToolOutput:N().optional()})),fs=H(()=>B({hookEventName:F(`PostToolUseFailure`),additionalContext:j().optional()})),ps=H(()=>B({hookEventName:F(`PermissionDenied`),retry:R().optional()})),ms=H(()=>B({hookEventName:F(`Notification`),additionalContext:j().optional()})),hs=H(()=>B({hookEventName:F(`PermissionRequest`),decision:I([B({behavior:F(`allow`),updatedInput:P(j(),N()).optional(),updatedPermissions:z(xo()).optional()}),B({behavior:F(`deny`),message:j().optional(),interrupt:R().optional()})])})),gs=H(()=>B({hookEventName:F(`CwdChanged`),watchPaths:z(j()).optional()})),_s=H(()=>B({hookEventName:F(`FileChanged`),watchPaths:z(j()).optional()})),vs=H(()=>B({continue:R().optional(),suppressOutput:R().optional(),stopReason:j().optional(),decision:L([`approve`,`block`]).optional(),systemMessage:j().optional(),reason:j().optional(),hookSpecificOutput:I([os(),ss(),cs(),ls(),us(),ds(),fs(),ps(),ms(),hs(),ys(),bs(),gs(),_s(),xs()]).optional()})),ys=H(()=>B({hookEventName:F(`Elicitation`),action:L([`accept`,`decline`,`cancel`]).optional(),content:P(j(),N()).optional()}).describe(`Hook-specific output for the Elicitation event. Return this to programmatically accept or decline an MCP elicitation request.`)),bs=H(()=>B({hookEventName:F(`ElicitationResult`),action:L([`accept`,`decline`,`cancel`]).optional(),content:P(j(),N()).optional()}).describe(`Hook-specific output for the ElicitationResult event. Return this to override the action or content before the response is sent to the MCP server.`)),xs=H(()=>B({hookEventName:F(`WorktreeCreate`),worktreePath:j()}).describe(`Hook-specific output for the WorktreeCreate event. Provides the absolute path to the created worktree directory. Command hooks print the path on stdout instead.`));H(()=>I([as(),vs()]));var Ss=H(()=>B({key:j().describe(`Unique key for this option, returned in the response`),label:j().describe(`Display text for this option`),description:j().optional().describe(`Optional description shown below the label`)}));H(()=>B({prompt:j().describe(`Request ID. Presence of this key marks the line as a prompt request.`),message:j().describe(`The prompt message to display to the user`),options:z(Ss()).describe(`Available options for the user to choose from`)})),H(()=>B({prompt_response:j().describe(`The request ID from the corresponding prompt request`),selected:j().describe(`The key of the selected option`)}));var Cs=H(()=>B({name:j().describe(`Skill name (without the leading slash)`),description:j().describe(`Description of what the skill does`),argumentHint:j().describe(`Hint for skill arguments (e.g., "<file>")`)}).describe(`Information about an available skill (invoked via /command syntax).`)),ws=H(()=>B({name:j().describe(`Agent type identifier (e.g., "Explore")`),description:j().describe(`Description of when to use this agent`),model:j().optional().describe(`Model alias this agent uses. If omitted, inherits the parent's model`)}).describe(`Information about an available subagent that can be invoked via the Task tool.`)),Ts=H(()=>B({value:j().describe(`Model identifier to use in API calls`),displayName:j().describe(`Human-readable display name`),description:j().describe(`Description of the model's capabilities`),supportsAdaptiveThinking:R().optional().describe(`Whether this model supports adaptive thinking (Work Mate decides when and how much to think)`),supportsFastMode:R().optional().describe(`Whether this model supports fast mode`),supportsAutoMode:R().optional().describe(`Whether this model supports auto mode`)}).describe(`Information about an available model.`)),Es=H(()=>B({email:j().optional(),organization:j().optional(),subscriptionType:j().optional(),tokenSource:j().optional(),apiKeySource:j().optional(),apiProvider:L([`firstParty`,`bedrock`,`vertex`,`foundry`]).optional().describe(`Active API backend. Anthropic OAuth login only applies when "firstParty"; for 3P providers the other fields are absent and auth is external (AWS creds, gcloud ADC, etc.).`)}).describe(`Information about the logged in user's account.`)),Ds=H(()=>I([j(),P(j(),mo())])),Os=H(()=>B({description:j().describe(`Natural language description of when to use this agent`),tools:z(j()).optional().describe(`Array of allowed tool names. If omitted, inherits all tools from parent`),disallowedTools:z(j()).optional().describe(`Array of tool names to explicitly disallow for this agent`),prompt:j().describe(`The agent's system prompt`),model:j().optional().describe(`Model alias (e.g. 'sonnet', 'opus', 'haiku') or full model ID (e.g. 'claude-opus-4-5'). If omitted or 'inherit', uses the main model`),mcpServers:z(Ds()).optional(),criticalSystemReminder_EXPERIMENTAL:j().optional().describe(`Experimental: Critical reminder added to system prompt`),skills:z(j()).optional().describe(`Array of skill names to preload into the agent context`),initialPrompt:j().optional().describe(`Auto-submitted as the first user turn when this agent is the main thread agent. Slash commands are processed. Prepended to any user-provided prompt.`),maxTurns:M().int().positive().optional().describe(`Maximum number of agentic turns (API round-trips) before stopping`),background:R().optional().describe(`Run this agent as a background task (non-blocking, fire-and-forget) when invoked`),memory:L([`user`,`project`,`local`]).optional().describe(`Scope for auto-loading agent memory files. 'user' - ~/.workmate/agent-memory/<agentType>/, 'project' - .workmate/agent-memory/<agentType>/, 'local' - .workmate/agent-memory-local/<agentType>/`),permissionMode:Co().optional().describe(`Permission mode controlling how tool executions are handled`)}).describe(`Definition for a custom subagent that can be invoked via the Agent tool.`));H(()=>L([`user`,`project`,`local`]).describe(`Source for loading filesystem-based settings. 'user' - Global user settings (~/.workmate/settings.json). 'project' - Project settings (.workmate/settings.json). 'local' - Local settings (.workmate/settings.local.json).`)),H(()=>B({type:F(`local`).describe(`Plugin type. Currently only 'local' is supported`),path:j().describe(`Absolute or relative path to the plugin directory`)}).describe(`Configuration for loading a plugin.`)),H(()=>B({canRewind:R(),error:j().optional(),filesChanged:z(j()).optional(),insertions:M().optional(),deletions:M().optional()}).describe(`Result of a rewindFiles operation.`));var ks=H(()=>N()),As=H(()=>N()),js=H(()=>N()),Q=H(()=>j()),Ms=H(()=>N()),Ns=H(()=>L([`authentication_failed`,`billing_error`,`rate_limit`,`invalid_request`,`server_error`,`unknown`,`max_output_tokens`])),Ps=H(()=>I([F(`compacting`),ar()])),Fs=H(()=>B({type:F(`user`),message:ks(),parent_tool_use_id:j().nullable(),isSynthetic:R().optional(),tool_use_result:N().optional(),priority:L([`now`,`next`,`later`]).optional(),timestamp:j().optional().describe(`ISO timestamp when the message was created on the originating process. Older emitters omit it; consumers should fall back to receive time.`)})),Is=H(()=>Fs().extend({uuid:Q().optional(),session_id:j().optional()})),Ls=H(()=>Fs().extend({uuid:Q(),session_id:j(),isReplay:F(!0)})),Rs=H(()=>B({status:L([`allowed`,`allowed_warning`,`rejected`]),resetsAt:M().optional(),rateLimitType:L([`five_hour`,`seven_day`,`seven_day_opus`,`seven_day_sonnet`,`overage`]).optional(),utilization:M().optional(),overageStatus:L([`allowed`,`allowed_warning`,`rejected`]).optional(),overageResetsAt:M().optional(),overageDisabledReason:L([`overage_not_provisioned`,`org_level_disabled`,`org_level_disabled_until`,`out_of_credits`,`seat_tier_level_disabled`,`member_level_disabled`,`seat_tier_zero_credit_limit`,`group_zero_credit_limit`,`member_zero_credit_limit`,`org_service_level_disabled`,`org_service_zero_credit_limit`,`no_limits_configured`,`unknown`]).optional(),isUsingOverage:R().optional(),surpassedThreshold:M().optional()}).describe(`Rate limit information for claude.ai subscription users.`)),zs=H(()=>B({type:F(`assistant`),message:As(),parent_tool_use_id:j().nullable(),error:Ns().optional(),uuid:Q(),session_id:j()})),Bs=H(()=>B({type:F(`rate_limit_event`),rate_limit_info:Rs(),uuid:Q(),session_id:j()}).describe(`Rate limit event emitted when rate limit info changes.`)),Vs=H(()=>B({type:F(`streamlined_text`),text:j().describe(`Text content preserved from the assistant message`),session_id:j(),uuid:Q()}).describe(`@internal Streamlined text message - replaces SDKAssistantMessage in streamlined output. Text content preserved, thinking and tool_use blocks removed.`)),Hs=H(()=>B({type:F(`streamlined_tool_use_summary`),tool_summary:j().describe(`Summary of tool calls (e.g., "Read 2 files, wrote 1 file")`),session_id:j(),uuid:Q()}).describe(`@internal Streamlined tool use summary - replaces tool_use blocks in streamlined output with a cumulative summary string.`)),Us=H(()=>B({tool_name:j(),tool_use_id:j(),tool_input:P(j(),N())})),Ws=H(()=>B({type:F(`result`),subtype:F(`success`),duration_ms:M(),duration_api_ms:M(),is_error:R(),num_turns:M(),result:j(),stop_reason:j().nullable(),total_cost_usd:M(),usage:Ms(),modelUsage:P(j(),no()),permission_denials:z(Us()),structured_output:N().optional(),fast_mode_state:mc().optional(),uuid:Q(),session_id:j()})),Gs=H(()=>B({type:F(`result`),subtype:L([`error_during_execution`,`error_max_turns`,`error_max_budget_usd`,`error_max_structured_output_retries`]),duration_ms:M(),duration_api_ms:M(),is_error:R(),num_turns:M(),stop_reason:j().nullable(),total_cost_usd:M(),usage:Ms(),modelUsage:P(j(),no()),permission_denials:z(Us()),errors:z(j()),fast_mode_state:mc().optional(),uuid:Q(),session_id:j()})),Ks=H(()=>I([Ws(),Gs()])),qs=H(()=>B({type:F(`system`),subtype:F(`init`),agents:z(j()).optional(),apiKeySource:ao(),betas:z(j()).optional(),claude_code_version:j(),cwd:j(),tools:z(j()),mcp_servers:z(B({name:j(),status:j()})),model:j(),permissionMode:Co(),slash_commands:z(j()),output_style:j(),skills:z(j()),plugins:z(B({name:j(),path:j(),source:j().optional().describe(`@internal Plugin source identifier in "name\\@marketplace" format. Sentinels: "name\\@inline" for --plugin-dir, "name\\@builtin" for built-in plugins.`)})),fast_mode_state:mc().optional(),uuid:Q(),session_id:j()})),Js=H(()=>B({type:F(`stream_event`),event:js(),parent_tool_use_id:j().nullable(),uuid:Q(),session_id:j()})),Ys=H(()=>B({type:F(`system`),subtype:F(`compact_boundary`),compact_metadata:B({trigger:L([`manual`,`auto`]),pre_tokens:M(),preserved_segment:B({head_uuid:Q(),anchor_uuid:Q(),tail_uuid:Q()}).optional().describe(`Relink info for messagesToKeep. Loaders splice the preserved segment at anchor_uuid (summary for suffix-preserving, boundary for prefix-preserving partial compact) so resume includes preserved content. Unset when compaction summarizes everything (no messagesToKeep).`)}),uuid:Q(),session_id:j()})),Xs=H(()=>B({type:F(`system`),subtype:F(`status`),status:Ps(),permissionMode:Co().optional(),uuid:Q(),session_id:j()})),Zs=H(()=>B({type:F(`system`),subtype:F(`post_turn_summary`),summarizes_uuid:j(),status_category:L([`blocked`,`waiting`,`completed`,`review_ready`,`failed`]),status_detail:j(),is_noteworthy:R(),title:j(),description:j(),recent_action:j(),needs_action:j(),artifact_urls:z(j()),uuid:Q(),session_id:j()}).describe(`@internal Background post-turn summary emitted after each assistant turn. summarizes_uuid points to the assistant message this summarizes.`)),Qs=H(()=>B({type:F(`system`),subtype:F(`api_retry`),attempt:M(),max_retries:M(),retry_delay_ms:M(),error_status:M().nullable(),error:Ns(),uuid:Q(),session_id:j()}).describe(`Emitted when an API request fails with a retryable error and will be retried after a delay. error_status is null for connection errors (e.g. timeouts) that had no HTTP response.`)),$s=H(()=>B({type:F(`system`),subtype:F(`local_command_output`),content:j(),uuid:Q(),session_id:j()}).describe(`Output from a local slash command (e.g. /voice, /cost). Displayed as assistant-style text in the transcript.`)),ec=H(()=>B({type:F(`system`),subtype:F(`hook_started`),hook_id:j(),hook_name:j(),hook_event:j(),uuid:Q(),session_id:j()})),tc=H(()=>B({type:F(`system`),subtype:F(`hook_progress`),hook_id:j(),hook_name:j(),hook_event:j(),stdout:j(),stderr:j(),output:j(),uuid:Q(),session_id:j()})),nc=H(()=>B({type:F(`system`),subtype:F(`hook_response`),hook_id:j(),hook_name:j(),hook_event:j(),output:j(),stdout:j(),stderr:j(),exit_code:M().optional(),outcome:L([`success`,`error`,`cancelled`]),uuid:Q(),session_id:j()})),rc=H(()=>B({type:F(`tool_progress`),tool_use_id:j(),tool_name:j(),parent_tool_use_id:j().nullable(),elapsed_time_seconds:M(),task_id:j().optional(),uuid:Q(),session_id:j()})),ic=H(()=>B({type:F(`auth_status`),isAuthenticating:R(),output:z(j()),error:j().optional(),uuid:Q(),session_id:j()})),ac=H(()=>B({type:F(`system`),subtype:F(`files_persisted`),files:z(B({filename:j(),file_id:j()})),failed:z(B({filename:j(),error:j()})),processed_at:j(),uuid:Q(),session_id:j()})),oc=H(()=>B({type:F(`system`),subtype:F(`task_notification`),task_id:j(),tool_use_id:j().optional(),status:L([`completed`,`failed`,`stopped`]),output_file:j(),summary:j(),usage:B({total_tokens:M(),tool_uses:M(),duration_ms:M()}).optional(),uuid:Q(),session_id:j()})),sc=H(()=>B({type:F(`system`),subtype:F(`task_started`),task_id:j(),tool_use_id:j().optional(),description:j(),task_type:j().optional(),workflow_name:j().optional().describe(`meta.name from the workflow script (e.g. 'spec'). Only set when task_type is 'local_workflow'.`),prompt:j().optional(),uuid:Q(),session_id:j()})),cc=H(()=>B({type:F(`system`),subtype:F(`session_state_changed`),state:L([`idle`,`running`,`requires_action`]),uuid:Q(),session_id:j()}).describe(`Mirrors notifySessionStateChanged. 'idle' fires after heldBackResult flushes and the bg-agent do-while exits — authoritative turn-over signal.`)),lc=H(()=>B({type:F(`system`),subtype:F(`task_progress`),task_id:j(),tool_use_id:j().optional(),description:j(),usage:B({total_tokens:M(),tool_uses:M(),duration_ms:M()}),last_tool_name:j().optional(),summary:j().optional(),uuid:Q(),session_id:j()})),uc=H(()=>B({type:F(`tool_use_summary`),summary:j(),preceding_tool_use_ids:z(j()),uuid:Q(),session_id:j()})),dc=H(()=>B({type:F(`system`),subtype:F(`elicitation_complete`),mcp_server_name:j(),elicitation_id:j(),uuid:Q(),session_id:j()}).describe(`Emitted when an MCP server confirms that a URL-mode elicitation is complete.`)),fc=H(()=>B({type:F(`prompt_suggestion`),suggestion:j(),uuid:Q(),session_id:j()}).describe(`Predicted next user prompt, emitted after each turn when promptSuggestions is enabled.`));H(()=>B({sessionId:j().describe(`Unique session identifier (UUID).`),summary:j().describe(`Display title for the session: custom title, auto-generated summary, or first prompt.`),lastModified:M().describe(`Last modified time in milliseconds since epoch.`),fileSize:M().optional().describe(`File size in bytes. Only populated for local JSONL storage.`),customTitle:j().optional().describe(`User-set session title via /rename.`),firstPrompt:j().optional().describe(`First meaningful user prompt in the session.`),gitBranch:j().optional().describe(`Git branch at the end of the session.`),cwd:j().optional().describe(`Working directory for the session.`),tag:j().optional().describe(`User-set session tag.`),createdAt:M().optional().describe(`Creation time in milliseconds since epoch, extracted from the first entry's timestamp.`)}).describe(`Session metadata returned by listSessions and getSessionInfo.`));var pc=H(()=>I([zs(),Is(),Ls(),Ks(),qs(),Js(),Ys(),Xs(),Qs(),$s(),ec(),tc(),nc(),rc(),ic(),oc(),sc(),lc(),cc(),ac(),uc(),Bs(),dc(),fc()])),mc=H(()=>L([`off`,`cooldown`,`on`]).describe(`Fast mode state: off, in cooldown after rate limit, or actively enabled.`));sr(),cr();var hc=H(()=>N()),gc=H(()=>B({matcher:j().optional(),hookCallbackIds:z(j()),timeout:M().optional()}).describe(`Configuration for matching and routing hook callbacks.`)),_c=H(()=>B({subtype:F(`initialize`),hooks:P(To(),z(gc())).optional(),sdkMcpServers:z(j()).optional(),jsonSchema:P(j(),N()).optional(),systemPrompt:j().optional(),appendSystemPrompt:j().optional(),agents:P(j(),Os()).optional(),promptSuggestions:R().optional(),agentProgressSummaries:R().optional()}).describe(`Initializes the SDK session with hooks, MCP servers, and agent configuration.`));H(()=>B({commands:z(Cs()),agents:z(ws()),output_style:j(),available_output_styles:z(j()),models:z(Ts()),account:Es(),pid:M().optional().describe(`@internal CLI process PID for tmux socket isolation`),fast_mode_state:mc().optional()}).describe(`Response from session initialization with available commands, models, and account info.`));var vc=H(()=>B({subtype:F(`interrupt`)}).describe(`Interrupts the currently running conversation turn.`)),yc=H(()=>B({subtype:F(`can_use_tool`),tool_name:j(),input:P(j(),N()),permission_suggestions:z(xo()).optional(),blocked_path:j().optional(),decision_reason:j().optional(),title:j().optional(),display_name:j().optional(),tool_use_id:j(),agent_id:j().optional(),description:j().optional()}).describe(`Requests permission to use a tool with the given input.`)),bc=H(()=>B({subtype:F(`set_permission_mode`),mode:Co()}).describe(`Sets the permission mode for tool execution handling.`)),xc=H(()=>B({subtype:F(`set_model`),model:j().optional()}).describe(`Sets the model to use for subsequent conversation turns.`)),Sc=H(()=>B({subtype:F(`set_max_thinking_tokens`),max_thinking_tokens:M().nullable()}).describe(`Sets the maximum number of thinking tokens for extended thinking.`)),Cc=H(()=>B({subtype:F(`mcp_status`)}).describe(`Requests the current status of all MCP server connections.`));H(()=>B({mcpServers:z(_o())}).describe(`Response containing the current status of all MCP server connections.`));var wc=H(()=>B({subtype:F(`get_context_usage`)}).describe(`Requests a breakdown of current context window usage by category.`)),Tc=H(()=>B({name:j(),tokens:M(),color:j(),isDeferred:R().optional()})),Ec=H(()=>B({color:j(),isFilled:R(),categoryName:j(),tokens:M(),percentage:M(),squareFullness:M()}));H(()=>B({categories:z(Tc()),totalTokens:M(),maxTokens:M(),rawMaxTokens:M(),percentage:M(),gridRows:z(z(Ec())),model:j(),memoryFiles:z(B({path:j(),type:j(),tokens:M()})),mcpTools:z(B({name:j(),serverName:j(),tokens:M(),isLoaded:R().optional()})),deferredBuiltinTools:z(B({name:j(),tokens:M(),isLoaded:R()})).optional(),systemTools:z(B({name:j(),tokens:M()})).optional(),systemPromptSections:z(B({name:j(),tokens:M()})).optional(),agents:z(B({agentType:j(),source:j(),tokens:M()})),slashCommands:B({totalCommands:M(),includedCommands:M(),tokens:M()}).optional(),skills:B({totalSkills:M(),includedSkills:M(),tokens:M(),skillFrontmatter:z(B({name:j(),source:j(),tokens:M()}))}).optional(),autoCompactThreshold:M().optional(),isAutoCompactEnabled:R(),messageBreakdown:B({toolCallTokens:M(),toolResultTokens:M(),attachmentTokens:M(),assistantMessageTokens:M(),userMessageTokens:M(),toolCallsByType:z(B({name:j(),callTokens:M(),resultTokens:M()})),attachmentsByType:z(B({name:j(),tokens:M()}))}).optional(),apiUsage:B({input_tokens:M(),output_tokens:M(),cache_creation_input_tokens:M(),cache_read_input_tokens:M()}).nullable()}).describe(`Breakdown of current context window usage by category (system prompt, tools, messages, etc.).`));var Dc=H(()=>B({subtype:F(`rewind_files`),user_message_id:j(),dry_run:R().optional()}).describe(`Rewinds file changes made since a specific user message.`));H(()=>B({canRewind:R(),error:j().optional(),filesChanged:z(j()).optional(),insertions:M().optional(),deletions:M().optional()}).describe(`Result of a rewindFiles operation.`));var Oc=H(()=>B({subtype:F(`cancel_async_message`),message_uuid:j()}).describe(`Drops a pending async user message from the command queue by uuid. No-op if already dequeued for execution.`));H(()=>B({cancelled:R()}).describe(`Result of a cancel_async_message operation. cancelled=false means the message was not in the queue (already dequeued or never enqueued).`));var kc=H(()=>B({subtype:F(`seed_read_state`),path:j(),mtime:M()}).describe(`Seeds the readFileState cache with a path+mtime entry. Use when a prior Read was removed from context (e.g. by snip) so Edit validation would fail despite the client having observed the Read. The mtime lets the CLI detect if the file changed since the seeded Read — same staleness check as the normal path.`)),Ac=H(()=>B({subtype:F(`hook_callback`),callback_id:j(),input:is(),tool_use_id:j().optional()}).describe(`Delivers a hook callback with its input data.`)),jc=H(()=>B({subtype:F(`mcp_message`),server_name:j(),message:hc()}).describe(`Sends a JSON-RPC message to a specific MCP server.`)),Mc=H(()=>B({subtype:F(`mcp_set_servers`),servers:P(j(),mo())}).describe(`Replaces the set of dynamically managed MCP servers.`));H(()=>B({added:z(j()),removed:z(j()),errors:P(j(),j())}).describe(`Result of replacing the set of dynamically managed MCP servers.`));var Nc=H(()=>B({subtype:F(`reload_plugins`)}).describe(`Reloads plugins from disk and returns the refreshed session components.`));H(()=>B({commands:z(Cs()),agents:z(ws()),plugins:z(B({name:j(),path:j(),source:j().optional()})),mcpServers:z(_o()),error_count:M()}).describe(`Refreshed commands, agents, plugins, and MCP server status after reload.`));var Pc=H(()=>B({subtype:F(`mcp_reconnect`),serverName:j()}).describe(`Reconnects a disconnected or failed MCP server.`)),Fc=H(()=>B({subtype:F(`mcp_toggle`),serverName:j(),enabled:R()}).describe(`Enables or disables an MCP server.`)),Ic=H(()=>B({subtype:F(`stop_task`),task_id:j()}).describe(`Stops a running task.`)),Lc=H(()=>B({subtype:F(`apply_flag_settings`),settings:P(j(),N())}).describe(`Merges the provided settings into the flag settings layer, updating the active configuration.`)),Rc=H(()=>B({subtype:F(`get_settings`)}).describe(`Returns the effective merged settings and the raw per-source settings.`));H(()=>B({effective:P(j(),N()),sources:z(B({source:L([`userSettings`,`projectSettings`,`localSettings`,`flagSettings`,`policySettings`]),settings:P(j(),N())})).describe(`Ordered low-to-high priority — later entries override earlier ones.`),applied:B({model:j()}).optional().describe("Runtime-resolved values after env overrides, session state, and model-specific defaults are applied. Unlike `effective` (disk merge), these reflect what will actually be sent to the API.")}).describe(`Effective merged settings plus raw per-source settings in merge order.`));var zc=H(()=>B({subtype:F(`elicitation`),mcp_server_name:j(),message:j(),mode:L([`form`,`url`]).optional(),url:j().optional(),elicitation_id:j().optional(),requested_schema:P(j(),N()).optional()}).describe(`Requests the SDK consumer to handle an MCP elicitation (user input request).`)),Bc=H(()=>B({action:L([`accept`,`decline`,`cancel`]),content:P(j(),N()).optional()}).describe(`Response from the SDK consumer for an elicitation request.`)),Vc=H(()=>I([vc(),yc(),_c(),bc(),xc(),Sc(),Cc(),wc(),Ac(),jc(),Dc(),Oc(),kc(),Mc(),Nc(),Pc(),Fc(),Ic(),Lc(),Rc(),zc()])),Hc=H(()=>B({type:F(`control_request`),request_id:j(),request:Vc()})),Uc=H(()=>B({subtype:F(`success`),request_id:j(),response:P(j(),N()).optional()})),Wc=H(()=>B({subtype:F(`error`),request_id:j(),error:j(),pending_permission_requests:z(or(()=>Hc())).optional()})),Gc=H(()=>B({type:F(`control_response`),response:I([Uc(),Wc()])})),Kc=H(()=>B({type:F(`control_cancel_request`),request_id:j()}).describe(`Cancels a currently open control request.`)),qc=H(()=>B({type:F(`keep_alive`)}).describe(`Keep-alive message to maintain WebSocket connection.`)),Jc=H(()=>B({type:F(`update_environment_variables`),variables:P(j(),j())}).describe(`Updates environment variables at runtime.`));H(()=>I([pc(),Vs(),Hs(),Zs(),Gc(),Hc(),Kc(),qc()])),H(()=>I([Is(),Hc(),Gc(),qc(),Jc()])),Re(),sr(),cr(),ie(),re(),H(()=>V.object({tool_name:V.string().describe(`The name of the tool requesting permission`),input:V.record(V.string(),V.unknown()).describe(`The input for the tool`),tool_use_id:V.string().optional().describe(`The unique tool use request ID`)}));var Yc=H(()=>V.enum([`user_temporary`,`user_permanent`,`user_reject`]).optional().catch(void 0)),Xc=H(()=>V.object({behavior:V.literal(`allow`),updatedInput:V.record(V.string(),V.unknown()),updatedPermissions:V.array(Wn()).optional().catch(e=>{G(`Malformed updatedPermissions from SDK host ignored: ${e.error.issues[0]?.message??`unknown`}`,{level:`warn`})}),toolUseID:V.string().optional(),decisionClassification:Yc()})),Zc=H(()=>V.object({behavior:V.literal(`deny`),message:V.string(),interrupt:V.boolean().optional(),toolUseID:V.string().optional(),decisionClassification:Yc()})),Qc=H(()=>V.union([Xc(),Zc()]));function $c(e,t,n,r){let i={type:`permissionPromptTool`,permissionPromptToolName:t.name,toolResult:e};if(e.behavior===`allow`){let t=e.updatedPermissions;t&&(r.setAppState(e=>({...e,toolPermissionContext:He(e.toolPermissionContext,t)})),yn(t));let a=Object.keys(e.updatedInput).length>0?e.updatedInput:n;return{...e,updatedInput:a,decisionReason:i}}else e.behavior===`deny`&&e.interrupt&&(G(`SDK permission prompt deny+interrupt: tool=${t.name} message=${e.message}`),r.abortController.abort());return{...e,decisionReason:i}}xr(),Rr(),Kr(),Ur(),Ri(),Fi(),Gi(),kt(),ht(),g(),Cn(),Ki(),ye(),rn(),A(),l(),Zi(),se(),x(),T(),we(),cn(),C(),be(),pt(),ft(),Bt(),We();var el=/\u2028|\u2029/g;function tl(e){return e.replace(el,e=>e===`\u2028`?`\\u2028`:`\\u2029`)}function nl(e){return tl(Cr(e))}Ar(),Pr(),sr(),ie();var rl=`SandboxNetworkAccess`;function il(e){if(e){if(e.type===`classifier`)return e.reason;switch(e.type){case`rule`:case`mode`:case`subcommandResults`:case`permissionPromptTool`:return;case`hook`:case`asyncAgent`:case`sandboxOverride`:case`workingDir`:case`safetyCheck`:case`other`:return e.reason}}}function al(e,t,n,r){let i;try{i=e.getActivityDescription?.(t)??e.getToolUseSummary?.(t)??e.userFacingName(t)}catch{i=e.name}return{tool_name:e.name,action_description:i,tool_use_id:n,request_id:r,input:t}}var ol=1e3,sl=class{constructor(e,t){o(this,`input`,void 0),o(this,`replayUserMessages`,void 0),o(this,`structuredInput`,void 0),o(this,`pendingRequests`,new Map),o(this,`restoredWorkerState`,Promise.resolve(null)),o(this,`inputClosed`,!1),o(this,`unexpectedResponseCallback`,void 0),o(this,`resolvedToolUseIds`,new Set),o(this,`prependedLines`,[]),o(this,`onControlRequestSent`,void 0),o(this,`onControlRequestResolved`,void 0),o(this,`outbound`,new Ge),this.input=e,this.replayUserMessages=t,this.input=e,this.structuredInput=this.read()}trackResolvedToolUseId(e){let t=e.request;if(t.subtype===`can_use_tool`&&(this.resolvedToolUseIds.add(t.tool_use_id),this.resolvedToolUseIds.size>ol)){let e=this.resolvedToolUseIds.values().next().value;e!==void 0&&this.resolvedToolUseIds.delete(e)}}flushInternalEvents(){return Promise.resolve()}get internalEventsPending(){return 0}prependUserMessage(e){this.prependedLines.push(`${Cr({type:`user`,content:e,uuid:``,session_id:``,message:{role:`user`,content:e},parent_tool_use_id:null})}\n`)}async*read(){let e=``,t=async function*(){for(;;){this.prependedLines.length>0&&(e=this.prependedLines.join(``)+e,this.prependedLines=[]);let t=e.indexOf(`
2
- `);if(t===-1)break;let n=e.slice(0,t);e=e.slice(t+1);let r=await this.processLine(n);r&&($r(`info`,`cli_stdin_message_parsed`,{type:r.type}),yield r)}}.bind(this);yield*t();for await(let n of this.input)e+=n,yield*t();if(e){let t=await this.processLine(e);t&&(yield t)}this.inputClosed=!0;for(let e of this.pendingRequests.values())e.reject(Error(`Tool permission stream closed before response received`))}getPendingPermissionRequests(){return Array.from(this.pendingRequests.values()).map(e=>e.request).filter(e=>e.request.subtype===`can_use_tool`)}setUnexpectedResponseCallback(e){this.unexpectedResponseCallback=e}injectControlResponse(e){let t=e.response,n=t?.request_id;if(!n)return;let r=this.pendingRequests.get(n);if(r)if(this.trackResolvedToolUseId(r.request),this.pendingRequests.delete(n),this.write({type:`control_cancel_request`,request_id:n}),t.subtype===`error`)r.reject(Error(t.error));else{let e=t.response;if(r.schema)try{r.resolve(r.schema.parse(e))}catch(e){r.reject(e)}else r.resolve({})}}setOnControlRequestSent(e){this.onControlRequestSent=e}setOnControlRequestResolved(e){this.onControlRequestResolved=e}async processLine(e){if(e)try{let t=ha(Er(e));if(t.type===`keep_alive`)return;if(t.type===`update_environment_variables`){let e=t.variables??{},n=Object.keys(e);for(let[t,n]of Object.entries(e))process.env[t]=n;G(`[structuredIO] applied update_environment_variables: ${n.join(`, `)}`);return}if(t.type===`control_response`){let e=`uuid`in t&&typeof t.uuid==`string`?t.uuid:void 0;e&&zt(e,`completed`);let n=t.response,r=this.pendingRequests.get(n.request_id);if(!r){let e=(n.subtype===`success`?n.response:void 0)?.toolUseID;if(typeof e==`string`&&this.resolvedToolUseIds.has(e)){G(`Ignoring duplicate control_response for already-resolved toolUseID=${e} request_id=${n.request_id}`);return}this.unexpectedResponseCallback&&await this.unexpectedResponseCallback(t);return}if(this.trackResolvedToolUseId(r.request),this.pendingRequests.delete(n.request_id),r.request.request.subtype===`can_use_tool`&&this.onControlRequestResolved&&this.onControlRequestResolved(n.request_id),n.subtype===`error`){r.reject(Error(n.error??`Unknown error`));return}let i=n.response;if(r.schema)try{r.resolve(r.schema.parse(i))}catch(e){r.reject(e)}else r.resolve({});return this.replayUserMessages?t:void 0}if(t.type!==`user`&&t.type!==`control_request`&&t.type!==`assistant`&&t.type!==`system`){G(`Ignoring unknown message type: ${t.type}`,{level:`warn`});return}return t.type===`control_request`?(t.request||cl(`Error: Missing request on control_request`),t):(t.type===`assistant`||t.type===`system`||t.message?.role!==`user`&&cl(`Error: Expected message role 'user', got '${t.message?.role}'`),t)}catch(t){console.error(`Error parsing streaming input line: ${e}: ${t}`),process.exit(1)}}async write(e){K(`${nl(e)}\n`)}async sendRequest(e,t,n,r=Y()){let i={type:`control_request`,request_id:r,request:e};if(this.inputClosed)throw Error(`Stream closed`);if(n?.aborted)throw Error(`Request aborted`);this.outbound.enqueue(i),e.subtype===`can_use_tool`&&this.onControlRequestSent&&this.onControlRequestSent(i);let a=()=>{this.outbound.enqueue({type:`control_cancel_request`,request_id:r});let e=this.pendingRequests.get(r);e&&(this.trackResolvedToolUseId(e.request),e.reject(new wr))};n&&n.addEventListener(`abort`,a,{once:!0});try{return await new Promise((n,i)=>{this.pendingRequests.set(r,{request:{type:`control_request`,request_id:r,request:e},resolve:e=>{n(e)},reject:i,schema:t})})}finally{n&&n.removeEventListener(`abort`,a),this.pendingRequests.delete(r)}}createCanUseTool(e){return async(t,n,r,i,a,o)=>{let s=o??await h(t,n,r,i,a);if(s.behavior===`allow`||s.behavior===`deny`)return s;let c=new AbortController,l=r.abortController.signal,u=()=>c.abort();l.addEventListener(`abort`,u,{once:!0});try{let i=ll(t.name,a,n,r,s.suggestions).then(e=>({source:`hook`,decision:e})),o=Y();e?.(al(t,n,a,o));let l=this.sendRequest({subtype:`can_use_tool`,tool_name:t.name,input:n,permission_suggestions:s.suggestions,blocked_path:s.blockedPath,decision_reason:il(s.decisionReason),tool_use_id:a,agent_id:r.agentId},Qc(),c.signal,o).then(e=>({source:`sdk`,result:e})),u=await Promise.race([i,l]);return u.source===`hook`?u.decision?(l.catch(()=>{}),c.abort(),u.decision):$c((await l).result,t,n,r):$c(u.result,t,n,r)}catch(e){return $c({behavior:`deny`,message:`Tool permission request failed: ${e}`,toolUseID:a},t,n,r)}finally{this.getPendingPermissionRequests().length===0&&$i(`running`),l.removeEventListener(`abort`,u)}}}createHookCallback(e,t){return{type:`callback`,timeout:t,callback:async(t,n,r)=>{try{return await this.sendRequest({subtype:`hook_callback`,callback_id:e,input:t,tool_use_id:n||void 0},Jn(),r)}catch(t){return console.error(`Error in hook callback ${e}:`,t),{}}}}}async handleElicitation(e,t,n,r,i,a,o){try{return await this.sendRequest({subtype:`elicitation`,mcp_server_name:e,message:t,mode:i,url:a,elicitation_id:o,requested_schema:n},Bc(),r)}catch{return{action:`cancel`}}}createSandboxAskCallback(){return async e=>{try{return(await this.sendRequest({subtype:`can_use_tool`,tool_name:rl,input:{host:e.host},tool_use_id:Y(),description:`Allow network connection to ${e.host}?`},Qc())).behavior===`allow`}catch{return!1}}}async sendMcpMessage(e,t){return(await this.sendRequest({subtype:`mcp_message`,server_name:e,message:t},B({mcp_response:rr()}))).mcp_response}};function cl(e){console.error(e),process.exit(1)}async function ll(e,t,n,r,i){let a=r.getAppState().toolPermissionContext.mode,o=Je(e,t,n,r,a,i,r.abortController.signal);for await(let e of o)if(e.permissionRequestResult&&(e.permissionRequestResult.behavior===`allow`||e.permissionRequestResult.behavior===`deny`)){let t=e.permissionRequestResult;if(t.behavior===`allow`){let e=t.updatedInput||n,i=t.updatedPermissions??[];if(i.length>0){yn(i);let e=He(r.getAppState().toolPermissionContext,i);r.setAppState(t=>t.toolPermissionContext===e?t:{...t,toolPermissionContext:e})}return{behavior:`allow`,updatedInput:e,userModified:!1,decisionReason:{type:`hook`,hookName:`PermissionRequest`}}}else return{behavior:`deny`,message:t.message||`Permission denied by PermissionRequest hook`,decisionReason:{type:`hook`,hookName:`PermissionRequest`}}}}Bi(),ba();function ul(e,t={},r,i){if(n(process.env.CLAUDE_CODE_USE_CCR_V2)){let n=new to(e.href);return n.protocol===`wss:`?n.protocol=`https:`:n.protocol===`ws:`&&(n.protocol=`http:`),n.pathname=`${n.pathname.replace(/\/$/,``)}/worker/events/stream`,new xa(n,t,r,i)}if(e.protocol===`ws:`||e.protocol===`wss:`)return n(process.env.CLAUDE_CODE_POST_FOR_SESSION_INGRESS_V2)?new ya(e,t,r,i):new va(e,t,r,i);throw Error(`Unsupported protocol: ${e.protocol}`)}rn(),Ar(),Qr(),r(),Tr(),Xr(),Zi(),ba(),a();var dl=class extends sl{constructor(e,t,r){let i=new Xa({encoding:`utf8`});super(i,r),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=i,this.url=new to(e);let a={},s=Vi();s?a.Authorization=`Bearer ${s}`:G(`[remote-io] No session ingress token available`,{level:`error`});let c=process.env.CLAUDE_CODE_ENVIRONMENT_RUNNER_VERSION;c&&(a[`x-environment-runner-version`]=c);let l=()=>{let e={},t=Vi();t&&(e.Authorization=`Bearer ${t}`);let n=process.env.CLAUDE_CODE_ENVIRONMENT_RUNNER_VERSION;return n&&(e[`x-environment-runner-version`]=n),e};if(this.transport=ul(this.url,a,U(),l),this.isBridge=process.env.CLAUDE_CODE_ENVIRONMENT_KIND===`bridge`,this.isDebug=Or(),this.transport.setOnData(e=>{this.inputStream.write(e),this.isBridge&&this.isDebug&&K(e.endsWith(`
3
- `)?e:`${e}\n`)}),this.transport.setOnClose(()=>{this.inputStream.end()}),n(process.env.CLAUDE_CODE_USE_CCR_V2)){if(!(this.transport instanceof xa))throw Error(`CCR v2 requires SSETransport; check getTransportForUrl`);this.ccrClient=new _a(this.transport,this.url);let e=this.ccrClient.initialize();this.restoredWorkerState=e.catch(()=>null),e.catch(e=>{$r(`error`,`cli_worker_lifecycle_init_failed`,{reason:e instanceof ga?e.reason:`unknown`}),q(Error(`CCRClient initialization failed: ${W(e)}`)),et(1,`other`)}),jr(async()=>this.ccrClient?.close()),it((e,t,n)=>this.ccrClient.writeInternalEvent(e,t,n)),Pt(()=>this.ccrClient.readInternalEvents(),()=>this.ccrClient.readSubagentInternalEvents());let t={started:`processing`,completed:`processed`};Ft((e,n)=>{this.ccrClient?.reportDelivery(e,t[n])}),Xi((e,t)=>{this.ccrClient?.reportState(e,t)}),qi(e=>{this.ccrClient?.reportMetadata(e)},{replayCurrent:!0})}this.transport.connect();let u=ma().session_keepalive_interval_v2_ms;if(this.isBridge&&u>0&&(this.keepAliveTimer=setInterval(()=>{G(`[remote-io] keep_alive sent`),this.write({type:`keep_alive`}).catch(e=>{G(`[remote-io] keep_alive write failed: ${W(e)}`)})},u),this.keepAliveTimer.unref?.()),jr(async()=>this.close()),t){let e=this.inputStream;(async()=>{for await(let n of t)e.write(`${String(n).replace(/\n$/,``)}\n`)})()}}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)&&K(`${nl(e)}\n`)}close(){this.keepAliveTimer&&(clearInterval(this.keepAliveTimer),this.keepAliveTimer=null),this.transport.close(),this.inputStream.end()}};Mi(),Ir(),zi(),[...Ii],Mr(),Ar();var fl=`[stdout-guard]`,pl=!1,$=``,ml=null;function hl(e){if(e.length===0)return!0;try{return JSON.parse(e),!0}catch{return!1}}function gl(){pl||(pl=!0,ml=process.stdout.write.bind(process.stdout),process.stdout.write=((e,t,n)=>{let r=typeof e==`string`?e:Buffer.from(e).toString(`utf-8`);$+=r;let i,a=!0;for(;(i=$.indexOf(`
4
- `))!==-1;){let e=$.slice(0,i);$=$.slice(i+1),hl(e)?a=ml(`${e}\n`):(process.stderr.write(`${fl} ${e}\n`),G(`streamJsonStdoutGuard diverted non-JSON stdout line: ${e.slice(0,200)}`))}let o=typeof t==`function`?t:n;return o&&queueMicrotask(()=>o()),a}),jr(async()=>{$.length>0&&(ml&&hl($)?ml(`${$}\n`):process.stderr.write(`${fl} ${$}\n`),$=``),ml&&(process.stdout.write=ml,ml=null),pl=!1}))}Jr(),nt(),Hi(),ue(),v(),d(),Ni(),tn(),_(),ut(),Gn(),vn(),bn(),an(),le(),_t(),dn(),Aa(),Yn(),Tr(),ri(),Bi(),fn(),Ar(),l();function _l(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&&(G(`Exiting after ${n}ms of idle time`),E())},n))},stop(){i&&(clearTimeout(i),i=null)}}}aa(),Kn(),Ot(),xn(),Sn();function vl(e){if(e.type!==`user`)return;let t=e.message?.content;if(!t||Array.isArray(t)&&t.length===0)return;let n=`uuid`in e&&typeof e.uuid==`string`?e.uuid:void 0;return{content:Array.isArray(t)?yl(t):t,uuid:n}}function yl(e){return e.some(bl)?e.map(e=>{if(!bl(e))return e;let t=e.source,n=typeof t.mediaType==`string`&&t.mediaType?t.mediaType:ln(e.source.data);return{...e,source:{type:`base64`,media_type:n,data:e.source.data}}}):e}function bl(e){return e.type!==`image`||e.source?.type!==`base64`?!1:!e.source.media_type}sr(),hr(),Ar(),r(),cr(),oa();var xl=3e4;function Sl(e){G(`[bridge:inbound-attach] ${e}`)}var Cl=H(()=>B({file_uuid:j(),file_name:j()})),wl=H(()=>z(Cl()));function Tl(e){if(typeof e!=`object`||!e||!(`file_attachments`in e))return[];let t=wl().safeParse(e.file_attachments);return t.success?t.data:[]}function El(e){return qa(e).replace(/[^a-zA-Z0-9._-]/g,`_`)||`attachment`}function Dl(){return Ya(t(),`uploads`,U())}async function Ol(e){let t=ca();if(!t){Sl(`skip: no oauth token`);return}let n;try{let r=`${sa()}/api/oauth/files/${encodeURIComponent(e.file_uuid)}/content`,i=await s.get(r,{headers:{Authorization:`Bearer ${t}`},responseType:`arraybuffer`,timeout:xl,validateStatus:()=>!0});if(i.status!==200){Sl(`fetch ${e.file_uuid} failed: status=${i.status}`);return}n=Buffer.from(i.data)}catch(t){Sl(`fetch ${e.file_uuid} threw: ${t}`);return}let r=El(e.file_name),i=(e.file_uuid.slice(0,8)||Y().slice(0,8)).replace(/[^a-zA-Z0-9_-]/g,`_`),a=Dl(),o=Ya(a,`${i}-${r}`);try{await Za(a,{recursive:!0}),await eo(o,n)}catch(e){Sl(`write ${o} failed: ${e}`);return}return Sl(`resolved ${e.file_uuid} → ${o} (${n.length} bytes)`),o}async function kl(e){if(e.length===0)return``;Sl(`resolving ${e.length} attachment(s)`);let t=(await Promise.all(e.map(Ol))).filter(e=>e!==void 0);return t.length===0?``:`${t.map(e=>`@"${e}"`).join(` `)} `}function Al(e,t){if(!t)return e;if(typeof e==`string`)return t+e;let n=e.findLastIndex(e=>e.type===`text`);if(n!==-1){let r=e[n];if(r.type===`text`)return[...e.slice(0,n),{...r,text:t+r.text},...e.slice(n+1)]}return[...e,{type:`text`,text:t.trimEnd()}]}async function jl(e,t){let n=Tl(e);return n.length===0?t:Al(t,await kl(n))}vi(),xe(),On(),Zt(),Ct(),lt(),pa(),Fa();function Ml(e){if(e.toLowerCase().endsWith(`.jsonl`))return{sessionId:Y(),ingressUrl:null,isUrl:!1,jsonlFile:e,isJsonlFile:!0};if(tt(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}Ci(),me(),de(),b(),Kt(),Be(),Un(),dt(),At(),Tn(),_e(),ua(),Ra(),za(),Ar(),Pr();async function Nl(){try{let e=await Qa(xt(),`utf-8`),t=Br().safeParse(Er(e));return t.success?t.data:(G(`Invalid known_marketplaces.json in zip cache: ${t.error.message}`,{level:`error`}),{})}catch{return{}}}async function Pl(e){await En(xt(),Cr(e,null,2))}async function Fl(e,t){let n=Pn();if(!n)return;let r=await Il(t);r!==null&&await En(Ya(n,$t(e)),r)}async function Il(e){let t=[Ya(e,`.claude-plugin`,`marketplace.json`),Ya(e,`marketplace.json`),e];for(let e of t)try{return await Qa(e,`utf-8`)}catch{}return null}async function Ll(){let e=await Fe();for(let[t,n]of Object.entries(e))if(n.installLocation)try{await Fl(t,n.installLocation)}catch(e){G(`Failed to save marketplace JSON for ${t}: ${e}`)}await Pl({...await Nl(),...e})}si(),Mr(),Ar(),Qr(),ri(),le(),an();async function Rl(){let e=It();G(`installPluginsForHeadless: starting${e?` (zip cache mode)`:``}`);let t=await qe();t&&(qt(),Wt(`headlessPluginInstall: seed marketplaces registered`)),e&&(await Nr().mkdir(jt()),await Nr().mkdir(_n()));let n=Object.keys(w()).length,r={marketplaces_installed:0,delisted_count:0},i=t;try{if(n===0)G(`installPluginsForHeadless: no marketplaces declared`);else{let t=await Zr(`headless_marketplace_reconcile`,()=>Wa({skip:e?(e,t)=>!Vt(t):void 0,onProgress:e=>{e.type===`installed`?G(`installPluginsForHeadless: installed marketplace ${e.name}`):e.type===`failed`&&G(`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&&G(`installPluginsForHeadless: skipped ${t.skipped.length} marketplace(s) unsupported by zip cache: ${t.skipped.join(`, `)}`);let n=t.installed.length+t.updated.length;n>0&&(qt(),Wt(`headlessPluginInstall: marketplaces reconciled`),i=!0),r.marketplaces_installed=n}e&&await Ll();let t=await Da();return r.delisted_count=t.length,t.length>0&&(i=!0),i&&Wt(`headlessPluginInstall: plugins changed`),e&&jr(vt),i}catch(e){return q(e),!1}finally{J(`tengu_headless_plugin_install`,r)}}si(),Ar(),Qr(),rn(),Zi(),ri(),Xr(),A(),l(),Mr(),xr(),We(),hr(),pt(),Bt(),C(),Pr(),r(),Ka(),_t(),he(),S(),u(),Tr();var zl=1e4,Bl=new Set,Vl=[];function Hl(e){if(Bl.has(e))return!1;if(Bl.add(e),Vl.push(e),Vl.length>zl){let e=Vl.splice(0,Vl.length-zl);for(let t of e)Bl.delete(t)}return!0}function Ul(e){return typeof e==`string`?[{type:`text`,text:e}]:e}function Wl(e){return e.length===1?e[0]:e.every(e=>typeof e==`string`)?e.join(`
5
- `):e.flatMap(Ul)}function Gl(e,t){return t!==void 0&&t.mode===`prompt`&&t.workload===e.workload&&t.isMeta===e.isMeta}async function Kl(e,t,r,i,a,o,s,c){if(mn.subscribe(e=>{Tt(e,r),Di()&&r(e=>{let t=e.settings,n=t.fastMode===!0&&!t.fastModePerSessionOptIn;return{...e,fastMode:n}})}),!na()&&n(process.env.CLAUDE_CODE_PROACTIVE)&&Qi(`command`),typeof Bun<`u`&&setInterval(()=>{process.memoryUsage.rss()>350*1024*1024?Bun.gc(!0):Bun.gc(!1)},1e3).unref(),bt(),Mn(`runHeadless_entry`),await Sa()&&await Ca(),Mn(`after_grove_check`),c.resumeSessionAt&&!c.resume){process.stderr.write(`Error: --resume-session-at requires --resume
6
- `),E(1);return}if(c.rewindFiles&&!c.resume){process.stderr.write(`Error: --rewind-files requires --resume
7
- `),E(1);return}if(c.rewindFiles&&e){process.stderr.write(`Error: --rewind-files is a standalone operation and cannot be used with a prompt
8
- `),E(1);return}let l=nu(e,c);c.outputFormat===`stream-json`&&gl();let u=ot.getSandboxUnavailableReason();if(u){if(ot.isSandboxRequired()){process.stderr.write(`\nError: sandbox required but unavailable: ${u}\n sandbox.failIfUnavailable is set — refusing to start without a working sandbox.\n\n`),E(1);return}process.stderr.write(`\n⚠ Sandbox disabled: ${u}\n Commands will run WITHOUT sandboxing. Network and filesystem restrictions will NOT be enforced.\n\n`)}else if(ot.isSandboxingEnabled())try{await ot.initialize(l.createSandboxAskCallback())}catch(e){process.stderr.write(`\n❌ Sandbox Error: ${W(e)}\n`),E(1,`other`);return}c.outputFormat===`stream-json`&&c.verbose&&Ae(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 Mt(c.setupTrigger),Mn(`before_loadInitialMessages`);let d=t(),{messages:f,turnInterruptionState:p,agentSetting:m}=await tu(r,{continue:c.continue,teleport:c.teleport,resume:c.resume,resumeSessionAt:c.resumeSessionAt,forkSession:c.forkSession,outputFormat:c.outputFormat,sessionStartHooksPromise:c.sessionStartHooksPromise,restoredWorkerState:l.restoredWorkerState}),h=rt();if(h&&l.prependUserMessage(h),!c.agent&&!gr()&&m){let{agentDefinition:e}=Va(m,void 0,{activeAgents:s,allAgents:s});if(e){if(r(t=>({...t,agent:e.agentType})),!c.systemPrompt&&!wn(e)){let t=e.getSystemPrompt();t&&(c.systemPrompt=t)}Ut(e.agentType)}}if(f.length===0&&process.exitCode!==void 0)return;if(c.rewindFiles){if(f.find(e=>e.uuid===c.rewindFiles)?.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`),E(1);return}let e=t(),n=await Zl(c.rewindFiles,e,r,!1);if(!n.canRewind){process.stderr.write(`Error: ${n.error||`Unexpected error`}\n`),E(1);return}process.stdout.write(`Files rewound to state at message ${c.rewindFiles}\n`),E(0);return}let g=typeof c.resume==`string`&&(!!tt(c.resume)||c.resume.endsWith(`.jsonl`)),ee=!!c.sdkUrl;if(!e&&!g&&!ee){process.stderr.write(`Error: Input must be provided either through stdin or as a prompt argument when using --print
9
- `),E(1);return}if(c.outputFormat===`stream-json`&&!c.verbose){process.stderr.write(`Error: When using --print, --output-format=stream-json requires --verbose
10
- `),E(1);return}let _=k(d.mcp.tools,d.toolPermissionContext),te=[...a,..._],ne=Yl(c.sdkUrl?`stdio`:c.permissionPromptToolName,l,()=>t().mcp.tools,e=>{r(e=>({...e,attribution:{...e.attribution,permissionPromptCount:e.attribution.permissionPromptCount+1}})),$i(`requires_action`,e)});c.permissionPromptToolName&&(te=te.filter(e=>!Li(e,c.permissionPromptToolName))),Yr(),Mn(`after_loadInitialMessages`),await fi(),Mn(`after_modelStrings`);let re=c.outputFormat===`json`&&c.verbose,v=[],y;Mn(`before_runHeadlessStreaming`);for await(let e of ql(l,d.mcp.clients,[...i,...d.mcp.commands],te,f,ne,o,t,r,s,c,p))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`&&(re&&v.push(e),y=e);switch(c.outputFormat){case`json`:if(y?.type!==`result`)throw Error(`No messages returned`);if(c.verbose){K(`${Cr(v)}\n`);break}K(`${Cr(y)}\n`);break;case`stream-json`:break;default:if(y?.type!==`result`)throw Error(`No messages returned`);switch(y.subtype){case`success`:K(y.result.endsWith(`
11
- `)?y.result:`${y.result}\n`);break;case`error_during_execution`:K(`Execution error`);break;case`error_max_turns`:K(`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`:K(`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`:K(`Error: Failed to provide valid structured output after maximum retries.
12
- Tip: Simplify your schema or check if the output format matches the expected structure.`)}}if(gn(),qr())try{let{drainPendingExtraction:e}=await import(`./extractMemories-B1KbTMY0.js`);await e()}catch{}E(y?.type===`result`&&y?.is_error?1:0)}function ql(t,r,a,o,s,c,l,u,d,f,m,h){let g=!1,_,ne=!1,re=null,v,b=t.outbound;process.on(`SIGINT`,()=>{$r(`info`,`shutdown_signal`,{signal:`SIGINT`}),v&&!v.signal.aborted&&v.abort(),et(0)}),jr(async()=>{let e={};for(let t of oe(u()))ve(t)&&(e[t.type]=(e[t.type]??0)+1);$r(`info`,`run_state_at_shutdown`,{run_active:g,run_phase:_,worker_status:ra(),internal_events_pending:t.internalEventsPending,bg_tasks:e})}),ta(e=>{(e==="default"||e===`acceptEdits`||e===`bypassPermissions`||e===`plan`||e===`auto`||e===`dontAsk`)&&b.enqueue({type:`system`,subtype:`status`,status:null,permissionMode:e,uuid:Y(),session_id:U()})});let x={abortController:null,inflightPromise:null,lastEmitted:null,pendingSuggestion:null,pendingLastEmittedEntry:null},ie;m.enableAuthStatus&&(ie=yi.getInstance().subscribe(e=>{b.enqueue({type:`auth_status`,isAuthenticating:e.isAuthenticating,output:e.output,error:e.error,uuid:Y(),session_id:U()})}));let se=e=>{let t=da(e);t&&b.enqueue({type:`rate_limit_event`,rate_limit_info:t,uuid:Y(),session_id:U()})};Ie.add(se);let S=s,ce=ae(s,X(),100),le=Me(100),ue=process.env.CLAUDE_CODE_RESUME_INTERRUPTED_TURN;h&&h.kind!==`none`&&ue&&(G(`[print.ts] Auto-resuming interrupted turn (kind: ${h.kind})`),eu(S,h.message),Xe({mode:`prompt`,value:h.message.message.content,uuid:Y()}));let de=Ba().map(e=>{let t=e.value===null?`default`:e.value,n=t==="default"?wi():li(t),r=Qt(n),i=xi(e.value),a=di(n);return{name:t,value:t,displayName:e.label,description:e.description,...r&&{supportsAdaptiveThinking:!0},...i&&{supportsFastMode:!0},...a&&{supportsAutoMode:!0}}}),me=m.userSpecifiedModel;function he(e,t){let n=Nt(e,ji(t));S.push(...n);for(let e of n)typeof e.message.content==`string`&&e.message.content.includes(`<local-command-stdout>`)&&b.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 C=[],_e=[],ye=new Set;function be(e){for(let n of e){if(n.type!==`connected`||ye.has(n.name)||n.config.type===`sdk`)continue;let e=n.name;try{n.client.setRequestHandler(Xt,async(n,r)=>{ti(e,`Elicitation request received in print mode: ${Cr(n)}`);let i=n.params.mode===`url`?`url`:`form`;J(`tengu_mcp_elicitation_shown`,{mode:i});let a=await ge(e,n.params,r.signal);if(a)return ti(e,`Elicitation resolved by hook: ${Cr(a)}`),J(`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 t.handleElicitation(e,n.params.message,s,r.signal,i,o,c),u=await Ne(e,l,r.signal,i,c);return J(`tengu_mcp_elicitation_response`,{mode:i,action:u.action}),u}),n.client.setNotificationHandler(Gt,t=>{let{elicitationId:n}=t.params;ti(e,`Elicitation completion notification: ${n}`),te({message:`MCP server "${e}" confirmed elicitation ${n} complete`,notificationType:`elicitation_complete`}),b.enqueue({type:`system`,subtype:`elicitation_complete`,mcp_server_name:e,elicitation_id:n,uuid:Y(),session_id:U()})}),ye.add(e)}catch{}}}async function xe(){let e=new Set(Object.keys(l)),n=new Set(C.map(e=>e.name)),r=Array.from(e).some(e=>!n.has(e)),i=Array.from(n).some(t=>!e.has(t)),a=C.some(e=>e.type===`pending`),o=C.some(e=>e.type===`failed`);if(r||i||a||o){for(let t of C)e.has(t.name)||t.type===`connected`&&await t.cleanup();let r=await Oe(l,(e,n)=>t.sendMcpMessage(e,n));C=r.clients,_e=r.tools;let i=Fr([...n,...e]);d(e=>({...e,mcp:{...e.mcp,tools:[...e.mcp.tools.filter(e=>!i.some(t=>e.name.startsWith(Wr(t)))),..._e]}})),Ke(C)}}xe();let w={clients:[],tools:[],configs:{}},we=e=>{let t=Ve(e.toolPermissionContext,e.mcp.tools),n=Ln(ka([...o,..._e,...w.tools],t,e.toolPermissionContext.mode),`name`);m.permissionPromptToolName&&(n=n.filter(e=>!Li(e,m.permissionPromptToolName)));let r=mr();if(r&&!m.jsonSchema){let e=Pi(r);`tool`in e&&(n=[...n,e.tool])}return n},T=null,De=0;function ke(){if(!T)return;let e=Math.min(De,S.length),t=S.slice(e).filter(e=>e.type===`user`||e.type===`assistant`);De=S.length,t.length>0&&T.writeMessages(t)}let Ae=Promise.resolve({response:{added:[],removed:[],errors:{}},sdkServersChanged:!1});function je(e){let t=async()=>{let t=new Set(C.map(e=>e.name)),n=await au(e,{configs:l,clients:C,tools:_e},w,d);for(let e of Object.keys(l))delete l[e];if(Object.assign(l,n.newSdkState.configs),C=n.newSdkState.clients,_e=n.newSdkState.tools,w=n.newDynamicState,n.sdkServersChanged){let e=new Set(C.map(e=>e.name)),n=Fr([...t,...e]);d(e=>({...e,mcp:{...e.mcp,tools:[...e.mcp.tools.filter(e=>!n.some(t=>e.name.startsWith(Wr(t)))),..._e]}}))}return{response:n.response,sdkServersChanged:n.sdkServersChanged}};return Ae=Ae.then(t,t),Ae}function Fe(){let e=u(),t=e.mcp.clients,n=Ln([...e.mcp.tools,...w.tools],`name`),r=new Set([...t.map(e=>e.name),...C.map(e=>e.name)]);return[...t,...C,...w.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`?mt(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;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}})}async function Le(){try{await Promise.all([Promise.resolve(),Zr(`headless_managed_settings_wait`,()=>wa())]),await Rl()&&await We()}catch(e){q(e)}}let Re=null;i()||(n(process.env.CLAUDE_CODE_SYNC_PLUGIN_INSTALL)?Re=Le():Le());let ze=_l(()=>!g),Be=a,O=f;async function He(){let{agentDefinitions:e}=await Ga(d);Be=await Ce(X());let t=O.filter(e=>e.source===`flagSettings`);O=[...e.allAgents,...t]}async function We(){let{servers:e}=await Yt(),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(l))n.type===`sdk`&&!(e in t)&&(t[e]=n);let{response:n,sdkServersChanged:r}=await je(t);r&&xe(),G(`Headless MCP refresh: added=${n.added.length}, removed=${n.removed.length}`)}let Ge=Ua.subscribe(()=>{y(),Ce(X()).then(e=>{Be=e})}),qe=()=>{setTimeout(()=>{!na()||Ji()||ne||(async()=>{let e=await qn({basePrompt:`<${ei}>${new Date().toLocaleTimeString()}</${ei}>`,currentDir:X(),shouldCreate:()=>!ne});if(ne){await at({commands:e});return}for(let t of e)Xe({...t,uuid:Y()});Je()})().catch(e=>{q(e),G(`[Proactive] failed to create headless tick: ${e}`,{level:`error`})})},0)};en(()=>{v&&jn(`now`).length>0&&v.abort(`interrupt`)});let Je=async()=>{if(g)return;if(g=!0,_=void 0,$i(`running`),ze.stop(),Mn(`run_entry`),await xe(),Mn(`after_updateSdkMcp`),Re){let e=parseInt(process.env.CLAUDE_CODE_SYNC_PLUGIN_INSTALL_TIMEOUT_MS||``,10);if(e>0){let t=Ai(e).then(()=>`timeout`);await Promise.race([Re,t])===`timeout`&&(q(Error(`CLAUDE_CODE_SYNC_PLUGIN_INSTALL: plugin installation timed out after ${e}ms`)),J(`tengu_sync_plugin_install_timeout`,{timeout_ms:e}))}else await Re;Re=null,await He();let{setupPluginHookHotReload:t}=await import(`./loadPluginHooks-C-Yk5KlI.js`);t()}let n=e=>e.agentId===void 0;try{let r,i=!1,a=async()=>{for(;r=pe(n);){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(;Gl(r,pn(n));)i.push(pe(n));let a=await Rn(i);if(i=a.attachmentCommands,i.length===0)continue;r=i[0],r.mode===`prompt`&&i.length>1&&(r={...r,value:Wl(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(m.replayUserMessages&&i.length>1)for(let e of i)e.uuid&&e.uuid!==r.uuid&&b.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=u(),l=[...s.mcp.clients,...C,...w.clients];be(l);let f=we(s);for(let e of o)zt(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`,u=e.match(/<usage>([\s\S]*?)<\/usage>/)?.[1]??``,d=u.match(/<total_tokens>(\d+)<\/total_tokens>/),f=u.match(/<tool_uses>(\d+)<\/tool_uses>/),p=u.match(/<duration_ms>(\d+)<\/duration_ms>/);a&&b.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:d&&f?{total_tokens:parseInt(d[1],10),tool_uses:parseInt(f[1],10),duration_ms:p?parseInt(p[1],10):0}:void 0,session_id:U(),uuid:Y()})}let p=r.value,h=a.claimedCommands;if(t instanceof dl&&r.mode===`prompt`&&J(`tengu_bridge_message_received`,{is_repl:!1}),x.abortController?.abort(),x.abortController=null,x.pendingSuggestion=null,x.pendingLastEmittedEntry=null,x.lastEmitted&&r.mode===`prompt`){let e=typeof p==`string`?p:p.find(e=>e.type===`text`)?.text;typeof e==`string`&&Dn(x.lastEmitted.text,e,x.lastEmitted.emittedAt,x.lastEmitted.promptId,x.lastEmitted.generationRequestId),x.lastEmitted=null}v=tr(),Mn(`before_ask`),ee();let g=r,_=!1;try{if(await Ei(g.workload??m.workload,async()=>{for await(let e of Ma({commands:Ln([...Be,...s.mcp.commands],`name`),prompt:p,promptUuid:g.uuid,isMeta:g.isMeta,cwd:X(),tools:f,verbose:m.verbose,mcpClients:l,thinkingConfig:m.thinkingConfig,maxTurns:m.maxTurns,maxBudgetUsd:m.maxBudgetUsd,taskBudget:m.taskBudget,canUseTool:c,userSpecifiedModel:me,fallbackModel:m.fallbackModel,jsonSchema:mr()??m.jsonSchema,mutableMessages:S,getReadFileCache:()=>le.size===0?ce:St(ce,le),setReadFileCache:e=>{ce=e;for(let[e,t]of le.entries()){let n=ce.get(e);(!n||t.timestamp>n.timestamp)&&ce.set(e,t)}le.clear()},customSystemPrompt:m.systemPrompt,appendSystemPrompt:m.appendSystemPrompt,getAppState:u,setAppState:d,abortController:v,replayUserMessages:m.replayUserMessages,includePartialMessages:m.includePartialMessages,handleElicitation:(e,n,r)=>t.handleElicitation(e,n.message,void 0,r,n.mode,n.url,`elicitationId`in n?n.elicitationId:void 0),agents:O,orphanedPermission:g.orphanedPermission,setSDKStatus:e=>{b.enqueue({type:`system`,subtype:`status`,status:e,session_id:U(),uuid:Y()})}}))if(ke(),e.type===`result`){_=!!e.is_error;for(let e of Ui())b.enqueue(e);oe(u()).some(e=>(e.type===`local_agent`||e.type===`local_workflow`)&&ve(e))?re=e:(re=null,b.enqueue(e))}else{for(let e of Ui())b.enqueue(e);b.enqueue(e)}}),_)await Qn({commands:h,outcome:{type:`failed`,message:`ask() returned an error result`},currentDir:X(),priority:`later`,workload:g.workload??m.workload});else{let e=await Qn({commands:h,outcome:{type:`completed`},currentDir:X(),priority:`later`,workload:g.workload??m.workload});for(let t of e)Xe({...t,uuid:Y()})}}catch(e){throw await Qn({commands:h,outcome:{type:`failed`,error:e},currentDir:X(),priority:`later`,workload:g.workload??m.workload}),e}for(let e of o)zt(e,`completed`);if(ke(),T?.sendResult(),m.promptSuggestions&&!e(process.env.CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION)){x.abortController?.abort();let e=new AbortController;x.abortController=e;let t=gt();if(!t)on(`sdk_no_params`,void 0,void 0,`sdk`);else{let n={promise:null};n.promise=(async()=>{try{let n=await Ht(e,S,u,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};re?(x.pendingSuggestion=r,x.pendingLastEmittedEntry={text:i.text,promptId:i.promptId,generationRequestId:i.generationRequestId}):(x.lastEmitted=i,b.enqueue(r))}catch(e){if(e instanceof Error&&(e.name===`AbortError`||e.name===`APIUserAbortError`)){on(`aborted`,void 0,void 0,`sdk`);return}q(Dr(e))}finally{x.inflightPromise===n.promise&&(x.inflightPromise=null)}})(),x.inflightPromise=n.promise}}gn(),Pe(),bt()}};do{for(let e of Ui())b.enqueue(e);_=`draining_commands`,await a(),i=!1;{let e=oe(u()).some(e=>ve(e)),t=pn(n)!==void 0;(e||t)&&(i=!0,t||(_=`waiting_for_agents`,await Ai(100)))}}while(i);re&&(b.enqueue(re),re=null,x.pendingSuggestion&&(b.enqueue(x.pendingSuggestion),x.pendingLastEmittedEntry&&(x.lastEmitted={...x.pendingLastEmittedEntry,emittedAt:Date.now()},x.pendingLastEmittedEntry=null),x.pendingSuggestion=null))}catch(e){try{await t.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:Yi,modelUsage:{},permission_denials:[],uuid:Y(),errors:[W(e),...ni().map(e=>e.error)]})}catch{}x.abortController?.abort(),E(1);return}finally{if(_=`finally_flush`,await t.flushInternalEvents(),_=`finally_post_flush`,!wt()){$i(`idle`);for(let e of Ui())b.enqueue(e)}g=!1,ze.start()}if(na()&&!Ji()&&pn(n)===void 0&&!ne){qe();return}if(pn(n)!==void 0){Je();return}ne&&(x.inflightPromise&&await Promise.race([x.inflightPromise,Ai(5e3)]),x.abortController?.abort(),x.abortController=null,await Jt(),Ge(),ie?.(),Ie.delete(se),b.done())},k=(e,t)=>{b.enqueue({type:`control_response`,response:{subtype:`success`,request_id:e.request_id,response:t}})},A=(e,t)=>{b.enqueue({type:`control_response`,response:{subtype:`error`,request_id:e.request_id,error:t}})},tt=new Set;t.setUnexpectedResponseCallback(async e=>{await ru({message:e,setAppState:d,handledToolUseIds:tt,onEnqueued:()=>{Je()}})});let nt=new Map,rt=new Map,it=new Set,ot=new Map,st=null;return(async()=>{let e=!1;$r(`info`,`cli_message_loop_started`);for await(let n of t.structuredInput){let i=`uuid`in n?n.uuid:void 0;if(i&&n.type!==`user`&&n.type!==`control_response`&&zt(i,`completed`),n.type===`control_request`){let i=n,o=i.request;if(i.request.subtype===`interrupt`)d(e=>({...e,attribution:{...e.attribution,escapeCount:e.attribution.escapeCount+1}})),v&&v.abort(),x.abortController?.abort(),x.abortController=null,x.lastEmitted=null,x.pendingSuggestion=null,k(i);else if(o.subtype===`end_session`){G(`[print.ts] end_session received, reason=${o.reason??`unspecified`}`),v&&v.abort(),x.abortController?.abort(),x.abortController=null,x.lastEmitted=null,x.pendingSuggestion=null,k(i);break}else if(i.request.subtype===`initialize`){if(i.request.sdkMcpServers&&i.request.sdkMcpServers.length>0)for(let e of i.request.sdkMcpServers)l[e]={type:`sdk`,name:e};await Xl(i.request,i.request_id,e,b,a,de,t,!!m.enableAuthStatus,m,f,u),i.request.promptSuggestions&&d(e=>e.promptSuggestionEnabled?e:{...e,promptSuggestionEnabled:!0}),i.request.agentProgressSummaries&&yr(!0),e=!0,un()&&Je()}else if(i.request.subtype===`set_permission_mode`){let e=i.request;d(t=>({...t,toolPermissionContext:Ql(e,i.request_id,t.toolPermissionContext,b)}))}else if(i.request.subtype===`set_model`){let e=i.request.model??`default`,t=e==="default"?wi():e;me=t,fr(t),Wi({model:t}),he(e,t),k(i)}else if(i.request.subtype===`set_max_thinking_tokens`)i.request.max_thinking_tokens===null?m.thinkingConfig=void 0:i.request.max_thinking_tokens===0?m.thinkingConfig={type:`disabled`}:m.thinkingConfig={type:`enabled`,budgetTokens:i.request.max_thinking_tokens},k(i);else if(i.request.subtype===`mcp_status`)k(i,{mcpServers:Fe()});else if(i.request.subtype===`get_context_usage`)try{let e=u(),t=await La({messages:S,getAppState:u,options:{mainLoopModel:ki(),tools:we(e),agentDefinitions:e.agentDefinitions,customSystemPrompt:m.systemPrompt,appendSystemPrompt:m.appendSystemPrompt}});k(i,{...t})}catch(e){A(i,W(e))}else if(i.request.subtype===`mcp_message`){let e=i.request,t=C.find(t=>t.name===e.server_name);t&&t.type===`connected`&&t.client?.transport?.onmessage&&t.client.transport.onmessage(e.message),k(i)}else if(i.request.subtype===`rewind_files`){let e=u(),t=await Zl(i.request.user_message_id,e,d,i.request.dry_run??!1);t.canRewind||i.request.dry_run?k(i,t):A(i,t.error??`Unexpected error`)}else if(i.request.subtype===`cancel_async_message`){let e=i.request.message_uuid,t=Qe(t=>t.uuid===e);k(i,{cancelled:t.length>0})}else if(i.request.subtype===`seed_read_state`){try{let e=Gr(i.request.path),t=Math.floor((await $a(e)).mtimeMs);if(t<=i.request.mtime){let n=await Qa(e,`utf-8`),r=(n.charCodeAt(0)===65279?n.slice(1):n).replaceAll(`\r
13
- `,`
14
- `);le.set(e,{content:r,timestamp:t,offset:void 0,limit:void 0})}}catch{}k(i)}else if(i.request.subtype===`mcp_set_servers`){let{response:e,sdkServersChanged:t}=await je(i.request.servers);k(i,e),t&&xe()}else if(i.request.subtype===`reload_plugins`)try{let e=await Ga(d),t=O.filter(e=>e.source===`flagSettings`);O=[...e.agentDefinitions.allAgents,...t];let n=[],[r,a,o]=await Promise.allSettled([Ce(X()),We(),Nn()]);r.status===`fulfilled`?Be=r.value:q(r.reason),a.status===`rejected`&&q(a.reason),o.status===`fulfilled`?n=o.value.enabled.map(e=>({name:e.name,path:e.path,source:e.source})):q(o.reason),k(i,{commands:Be.filter(e=>e.userInvocable!==!1).map(e=>({name:nr(e),description:p(e),argumentHint:e.argumentHint||``})),agents:O.map(e=>({name:e.agentType,description:e.whenToUse,model:e.model===`inherit`?void 0:e.model})),plugins:n,mcpServers:Fe(),error_count:e.error_count})}catch(e){A(i,W(e))}else if(i.request.subtype===`mcp_reconnect`){let e=u(),{serverName:t}=i.request;ye.delete(t);let n=Te(t)??r.find(e=>e.name===t)?.config??C.find(e=>e.name===t)?.config??w.clients.find(e=>e.name===t)?.config??e.mcp.clients.find(e=>e.name===t)?.config??null;if(!n)A(i,`Server not found: ${t}`);else{let e=await Ee(t,n),r=Wr(t);if(d(n=>({...n,mcp:{...n.mcp,clients:n.mcp.clients.map(n=>n.name===t?e.client:n),tools:[...D(n.mcp.tools,e=>e.name?.startsWith(r)),...e.tools],commands:[...D(n.mcp.commands,e=>Fn(e,t)),...e.commands],resources:e.resources&&e.resources.length>0?{...n.mcp.resources,[t]:e.resources}:ia(n.mcp.resources,t)}})),w={...w,clients:[...w.clients.filter(e=>e.name!==t),e.client],tools:[...w.tools.filter(e=>!e.name?.startsWith(r)),...e.tools]},e.client.type===`connected`)be([e.client]),k(i);else{let t=e.client.type===`failed`?e.client.error??`Connection failed`:`Server status: ${e.client.type}`;A(i,t)}}}else if(i.request.subtype===`mcp_toggle`){let e=u(),{serverName:t,enabled:n}=i.request;ye.delete(t);let a=Te(t)??r.find(e=>e.name===t)?.config??C.find(e=>e.name===t)?.config??w.clients.find(e=>e.name===t)?.config??e.mcp.clients.find(e=>e.name===t)?.config??null;if(!a)A(i,`Server not found: ${t}`);else if(n){Ye(t,!0);let e=await Ee(t,a),n=Wr(t);if(d(r=>({...r,mcp:{...r.mcp,clients:r.mcp.clients.map(n=>n.name===t?e.client:n),tools:[...D(r.mcp.tools,e=>e.name?.startsWith(n)),...e.tools],commands:[...D(r.mcp.commands,e=>Fn(e,t)),...e.commands],resources:e.resources&&e.resources.length>0?{...r.mcp.resources,[t]:e.resources}:ia(r.mcp.resources,t)}})),e.client.type===`connected`)be([e.client]),k(i);else{let t=e.client.type===`failed`?e.client.error??`Connection failed`:`Server status: ${e.client.type}`;A(i,t)}}else{Ye(t,!1);let n=[...r,...C,...w.clients,...e.mcp.clients].find(e=>e.name===t);n&&n.type===`connected`&&await Vn(t,a);let o=Wr(t);d(e=>({...e,mcp:{...e.mcp,clients:e.mcp.clients.map(e=>e.name===t?{name:t,type:`disabled`,config:a}:e),tools:D(e.mcp.tools,e=>e.name?.startsWith(o)),commands:D(e.mcp.commands,e=>Fn(e,t)),resources:ia(e.mcp.resources,t)}})),k(i)}}else if(o.subtype===`mcp_authenticate`){let e=o.serverName,t=u(),n=Te(e)??r.find(t=>t.name===e)?.config??t.mcp.clients.find(t=>t.name===e)?.config??null;if(!n)A(i,`Server not found: ${e}`);else if(n.type!==`sse`&&n.type!==`http`)A(i,`Server type "${n.type}" does not support OAuth authentication`);else try{nt.get(e)?.abort();let t=new AbortController;nt.set(e,t);let r,a=new Promise(e=>{r=e}),o=Ze(e,n,e=>r(e),t.signal,{skipBrowserOpen:!0,onWaitingForCallback:t=>{rt.set(e,t)}}),s=await Promise.race([a,o.then(()=>null)]);s?k(i,{authUrl:s,requiresUserAction:!0}):k(i,{requiresUserAction:!1}),ot.set(e,o),o.then(async()=>{if(Se(e)||it.has(e))return;let t=await Ee(e,n),r=Wr(e);d(n=>({...n,mcp:{...n.mcp,clients:n.mcp.clients.map(n=>n.name===e?t.client:n),tools:[...D(n.mcp.tools,e=>e.name?.startsWith(r)),...t.tools],commands:[...D(n.mcp.commands,t=>Fn(t,e)),...t.commands],resources:t.resources&&t.resources.length>0?{...n.mcp.resources,[e]:t.resources}:ia(n.mcp.resources,e)}})),w={...w,clients:[...w.clients.filter(t=>t.name!==e),t.client],tools:[...w.tools.filter(e=>!e.name?.startsWith(r)),...t.tools]}}).catch(t=>{G(`MCP OAuth failed for ${e}: ${t}`,{level:`error`})}).finally(()=>{nt.get(e)===t&&(nt.delete(e),rt.delete(e),it.delete(e),ot.delete(e))})}catch(e){A(i,W(e))}}else if(o.subtype===`mcp_oauth_callback_url`){let e=o.serverName,t=o.callbackUrl,n=rt.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)A(i,`Invalid callback URL: missing authorization code. Please paste the full redirect URL including the code parameter.`);else{it.add(e),n(t);let r=ot.get(e);if(r)try{await r,k(i)}catch(e){A(i,e instanceof Error?e.message:`OAuth authentication failed`)}else k(i)}}else A(i,`No active OAuth flow for server: ${e}`)}else if(o.subtype===`claude_authenticate`){let e=o.loginWithClaudeAi;st?.service.cleanup(),J(`tengu_oauth_flow_start`,{loginWithClaudeAi:e??!0});let t=new Ta,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 Ea(t),J(`tengu_oauth_success`,{loginWithClaudeAi:e??!0})}).finally(()=>{t.cleanup(),st?.service===t&&(st=null)});st={service:t,flow:a},a.catch(e=>G(`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`)})]);k(i,{manualUrl:e,automaticUrl:t})}catch(e){A(i,W(e))}}else if(o.subtype===`claude_oauth_callback`||o.subtype===`claude_oauth_wait_for_completion`)if(!st)A(i,`No active claude_authenticate flow`);else{o.subtype===`claude_oauth_callback`&&st.service.handleManualAuthCodeInput({authorizationCode:o.authorizationCode,state:o.state});let{flow:e}=st;e.then(()=>{let e=_i();k(i,{account:{email:e?.email,organization:e?.organization,subscriptionType:e?.subscription,tokenSource:e?.tokenSource,apiKeySource:e?.apiKeySource,apiProvider:bi()}})},e=>A(i,W(e)))}else if(o.subtype===`mcp_clear_auth`){let e=o.serverName,t=u(),n=Te(e)??r.find(t=>t.name===e)?.config??t.mcp.clients.find(t=>t.name===e)?.config??null;if(!n)A(i,`Server not found: ${e}`);else if(n.type!==`sse`&&n.type!==`http`)A(i,`Cannot clear auth for server type "${n.type}"`);else{await $e(e,n);let t=await Ee(e,n),r=Wr(e);d(n=>({...n,mcp:{...n.mcp,clients:n.mcp.clients.map(n=>n.name===e?t.client:n),tools:[...D(n.mcp.tools,e=>e.name?.startsWith(r)),...t.tools],commands:[...D(n.mcp.commands,t=>Fn(t,e)),...t.commands],resources:t.resources&&t.resources.length>0?{...n.mcp.resources,[e]:t.resources}:ia(n.mcp.resources,e)}})),k(i,{})}}else if(i.request.subtype===`apply_flag_settings`){let e=ki(),t=dr()??{},n=i.request.settings,r={...t,...n};for(let e of Object.keys(r))r[e]===null&&delete r[e];_r(r),mn.notifyChange(`flagSettings`),`model`in n&&(n.model==null?fr(void 0):fr(String(n.model)));let a=ki();if(a!==e){me=a;let e=n.model?String(n.model):`default`;Wi({model:a}),he(e,a)}k(i)}else if(i.request.subtype===`get_settings`){let e=ki();k(i,{...zr(),applied:{model:e}})}else if(i.request.subtype===`stop_task`){let{task_id:e}=i.request;try{await Et(e,{getAppState:u,setAppState:d}),k(i,{})}catch(e){A(i,W(e))}}else if(o.subtype===`generate_session_title`){let e=o.description,t=o.persist,n=(v&&!v.signal.aborted?v:tr()).signal;(async()=>{try{let r=await fa(e,n);if(r&&t)try{ct(U(),r)}catch(e){q(e)}k(i,{title:r})}catch(e){A(i,W(e))}})()}else if(o.subtype===`side_question`){let e=o.question;(async()=>{try{let t=gt(),n=t?{...t,toolUseContext:{...t.toolUseContext,abortController:tr()}}:await Na({tools:we(u()),commands:Be,mcpClients:[...u().mcp.clients,...C,...w.clients],messages:S,readFileState:ce,getAppState:u,setAppState:d,customSystemPrompt:m.systemPrompt,appendSystemPrompt:m.appendSystemPrompt,thinkingConfig:m.thinkingConfig,agents:O}),r=await Ia({question:e,cacheSafeParams:n});k(i,{response:r.response})}catch(e){A(i,W(e))}})()}else if(i.request.subtype===`set_proactive`)i.request.enabled?na()||(Qi(`command`),qe()):ea(),k(i);else if(o.subtype===`remote_control`)if(o.enabled)if(T)k(i,{session_url:yt(T.bridgeSessionId,T.sessionIngressUrl),connect_url:Pa(T.environmentId,T.sessionIngressUrl),environment_id:T.environmentId});else{let e;try{let{initReplBridge:n}=await import(`./initReplBridge-D09JEKHt.js`),r=await n({onInboundMessage(e){let t=vl(e);if(!t)return;let{content:n,uuid:r}=t;Xe({value:n,mode:`prompt`,uuid:r,skipSlashCommands:!0}),Je()},onPermissionResponse(e){t.injectControlResponse(e)},onInterrupt(){v?.abort()},onSetModel(e){let t=e==="default"?wi():e;me=t,fr(t)},onSetMaxThinkingTokens(e){e===null?m.thinkingConfig=void 0:e===0?m.thinkingConfig={type:`disabled`}:m.thinkingConfig={type:`enabled`,budgetTokens:e}},onStateChange(t,n){t===`failed`&&(e=n),G(`[bridge:sdk] State change: ${t}${n?` — ${n}`:``}`),b.enqueue({type:`system`,subtype:`bridge_state`,state:t,detail:n,uuid:Y(),session_id:U()})},initialMessages:S.length>0?S:void 0});r?(T=r,De=S.length,t.setOnControlRequestSent(e=>{r.sendControlRequest(e)}),t.setOnControlRequestResolved(e=>{r.sendControlCancelRequest(e)}),k(i,{session_url:yt(r.bridgeSessionId,r.sessionIngressUrl),connect_url:Pa(r.environmentId,r.sessionIngressUrl),environment_id:r.environmentId})):A(i,e??`Remote Control initialization failed`)}catch(e){A(i,W(e))}}else T&&(t.setOnControlRequestSent(void 0),t.setOnControlRequestResolved(void 0),await T.teardown(),T=null),k(i);else A(i,`Unsupported control request subtype: ${i.request.subtype}`);continue}else if(n.type===`control_response`){m.replayUserMessages&&b.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=la([n]);S.push(...e),n.type===`assistant`&&m.replayUserMessages&&b.enqueue(n);continue}if(n.type!==`user`)continue;let o=n;if(e=!0,o.uuid){let e=U(),t=await fe(e,o.uuid);if(t||Bl.has(o.uuid)){G(`Skipping duplicate user message: ${o.uuid}`),m.replayUserMessages&&(G(`Sending acknowledgment for duplicate user message: ${o.uuid}`),b.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&&zt(o.uuid,`completed`);continue}Hl(o.uuid)}Xe({mode:`prompt`,value:await jl(o,o.message.content),uuid:o.uuid,priority:o.priority}),d(e=>({...e,attribution:Hn(e.attribution,e=>{Ue(e).catch(e=>{G(`Attribution: Failed to save snapshot: ${e}`)})})})),Je()}ne=!0,g||(x.inflightPromise&&await Promise.race([x.inflightPromise,Ai(5e3)]),x.abortController?.abort(),x.abortController=null,await Jt(),Ge(),ie?.(),Ie.delete(se),b.done())})(),b}function Jl(e){let t=async(n,r,i,a,o,s)=>{let c=s??await h(n,r,i,a,o);if(c.behavior===`allow`||c.behavior===`deny`)return c;let{signal:l,cleanup:u}=$n(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,g=e.mapToolResultToToolResultBlockParam(m.data,`1`);if(!g.content||!Array.isArray(g.content)||!g.content[0]||g.content[0].type!==`text`||typeof g.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 $c(Qc().parse(oi(g.content[0].text)),e,r,i)};return t}function Yl(e,t,n,r){if(e===`stdio`)return t.createCanUseTool(r);if(!e)return async(e,t,n,r,i,a)=>a??await h(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`),E(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`),E(1),Error(t)}i=Jl(r)}return i(t,r,a,o,s,c)}}async function Xl(e,t,n,r,i,a,o,s,c,l,u){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=Dt(e.agents,`flagSettings`);l.push(...t)}if(c.agent){let e=gr()===c.agent,t=l.find(e=>e.agentType===c.agent);if(t&&!e){if(pr(t.agentType),!c.systemPrompt&&!wn(t)){let e=t.getSystemPrompt();e&&(c.systemPrompt=e)}!c.userSpecifiedModel&&t.model&&t.model!==`inherit`&&fr(li(t.model)),t.initialPrompt&&o.prependUserMessage(t.initialPrompt)}else t?.initialPrompt&&o.prependUserMessage(t.initialPrompt)}let d=Vr()?.outputStyle||`default`,f=await An(Sr()),m=_i();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}});lr(t)}e.jsonSchema&&br(e.jsonSchema);let h={commands:i.filter(e=>e.userInvocable!==!1).map(e=>({name:nr(e),description:p(e),argumentHint:e.argumentHint||``})),agents:l.map(e=>({name:e.agentType,description:e.whenToUse,model:e.model===`inherit`?void 0:e.model})),output_style:d,available_output_styles:Object.keys(f),models:a,account:{email:m?.email,organization:m?.organization,subscriptionType:m?.subscription,tokenSource:m?.tokenSource,apiKeySource:m?.apiKeySource,apiProvider:bi()},pid:process.pid};if(Di()&&Oi()){let e=u();h.fast_mode_state=pi(c.userSpecifiedModel??null,e.fastMode)}if(r.enqueue({type:`control_response`,response:{subtype:`success`,request_id:t,response:h}}),s){let e=yi.getInstance().getStatus();e&&r.enqueue({type:`auth_status`,isAuthenticating:e.isAuthenticating,output:e.output,error:e.error,uuid:Y(),session_id:U()})}}async function Zl(e,t,n,r){if(!nn())return{canRewind:!1,error:`File rewinding is not enabled.`,filesChanged:[]};if(!hn(t.fileHistory,e))return{canRewind:!1,error:`No file checkpoint found for this message.`,filesChanged:[]};if(r){let n=await Rt(t.fileHistory,e);return{canRewind:!0,filesChanged:n?.filesChanged??[],insertions:n?.insertions,deletions:n?.deletions}}try{await Zn(e=>n(t=>({...t,fileHistory:e(t.fileHistory)})),e)}catch(e){return{canRewind:!1,error:`Failed to rewind: ${W(e)}`,filesChanged:[]}}return{canRewind:!0,filesChanged:[]}}function Ql(e,t,n,r){if(e.mode===`bypassPermissions`){if(Bn())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`&&!ne()){let e=Xn();return r.enqueue({type:`control_response`,response:{subtype:`error`,request_id:t,error:e?`Cannot set permission mode to auto: ${In(e)}`:`Cannot set permission mode to auto`}}),n}return r.enqueue({type:`control_response`,response:{subtype:`success`,request_id:t,response:{mode:e.mode}}}),{...f(n.mode,e.mode,n),mode:e.mode}}function $l(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:Yi,modelUsage:{},permission_denials:[],uuid:Y(),errors:[e]};process.stdout.write(`${Cr(t)}\n`)}else process.stderr.write(`${e}\n`)}function eu(e,t){let n=e.findIndex(e=>e.uuid===t.uuid);n!==-1&&e.splice(n,2)}async function tu(e,t){let r=!ur();if(t.continue)try{J(`tengu_continue_print`,{});let n=await O(void 0,void 0);if(n)return t.forkSession||n.sessionId&&(vr(ce(n.sessionId),n.fullPath?Ja(n.fullPath):null),r&&await kn()),Ha(n,e),sn(t.forkSession?{...n,worktreeSession:void 0}:n),{messages:n.messages,turnInterruptionState:n.turnInterruptionState,agentSetting:n.agentSetting}}catch(e){return q(e),E(1),{messages:[]}}if(t.teleport)try{if(!st(`allow_remote_sessions`))throw Error(`Remote sessions are disabled by your organization's policy.`);if(J(`tengu_teleport_print`,{}),typeof t.teleport!=`string`)throw Error(`No session ID provided for teleport`);let{checkOutTeleportedSessionBranch:e,processMessagesForTeleportResume:n,teleportResumeCodeSession:r,validateGitState:i}=await import(`./teleport-IzyDplC7.js`);await i();let a=await r(t.teleport),{branchError:o}=await e(a.branch);return{messages:n(a.log,o)}}catch(e){return q(e),E(1),{messages:[]}}if(t.resume)try{J(`tengu_resume_print`,{});let i=Ml(typeof t.resume==`string`?t.resume:``);if(!i){let e=`Error: --resume requires a valid session ID when used with --print. Usage: claude -p --resume <session-id>`;return typeof t.resume==`string`&&(e+=`. Session IDs must be in UUID format (e.g., 550e8400-e29b-41d4-a716-446655440000). Provided value "${t.resume}" is not a valid UUID`),$l(e,t.outputFormat),E(1),{messages:[]}}if(n(process.env.CLAUDE_CODE_USE_CCR_V2)){let[,n]=await Promise.all([zn(i.sessionId),t.restoredWorkerState]);n&&(e(ja(n)),typeof n.model==`string`&&fr(n.model))}else i.isUrl&&i.ingressUrl&&n(process.env.ENABLE_SESSION_PERSISTENCE)&&await er(i.sessionId,i.ingressUrl);let a=await O(i.sessionId,i.jsonlFile||void 0);if(!a||a.messages.length===0)return i.isUrl||n(process.env.CLAUDE_CODE_USE_CCR_V2)?{messages:await(t.sessionStartHooksPromise??Lt(`startup`))}:($l(`No conversation found with session ID: ${i.sessionId}`,t.outputFormat),E(1),{messages:[]});if(t.resumeSessionAt){let e=a.messages.findIndex(e=>e.uuid===t.resumeSessionAt);if(e<0)return $l(`No message found with message.uuid of: ${t.resumeSessionAt}`,t.outputFormat),E(1),{messages:[]};a.messages=e>=0?a.messages.slice(0,e+1):[]}return!t.forkSession&&a.sessionId&&(vr(ce(a.sessionId),a.fullPath?Ja(a.fullPath):null),r&&await kn()),Ha(a,e),sn(t.forkSession?{...a,worktreeSession:void 0}:a),{messages:a.messages,turnInterruptionState:a.turnInterruptionState,agentSetting:a.agentSetting}}catch(e){return q(e),$l(e instanceof Error?`Failed to resume session: ${e.message}`:`Failed to resume session with --print mode`,t.outputFormat),E(1),{messages:[]}}return{messages:await(t.sessionStartHooksPromise??Lt(`startup`))}}function nu(e,t){let n;return n=typeof e==`string`?e.trim()===``?ke([]):ke([Cr({type:`user`,content:e,uuid:``,session_id:``,message:{role:`user`,content:e},parent_tool_use_id:null})]):e,t.sdkUrl?new dl(t.sdkUrl,n,t.replayUserMessages):new sl(n,t.replayUserMessages)}async function ru({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(G(`handleOrphanedPermissionResponse: received orphaned control_response for toolUseID=${t} request_id=${i.request_id}`),r.has(t))return G(`handleOrphanedPermissionResponse: skipping duplicate orphaned permission for toolUseID=${t} (already handled)`),!1;let a=await je(t);return a?(r.add(t),G(`handleOrphanedPermissionResponse: enqueuing orphaned permission for toolUseID=${t} messageID=${a.message.id}`),Xe({mode:`orphaned-permission`,value:[],orphanedPermission:{permissionResult:e,assistantMessage:a}}),n?.(),!0):(G(`handleOrphanedPermissionResponse: no unresolved tool_use found for toolUseID=${t} (already resolved in transcript)`),!1)}return!1}function iu(e){return{...e,scope:`dynamic`}}async function au(e,t,n,r){let{allowed:i,blocked:a}=m(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},h=[...t.clients],g=[...t.tools];for(let e of l)if(!u.has(e)){let t=h.find(t=>t.name===e);t&&t.type===`connected`&&await t.cleanup(),h=h.filter(t=>t.name!==e);let n=`mcp__${e}__`;g=g.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`}};h=[...h,n],d.push(e)}let ee=await ou(c,n,r);return{response:{added:[...d,...ee.response.added],removed:[...f,...ee.response.removed],errors:{...o,...ee.response.errors}},newSdkState:{configs:p,clients:h,tools:g},newDynamicState:ee.newState,sdkServersChanged:d.length>0||f.length>0}}async function ou(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||!Le(r,iu(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){q(e)}await Vn(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=iu(n);if(n.type===`sdk`){l.push(t);continue}try{let e=await ze(t,r);if(d.push(e),e.type===`connected`){let t=await De(e);f.push(...t)}else e.type===`failed`&&(u[t]=e.error||`Connection failed`);l.push(t)}catch(e){let n=Dr(e);u[t]=n.message,q(n)}}let p={};for(let t of i){let n=e[t];n&&(p[t]=iu(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{Kl as runHeadless};
@@ -1 +0,0 @@
1
- import{i as e,r as t}from"./prompt-Bm2EEG4F.js";t();export{e as isDeferredTool};
@@ -1 +0,0 @@
1
- import{cw as e,mw as t}from"./loadAgentsDir-CwEfQDOw.js";t();export{e as clearPromptCache};
@@ -1 +0,0 @@
1
- import{aT as e,cT as t}from"./loadAgentsDir-CwEfQDOw.js";t();export{e as SandboxManager};
@@ -1 +0,0 @@
1
- import{F_ as e,N_ as t}from"./loadAgentsDir-CwEfQDOw.js";t();export{e as isSearchExtraToolsEnabled};
@@ -1 +0,0 @@
1
- import{nh as e,rh as t}from"./loadAgentsDir-CwEfQDOw.js";e();export{t as registerSessionFileAccessHooks};
@@ -1 +0,0 @@
1
- import{n as e,r as t}from"./sessionObserver-iAgSetlC.js";t();export{e as heuristicObserverBackend};
@@ -1 +0,0 @@
1
- import{Dr as e,Xr as t,br as n}from"./loadAgentsDir-CwEfQDOw.js";n();export{e as linkSessionToPR,t as recordTranscript};
@@ -1,3 +0,0 @@
1
- import{n as e,t}from"./memoize-BK3gG5ob.js";import{l as n,o as r,s as i}from"./envUtils-DcaKZlRU.js";import{$S as a,At as o,Dm as s,Dv as c,Em as l,Ev as u,FC as d,Fa as f,HC as p,Ig as ee,Ky as m,La as h,Lg as g,Li as te,Mi as ne,Mm as re,Mn as ie,Nm as ae,Nn as oe,PC as _,RC as se,Sa as ce,St as le,UC as ue,VC as de,Vy as fe,Y_ as pe,_v as me,ac as he,br as ge,by as v,cm as y,cv as b,dc as x,di as S,dv as C,eC as w,eE as T,fv as E,gt as D,gv as O,hn as k,ht as A,hv as j,jm as M,jn as N,kv as P,lc as F,lm as I,lv as L,mn as _e,mv as ve,nE as ye,oc as be,ot as xe,pv as Se,sv as R,uv as Ce,vt as z,vv as we,yv as Te,zC as Ee}from"./loadAgentsDir-CwEfQDOw.js";import{di as B,fi as De}from"./src-DL3w8VPk2.js";import{B as Oe,Bn as ke,Hn as Ae,Wt as V,it as je,or as Me,pt as Ne,z as H}from"./state-BPFYBqm1.js";import{n as Pe,t as U}from"./cwd-Besi3Os3.js";import{F as Fe,P as Ie,R as W,f as G,u as Le}from"./debug-BQj6h99Q.js";import{Kt as Re,Ln as ze,Rn as Be,Yt as Ve}from"./settings-CvhsRFaT.js";import{h as He,o as Ue}from"./config-BSkuQZNf.js";import{O as We,k as K,l as Ge,m as Ke,n as qe,r as Je}from"./git-DplvjXEY.js";import{o as Ye,s as Xe}from"./log-BlJ7CcKG.js";import{n as q,r as J}from"./analytics-DJobLaWP.js";import{n as Ze,r as Y}from"./startupProfiler-2sjXZkIP.js";import{$r as Qe,Bt as $e,ei as et,rn as tt}from"./model-CeG-iOKF.js";import{dn as X,mn as nt}from"./prompt-Bm2EEG4F.js";import{h as rt,l as it,p as at,u as ot}from"./terminalSetup-JJiXmszo.js";import{ft as st,ut as Z}from"./esm-DtcV71xh.js";import{c as ct,t as lt}from"./nativeInstaller-CXFD8LDV.js";import{l as ut,s as dt}from"./logoV2Utils-DG9GwFjl.js";import{i as ft,r as pt}from"./runtimeObserver-Dt5sGJVb.js";import{t as mt}from"./sinks-Bje3hCkR.js";import{writeFile as Q}from"fs/promises";r(),De(),Pe(),We(),Ye(),Ke(),Ve(),He(),$e(),ye(),p(),se(),_(),g(),te(),ge(),k(),t(),V(),xe(),pe(),nt(),w(),Be(),F(),G(),y(),h(),oe(),Qe(),v(),c(),q(),l(),re(),E(),W();function ht(){return!1}function gt(){return{}}var $;function _t(e,t){let n=0,r=t==null;for(let i of e){if(!r){i.uuid===t&&(r=!0);continue}if(i.type===`assistant`){let e=i.message.content;Array.isArray(e)&&(n+=ze(e,e=>e.type===`tool_use`))}}return n}function vt(e){let t=P(e);if(!Se()){if(!Ce(t))return!1;O()}let n=C(t),r=_t(e,$)>=L(),i=f(e);if(n&&r||n&&!i){let t=e[e.length-1];return t?.uuid&&($=t.uuid),!0}return!1}async function yt(e){let t=Le(),n=N();await t.mkdir(n,{mode:448});let r=ie();try{await Q(r,``,{encoding:`utf-8`,mode:384,flag:`wx`}),await Q(r,await ae(),{encoding:`utf-8`,mode:384})}catch(e){if(Fe(e)!==`EEXIST`)throw e}e.readFileState.delete(r);let i=await a.call({file_path:r},e),o=``,s=i.data;return s.type===`text`&&(o=s.file.content),J(`tengu_session_memory_file_read`,{content_length:o.length}),{memoryPath:r,currentMemory:o}}var bt=e(()=>{let e=gt();Te({minimumMessageTokensToInit:e.minimumMessageTokensToInit&&e.minimumMessageTokensToInit>0?e.minimumMessageTokensToInit:R.minimumMessageTokensToInit,minimumTokensBetweenUpdate:e.minimumTokensBetweenUpdate&&e.minimumTokensBetweenUpdate>0?e.minimumTokensBetweenUpdate:R.minimumTokensBetweenUpdate,toolCallsBetweenUpdates:e.toolCallsBetweenUpdates&&e.toolCallsBetweenUpdates>0?e.toolCallsBetweenUpdates:R.toolCallsBetweenUpdates})}),xt=et(async e=>{let{messages:t,toolUseContext:n,querySource:r}=e;if(r!==`repl_main_thread`||!ht()||(bt(),!vt(t)))return;j();let i=be(n),{memoryPath:a,currentMemory:o}=await yt(i);await x({promptMessages:[ce({content:await M(o,a)})],cacheSafeParams:he(e),canUseTool:Ct(a),querySource:`session_memory`,forkLabel:`session_memory`,overrides:{readFileState:i.readFileState}});let s=t[t.length-1],c=s?u(s):void 0,l=b();J(`tengu_session_memory_extraction`,{input_tokens:c?.input_tokens,output_tokens:c?.output_tokens,cache_read_input_tokens:c?.cache_read_input_tokens??void 0,cache_creation_input_tokens:c?.cache_creation_input_tokens??void 0,config_min_message_tokens_to_init:l.minimumMessageTokensToInit,config_min_tokens_between_update:l.minimumTokensBetweenUpdate,config_tool_calls_between_updates:l.toolCallsBetweenUpdates}),me(P(t)),wt(t),ve()});function St(){Oe()||s()&&I(xt)}function Ct(e){return async(t,n)=>{if(t.name===`Edit`&&typeof n==`object`&&n&&`file_path`in n){let t=n.file_path;if(typeof t==`string`&&t===e)return{behavior:`allow`,updatedInput:n}}return{behavior:`deny`,message:`only ${X} on ${e} is allowed`,decisionReason:{type:`other`,reason:`only ${X} on ${e} is allowed`}}}}function wt(e){if(!f(e)){let t=e[e.length-1];t?.uuid&&we(t.uuid)}}q(),V(),ft(),ot(),m(),st(),W(),ut(),lt(),at(),Ze(),le();async function Tt(e,t,r,a,s,c,l,u,f){K(`info`,`setup_started`);let p=process.version.match(/^v(\d+)\./)?.[1];if((!p||parseInt(p,10)<18)&&(console.error(B.bold.red(`Error: Work Mate requires Node.js version 18 or higher.`)),process.exit(1)),l&&Me(ee(l)),!H())try{let e=await it();e.status===`restored`?console.log(B.yellow(`Detected an interrupted Terminal.app setup. Your original settings have been restored. You may need to restart Terminal.app for the changes to take effect.`)):e.status===`failed`&&console.error(B.red(`Failed to restore Terminal.app settings. Please manually restore your original settings with: defaults import com.apple.Terminal ${e.backupPath}.`))}catch(e){Xe(e)}d(e);let m=Date.now();if(de(),K(`info`,`setup_hooks_captured`,{duration_ms:Date.now()-m}),Ee(e),a){let t=_e(),n=await Ge();!t&&!n&&(process.stderr.write(B.red(`Error: Can only use --worktree in a git repository, but ${B.bold(e)} is not a git repository. Configure a WorktreeCreate hook in settings.json to use --worktree with other VCS systems.\n`)),process.exit(1));let r=u?`pr-${u}`:s??T(),i;if(n){let e=qe(U());e||(process.stderr.write(B.red(`Error: Could not determine the main git repository root.
2
- `)),process.exit(1)),e!==(Je(U())??U())&&(K(`info`,`worktree_resolved_to_main_repo`),process.chdir(e),d(e)),i=c?z(e,o(r)):void 0}else i=c?z(U(),o(r)):void 0;let a;try{a=await D(Ne(),r,i,u?{prNumber:u}:void 0)}catch(e){process.stderr.write(B.red(`Error creating worktree: ${Ie(e)}\n`)),process.exit(1)}if(J(`tengu_worktree_created`,{tmux_enabled:c}),c&&i){let e=await A(i,a.worktreePath);e.created?console.log(B.green(`Created tmux session: ${B.bold(i)}\nTo attach: ${B.bold(`tmux attach -t ${i}`)}`)):console.error(B.yellow(`Warning: Failed to create tmux session: ${e.error}`))}process.chdir(a.worktreePath),d(a.worktreePath),ke(U()),Ae(U()),S(a),fe(),ue()}K(`info`,`setup_background_jobs_starting`),i()||(St(),pt()),ct(),K(`info`,`setup_background_jobs_launched`),Y(`setup_before_prefetch`),K(`info`,`setup_prefetch_starting`);let h=H()&&n(process.env.CLAUDE_CODE_SYNC_PLUGIN_INSTALL)||i();if(h||ne(je()),import(`./loadPluginHooks-C-Yk5KlI.js`).then(e=>{h||(e.loadPluginHooks(),e.setupPluginHookHotReload())}),i()||import(`./sessionFileAccessHooks-yAPDTrbm.js`).then(e=>e.registerSessionFileAccessHooks()),mt(),J(`tengu_started`,{}),tt(H()),Y(`setup_after_prefetch`),!i()&&rt()&&await dt(),t===`bypassPermissions`||r){if(process.platform!==`win32`&&typeof process.getuid==`function`&&process.getuid()===0&&process.env.IS_SANDBOX!==`1`&&!n(process.env.CLAUDE_CODE_BUBBLEWRAP))if(process.stdin.isTTY){console.error(B.bold.red(`WARNING: Running as root/sudo with bypass permissions mode is dangerous.`)),console.error(B.yellow(`Bypass mode skips ALL permission checks. Combined with root, any command (rm -rf /, chmod, dd) executes without review.`));let e=(await import(`readline`)).createInterface({input:process.stdin,output:process.stdout}),t=await new Promise(t=>{e.question(`
3
- I understand the risks. Continue? [y/N] `,t)});e.close(),t.trim().toLowerCase()!==`y`&&(console.error(`Aborted.`),process.exit(1))}else console.error(`--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons`),process.exit(1);if(process.env.CLAUDE_CODE_ENTRYPOINT!==`local-agent`&&process.env.CLAUDE_CODE_ENTRYPOINT!==`claude-desktop`){let[e,t]=await Promise.all([Z.getIsDocker(),Re.hasInternetAccess()]),n=Z.getIsBubblewrapSandbox(),r=process.env.IS_SANDBOX===`1`;(!(e||n||r)||t)&&(console.error(`--dangerously-skip-permissions can only be used in Docker/sandbox containers with no internet access but got Docker: ${e}, Bubblewrap: ${n}, IS_SANDBOX: ${r}, hasInternet: ${t}`),process.exit(1))}}let g=Ue();g.lastCost!==void 0&&g.lastDuration!==void 0&&J(`tengu_exit`,{last_session_cost:g.lastCost,last_session_api_duration:g.lastAPIDuration,last_session_tool_duration:g.lastToolDuration,last_session_duration:g.lastDuration,last_session_lines_added:g.lastLinesAdded,last_session_lines_removed:g.lastLinesRemoved,last_session_total_input_tokens:g.lastTotalInputTokens,last_session_total_output_tokens:g.lastTotalOutputTokens,last_session_total_cache_creation_input_tokens:g.lastTotalCacheCreationInputTokens,last_session_total_cache_read_input_tokens:g.lastTotalCacheReadInputTokens,last_session_fps_average:g.lastFpsAverage,last_session_fps_low_1_pct:g.lastFpsLow1Pct,last_session_id:g.lastSessionId,...g.lastSessionMetrics})}export{Tt as setup};
@@ -1 +0,0 @@
1
- import{t as e}from"./sinks-Bje3hCkR.js";export{e as initSinks};
@@ -1 +0,0 @@
1
- import{Di as e,Ds as t,Ei as n,FC as r,Ig as i,JT as a,Ky as o,Lg as s,Li as ee,Nt as te,Ny as ne,Os as re,Ot as c,PC as ie,Py as ae,QS as l,Rn as oe,St as se,Th as ce,Vy as u,Wr as le,Xi as ue,Yi as d,ZS as de,Zi as fe,a_ as f,bc as p,bg as m,br as h,ci as pe,di as g,eh as me,fn as he,hc as ge,hn as _e,i_ as _,nE as ve,ni as ye,qT as v,qi as y,tE as b,th as x,ti as S,vg as C,yt as w}from"./loadAgentsDir-CwEfQDOw.js";import{Bn as T,J as E,Mn as D,Nn as O,Wt as k,h as A,lr as j,or as M,pt as N,ur as P}from"./state-BPFYBqm1.js";import{n as be,t as F}from"./cwd-Besi3Os3.js";import{c as I,f as xe,i as L,nt as Se,tt as R,u as Ce}from"./debug-BQj6h99Q.js";import{n as we,r as Te}from"./analytics-DJobLaWP.js";import{C as Ee,_ as De}from"./model-CeG-iOKF.js";import{Gt as Oe}from"./prompt-Bm2EEG4F.js";import*as z from"path";import{dirname as ke}from"path";k(),f(),ne(),Oe(),s(),o(),ce(),ge(),be(),L(),m(),De(),ve(),ie(),h(),de(),x(),se();function Ae(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n?.type!==`assistant`)continue;let r=n.message.content.find(e=>e.type===`tool_use`&&e.name===`TodoWrite`);if(r?.type!==`tool_use`)continue;let i=r.input;if(typeof i!=`object`||!i)return[];let a=me().safeParse(i.todos);return a.success?a.data:[]}return[]}function je(e,t){if(e.fileHistorySnapshots&&e.fileHistorySnapshots.length>0&&C(e.fileHistorySnapshots,e=>{t(t=>({...t,fileHistory:e}))}),!l()&&e.messages&&e.messages.length>0){let n=Ae(e.messages);if(n.length>0){let e=N();t(t=>({...t,todos:{...t.todos,[e]:n}}))}}}function B(e,t){if(!(!e&&!t))return{name:e??``,color:t==="default"?void 0:t}}function V(e,t,n){if(t)return{agentDefinition:t,agentType:void 0};if(!e)return O(void 0),{agentDefinition:void 0,agentType:void 0};let r=n.activeAgents.find(t=>t.agentType===e);return r?(O(r.agentType),!E()&&r.model&&r.model!==`inherit`&&D(Ee(r.model)),{agentDefinition:r,agentType:r.agentType}):(I(`Resumed session had agent "${e}" but it is no longer available. Using default behavior.`),O(void 0),{agentDefinition:void 0,agentType:void 0})}function H(e){let t=w();if(t){g(t);return}if(e){try{process.chdir(e.worktreePath)}catch{g(null);return}r(e.worktreePath),T(F()),c(e),u(),_(),b.cache.clear?.()}}function Me(){let e=w();if(e){c(null),u(),_(),b.cache.clear?.();try{process.chdir(e.originalCwd)}catch{return}r(e.originalCwd),T(F())}}async function Ne(e,t,n){if(t.forkSession)e.contentReplacements?.length&&await le(e.contentReplacements);else{let n=t.sessionIdOverride??e.sessionId;n&&(M(i(n),t.transcriptPath?ke(t.transcriptPath):null),await S(),ae(n))}ye(t.forkSession?{...e,worktreeSession:void 0}:e),t.forkSession||(H(e.worktreeSession),oe());let{agentDefinition:r,agentType:a}=V(e.agentSetting,n.mainThreadAgentDefinition,n.agentDefinitions);pe(`normal`),t.includeAttribution;let o=B(e.agentName,e.agentColor);p(e.agentName);let s=n.agentDefinitions;return{messages:e.messages,fileHistorySnapshots:e.fileHistorySnapshots,contentReplacements:e.contentReplacements,agentName:e.agentName,agentColor:e.agentColor==="default"?void 0:e.agentColor,restoredAgentDef:r,initialState:{...n.initialState,...a&&{agent:a},...o&&{standaloneAgentContext:o},agentDefinitions:s}}}a(),k(),ee(),we(),ue(),t(),R(),L(),xe(),_e(),P();var Pe=1e3,Fe=500,Ie=300,Le=2e3,Re=typeof Bun<`u`,U=null,W=null,G=new Set,K=!1,q=!1,J=!1,Y=null,X=j(),Z=null;async function ze(){if(K||q)return;K=!0,J||(J=!0,fe(()=>{n(),X.emit()}));let e=await Ve();e.length!==0&&(I(`Watching for changes in skill/command directories: ${e.join(`, `)}...`),U=v.watch(e,{persistent:!0,ignoreInitial:!0,depth:2,awaitWriteFinish:{stabilityThreshold:Z?.stabilityThreshold??Pe,pollInterval:Z?.pollInterval??Fe},ignored:(e,t)=>t&&!t.isFile()&&!t.isDirectory()?!0:e.split(z.sep).some(e=>e===`.git`),ignorePermissionErrors:!0,usePolling:Re,interval:Z?.chokidarInterval??Le,atomic:!0}),U.on(`add`,$),U.on(`change`,$),U.on(`unlink`,$),Y=Se(async()=>{await Q()}))}function Q(){q=!0,Y&&(Y(),Y=null);let e=Promise.resolve();return U&&(e=U.close(),U=null),W&&(clearTimeout(W),W=null),G.clear(),X.clear(),e}var Be=X.subscribe;async function Ve(){let e=Ce(),t=[],n=d(`userSettings`,`skills`);if(n)try{await e.stat(n),t.push(n)}catch{}let r=d(`userSettings`,`commands`);if(r)try{await e.stat(r),t.push(r)}catch{}let i=d(`projectSettings`,`skills`);if(i)try{let n=z.resolve(i);await e.stat(n),t.push(n)}catch{}let a=d(`projectSettings`,`commands`);if(a)try{let n=z.resolve(a);await e.stat(n),t.push(n)}catch{}for(let n of A()){let r=z.join(n,`.workmate`,`skills`);try{await e.stat(r),t.push(r)}catch{}}return t}function $(e){I(`Detected skill change: ${e}`),Te(`tengu_skill_file_changed`,{source:`chokidar`}),He(e)}function He(t){G.add(t),W&&clearTimeout(W),W=setTimeout(async()=>{W=null;let t=[...G];if(G.clear(),he(await te(`skills`,t[0]))){I(`ConfigChange hook blocked skill reload (${t.length} paths)`);return}y(),e(),re(),X.emit()},Z?.reloadDebounce??Ie)}async function Ue(e){U&&(await U.close(),U=null),W&&(clearTimeout(W),W=null),G.clear(),X.clear(),K=!1,q=!1,Z=e??null}var We={initialize:ze,dispose:Q,subscribe:Be,resetForTesting:Ue};export{V as a,Ne as i,B as n,je as o,Me as r,H as s,We as t};
@@ -1 +0,0 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{t}from"./jsx-runtime-Bb4Xn-E0.js";import{n,t as r}from"./Settings-D_i8HzEW.js";async function i(e,t){return(0,a.jsx)(r,{onClose:e,context:t,defaultTab:`Status`})}var a;e((()=>{n(),a=t()}))();export{i as call};
@@ -1 +0,0 @@
1
- import{n as e,r as t}from"./switcher-BkGOeIzI.js";e();export{t as restoreActiveProvider};
@@ -1 +0,0 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{Gn as t,Un as n,Wn as r}from"./settings-CvhsRFaT.js";import{u as i}from"./oauth-D38aRTUb.js";import{Bt as a,Ot as o,St as s,ii as c,oi as l,si as u}from"./model-CeG-iOKF.js";function d(){p=void 0,r()}function f(){if(p!==void 0)return p;if(c()!==`firstParty`||!u()||process.env.CLAUDE_CODE_ENTRYPOINT===`local-agent`)return p=t(!1);let e=o();if(e?.accessToken&&e.subscriptionType===null||e?.accessToken&&e.scopes?.includes(`user:inference`)&&(e.subscriptionType===`enterprise`||e.subscriptionType===`team`))return p=t(!0);try{let{key:e}=s({skipRetrievingKeyFromApiKeyHelper:!0});if(e)return p=t(!0)}catch{}return p=t(!1)}var p,m=e((()=>{i(),a(),l(),n()}));export{f as n,d as r,m as t};
@@ -1 +0,0 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{Cx as t,_T as n,vT as r,wx as i}from"./loadAgentsDir-CwEfQDOw.js";import{n as a,t as o}from"./partition-8vZDG3rY.js";function s(e,t,n){let[o,s]=a(r([...e,...t],`name`),i),c=(e,t)=>e.name.localeCompare(t.name);return[...s.sort(c),...o.sort(c)]}var c=e((()=>{o(),n(),t()}));export{s as n,c as t};
@@ -1 +0,0 @@
1
- import{r as e,t}from"./trustedDevice-DWZxDUxS.js";export{t as clearTrustedDeviceToken,e as enrollTrustedDevice};
@@ -1 +0,0 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{Xh as t,Zh as n}from"./loadAgentsDir-CwEfQDOw.js";import{C as r,_ as i,s as a}from"./model-CeG-iOKF.js";function o(){let e=n(e=>e.mainLoopModel);return r(n(e=>e.mainLoopModelForSession)??e??a())}var s=e((()=>{t(),i()}));export{o as n,s as t};
@@ -1 +0,0 @@
1
- import{St as e,_t as t}from"./loadAgentsDir-CwEfQDOw.js";e();export{t as execIntoTmuxWorktree};