@readmagic/workmate 0.0.11 → 0.0.13

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 (428) hide show
  1. package/dist/chunks/{AddWorkspaceDirectory-ag2JTpmU.js → AddWorkspaceDirectory-BzNj9rS6.js} +1 -1
  2. package/dist/chunks/AgentsMdExternalIncludesDialog-CDZPR488.js +1 -0
  3. package/dist/chunks/AgentsMdExternalIncludesDialog-CH9x1Ngp.js +1 -0
  4. package/dist/chunks/App-D-bYAYAl.js +1 -0
  5. package/dist/chunks/ApproveApiKey-BEGV9Zj9.js +1 -0
  6. package/dist/chunks/ApproveApiKey-CjacpIqq.js +1 -0
  7. package/dist/chunks/BackgroundTasksDialog-A9hw_SV0.js +2 -0
  8. package/dist/chunks/{BypassPermissionsModeDialog-B05t83wa.js → BypassPermissionsModeDialog-B0BizN_J.js} +1 -1
  9. package/dist/chunks/{DiffDialog-DUbFrzKu.js → DiffDialog-mQ-5_TSv.js} +2 -2
  10. package/dist/chunks/Doctor-BC6IuQhd.js +3 -0
  11. package/dist/chunks/Doctor-i_5_AQd-.js +1 -0
  12. package/dist/chunks/ExitFlow-Bu2cVGpC.js +2 -0
  13. package/dist/chunks/{Grove-BDoVj02t.js → Grove-D0nn8zOV.js} +2 -2
  14. package/dist/chunks/{HybridTransport-C_U0IJfz.js → HybridTransport-BQNLZNa_.js} +1 -1
  15. package/dist/chunks/InvalidConfigDialog-C5CIiSIE.js +1 -0
  16. package/dist/chunks/{InvalidSettingsDialog-Br8kQOHz.js → InvalidSettingsDialog-Dq7hKXcO.js} +1 -1
  17. package/dist/chunks/MCPConnectionManager-aDDsYkGM.js +1 -0
  18. package/dist/chunks/MCPToolListView-Cr0MDkzT.js +1 -0
  19. package/dist/chunks/{McpParsingWarnings-COa71S9q.js → McpParsingWarnings-CUx2zexI.js} +1 -1
  20. package/dist/chunks/MessageSelector-DwGOWKKL.js +3 -0
  21. package/dist/chunks/Messages-C1jh4ixt.js +11 -0
  22. package/dist/chunks/Onboarding-t-P6Q5O6.js +1 -0
  23. package/dist/chunks/{PromptInputFooterSuggestions-to5eYBvI.js → PromptInputFooterSuggestions-R12fbdmp.js} +1 -1
  24. package/dist/chunks/{PromptInputHelpMenu-CfMFx-TF.js → PromptInputHelpMenu-BgADIzRj.js} +1 -1
  25. package/dist/chunks/QueryEngine-HlLQJmsd.js +1 -0
  26. package/dist/chunks/REPL-Rs_JQkDc.js +1 -0
  27. package/dist/chunks/REPL-VKAmKkII.js +133 -0
  28. package/dist/chunks/RemoteSessionManager-BbgXeM-t.js +2 -0
  29. package/dist/chunks/ResumeConversation-66zbx12g.js +1 -0
  30. package/dist/chunks/{SSETransport-DN4tCDEh.js → SSETransport-BBQkdn4e.js} +1 -1
  31. package/dist/chunks/SearchExtraToolsTool-Bq87I_vu.js +1 -0
  32. package/dist/chunks/Settings-BKdLcyXe.js +2 -0
  33. package/dist/chunks/{TeleportProgress-C2LQVLav.js → TeleportProgress-3hmIApkj.js} +1 -1
  34. package/dist/chunks/{TeleportRepoMismatchDialog-BZL8Zblz.js → TeleportRepoMismatchDialog-BA1a66RK.js} +1 -1
  35. package/dist/chunks/{TeleportResumeWrapper-wPiIs8xg.js → TeleportResumeWrapper-BT4O-Wsi.js} +1 -1
  36. package/dist/chunks/{ThemePicker-BT_NaRQC.js → ThemePicker-DUlhcoso.js} +1 -1
  37. package/dist/chunks/TrustDialog-Dpk03V1Y.js +1 -0
  38. package/dist/chunks/{ValidationErrorsList-C-hWdy_8.js → ValidationErrorsList-DSSUWdgd.js} +1 -1
  39. package/dist/chunks/add-dir-BUr0z-VU.js +1 -0
  40. package/dist/chunks/{agentDisplay-CuSHqgZc.js → agentDisplay-D7bdOOG7.js} +1 -1
  41. package/dist/chunks/{agents-CMC0iQP4.js → agents-22wiC58F.js} +1 -1
  42. package/dist/chunks/agents-8ELI8RJo.js +103 -0
  43. package/dist/chunks/allErrors-C1eMbHSv.js +1 -0
  44. package/dist/chunks/api-DgjIFdMn.js +1 -0
  45. package/dist/chunks/{api-BbJfMXRS.js → api-f3GN2I_J.js} +1 -1
  46. package/dist/chunks/auth-B73a4Cob.js +1 -0
  47. package/dist/chunks/{auth-7mJGtlZp.js → auth-Czy7GoRh.js} +1 -1
  48. package/dist/chunks/auth-D_0waidQ.js +1 -0
  49. package/dist/chunks/backgroundHousekeeping-C_ArdTFX.js +17 -0
  50. package/dist/chunks/backgroundHousekeeping-YJhvZ0dh.js +1 -0
  51. package/dist/chunks/{banner-1Wyeyawe.js → banner-BcAM7iSx.js} +1 -1
  52. package/dist/chunks/bg-Ci7pG4eo.js +9 -0
  53. package/dist/chunks/branch-bb4-bErF.js +3 -0
  54. package/dist/chunks/{break-cache-CAoZ9b72.js → break-cache-4rlQORVk.js} +2 -2
  55. package/dist/chunks/{bridgeConfig-UgaUfuP6.js → bridgeConfig-B80T_lw7.js} +1 -1
  56. package/dist/chunks/bridgeConfig-DywkIo_k.js +1 -0
  57. package/dist/chunks/{bridgeMessaging-Ci5H68MX.js → bridgeMessaging-DyvHd16Z.js} +1 -1
  58. package/dist/chunks/{bridgePointer-BL8-lGvN.js → bridgePointer-DHWK3LEe.js} +1 -1
  59. package/dist/chunks/{bridgeStatusUtil-C36w15ge.js → bridgeStatusUtil-DStiD05t.js} +1 -1
  60. package/dist/chunks/btw-BRmV51bR.js +1 -0
  61. package/dist/chunks/caches-C5DIVdvI.js +1 -0
  62. package/dist/chunks/caches-zDZEgNKq.js +1 -0
  63. package/dist/chunks/{capacityWake-BOySRJUJ.js → capacityWake-ByL6fM6I.js} +1 -1
  64. package/dist/chunks/{ccrClient-Br4LAofR.js → ccrClient-BALhzhPF.js} +1 -1
  65. package/dist/chunks/{claudeDesktop-Bgds1-YT.js → claudeDesktop-Ct_hyICL.js} +1 -1
  66. package/dist/chunks/{clear-C4Vtnbye.js → clear-B_yVyJXP.js} +1 -1
  67. package/dist/chunks/cliLaunch-OPOtzhvA.js +1 -0
  68. package/dist/chunks/client-7lIxWcaM.js +1 -0
  69. package/dist/chunks/{client-B9404qIP.js → client-BMA05FW8.js} +1 -1
  70. package/dist/chunks/client-DVg8PpFX.js +1 -0
  71. package/dist/chunks/commands-ByFXqW43.js +1 -0
  72. package/dist/chunks/compact-BUShp2eQ.js +2 -0
  73. package/dist/chunks/config-9rLTDOYW.js +3 -0
  74. package/dist/chunks/config-BwHNU_pI.js +1 -0
  75. package/dist/chunks/{config-kB2eazPX.js → config-DMKtiMzJ.js} +1 -1
  76. package/dist/chunks/{context-BN7DEjoH.js → context-6Pk3iVhh.js} +1 -1
  77. package/dist/chunks/{context-noninteractive-D91W2B8e.js → context-noninteractive-CHzerxnH.js} +2 -2
  78. package/dist/chunks/context-noninteractive-DFwRQyFE.js +1 -0
  79. package/dist/chunks/conversation-5zb5XkSA.js +1 -0
  80. package/dist/chunks/conversation-JP2ZXrwu.js +1 -0
  81. package/dist/chunks/createSSHSession-XkHMiGRN.js +6 -0
  82. package/dist/chunks/{createSession-DRqkLZWt.js → createSession-BNGm9fL4.js} +1 -1
  83. package/dist/chunks/createSession-VTqzWAu6.js +1 -0
  84. package/dist/chunks/crossProjectResume-DxgQVYSi.js +40 -0
  85. package/dist/chunks/{cwd-Cfdf7z7s.js → cwd-Besi3Os3.js} +1 -1
  86. package/dist/chunks/cwd-DpqwaYHw.js +1 -0
  87. package/dist/chunks/datadog-3WUWcCFn.js +1 -0
  88. package/dist/chunks/{debug-BecbSVoN.js → debug-Dr1SjdXn.js} +2 -2
  89. package/dist/chunks/{debugUtils-CmJfIUxW.js → debugUtils-cK-iOsEV.js} +1 -1
  90. package/dist/chunks/detached-CqfQYVOi.js +5 -0
  91. package/dist/chunks/detectRepository-BsKZDRoI.js +1 -0
  92. package/dist/chunks/{detectRepository-C15umvKN.js → detectRepository-CMEkS5_2.js} +1 -1
  93. package/dist/chunks/{diff-DeK4bwjw.js → diff-CKlLimGq.js} +1 -1
  94. package/dist/chunks/{directoryCompletion-BJCu19HJ.js → directoryCompletion-ByBTSuLu.js} +1 -1
  95. package/dist/chunks/doctor-Bvx0u0sO.js +1 -0
  96. package/dist/chunks/{entry-mdegyj8z.js → entry-DCbq734V.js} +4 -4
  97. package/dist/chunks/{envUtils-BDhHQY0-.js → envUtils-DcaKZlRU.js} +1 -1
  98. package/dist/chunks/{esm-Ka3lhafK.js → esm-CtQkOk5D.js} +1 -1
  99. package/dist/chunks/{execFileNoThrow-DHyW8FMX.js → execFileNoThrow-mXq4K0rl.js} +1 -1
  100. package/dist/chunks/{execSyncWrapper-CDzB0BM1.js → execSyncWrapper-Ne33rRiD.js} +1 -1
  101. package/dist/chunks/exit-DTsz5Lcb.js +1 -0
  102. package/dist/chunks/{extraUsage-BrKbpBK-.js → extraUsage-C86bZVgt.js} +1 -1
  103. package/dist/chunks/extractMemories-6OnMgL2S.js +1 -0
  104. package/dist/chunks/fast-B2ziqJEA.js +1 -0
  105. package/dist/chunks/{fast-DWn40OcQ.js → fast-BkhjaTkZ.js} +1 -1
  106. package/dist/chunks/{fileSuggestions-C7Pwq2yj.js → fileSuggestions-BalHmi1-.js} +2 -2
  107. package/dist/chunks/{firstPartyEventLogger-BHjBQH0J.js → firstPartyEventLogger-1RTgXHSz.js} +2 -2
  108. package/dist/chunks/firstPartyEventLogger-CXMzhLrF.js +1 -0
  109. package/dist/chunks/{flushGate-DdJjxCes.js → flushGate-DWL05x7v.js} +1 -1
  110. package/dist/chunks/{gemini-DHv2iVfy.js → gemini-BLpLJyli.js} +1 -1
  111. package/dist/chunks/generateSessionName-CdbMksHi.js +1 -0
  112. package/dist/chunks/{genericProcessUtils-B2HcDYhg.js → genericProcessUtils-Dc1pfb7J.js} +1 -1
  113. package/dist/chunks/git-Bs1vtuvX.js +1 -0
  114. package/dist/chunks/{git-DBlOv64X.js → git-CoQQ6YEf.js} +1 -1
  115. package/dist/chunks/{githubRepoPathMapping-CK56bUDe.js → githubRepoPathMapping-CmpEaQoo.js} +1 -1
  116. package/dist/chunks/{goal-BZG4gtnb.js → goal-V3qix-i1.js} +3 -3
  117. package/dist/chunks/grok-BLLATotv.js +1 -0
  118. package/dist/chunks/{grove-_zlQ83yR.js → grove-b9gGKgu4.js} +1 -1
  119. package/dist/chunks/{help-C_2tdXHC.js → help-BR7UEr5R.js} +1 -1
  120. package/dist/chunks/{hooks-C7Bn7MBe.js → hooks-C-QMGvCg.js} +3 -3
  121. package/dist/chunks/hooks-D6wtd0Qq.js +1 -0
  122. package/dist/chunks/{initReplBridge-NkZRcM77.js → initReplBridge-DyScxedy.js} +1 -1
  123. package/dist/chunks/{install-Du-DSVzj.js → install-DGH_bjUh.js} +1 -1
  124. package/dist/chunks/{instrumentation-DMs3b82f.js → instrumentation-DQ705pC7.js} +4 -4
  125. package/dist/chunks/{job-rbX1VZmp.js → job-BaMT6Lb2.js} +1 -1
  126. package/dist/chunks/{jwtUtils-OzxN2zts.js → jwtUtils-FQWtM6iM.js} +1 -1
  127. package/dist/chunks/keybindings-CG292HS1.js +2 -0
  128. package/dist/chunks/{launchLocalMemory-BLRCK1_o.js → launchLocalMemory-CtZrkmaw.js} +2 -2
  129. package/dist/chunks/{launchOnboarding-Al_X75Vz.js → launchOnboarding-CyOtdZkT.js} +1 -1
  130. package/dist/chunks/loadAgentsDir-4UC4yLg1.js +1 -0
  131. package/dist/chunks/{loadAgentsDir-BL93ulMm.js → loadAgentsDir-mcRW90aq.js} +596 -604
  132. package/dist/chunks/loadPluginHooks-CWI0RMUx.js +1 -0
  133. package/dist/chunks/{localSearch-C5ipegd9.js → localSearch-CCCDKpYx.js} +1 -1
  134. package/dist/chunks/localSearch-D4hVR7-d.js +1 -0
  135. package/dist/chunks/{log-Dauqle-Z.js → log-27kCA_9u.js} +1 -1
  136. package/dist/chunks/{logoV2Utils-CkvOihX7.js → logoV2Utils--8OUQQPd.js} +1 -1
  137. package/dist/chunks/{magicDocs-DLav5QK0.js → magicDocs-26J_l1De.js} +3 -3
  138. package/dist/chunks/main-CGLCy2pM.js +31 -0
  139. package/dist/chunks/main-DUjtDK1Q.js +513 -0
  140. package/dist/chunks/managedEnv-BuCurT_S.js +1 -0
  141. package/dist/chunks/{managedEnv-DJSCuqCb.js → managedEnv-Ds6MlFQE.js} +1 -1
  142. package/dist/chunks/{mappers-DQxMcezy.js → mappers-DwZw084m.js} +1 -1
  143. package/dist/chunks/mcp-CEKR7PjL.js +6 -0
  144. package/dist/chunks/mcp-DCAf2hHD.js +1 -0
  145. package/dist/chunks/mcp-mCuc8dNe.js +2 -0
  146. package/dist/chunks/{memoize-FeyE7JEh.js → memoize-Co4vS6UF.js} +1 -1
  147. package/dist/chunks/memory-B5SkpC7u.js +1 -0
  148. package/dist/chunks/{mode-Bl2RZC8M.js → mode-B80CHkqo.js} +1 -1
  149. package/dist/chunks/model-BqaneI4D.js +1 -0
  150. package/dist/chunks/model-C29_32BD.js +1 -0
  151. package/dist/chunks/model-NG8fvuT2.js +1 -0
  152. package/dist/chunks/{modelOptions-BtEZe5BB.js → modelOptions-CiZgZxZC.js} +1 -1
  153. package/dist/chunks/{nativeInstaller-BEwayifa.js → nativeInstaller-DqbEfGSX.js} +1 -1
  154. package/dist/chunks/oauth-D38aRTUb.js +1 -0
  155. package/dist/chunks/oauth-U649LV5H.js +1 -0
  156. package/dist/chunks/{observationStore-BpjlK0pG.js → observationStore-D0rm3GhP.js} +1 -1
  157. package/dist/chunks/{omit--yH_T4rf.js → omit-KEhe84f4.js} +1 -1
  158. package/dist/chunks/{onChangeAppState-ZdwI7boX.js → onChangeAppState-Dq1tIEJI.js} +1 -1
  159. package/dist/chunks/openai-BvnsYTpQ.js +10 -0
  160. package/dist/chunks/{panel-CoNfXy3K.js → panel-CoF2a-h4.js} +1 -1
  161. package/dist/chunks/parser-B2PlJg4C.js +1 -0
  162. package/dist/chunks/{parser-BH4u7QiV.js → parser-CUUiH40T.js} +1 -1
  163. package/dist/chunks/partition-DeT341qu.js +1 -0
  164. package/dist/chunks/permissions-BPpeHxpk.js +3 -0
  165. package/dist/chunks/pidLock-DQGDoFQP.js +3 -0
  166. package/dist/chunks/{plan-BNYDTnQd.js → plan-BRiC5ujG.js} +1 -1
  167. package/dist/chunks/{platform-B0uTQc9P.js → platform-Dg1c9F_1.js} +1 -1
  168. package/dist/chunks/plugin-Dcg_GGR9.js +17 -0
  169. package/dist/chunks/pluginAutoupdate-ByH9IPC9.js +1 -0
  170. package/dist/chunks/pluginBlocklist-BfoLN9a-.js +1 -0
  171. package/dist/chunks/pluginCliCommands-Bc2Iybhz.js +1 -0
  172. package/dist/chunks/{pluginFlagging-DcJ_FQuv.js → pluginFlagging-Cr0d0hBA.js} +1 -1
  173. package/dist/chunks/pluginOperations-CKNyYjS-.js +2 -0
  174. package/dist/chunks/pluginStartupCheck-B48_cGgo.js +1 -0
  175. package/dist/chunks/{pluginStartupCheck-CKBFaMFr.js → pluginStartupCheck-DiCDQQlr.js} +1 -1
  176. package/dist/chunks/plugins-BP_36tOl.js +4 -0
  177. package/dist/chunks/poorMode-Djw0P9Gu.js +1 -0
  178. package/dist/chunks/{poorMode-B_xEvuEV.js → poorMode-DxgO_bUb.js} +1 -1
  179. package/dist/chunks/print-2uavraPq.js +26 -0
  180. package/dist/chunks/processBashCommand-g3sAMpHt.js +1 -0
  181. package/dist/chunks/processSlashCommand-tIbeCrv5.js +5 -0
  182. package/dist/chunks/{projectContext-CIxul6vA.js → projectContext-BN2ZWzOG.js} +1 -1
  183. package/dist/chunks/{projectContext-RUMJB798.js → projectContext-Bw3o5BrN.js} +1 -1
  184. package/dist/chunks/{prompt-Dx7IWhBt.js → prompt-DIlq8NTy.js} +4 -4
  185. package/dist/chunks/prompt-DLv-Cd67.js +1 -0
  186. package/dist/chunks/prompt-DV5tCLRh.js +1 -0
  187. package/dist/chunks/{promptEditor-WCkmpejM.js → promptEditor-BILqOGl1.js} +2 -2
  188. package/dist/chunks/{protocolHandler-BiVWrpHi.js → protocolHandler-B83fCYI4.js} +1 -1
  189. package/dist/chunks/{proxy-CVn7o19p.js → proxy-BEKNaTXI.js} +1 -1
  190. package/dist/chunks/rcDebugLog-DSchf3Hs.js +1 -0
  191. package/dist/chunks/reconciler-CDq6XgAS.js +1 -0
  192. package/dist/chunks/refresh-ysrhoWCo.js +1 -0
  193. package/dist/chunks/{registerProtocol-E0Iu5hEx.js → registerProtocol-DduKPsn_.js} +1 -1
  194. package/dist/chunks/{reload-plugins-D-3AUT9g.js → reload-plugins-CGb0HTsH.js} +1 -1
  195. package/dist/chunks/{remoteBridgeCore-CV6we3ZA.js → remoteBridgeCore-BmteXmI9.js} +1 -1
  196. package/dist/chunks/{remoteManagedSettings-D26Q09-7.js → remoteManagedSettings-CwDGxL5p.js} +1 -1
  197. package/dist/chunks/rename-1GLIUlYk.js +1 -0
  198. package/dist/chunks/{renderOptions-DDLbSMQU.js → renderOptions-45A-EdsK.js} +1 -1
  199. package/dist/chunks/resume-DWtlUiHW.js +2 -0
  200. package/dist/chunks/ripgrep-BLQnqPnE.js +1 -0
  201. package/dist/chunks/{ripgrep-C1ydIMzT.js → ripgrep-DQ_ILUJV.js} +1 -1
  202. package/dist/chunks/{runtimeObserver-L7pSIWBT.js → runtimeObserver-4ZqaCXYy.js} +4 -4
  203. package/dist/chunks/{runtimeObserver-OU8KrZQG.js → runtimeObserver-CtNY8Al2.js} +1 -1
  204. package/dist/chunks/sandbox-adapter-BzjRQh_r.js +1 -0
  205. package/dist/chunks/sandbox-toggle-Bz49-F6e.js +1 -0
  206. package/dist/chunks/searchExtraTools-D6vj8qJ-.js +1 -0
  207. package/dist/chunks/{session-DUYsfPy_.js → session-wb6X4Wrq.js} +2 -2
  208. package/dist/chunks/sessionFileAccessHooks-Da97UA2n.js +1 -0
  209. package/dist/chunks/{sessionObserver-Dv3Ba8eA.js → sessionObserver-BJQ5hwjU.js} +2 -2
  210. package/dist/chunks/sessionObserver-DXO4trhk.js +1 -0
  211. package/dist/chunks/{sessionState-D-SaBzWD.js → sessionState-Bn3ESS5f.js} +1 -1
  212. package/dist/chunks/sessionStorage-DlPVsQn9.js +1 -0
  213. package/dist/chunks/{sessionStoragePortable-JZnGwqUM.js → sessionStoragePortable-BhkGMZWp.js} +1 -1
  214. package/dist/chunks/sessionTitle-Cbzrb9jT.js +14 -0
  215. package/dist/chunks/{sessionTracing-Bqb3vJTt.js → sessionTracing-CEsm8pZL.js} +1 -1
  216. package/dist/chunks/settings-3ionQKNv.js +1 -0
  217. package/dist/chunks/settings-DiBMs2gM.js +20 -0
  218. package/dist/chunks/settingsSync-eHaSngKo.js +1 -0
  219. package/dist/chunks/setup-DeyiuGNX.js +3 -0
  220. package/dist/chunks/{shadowedRuleDetection-BzAZ57p2.js → shadowedRuleDetection-D5X5fhzj.js} +1 -1
  221. package/dist/chunks/{shellQuote-DS6WrivY.js → shellQuote-C_I6DHLV.js} +1 -1
  222. package/dist/chunks/{sideQuestion-CvMBBjI8.js → sideQuestion-BHRtwhyj.js} +3 -3
  223. package/dist/chunks/{sinks-f7qYjbKJ.js → sinks-Bgy2UNK-.js} +2 -2
  224. package/dist/chunks/sinks-CgzLmim2.js +1 -0
  225. package/dist/chunks/skillChangeDetector-BlSP16j6.js +1 -0
  226. package/dist/chunks/{skillGapStore-CqaT8c0C.js → skillGapStore-BjQSSz2E.js} +2 -2
  227. package/dist/chunks/{skillLifecycle-CnR8IqJM.js → skillLifecycle-Sp8strFv.js} +2 -2
  228. package/dist/chunks/{skillSearchPanel-D9qrOXpI.js → skillSearchPanel-3sYRez_Q.js} +5 -5
  229. package/dist/chunks/skills-CJhWI8t1.js +1 -0
  230. package/dist/chunks/startupProfiler-CUlV07MD.js +1 -0
  231. package/dist/chunks/{startupProfiler-CmH_aVy2.js → startupProfiler-Dc5r6LgE.js} +2 -2
  232. package/dist/chunks/{state-BemZdQIl.js → state-BPFYBqm1.js} +1 -1
  233. package/dist/chunks/state-CsdHk8n-.js +1 -0
  234. package/dist/chunks/{stats-B8uQ-UDi.js → stats-BkadEKa-.js} +1 -1
  235. package/dist/chunks/status-CDCurOqs.js +2 -0
  236. package/dist/chunks/{status-BekdWoIj.js → status-yoQIQ2Ni.js} +1 -1
  237. package/dist/chunks/statusNoticeHelpers-Sl4jjauz.js +1 -0
  238. package/dist/chunks/{stringUtils-C8PaYpQF.js → stringUtils-Df-Lnjxd.js} +1 -1
  239. package/dist/chunks/{subprocessEnv-Ci8VV_bi.js → subprocessEnv-CNBOhlDV.js} +1 -1
  240. package/dist/chunks/subprocessEnv-DtBCqQIo.js +1 -0
  241. package/dist/chunks/switcher-C-m6MUwE.js +1 -0
  242. package/dist/chunks/switcher-uoQMHmEZ.js +1 -0
  243. package/dist/chunks/{syncCache-ClP9aBqK.js → syncCache-BooMjgU6.js} +1 -1
  244. package/dist/chunks/{tasks-Dmh6qikm.js → tasks-CHG_6sXQ.js} +1 -1
  245. package/dist/chunks/teleport-C9KRE4X8.js +1 -0
  246. package/dist/chunks/{templateJobs-CxqU-s5i.js → templateJobs-BYYfF4m5.js} +2 -2
  247. package/dist/chunks/{terminalSetup-BKGcmlWp.js → terminalSetup-CbXKCpWM.js} +1 -1
  248. package/dist/chunks/{terminalSetup-Cy19F1Js.js → terminalSetup-fwhFTxGi.js} +1 -1
  249. package/dist/chunks/{theme-U7lMFHQ0.js → theme-MvX7hojJ.js} +1 -1
  250. package/dist/chunks/tmux-d3cNCIZA.js +1 -0
  251. package/dist/chunks/{toolEventObserver-D9qjoVl5.js → toolEventObserver-BFEl47bq.js} +1 -1
  252. package/dist/chunks/toolPool-Cq74Cvjp.js +1 -0
  253. package/dist/chunks/trustedDevice-BGwujSqc.js +1 -0
  254. package/dist/chunks/{trustedDevice-DL0pWP4_.js → trustedDevice-BLiKbGpG.js} +1 -1
  255. package/dist/chunks/{types-DafcFtmb.js → types-BJ7qTz75.js} +1 -1
  256. package/dist/chunks/{udsClient-CWnfsgFP.js → udsClient-CF8BmZgN.js} +1 -1
  257. package/dist/chunks/{updateCCB-C6XftzIG.js → updateCCB-CfckOy7T.js} +1 -1
  258. package/dist/chunks/{upstreamproxy-CXmjxHpl.js → upstreamproxy-BuBFDFAD.js} +1 -1
  259. package/dist/chunks/{useExitOnCtrlCDWithKeybindings-DEEJhm_W.js → useExitOnCtrlCDWithKeybindings-CPLBDluY.js} +1 -1
  260. package/dist/chunks/useMainLoopModel-C00PbZ1Q.js +1 -0
  261. package/dist/chunks/useManagePlugins-DFaGntzJ.js +1 -0
  262. package/dist/chunks/{useMergedTools-DbhqKk1-.js → useMergedTools-DYobZ5N4.js} +1 -1
  263. package/dist/chunks/{useSearchInput-gUDbkLaC.js → useSearchInput-KFKh2ozY.js} +1 -1
  264. package/dist/chunks/useSettingsErrors-BRgjvaHd.js +1 -0
  265. package/dist/chunks/{userAgent-CU7Ndh79.js → userAgent-DUrr02yh.js} +1 -1
  266. package/dist/chunks/util-D7uwPgF1.js +1 -0
  267. package/dist/chunks/validatePlugin-VukX52bx.js +1 -0
  268. package/dist/chunks/{vim-w37BfGZ5.js → vim-C4Hs5U2h.js} +1 -1
  269. package/dist/chunks/{which-BRWBO7Gu.js → which-mplwBbc0.js} +1 -1
  270. package/dist/chunks/windowsPaths-B8p9tFRF.js +1 -0
  271. package/dist/chunks/{windowsPaths-DtWHLjmE.js → windowsPaths-C7Mdo9aU.js} +1 -1
  272. package/dist/chunks/{workSecret-BEhXgH2M.js → workSecret-XLodD7tw.js} +1 -1
  273. package/dist/chunks/workerRegistry-BA37PVbv.js +6 -0
  274. package/dist/chunks/worktree-Lik8xuKd.js +1 -0
  275. package/dist/cli.js +1 -1
  276. package/package.json +1 -1
  277. package/dist/chunks/App-BuKmqFPm.js +0 -1
  278. package/dist/chunks/ApproveApiKey-CIWOi_7v.js +0 -1
  279. package/dist/chunks/ApproveApiKey-M6U-NafA.js +0 -1
  280. package/dist/chunks/BackgroundTasksDialog-Pnpl3Ixx.js +0 -2
  281. package/dist/chunks/ClaudeMdExternalIncludesDialog-CSywJdVL.js +0 -1
  282. package/dist/chunks/ClaudeMdExternalIncludesDialog-D-w166RC.js +0 -1
  283. package/dist/chunks/ConsoleOAuthFlow-CV6PcJOP.js +0 -1
  284. package/dist/chunks/Doctor-BcnUfJ4I.js +0 -1
  285. package/dist/chunks/Doctor-Dz4TuYas.js +0 -3
  286. package/dist/chunks/ExitFlow-BwyAtIHx.js +0 -2
  287. package/dist/chunks/InvalidConfigDialog-bih293Xt.js +0 -1
  288. package/dist/chunks/MCPConnectionManager-B9n4SXN4.js +0 -1
  289. package/dist/chunks/MCPToolListView-DJ06N1DG.js +0 -1
  290. package/dist/chunks/MessageSelector-o4ULADFg.js +0 -3
  291. package/dist/chunks/Messages-qqwHuAW5.js +0 -11
  292. package/dist/chunks/Onboarding-BzuQjney.js +0 -1
  293. package/dist/chunks/QueryEngine-Dt0BKUeF.js +0 -1
  294. package/dist/chunks/REPL-CUbEDqEl.js +0 -133
  295. package/dist/chunks/REPL-DMaKNhTa.js +0 -1
  296. package/dist/chunks/RemoteSessionManager-Bf44A0Ol.js +0 -2
  297. package/dist/chunks/ResumeConversation-Ctw5Q1g9.js +0 -1
  298. package/dist/chunks/SearchExtraToolsTool-C80OdtPZ.js +0 -1
  299. package/dist/chunks/Settings-DfdcmvOV.js +0 -2
  300. package/dist/chunks/TrustDialog-ACaJ_m7A.js +0 -1
  301. package/dist/chunks/WelcomeV2-ZQRKlcT4.js +0 -1
  302. package/dist/chunks/add-dir-SAKTkw0S.js +0 -1
  303. package/dist/chunks/agents-ZgRKpjHv.js +0 -103
  304. package/dist/chunks/allErrors-_cOQksHC.js +0 -1
  305. package/dist/chunks/api-DS1MiW01.js +0 -1
  306. package/dist/chunks/auth-DGZzCbU0.js +0 -1
  307. package/dist/chunks/auth-DN1MUpB8.js +0 -1
  308. package/dist/chunks/autoMode-CBtY7ACs.js +0 -45
  309. package/dist/chunks/autonomy-DuQmYhq6.js +0 -15
  310. package/dist/chunks/autonomy-lJV7yWUl.js +0 -1
  311. package/dist/chunks/autonomyPanel-DAQm6lDz.js +0 -1
  312. package/dist/chunks/backgroundHousekeeping-BTy71bcY.js +0 -1
  313. package/dist/chunks/backgroundHousekeeping-Cc7Ag7JG.js +0 -17
  314. package/dist/chunks/bg-CJ0YWFli.js +0 -9
  315. package/dist/chunks/bg-CeUrRz_7.js +0 -1
  316. package/dist/chunks/branch-k3kirqbA.js +0 -3
  317. package/dist/chunks/bridgeConfig-CzRUPn-D.js +0 -1
  318. package/dist/chunks/btw-nVoVuIae.js +0 -1
  319. package/dist/chunks/caches-B8sM3Zys.js +0 -1
  320. package/dist/chunks/caches-Bp9MZ7IE.js +0 -1
  321. package/dist/chunks/cliLaunch-BTpfAGGI.js +0 -1
  322. package/dist/chunks/client-BCAbKdNz.js +0 -1
  323. package/dist/chunks/client-CJE6gEvU.js +0 -1
  324. package/dist/chunks/commands-DL-BzoMQ.js +0 -1
  325. package/dist/chunks/compact-Cx7BPXLU.js +0 -2
  326. package/dist/chunks/config-S5OW4Xqr.js +0 -1
  327. package/dist/chunks/config-aRiTrtCv.js +0 -3
  328. package/dist/chunks/connectHeadless-CqRoEtrg.js +0 -1
  329. package/dist/chunks/context-noninteractive-DPacEFJ1.js +0 -1
  330. package/dist/chunks/conversation-D5Nbu9eT.js +0 -1
  331. package/dist/chunks/conversation-hcUx9e-C.js +0 -1
  332. package/dist/chunks/createSSHSession-DecOR6M5.js +0 -6
  333. package/dist/chunks/createSession-D27zvmOs.js +0 -1
  334. package/dist/chunks/crossProjectResume-Bw3U0Ty6.js +0 -40
  335. package/dist/chunks/cwd-ClLru_7T.js +0 -1
  336. package/dist/chunks/dangerousBackend-DwcP0P08.js +0 -1
  337. package/dist/chunks/datadog-bm551AVV.js +0 -1
  338. package/dist/chunks/detached-CIyF0M5O.js +0 -5
  339. package/dist/chunks/detectRepository-DDfLfKcM.js +0 -1
  340. package/dist/chunks/doctor-BJORBomU.js +0 -1
  341. package/dist/chunks/exit-CF3KBl-S.js +0 -1
  342. package/dist/chunks/extractMemories-4lBn134y.js +0 -1
  343. package/dist/chunks/fast-0Vi354KI.js +0 -1
  344. package/dist/chunks/firstPartyEventLogger-BNBnLYPK.js +0 -1
  345. package/dist/chunks/generateSessionName-DhS_6oHd.js +0 -1
  346. package/dist/chunks/git-DF4RFFaT.js +0 -1
  347. package/dist/chunks/grok-BS57ZhyW.js +0 -1
  348. package/dist/chunks/hooks-DT80Arzc.js +0 -1
  349. package/dist/chunks/keybindings-CwdC_8S0.js +0 -2
  350. package/dist/chunks/loadAgentsDir-eVKq8efm.js +0 -1
  351. package/dist/chunks/loadPluginHooks-B0au35a4.js +0 -1
  352. package/dist/chunks/localSearch-CZlFfR_X.js +0 -1
  353. package/dist/chunks/lockfile-D5-j7HOZ.js +0 -1
  354. package/dist/chunks/main-CVNWNAoh.js +0 -513
  355. package/dist/chunks/main-LMyE3jXY.js +0 -31
  356. package/dist/chunks/managedEnv-CYepSnm8.js +0 -1
  357. package/dist/chunks/mcp-BAbbEaBA.js +0 -1
  358. package/dist/chunks/mcp-Ct4Sum6A.js +0 -6
  359. package/dist/chunks/mcp-D5HkCqUh.js +0 -2
  360. package/dist/chunks/memory-COa7aUbx.js +0 -1
  361. package/dist/chunks/model-B7rtZ7KV.js +0 -1
  362. package/dist/chunks/model-Bgh_r4lg.js +0 -1
  363. package/dist/chunks/model-DiuEAv6h.js +0 -1
  364. package/dist/chunks/oauth-BN2I0_jl.js +0 -1
  365. package/dist/chunks/oauth-C9VBDB0Y.js +0 -1
  366. package/dist/chunks/openai-DWs4D-nQ.js +0 -10
  367. package/dist/chunks/parseConnectUrl-BiyKR5-x.js +0 -1
  368. package/dist/chunks/parser-BMIaRErw.js +0 -1
  369. package/dist/chunks/partition-DLcW5Oo_.js +0 -1
  370. package/dist/chunks/permissions-CaucYK3s.js +0 -3
  371. package/dist/chunks/pidLock-DgOBc1Xo.js +0 -3
  372. package/dist/chunks/plugin-BN-of1_H.js +0 -17
  373. package/dist/chunks/pluginAutoupdate-BBU9Jn4p.js +0 -1
  374. package/dist/chunks/pluginBlocklist-DXQlbG0P.js +0 -1
  375. package/dist/chunks/pluginCliCommands-CfdVNs8D.js +0 -1
  376. package/dist/chunks/pluginOperations-DnhzFbYI.js +0 -2
  377. package/dist/chunks/pluginStartupCheck-CpNB4jxG.js +0 -1
  378. package/dist/chunks/plugins-CBW7kPyp.js +0 -4
  379. package/dist/chunks/poorMode-yH1o41cQ.js +0 -1
  380. package/dist/chunks/print-BZOx09SU.js +0 -26
  381. package/dist/chunks/processBashCommand-dcCNCiBp.js +0 -1
  382. package/dist/chunks/processSlashCommand-YDiM63Qr.js +0 -5
  383. package/dist/chunks/prompt-CXGy0llt.js +0 -1
  384. package/dist/chunks/prompt-DovNDmcx.js +0 -1
  385. package/dist/chunks/rcDebugLog-CARUIORE.js +0 -1
  386. package/dist/chunks/reconciler-C2Nd_e4n.js +0 -1
  387. package/dist/chunks/refresh-B84H2Ezd.js +0 -1
  388. package/dist/chunks/rename-CSavuBIE.js +0 -1
  389. package/dist/chunks/resume-CROylN3J.js +0 -2
  390. package/dist/chunks/ripgrep-2M1GkXqJ.js +0 -1
  391. package/dist/chunks/sandbox-adapter-6UwMLh6e.js +0 -1
  392. package/dist/chunks/sandbox-toggle-YrQNWGsr.js +0 -1
  393. package/dist/chunks/searchExtraTools-Bdv5HJ74.js +0 -1
  394. package/dist/chunks/server-LdbAb0sV.js +0 -1
  395. package/dist/chunks/serverBanner-BdExKFHT.js +0 -1
  396. package/dist/chunks/serverLog-BFmvyJ93.js +0 -1
  397. package/dist/chunks/sessionFileAccessHooks-Czen7Ejz.js +0 -1
  398. package/dist/chunks/sessionManager-CPa049BO.js +0 -1
  399. package/dist/chunks/sessionObserver-B0zucj_c.js +0 -1
  400. package/dist/chunks/sessionStorage-BM1x51Z7.js +0 -1
  401. package/dist/chunks/sessionTitle-uCuYaNif.js +0 -14
  402. package/dist/chunks/settings-BG15IFYx.js +0 -1
  403. package/dist/chunks/settings-D4CpDv2y.js +0 -20
  404. package/dist/chunks/settingsSync-BSrpnyqo.js +0 -1
  405. package/dist/chunks/setup-C62oq4AZ.js +0 -3
  406. package/dist/chunks/sinks-WJ7nzLQs.js +0 -1
  407. package/dist/chunks/skillChangeDetector-U5kRU5nd.js +0 -1
  408. package/dist/chunks/skills-BgcFh0vy.js +0 -1
  409. package/dist/chunks/startupProfiler-B4HBBbHN.js +0 -1
  410. package/dist/chunks/state-BAGmpVBn.js +0 -1
  411. package/dist/chunks/state-D_lk6z-C.js +0 -1
  412. package/dist/chunks/status-D6KlRJmR.js +0 -2
  413. package/dist/chunks/statusNoticeHelpers-BMM8_uJ1.js +0 -1
  414. package/dist/chunks/subprocessEnv-CZkA9Cdp.js +0 -1
  415. package/dist/chunks/switcher-Ck9CrXrr.js +0 -1
  416. package/dist/chunks/switcher-DnAhkyIn.js +0 -1
  417. package/dist/chunks/teleport-DH3IuAUQ.js +0 -1
  418. package/dist/chunks/tmux-D5EvHWi3.js +0 -1
  419. package/dist/chunks/toolPool-69mfSPAs.js +0 -1
  420. package/dist/chunks/trustedDevice-B6AKlsl_.js +0 -1
  421. package/dist/chunks/useMainLoopModel-6w7mhwhU.js +0 -1
  422. package/dist/chunks/useManagePlugins-CjnsO-Of.js +0 -1
  423. package/dist/chunks/useSettingsErrors-CgPad-H0.js +0 -1
  424. package/dist/chunks/util-B4oMhJKh.js +0 -1
  425. package/dist/chunks/validatePlugin-y_O_tCEL.js +0 -1
  426. package/dist/chunks/windowsPaths-BY-IVNwQ.js +0 -1
  427. package/dist/chunks/workerRegistry-Bq9bS5pw.js +0 -6
  428. package/dist/chunks/worktree-4SUJ4dtz.js +0 -1
@@ -0,0 +1,26 @@
1
+ import{a as e}from"./rolldown-runtime-DaDcL9Zw.js";import{c as t,i as n,l as r,o as i,s as a}from"./envUtils-DcaKZlRU.js";import{n as o,t as s}from"./defineProperty-C-QyHrDq.js";import{n as c,t as l}from"./axios-DaWTGg7G.js";import{$g as u,$p as d,$v as f,Ah as p,BS as m,Bf as h,Bo as g,CS as _,CT as v,C_ as ee,Cm as y,Cn as b,Cu as x,Dm as S,E as C,Eg as te,En as w,Fb as ne,Fs as re,Gb as ie,Gc as ae,Gr as oe,Gv as se,H as ce,HS as le,Hb as ue,Hc as de,Hg as fe,Hx as pe,Ib as me,Is as T,Jb as he,Jc as ge,Jx as _e,Kb as ve,Kg as ye,M as be,MT as E,Mi as xe,NT as D,Nb as Se,No as O,Ns as Ce,OT as we,Pi as Te,Po as Ee,Ps as De,Px as Oe,Qd as ke,Ql as Ae,Qv as je,Qx as Me,Ro as Ne,S as Pe,SS as Fe,S_ as Ie,Sm as Le,Sn as Re,Sr as ze,Su as Be,T as Ve,Tg as He,Tn as Ue,U as We,Ug as Ge,Uo as k,Ut as A,Ux as Ke,Vc as qe,Vi as Je,Vt as Ye,Vx as Xe,Wb as Ze,Wc as Qe,Wv as $e,Xb as et,Xc as tt,Xd as j,Xn as nt,Yb as rt,Yc as it,Yd as at,Yg as ot,Ys as st,Zb as ct,Zc as lt,Zd as ut,Zg as dt,Zl as ft,_E as pt,_m as mt,_n as ht,_s as gt,ax as _t,b as vt,b_ as yt,bg as bt,bm as xt,br as St,cf as Ct,cx as wt,cy as Tt,db as Et,dc as Dt,ds as Ot,el as kt,em as At,er as jt,f as Mt,fo as Nt,fp as Pt,fs as Ft,gT as It,gm as Lt,gs as Rt,gy as zt,hm as Bt,hs as Vt,ic as Ht,ii as Ut,io as Wt,jx as Gt,kT as Kt,kh as qt,ki as Jt,lb as Yt,ls as Xt,ly as Zt,mm as Qt,ms as $t,mw as en,nc as tn,ny as nn,o as rn,oc as an,of as on,og as sn,oi as cn,oo as ln,ox as un,pm as dn,ps as fn,pw as pn,py as mn,qc as hn,qg as gn,qs as _n,qx as vn,rC as yn,rc as bn,ri as xn,ro as Sn,ry as Cn,s as wn,sg as Tn,si as En,ty as Dn,ub as On,uc as kn,uo as An,up as jn,us as Mn,uy as Nn,va as Pn,vi as Fn,vm as In,vs as Ln,wT as Rn,wm as zn,wn as Bn,x_ as Vn,xg as Hn,xm as Un,xn as Wn,xr as Gn,xx as Kn,y as qn,yT as Jn,yg as Yn,yi as Xn,ym as Zn,yu as Qn,za as $n,zb as er,zf as tr,zi as nr}from"./loadAgentsDir-mcRW90aq.js";import{A as M,C as N,M as P,O as F,b as I,f as rr,g as ir,j as L,l as R,m as z,p as B,u as ar,w as V,y as or}from"./external-CEp-aPkt.js";import{i as H,n as U,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 W,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 G,R as Tr,S as Er,U as Dr,a as Or,c as K,f as kr,i as Ar,nt as jr,tt as Mr,u as Nr,x as Pr}from"./debug-Dr1SjdXn.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-DiBMs2gM.js";import{F as qr,M as Jr}from"./config-9rLTDOYW.js";import{i as Yr,n as Xr,o as q}from"./process-gEbdy6uY.js";import{A as Zr,O as Qr,k as $r}from"./git-CoQQ6YEf.js";import{H as ei,c as ti,i as ni,o as ri,q as ii,s as J}from"./log-27kCA_9u.js";import{s as ai,u as oi}from"./types-BJ7qTz75.js";import{n as si,r as Y}from"./analytics-DJobLaWP.js";import{Bt as ci,C as li,Gr as ui,Mn as di,Y as fi,_ as pi,_n as mi,_r as hi,ai as gi,bt as _i,et as vi,ii as yi,it as bi,jn as xi,o as Si,qr as Ci,ri as wi,rt as Ti,si as Ei,tt as Di,u as Oi,vn as ki,vr as Ai,x as ji}from"./model-C29_32BD.js";import{at as Mi,bn as Ni,bt as Pi,ot as Fi,rn as Ii,vt as Li,xn as Ri,yt as zi}from"./prompt-DIlq8NTy.js";import{A as Bi,D as Vi,M as Hi,_ as Ui,a as Wi,c as Gi,k as Ki,l as qi,n as Ji,o as Yi,s as Xi,st as Zi,t as Qi,w as $i,x as ea}from"./sessionState-Bn3ESS5f.js";import{n as ta,t as na}from"./omit-KEhe84f4.js";import{a as ra,n as ia,t as aa}from"./bridgeConfig-B80T_lw7.js";import{i as oa,n as sa,s as ca}from"./mappers-DwZw084m.js";import{n as la,r as ua}from"./sessionTitle-Cbzrb9jT.js";import{t as da}from"./pollConfig-BgpfHQPJ.js";import{t as fa}from"./controlMessageCompat-IFu4Gc1y.js";import{n as pa,t as ma}from"./ccrClient-BALhzhPF.js";import{n as ha,t as ga}from"./HybridTransport-BQNLZNa_.js";import{n as _a,t as va}from"./SSETransport-BBQkdn4e.js";import{a as ya,n as ba}from"./grove-b9gGKgu4.js";import{o as xa}from"./remoteManagedSettings-CwDGxL5p.js";import{i as Sa,r as Ca}from"./auth-Czy7GoRh.js";import{t as wa}from"./pluginBlocklist-BfoLN9a-.js";import{t as Ta}from"./settingsSync-eHaSngKo.js";import{n as Ea,t as Da}from"./toolPool-Cq74Cvjp.js";import{t as Oa}from"./onChangeAppState-Dq1tIEJI.js";import{n as ka,r as Aa}from"./QueryEngine-HlLQJmsd.js";import{r as ja}from"./bridgeStatusUtil-DStiD05t.js";import{n as Ma,r as Na}from"./sideQuestion-BHRtwhyj.js";import{n as Pa,r as Fa}from"./context-noninteractive-CHzerxnH.js";import{n as Ia,t as La}from"./modelOptions-CiZgZxZC.js";import{a as Ra,o as za,t as Ba}from"./skillChangeDetector-BlSP16j6.js";import{n as Va}from"./reconciler-CDq6XgAS.js";import{n as Ha,t as Ua}from"./refresh-ysrhoWCo.js";import{basename as Wa,dirname as Ga,join as Ka}from"path";import{PassThrough as qa}from"stream";import{randomUUID as X}from"crypto";import{mkdir as Ja,readFile as Ya,stat as Xa,writeFile as Za}from"fs/promises";import{URL as Qa}from"url";import{cwd as $a}from"process";i(),o(),l(),hr(),Mr(),Tr(),Pr(),kr(),Xr(),Ar(),Qr(),ii(),ri(),Lr(),ai(),Hr(),Ei(),Ci(),Ai(),xi(),mi(),ci(),pi(),Ta(),sr(),cr();var eo=U(()=>V({inputTokens:N(),outputTokens:N(),cacheReadInputTokens:N(),cacheCreationInputTokens:N(),webSearchRequests:N(),costUSD:N(),contextWindow:N(),maxOutputTokens:N()})),to=U(()=>I(`json_schema`));U(()=>V({type:to()}));var no=U(()=>V({type:I(`json_schema`),schema:F(M(),P())}));U(()=>no());var ro=U(()=>R([`user`,`project`,`org`,`temporary`,`oauth`]));U(()=>R([`local`,`user`,`project`]).describe(`Config scope for settings.`)),U(()=>I(`context-1m-2025-08-07`));var io=U(()=>V({type:I(`adaptive`)}).describe(`Claude decides when and how much to think (Opus 4.6+).`)),ao=U(()=>V({type:I(`enabled`),budgetTokens:N().optional()}).describe(`Fixed thinking token budget (older models)`)),oo=U(()=>V({type:I(`disabled`)}).describe(`No extended thinking`));U(()=>L([io(),ao(),oo()]).describe(`Controls Claude's thinking/reasoning behavior. When set, takes precedence over the deprecated maxThinkingTokens.`));var so=U(()=>V({type:I(`stdio`).optional(),command:M(),args:B(M()).optional(),env:F(M(),M()).optional()})),co=U(()=>V({type:I(`sse`),url:M(),headers:F(M(),M()).optional()})),lo=U(()=>V({type:I(`http`),url:M(),headers:F(M(),M()).optional()})),uo=U(()=>V({type:I(`sdk`),name:M()})),fo=U(()=>L([so(),co(),lo(),uo()])),po=U(()=>V({type:I(`claudeai-proxy`),url:M(),id:M()})),mo=U(()=>L([fo(),po()])),ho=U(()=>V({name:M().describe(`Server name as configured`),status:R([`connected`,`failed`,`needs-auth`,`pending`,`disabled`]).describe(`Current connection status`),serverInfo:V({name:M(),version:M()}).optional().describe(`Server information (available when connected)`),error:M().optional().describe(`Error message (available when status is 'failed')`),config:mo().optional().describe(`Server configuration (includes URL for HTTP/SSE servers)`),scope:M().optional().describe(`Configuration scope (e.g., project, user, local, claudeai, managed)`),tools:B(V({name:M(),description:M().optional(),annotations:V({readOnly:z().optional(),destructive:z().optional(),openWorld:z().optional()}).optional()})).optional().describe(`Tools provided by this server (available when connected)`),capabilities:V({experimental:F(M(),P()).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.`));U(()=>V({added:B(M()).describe(`Names of servers that were added`),removed:B(M()).describe(`Names of servers that were removed`),errors:F(M(),M()).describe(`Map of server names to error messages for servers that failed to connect`)}).describe(`Result of a setMcpServers operation.`));var go=U(()=>R([`userSettings`,`projectSettings`,`localSettings`,`session`,`cliArg`])),_o=U(()=>R([`allow`,`deny`,`ask`])),vo=U(()=>V({toolName:M(),ruleContent:M().optional()})),yo=U(()=>ir(`type`,[V({type:I(`addRules`),rules:B(vo()),behavior:_o(),destination:go()}),V({type:I(`replaceRules`),rules:B(vo()),behavior:_o(),destination:go()}),V({type:I(`removeRules`),rules:B(vo()),behavior:_o(),destination:go()}),V({type:I(`setMode`),mode:or(()=>xo()),destination:go()}),V({type:I(`addDirectories`),directories:B(M()),destination:go()}),V({type:I(`removeDirectories`),directories:B(M()),destination:go()})])),bo=U(()=>R([`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).`));U(()=>L([V({behavior:I(`allow`),updatedInput:F(M(),P()).optional(),updatedPermissions:B(yo()).optional(),toolUseID:M().optional(),decisionClassification:bo().optional()}),V({behavior:I(`deny`),message:M(),interrupt:z().optional(),toolUseID:M().optional(),decisionClassification:bo().optional()})]));var xo=U(()=>R([`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).`)),So=`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(`.`),Co=U(()=>R(So)),Z=U(()=>V({session_id:M(),transcript_path:M(),cwd:M(),permission_mode:M().optional(),agent_id:M().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:M().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).`)})),wo=U(()=>Z().and(V({hook_event_name:I(`PreToolUse`),tool_name:M(),tool_input:P(),tool_use_id:M()}))),To=U(()=>Z().and(V({hook_event_name:I(`PermissionRequest`),tool_name:M(),tool_input:P(),permission_suggestions:B(yo()).optional()}))),Eo=U(()=>Z().and(V({hook_event_name:I(`PostToolUse`),tool_name:M(),tool_input:P(),tool_response:P(),tool_use_id:M()}))),Do=U(()=>Z().and(V({hook_event_name:I(`PostToolUseFailure`),tool_name:M(),tool_input:P(),tool_use_id:M(),error:M(),is_interrupt:z().optional()}))),Oo=U(()=>Z().and(V({hook_event_name:I(`PermissionDenied`),tool_name:M(),tool_input:P(),tool_use_id:M(),reason:M()}))),ko=U(()=>Z().and(V({hook_event_name:I(`Notification`),message:M(),title:M().optional(),notification_type:M()}))),Ao=U(()=>Z().and(V({hook_event_name:I(`UserPromptSubmit`),prompt:M()}))),jo=U(()=>Z().and(V({hook_event_name:I(`SessionStart`),source:R([`startup`,`resume`,`clear`,`compact`]),agent_type:M().optional(),model:M().optional()}))),Mo=U(()=>Z().and(V({hook_event_name:I(`Setup`),trigger:R([`init`,`maintenance`])}))),No=U(()=>Z().and(V({hook_event_name:I(`Stop`),stop_hook_active:z(),last_assistant_message:M().optional().describe(`Text content of the last assistant message before stopping. Avoids the need to read and parse the transcript file.`)}))),Po=U(()=>Z().and(V({hook_event_name:I(`StopFailure`),error:js(),error_details:M().optional(),last_assistant_message:M().optional()}))),Fo=U(()=>Z().and(V({hook_event_name:I(`SubagentStart`),agent_id:M(),agent_type:M()}))),Io=U(()=>Z().and(V({hook_event_name:I(`SubagentStop`),stop_hook_active:z(),agent_id:M(),agent_transcript_path:M(),agent_type:M(),last_assistant_message:M().optional().describe(`Text content of the last assistant message before stopping. Avoids the need to read and parse the transcript file.`)}))),Lo=U(()=>Z().and(V({hook_event_name:I(`PreCompact`),trigger:R([`manual`,`auto`]),custom_instructions:M().nullable()}))),Ro=U(()=>Z().and(V({hook_event_name:I(`PostCompact`),trigger:R([`manual`,`auto`]),compact_summary:M().describe(`The conversation summary produced by compaction`)}))),zo=U(()=>Z().and(V({hook_event_name:I(`TeammateIdle`),teammate_name:M(),team_name:M()}))),Bo=U(()=>Z().and(V({hook_event_name:I(`TaskCreated`),task_id:M(),task_subject:M(),task_description:M().optional(),teammate_name:M().optional(),team_name:M().optional()}))),Vo=U(()=>Z().and(V({hook_event_name:I(`TaskCompleted`),task_id:M(),task_subject:M(),task_description:M().optional(),teammate_name:M().optional(),team_name:M().optional()}))),Ho=U(()=>Z().and(V({hook_event_name:I(`Elicitation`),mcp_server_name:M(),message:M(),mode:R([`form`,`url`]).optional(),url:M().optional(),elicitation_id:M().optional(),requested_schema:F(M(),P()).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.`)),Uo=U(()=>Z().and(V({hook_event_name:I(`ElicitationResult`),mcp_server_name:M(),elicitation_id:M().optional(),mode:R([`form`,`url`]).optional(),action:R([`accept`,`decline`,`cancel`]),content:F(M(),P()).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.`)),Wo=[`user_settings`,`project_settings`,`local_settings`,`policy_settings`,`skills`],Go=U(()=>Z().and(V({hook_event_name:I(`ConfigChange`),source:R(Wo),file_path:M().optional()}))),Ko=[`session_start`,`nested_traversal`,`path_glob_match`,`include`,`compact`],qo=[`User`,`Project`,`Local`,`Managed`],Jo=U(()=>Z().and(V({hook_event_name:I(`InstructionsLoaded`),file_path:M(),memory_type:R(qo),load_reason:R(Ko),globs:B(M()).optional(),trigger_file_path:M().optional(),parent_file_path:M().optional()}))),Yo=U(()=>Z().and(V({hook_event_name:I(`WorktreeCreate`),name:M()}))),Xo=U(()=>Z().and(V({hook_event_name:I(`WorktreeRemove`),worktree_path:M()}))),Zo=U(()=>Z().and(V({hook_event_name:I(`CwdChanged`),old_cwd:M(),new_cwd:M()}))),Qo=U(()=>Z().and(V({hook_event_name:I(`FileChanged`),file_path:M(),event:R([`change`,`add`,`unlink`])}))),$o=[`clear`,`resume`,`logout`,`prompt_input_exit`,`other`,`bypass_permissions_disabled`],es=U(()=>R($o)),ts=U(()=>Z().and(V({hook_event_name:I(`SessionEnd`),reason:es()}))),ns=U(()=>L([wo(),Eo(),Do(),Oo(),ko(),Ao(),jo(),ts(),No(),Po(),Fo(),Io(),Lo(),Ro(),To(),Mo(),zo(),Bo(),Vo(),Ho(),Uo(),Go(),Jo(),Yo(),Xo(),Zo(),Qo()])),rs=U(()=>V({async:I(!0),asyncTimeout:N().optional()})),is=U(()=>V({hookEventName:I(`PreToolUse`),permissionDecision:_o().optional(),permissionDecisionReason:M().optional(),updatedInput:F(M(),P()).optional(),additionalContext:M().optional()})),as=U(()=>V({hookEventName:I(`UserPromptSubmit`),additionalContext:M().optional()})),os=U(()=>V({hookEventName:I(`SessionStart`),additionalContext:M().optional(),initialUserMessage:M().optional(),watchPaths:B(M()).optional()})),ss=U(()=>V({hookEventName:I(`Setup`),additionalContext:M().optional()})),cs=U(()=>V({hookEventName:I(`SubagentStart`),additionalContext:M().optional()})),ls=U(()=>V({hookEventName:I(`PostToolUse`),additionalContext:M().optional(),updatedMCPToolOutput:P().optional()})),us=U(()=>V({hookEventName:I(`PostToolUseFailure`),additionalContext:M().optional()})),ds=U(()=>V({hookEventName:I(`PermissionDenied`),retry:z().optional()})),fs=U(()=>V({hookEventName:I(`Notification`),additionalContext:M().optional()})),ps=U(()=>V({hookEventName:I(`PermissionRequest`),decision:L([V({behavior:I(`allow`),updatedInput:F(M(),P()).optional(),updatedPermissions:B(yo()).optional()}),V({behavior:I(`deny`),message:M().optional(),interrupt:z().optional()})])})),ms=U(()=>V({hookEventName:I(`CwdChanged`),watchPaths:B(M()).optional()})),hs=U(()=>V({hookEventName:I(`FileChanged`),watchPaths:B(M()).optional()})),gs=U(()=>V({continue:z().optional(),suppressOutput:z().optional(),stopReason:M().optional(),decision:R([`approve`,`block`]).optional(),systemMessage:M().optional(),reason:M().optional(),hookSpecificOutput:L([is(),as(),os(),ss(),cs(),ls(),us(),ds(),fs(),ps(),_s(),vs(),ms(),hs(),ys()]).optional()})),_s=U(()=>V({hookEventName:I(`Elicitation`),action:R([`accept`,`decline`,`cancel`]).optional(),content:F(M(),P()).optional()}).describe(`Hook-specific output for the Elicitation event. Return this to programmatically accept or decline an MCP elicitation request.`)),vs=U(()=>V({hookEventName:I(`ElicitationResult`),action:R([`accept`,`decline`,`cancel`]).optional(),content:F(M(),P()).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.`)),ys=U(()=>V({hookEventName:I(`WorktreeCreate`),worktreePath:M()}).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.`));U(()=>L([rs(),gs()]));var bs=U(()=>V({key:M().describe(`Unique key for this option, returned in the response`),label:M().describe(`Display text for this option`),description:M().optional().describe(`Optional description shown below the label`)}));U(()=>V({prompt:M().describe(`Request ID. Presence of this key marks the line as a prompt request.`),message:M().describe(`The prompt message to display to the user`),options:B(bs()).describe(`Available options for the user to choose from`)})),U(()=>V({prompt_response:M().describe(`The request ID from the corresponding prompt request`),selected:M().describe(`The key of the selected option`)}));var xs=U(()=>V({name:M().describe(`Skill name (without the leading slash)`),description:M().describe(`Description of what the skill does`),argumentHint:M().describe(`Hint for skill arguments (e.g., "<file>")`)}).describe(`Information about an available skill (invoked via /command syntax).`)),Ss=U(()=>V({name:M().describe(`Agent type identifier (e.g., "Explore")`),description:M().describe(`Description of when to use this agent`),model:M().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.`)),Cs=U(()=>V({value:M().describe(`Model identifier to use in API calls`),displayName:M().describe(`Human-readable display name`),description:M().describe(`Description of the model's capabilities`),supportsAdaptiveThinking:z().optional().describe(`Whether this model supports adaptive thinking (Claude decides when and how much to think)`),supportsFastMode:z().optional().describe(`Whether this model supports fast mode`),supportsAutoMode:z().optional().describe(`Whether this model supports auto mode`)}).describe(`Information about an available model.`)),ws=U(()=>V({email:M().optional(),organization:M().optional(),subscriptionType:M().optional(),tokenSource:M().optional(),apiKeySource:M().optional(),apiProvider:R([`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.`)),Ts=U(()=>L([M(),F(M(),fo())])),Es=U(()=>V({description:M().describe(`Natural language description of when to use this agent`),tools:B(M()).optional().describe(`Array of allowed tool names. If omitted, inherits all tools from parent`),disallowedTools:B(M()).optional().describe(`Array of tool names to explicitly disallow for this agent`),prompt:M().describe(`The agent's system prompt`),model:M().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:B(Ts()).optional(),criticalSystemReminder_EXPERIMENTAL:M().optional().describe(`Experimental: Critical reminder added to system prompt`),skills:B(M()).optional().describe(`Array of skill names to preload into the agent context`),initialPrompt:M().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:N().int().positive().optional().describe(`Maximum number of agentic turns (API round-trips) before stopping`),background:z().optional().describe(`Run this agent as a background task (non-blocking, fire-and-forget) when invoked`),memory:R([`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:xo().optional().describe(`Permission mode controlling how tool executions are handled`)}).describe(`Definition for a custom subagent that can be invoked via the Agent tool.`));U(()=>R([`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).`)),U(()=>V({type:I(`local`).describe(`Plugin type. Currently only 'local' is supported`),path:M().describe(`Absolute or relative path to the plugin directory`)}).describe(`Configuration for loading a plugin.`)),U(()=>V({canRewind:z(),error:M().optional(),filesChanged:B(M()).optional(),insertions:N().optional(),deletions:N().optional()}).describe(`Result of a rewindFiles operation.`));var Ds=U(()=>P()),Os=U(()=>P()),ks=U(()=>P()),Q=U(()=>M()),As=U(()=>P()),js=U(()=>R([`authentication_failed`,`billing_error`,`rate_limit`,`invalid_request`,`server_error`,`unknown`,`max_output_tokens`])),Ms=U(()=>L([I(`compacting`),ar()])),Ns=U(()=>V({type:I(`user`),message:Ds(),parent_tool_use_id:M().nullable(),isSynthetic:z().optional(),tool_use_result:P().optional(),priority:R([`now`,`next`,`later`]).optional(),timestamp:M().optional().describe(`ISO timestamp when the message was created on the originating process. Older emitters omit it; consumers should fall back to receive time.`)})),Ps=U(()=>Ns().extend({uuid:Q().optional(),session_id:M().optional()})),Fs=U(()=>Ns().extend({uuid:Q(),session_id:M(),isReplay:I(!0)})),Is=U(()=>V({status:R([`allowed`,`allowed_warning`,`rejected`]),resetsAt:N().optional(),rateLimitType:R([`five_hour`,`seven_day`,`seven_day_opus`,`seven_day_sonnet`,`overage`]).optional(),utilization:N().optional(),overageStatus:R([`allowed`,`allowed_warning`,`rejected`]).optional(),overageResetsAt:N().optional(),overageDisabledReason:R([`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:z().optional(),surpassedThreshold:N().optional()}).describe(`Rate limit information for claude.ai subscription users.`)),Ls=U(()=>V({type:I(`assistant`),message:Os(),parent_tool_use_id:M().nullable(),error:js().optional(),uuid:Q(),session_id:M()})),Rs=U(()=>V({type:I(`rate_limit_event`),rate_limit_info:Is(),uuid:Q(),session_id:M()}).describe(`Rate limit event emitted when rate limit info changes.`)),zs=U(()=>V({type:I(`streamlined_text`),text:M().describe(`Text content preserved from the assistant message`),session_id:M(),uuid:Q()}).describe(`@internal Streamlined text message - replaces SDKAssistantMessage in streamlined output. Text content preserved, thinking and tool_use blocks removed.`)),Bs=U(()=>V({type:I(`streamlined_tool_use_summary`),tool_summary:M().describe(`Summary of tool calls (e.g., "Read 2 files, wrote 1 file")`),session_id:M(),uuid:Q()}).describe(`@internal Streamlined tool use summary - replaces tool_use blocks in streamlined output with a cumulative summary string.`)),Vs=U(()=>V({tool_name:M(),tool_use_id:M(),tool_input:F(M(),P())})),Hs=U(()=>V({type:I(`result`),subtype:I(`success`),duration_ms:N(),duration_api_ms:N(),is_error:z(),num_turns:N(),result:M(),stop_reason:M().nullable(),total_cost_usd:N(),usage:As(),modelUsage:F(M(),eo()),permission_denials:B(Vs()),structured_output:P().optional(),fast_mode_state:fc().optional(),uuid:Q(),session_id:M()})),Us=U(()=>V({type:I(`result`),subtype:R([`error_during_execution`,`error_max_turns`,`error_max_budget_usd`,`error_max_structured_output_retries`]),duration_ms:N(),duration_api_ms:N(),is_error:z(),num_turns:N(),stop_reason:M().nullable(),total_cost_usd:N(),usage:As(),modelUsage:F(M(),eo()),permission_denials:B(Vs()),errors:B(M()),fast_mode_state:fc().optional(),uuid:Q(),session_id:M()})),Ws=U(()=>L([Hs(),Us()])),Gs=U(()=>V({type:I(`system`),subtype:I(`init`),agents:B(M()).optional(),apiKeySource:ro(),betas:B(M()).optional(),claude_code_version:M(),cwd:M(),tools:B(M()),mcp_servers:B(V({name:M(),status:M()})),model:M(),permissionMode:xo(),slash_commands:B(M()),output_style:M(),skills:B(M()),plugins:B(V({name:M(),path:M(),source:M().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:fc().optional(),uuid:Q(),session_id:M()})),Ks=U(()=>V({type:I(`stream_event`),event:ks(),parent_tool_use_id:M().nullable(),uuid:Q(),session_id:M()})),qs=U(()=>V({type:I(`system`),subtype:I(`compact_boundary`),compact_metadata:V({trigger:R([`manual`,`auto`]),pre_tokens:N(),preserved_segment:V({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:M()})),Js=U(()=>V({type:I(`system`),subtype:I(`status`),status:Ms(),permissionMode:xo().optional(),uuid:Q(),session_id:M()})),Ys=U(()=>V({type:I(`system`),subtype:I(`post_turn_summary`),summarizes_uuid:M(),status_category:R([`blocked`,`waiting`,`completed`,`review_ready`,`failed`]),status_detail:M(),is_noteworthy:z(),title:M(),description:M(),recent_action:M(),needs_action:M(),artifact_urls:B(M()),uuid:Q(),session_id:M()}).describe(`@internal Background post-turn summary emitted after each assistant turn. summarizes_uuid points to the assistant message this summarizes.`)),Xs=U(()=>V({type:I(`system`),subtype:I(`api_retry`),attempt:N(),max_retries:N(),retry_delay_ms:N(),error_status:N().nullable(),error:js(),uuid:Q(),session_id:M()}).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.`)),Zs=U(()=>V({type:I(`system`),subtype:I(`local_command_output`),content:M(),uuid:Q(),session_id:M()}).describe(`Output from a local slash command (e.g. /voice, /cost). Displayed as assistant-style text in the transcript.`)),Qs=U(()=>V({type:I(`system`),subtype:I(`hook_started`),hook_id:M(),hook_name:M(),hook_event:M(),uuid:Q(),session_id:M()})),$s=U(()=>V({type:I(`system`),subtype:I(`hook_progress`),hook_id:M(),hook_name:M(),hook_event:M(),stdout:M(),stderr:M(),output:M(),uuid:Q(),session_id:M()})),ec=U(()=>V({type:I(`system`),subtype:I(`hook_response`),hook_id:M(),hook_name:M(),hook_event:M(),output:M(),stdout:M(),stderr:M(),exit_code:N().optional(),outcome:R([`success`,`error`,`cancelled`]),uuid:Q(),session_id:M()})),tc=U(()=>V({type:I(`tool_progress`),tool_use_id:M(),tool_name:M(),parent_tool_use_id:M().nullable(),elapsed_time_seconds:N(),task_id:M().optional(),uuid:Q(),session_id:M()})),nc=U(()=>V({type:I(`auth_status`),isAuthenticating:z(),output:B(M()),error:M().optional(),uuid:Q(),session_id:M()})),rc=U(()=>V({type:I(`system`),subtype:I(`files_persisted`),files:B(V({filename:M(),file_id:M()})),failed:B(V({filename:M(),error:M()})),processed_at:M(),uuid:Q(),session_id:M()})),ic=U(()=>V({type:I(`system`),subtype:I(`task_notification`),task_id:M(),tool_use_id:M().optional(),status:R([`completed`,`failed`,`stopped`]),output_file:M(),summary:M(),usage:V({total_tokens:N(),tool_uses:N(),duration_ms:N()}).optional(),uuid:Q(),session_id:M()})),ac=U(()=>V({type:I(`system`),subtype:I(`task_started`),task_id:M(),tool_use_id:M().optional(),description:M(),task_type:M().optional(),workflow_name:M().optional().describe(`meta.name from the workflow script (e.g. 'spec'). Only set when task_type is 'local_workflow'.`),prompt:M().optional(),uuid:Q(),session_id:M()})),oc=U(()=>V({type:I(`system`),subtype:I(`session_state_changed`),state:R([`idle`,`running`,`requires_action`]),uuid:Q(),session_id:M()}).describe(`Mirrors notifySessionStateChanged. 'idle' fires after heldBackResult flushes and the bg-agent do-while exits — authoritative turn-over signal.`)),sc=U(()=>V({type:I(`system`),subtype:I(`task_progress`),task_id:M(),tool_use_id:M().optional(),description:M(),usage:V({total_tokens:N(),tool_uses:N(),duration_ms:N()}),last_tool_name:M().optional(),summary:M().optional(),uuid:Q(),session_id:M()})),cc=U(()=>V({type:I(`tool_use_summary`),summary:M(),preceding_tool_use_ids:B(M()),uuid:Q(),session_id:M()})),lc=U(()=>V({type:I(`system`),subtype:I(`elicitation_complete`),mcp_server_name:M(),elicitation_id:M(),uuid:Q(),session_id:M()}).describe(`Emitted when an MCP server confirms that a URL-mode elicitation is complete.`)),uc=U(()=>V({type:I(`prompt_suggestion`),suggestion:M(),uuid:Q(),session_id:M()}).describe(`Predicted next user prompt, emitted after each turn when promptSuggestions is enabled.`));U(()=>V({sessionId:M().describe(`Unique session identifier (UUID).`),summary:M().describe(`Display title for the session: custom title, auto-generated summary, or first prompt.`),lastModified:N().describe(`Last modified time in milliseconds since epoch.`),fileSize:N().optional().describe(`File size in bytes. Only populated for local JSONL storage.`),customTitle:M().optional().describe(`User-set session title via /rename.`),firstPrompt:M().optional().describe(`First meaningful user prompt in the session.`),gitBranch:M().optional().describe(`Git branch at the end of the session.`),cwd:M().optional().describe(`Working directory for the session.`),tag:M().optional().describe(`User-set session tag.`),createdAt:N().optional().describe(`Creation time in milliseconds since epoch, extracted from the first entry's timestamp.`)}).describe(`Session metadata returned by listSessions and getSessionInfo.`));var dc=U(()=>L([Ls(),Ps(),Fs(),Ws(),Gs(),Ks(),qs(),Js(),Xs(),Zs(),Qs(),$s(),ec(),tc(),nc(),ic(),ac(),sc(),oc(),rc(),cc(),Rs(),lc(),uc()])),fc=U(()=>R([`off`,`cooldown`,`on`]).describe(`Fast mode state: off, in cooldown after rate limit, or actively enabled.`));sr(),cr();var pc=U(()=>P()),mc=U(()=>V({matcher:M().optional(),hookCallbackIds:B(M()),timeout:N().optional()}).describe(`Configuration for matching and routing hook callbacks.`)),hc=U(()=>V({subtype:I(`initialize`),hooks:F(Co(),B(mc())).optional(),sdkMcpServers:B(M()).optional(),jsonSchema:F(M(),P()).optional(),systemPrompt:M().optional(),appendSystemPrompt:M().optional(),agents:F(M(),Es()).optional(),promptSuggestions:z().optional(),agentProgressSummaries:z().optional()}).describe(`Initializes the SDK session with hooks, MCP servers, and agent configuration.`));U(()=>V({commands:B(xs()),agents:B(Ss()),output_style:M(),available_output_styles:B(M()),models:B(Cs()),account:ws(),pid:N().optional().describe(`@internal CLI process PID for tmux socket isolation`),fast_mode_state:fc().optional()}).describe(`Response from session initialization with available commands, models, and account info.`));var gc=U(()=>V({subtype:I(`interrupt`)}).describe(`Interrupts the currently running conversation turn.`)),_c=U(()=>V({subtype:I(`can_use_tool`),tool_name:M(),input:F(M(),P()),permission_suggestions:B(yo()).optional(),blocked_path:M().optional(),decision_reason:M().optional(),title:M().optional(),display_name:M().optional(),tool_use_id:M(),agent_id:M().optional(),description:M().optional()}).describe(`Requests permission to use a tool with the given input.`)),vc=U(()=>V({subtype:I(`set_permission_mode`),mode:xo()}).describe(`Sets the permission mode for tool execution handling.`)),yc=U(()=>V({subtype:I(`set_model`),model:M().optional()}).describe(`Sets the model to use for subsequent conversation turns.`)),bc=U(()=>V({subtype:I(`set_max_thinking_tokens`),max_thinking_tokens:N().nullable()}).describe(`Sets the maximum number of thinking tokens for extended thinking.`)),xc=U(()=>V({subtype:I(`mcp_status`)}).describe(`Requests the current status of all MCP server connections.`));U(()=>V({mcpServers:B(ho())}).describe(`Response containing the current status of all MCP server connections.`));var Sc=U(()=>V({subtype:I(`get_context_usage`)}).describe(`Requests a breakdown of current context window usage by category.`)),Cc=U(()=>V({name:M(),tokens:N(),color:M(),isDeferred:z().optional()})),wc=U(()=>V({color:M(),isFilled:z(),categoryName:M(),tokens:N(),percentage:N(),squareFullness:N()}));U(()=>V({categories:B(Cc()),totalTokens:N(),maxTokens:N(),rawMaxTokens:N(),percentage:N(),gridRows:B(B(wc())),model:M(),memoryFiles:B(V({path:M(),type:M(),tokens:N()})),mcpTools:B(V({name:M(),serverName:M(),tokens:N(),isLoaded:z().optional()})),deferredBuiltinTools:B(V({name:M(),tokens:N(),isLoaded:z()})).optional(),systemTools:B(V({name:M(),tokens:N()})).optional(),systemPromptSections:B(V({name:M(),tokens:N()})).optional(),agents:B(V({agentType:M(),source:M(),tokens:N()})),slashCommands:V({totalCommands:N(),includedCommands:N(),tokens:N()}).optional(),skills:V({totalSkills:N(),includedSkills:N(),tokens:N(),skillFrontmatter:B(V({name:M(),source:M(),tokens:N()}))}).optional(),autoCompactThreshold:N().optional(),isAutoCompactEnabled:z(),messageBreakdown:V({toolCallTokens:N(),toolResultTokens:N(),attachmentTokens:N(),assistantMessageTokens:N(),userMessageTokens:N(),toolCallsByType:B(V({name:M(),callTokens:N(),resultTokens:N()})),attachmentsByType:B(V({name:M(),tokens:N()}))}).optional(),apiUsage:V({input_tokens:N(),output_tokens:N(),cache_creation_input_tokens:N(),cache_read_input_tokens:N()}).nullable()}).describe(`Breakdown of current context window usage by category (system prompt, tools, messages, etc.).`));var Tc=U(()=>V({subtype:I(`rewind_files`),user_message_id:M(),dry_run:z().optional()}).describe(`Rewinds file changes made since a specific user message.`));U(()=>V({canRewind:z(),error:M().optional(),filesChanged:B(M()).optional(),insertions:N().optional(),deletions:N().optional()}).describe(`Result of a rewindFiles operation.`));var Ec=U(()=>V({subtype:I(`cancel_async_message`),message_uuid:M()}).describe(`Drops a pending async user message from the command queue by uuid. No-op if already dequeued for execution.`));U(()=>V({cancelled:z()}).describe(`Result of a cancel_async_message operation. cancelled=false means the message was not in the queue (already dequeued or never enqueued).`));var Dc=U(()=>V({subtype:I(`seed_read_state`),path:M(),mtime:N()}).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.`)),Oc=U(()=>V({subtype:I(`hook_callback`),callback_id:M(),input:ns(),tool_use_id:M().optional()}).describe(`Delivers a hook callback with its input data.`)),kc=U(()=>V({subtype:I(`mcp_message`),server_name:M(),message:pc()}).describe(`Sends a JSON-RPC message to a specific MCP server.`)),Ac=U(()=>V({subtype:I(`mcp_set_servers`),servers:F(M(),fo())}).describe(`Replaces the set of dynamically managed MCP servers.`));U(()=>V({added:B(M()),removed:B(M()),errors:F(M(),M())}).describe(`Result of replacing the set of dynamically managed MCP servers.`));var jc=U(()=>V({subtype:I(`reload_plugins`)}).describe(`Reloads plugins from disk and returns the refreshed session components.`));U(()=>V({commands:B(xs()),agents:B(Ss()),plugins:B(V({name:M(),path:M(),source:M().optional()})),mcpServers:B(ho()),error_count:N()}).describe(`Refreshed commands, agents, plugins, and MCP server status after reload.`));var Mc=U(()=>V({subtype:I(`mcp_reconnect`),serverName:M()}).describe(`Reconnects a disconnected or failed MCP server.`)),Nc=U(()=>V({subtype:I(`mcp_toggle`),serverName:M(),enabled:z()}).describe(`Enables or disables an MCP server.`)),Pc=U(()=>V({subtype:I(`stop_task`),task_id:M()}).describe(`Stops a running task.`)),Fc=U(()=>V({subtype:I(`apply_flag_settings`),settings:F(M(),P())}).describe(`Merges the provided settings into the flag settings layer, updating the active configuration.`)),Ic=U(()=>V({subtype:I(`get_settings`)}).describe(`Returns the effective merged settings and the raw per-source settings.`));U(()=>V({effective:F(M(),P()),sources:B(V({source:R([`userSettings`,`projectSettings`,`localSettings`,`flagSettings`,`policySettings`]),settings:F(M(),P())})).describe(`Ordered low-to-high priority — later entries override earlier ones.`),applied:V({model:M()}).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 Lc=U(()=>V({subtype:I(`elicitation`),mcp_server_name:M(),message:M(),mode:R([`form`,`url`]).optional(),url:M().optional(),elicitation_id:M().optional(),requested_schema:F(M(),P()).optional()}).describe(`Requests the SDK consumer to handle an MCP elicitation (user input request).`)),Rc=U(()=>V({action:R([`accept`,`decline`,`cancel`]),content:F(M(),P()).optional()}).describe(`Response from the SDK consumer for an elicitation request.`)),zc=U(()=>L([gc(),_c(),hc(),vc(),yc(),bc(),xc(),Sc(),Oc(),kc(),Tc(),Ec(),Dc(),Ac(),jc(),Mc(),Nc(),Pc(),Fc(),Ic(),Lc()])),Bc=U(()=>V({type:I(`control_request`),request_id:M(),request:zc()})),Vc=U(()=>V({subtype:I(`success`),request_id:M(),response:F(M(),P()).optional()})),Hc=U(()=>V({subtype:I(`error`),request_id:M(),error:M(),pending_permission_requests:B(or(()=>Bc())).optional()})),Uc=U(()=>V({type:I(`control_response`),response:L([Vc(),Hc()])})),Wc=U(()=>V({type:I(`control_cancel_request`),request_id:M()}).describe(`Cancels a currently open control request.`)),Gc=U(()=>V({type:I(`keep_alive`)}).describe(`Keep-alive message to maintain WebSocket connection.`)),Kc=U(()=>V({type:I(`update_environment_variables`),variables:F(M(),M())}).describe(`Updates environment variables at runtime.`));U(()=>L([dc(),zs(),Bs(),Ys(),Uc(),Bc(),Wc(),Gc()])),U(()=>L([Ps(),Bc(),Uc(),Gc(),Kc()])),Bn(),sr(),cr(),dt(),Ue(),U(()=>H.object({tool_name:H.string().describe(`The name of the tool requesting permission`),input:H.record(H.string(),H.unknown()).describe(`The input for the tool`),tool_use_id:H.string().optional().describe(`The unique tool use request ID`)}));var qc=U(()=>H.enum([`user_temporary`,`user_permanent`,`user_reject`]).optional().catch(void 0)),Jc=U(()=>H.object({behavior:H.literal(`allow`),updatedInput:H.record(H.string(),H.unknown()),updatedPermissions:H.array(w()).optional().catch(e=>{K(`Malformed updatedPermissions from SDK host ignored: ${e.error.issues[0]?.message??`unknown`}`,{level:`warn`})}),toolUseID:H.string().optional(),decisionClassification:qc()})),Yc=U(()=>H.object({behavior:H.literal(`deny`),message:H.string(),interrupt:H.boolean().optional(),toolUseID:H.string().optional(),decisionClassification:qc()})),Xc=U(()=>H.union([Jc(),Yc()]));function Zc(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:ot(e.toolPermissionContext,t)})),u(t));let a=Object.keys(e.updatedInput).length>0?e.updatedInput:n;return{...e,updatedInput:a,decisionReason:i}}else e.behavior===`deny`&&e.interrupt&&(K(`SDK permission prompt deny+interrupt: tool=${t.name} message=${e.message}`),r.abortController.abort());return{...e,decisionReason:i}}xr(),Rr(),Kr(),Ur(),Ni(),Ii(),v(),Jn(),ct(),Nn(),Vi(),Ge(),mt(),d(),ut(),Ji(),it(),de(),re(),De(),Wt(),$n(),nr(),ze(),Re(),ht(),We();var Qc=/\u2028|\u2029/g;function $c(e){return e.replace(Qc,e=>e===`\u2028`?`\\u2028`:`\\u2029`)}function el(e){return $c(Cr(e))}Ar(),Pr(),sr(),dt();var tl=`SandboxNetworkAccess`;function nl(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 rl(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 il=1e3,al=class{constructor(e,t){s(this,`input`,void 0),s(this,`replayUserMessages`,void 0),s(this,`structuredInput`,void 0),s(this,`pendingRequests`,new Map),s(this,`restoredWorkerState`,Promise.resolve(null)),s(this,`inputClosed`,!1),s(this,`unexpectedResponseCallback`,void 0),s(this,`resolvedToolUseIds`,new Set),s(this,`prependedLines`,[]),s(this,`onControlRequestSent`,void 0),s(this,`onControlRequestResolved`,void 0),s(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>il)){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})+`
2
+ `)}async*read(){let e=``,t=async function*(){for(;;){this.prependedLines.length>0&&(e=this.prependedLines.join(``)+e,this.prependedLines=[]);let t=e.indexOf(`
3
+ `);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=fa(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;K(`[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&&In(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)){K(`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`){K(`Ignoring unknown message type: ${t.type}`,{level:`warn`});return}return t.type===`control_request`?(t.request||ol(`Error: Missing request on control_request`),t):(t.type===`assistant`||t.type===`system`||t.message?.role!==`user`&&ol(`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){q(el(e)+`
4
+ `)}async sendRequest(e,t,n,r=X()){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 ce(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=sl(t.name,a,n,r,s.suggestions).then(e=>({source:`hook`,decision:e})),o=X();e?.(rl(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:nl(s.decisionReason),tool_use_id:a,agent_id:r.agentId},Xc(),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):Zc((await l).result,t,n,r):Zc(u.result,t,n,r)}catch(e){return Zc({behavior:`deny`,message:`Tool permission request failed: ${e}`,toolUseID:a},t,n,r)}finally{this.getPendingPermissionRequests().length===0&&Yi(`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},b(),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},Rc(),r)}catch{return{action:`cancel`}}}createSandboxAskCallback(){return async e=>{try{return(await this.sendRequest({subtype:`can_use_tool`,tool_name:tl,input:{host:e.host},tool_use_id:X(),description:`Allow network connection to ${e.host}?`},Xc())).behavior===`allow`}catch{return!1}}}async sendMcpMessage(e,t){return(await this.sendRequest({subtype:`mcp_message`,server_name:e,message:t},V({mcp_response:rr()}))).mcp_response}};function ol(e){console.error(e),process.exit(1)}async function sl(e,t,n,r,i){let a=r.getAppState().toolPermissionContext.mode,o=A(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){u(i);let e=ot(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(),_a();function cl(e,t={},n,i){if(r(process.env.CLAUDE_CODE_USE_CCR_V2)){let r=new Qa(e.href);return r.protocol===`wss:`?r.protocol=`https:`:r.protocol===`ws:`&&(r.protocol=`http:`),r.pathname=r.pathname.replace(/\/$/,``)+`/worker/events/stream`,new va(r,t,n,i)}if(e.protocol===`ws:`||e.protocol===`wss:`)return r(process.env.CLAUDE_CODE_POST_FOR_SESSION_INGRESS_V2)?new ga(e,t,n,i):new ha(e,t,n,i);throw Error(`Unsupported protocol: ${e.protocol}`)}mt(),Ar(),Qr(),i(),Tr(),Xr(),Ji(),_a(),o();var ll=class extends al{constructor(e,t,n){let i=new qa({encoding:`utf8`});super(i,n),s(this,`url`,void 0),s(this,`transport`,void 0),s(this,`inputStream`,void 0),s(this,`isBridge`,!1),s(this,`isDebug`,!1),s(this,`ccrClient`,null),s(this,`keepAliveTimer`,null),this.inputStream=i,this.url=new Qa(e);let a={},o=Ki();o?a.Authorization=`Bearer ${o}`:K(`[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=Ki();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=cl(this.url,a,W(),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&&q(e.endsWith(`
5
+ `)?e:e+`
6
+ `)}),this.transport.setOnClose(()=>{this.inputStream.end()}),r(process.env.CLAUDE_CODE_USE_CCR_V2)){if(!(this.transport instanceof va))throw Error(`CCR v2 requires SSETransport; check getTransportForUrl`);this.ccrClient=new ma(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 pa?e.reason:`unknown`}),J(Error(`CCRClient initialization failed: ${G(e)}`)),at(1,`other`)}),jr(async()=>this.ccrClient?.close()),Xn((e,t,n)=>this.ccrClient.writeInternalEvent(e,t,n)),Fn(()=>this.ccrClient.readInternalEvents(),()=>this.ccrClient.readSubagentInternalEvents());let t={started:`processing`,completed:`processed`};Zn((e,n)=>{this.ccrClient?.reportDelivery(e,t[n])}),qi((e,t)=>{this.ccrClient?.reportState(e,t)}),Gi(e=>{this.ccrClient?.reportMetadata(e)},{replayCurrent:!0})}this.transport.connect();let u=da().session_keepalive_interval_v2_ms;if(this.isBridge&&u>0&&(this.keepAliveTimer=setInterval(()=>{K(`[remote-io] keep_alive sent`),this.write({type:`keep_alive`}).catch(e=>{K(`[remote-io] keep_alive write failed: ${G(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$/,``)+`
7
+ `)})()}}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)&&q(el(e)+`
8
+ `)}close(){this.keepAliveTimer&&(clearInterval(this.keepAliveTimer),this.keepAliveTimer=null),this.transport.close(),this.inputStream.end()}};Li(),Ir(),Pi(),[...zi],Mr(),Ar();var ul=`[stdout-guard]`,dl=!1,$=``,fl=null;function pl(e){if(e.length===0)return!0;try{return JSON.parse(e),!0}catch{return!1}}function ml(){dl||(dl=!0,fl=process.stdout.write.bind(process.stdout),process.stdout.write=function(e,t,n){let r=typeof e==`string`?e:Buffer.from(e).toString(`utf-8`);$+=r;let i,a=!0;for(;(i=$.indexOf(`
9
+ `))!==-1;){let e=$.slice(0,i);$=$.slice(i+1),pl(e)?a=fl(e+`
10
+ `):(process.stderr.write(`${ul} ${e}\n`),K(`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&&(fl&&pl($)?fl($+`
11
+ `):process.stderr.write(`${ul} ${$}\n`),$=``),fl&&(process.stdout.write=fl,fl=null),dl=!1}))}Jr(),we(),Hi(),vn(),Oe(),On(),Fi(),yt(),ye(),te(),Be(),kt(),st(),Rt(),Ne(),An(),rn(),Da(),Qn(),Tr(),ri(),Bi(),pt(),Ar(),ut();function hl(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&&(K(`Exiting after ${n}ms of idle time`),j())},n))},stop(){i&&(clearTimeout(i),i=null)}}}na(),E(),_(),on(),en();function gl(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)?_l(t):t,uuid:n}}function _l(e){return e.some(vl)?e.map(e=>{if(!vl(e))return e;let t=e.source,n=typeof t.mediaType==`string`&&t.mediaType?t.mediaType:pn(e.source.data);return{...e,source:{type:`base64`,media_type:n,data:e.source.data}}}):e}function vl(e){return e.type!==`image`||e.source?.type!==`base64`?!1:!e.source.media_type}sr(),hr(),Ar(),i(),cr(),ra();var yl=3e4;function bl(e){K(`[bridge:inbound-attach] ${e}`)}var xl=U(()=>V({file_uuid:M(),file_name:M()})),Sl=U(()=>B(xl()));function Cl(e){if(typeof e!=`object`||!e||!(`file_attachments`in e))return[];let t=Sl().safeParse(e.file_attachments);return t.success?t.data:[]}function wl(e){return Wa(e).replace(/[^a-zA-Z0-9._-]/g,`_`)||`attachment`}function Tl(){return Ka(n(),`uploads`,W())}async function El(e){let t=aa();if(!t){bl(`skip: no oauth token`);return}let n;try{let r=`${ia()}/api/oauth/files/${encodeURIComponent(e.file_uuid)}/content`,i=await c.get(r,{headers:{Authorization:`Bearer ${t}`},responseType:`arraybuffer`,timeout:yl,validateStatus:()=>!0});if(i.status!==200){bl(`fetch ${e.file_uuid} failed: status=${i.status}`);return}n=Buffer.from(i.data)}catch(t){bl(`fetch ${e.file_uuid} threw: ${t}`);return}let r=wl(e.file_name),i=(e.file_uuid.slice(0,8)||X().slice(0,8)).replace(/[^a-zA-Z0-9_-]/g,`_`),a=Tl(),o=Ka(a,`${i}-${r}`);try{await Ja(a,{recursive:!0}),await Za(o,n)}catch(e){bl(`write ${o} failed: ${e}`);return}return bl(`resolved ${e.file_uuid} → ${o} (${n.length} bytes)`),o}async function Dl(e){if(e.length===0)return``;bl(`resolving ${e.length} attachment(s)`);let t=(await Promise.all(e.map(El))).filter(e=>e!==void 0);return t.length===0?``:t.map(e=>`@"${e}"`).join(` `)+` `}function Ol(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 kl(e,t){let n=Cl(e);return n.length===0?t:Ol(t,await Dl(n))}vi(),$e(),Tn(),Dt(),tn(),Pe(),ua(),Ma();function Al(e){if(e.toLowerCase().endsWith(`.jsonl`))return{sessionId:X(),ingressUrl:null,isUrl:!1,jsonlFile:e,isJsonlFile:!0};if(At(e))return{sessionId:e,ingressUrl:null,isUrl:!1,jsonlFile:null,isJsonlFile:!1};try{let t=new URL(e);return{sessionId:X(),ingressUrl:t.href,isUrl:!0,jsonlFile:null,isJsonlFile:!1}}catch{}return null}wi(),yn(),_t(),ve(),ue(),p(),S(),y(),Bt(),jn(),Qe(),sa(),Fa(),Ia(),Ar(),Pr();async function jl(){try{let e=await Ya(fn(),`utf-8`),t=Br().safeParse(Er(e));return t.success?t.data:(K(`Invalid known_marketplaces.json in zip cache: ${t.error.message}`,{level:`error`}),{})}catch{return{}}}async function Ml(e){await Xt(fn(),Cr(e,null,2))}async function Nl(e,t){let n=Ft();if(!n)return;let r=await Pl(t);r!==null&&await Xt(Ka(n,Ot(e)),r)}async function Pl(e){let t=[Ka(e,`.claude-plugin`,`marketplace.json`),Ka(e,`marketplace.json`),e];for(let e of t)try{return await Ya(e,`utf-8`)}catch{}return null}async function Fl(){let e=await g();for(let[t,n]of Object.entries(e))if(n.installLocation)try{await Nl(t,n.installLocation)}catch(e){K(`Failed to save marketplace JSON for ${t}: ${e}`)}await Ml({...await jl(),...e})}si(),Mr(),Ar(),Qr(),ri(),Ne(),Rt();async function Il(){let e=Ln();K(`installPluginsForHeadless: starting${e?` (zip cache mode)`:``}`);let t=await k();t&&(O(),ln(`headlessPluginInstall: seed marketplaces registered`)),e&&(await Nr().mkdir($t()),await Nr().mkdir(Vt()));let n=Object.keys(Ee()).length,r={marketplaces_installed:0,delisted_count:0},i=t;try{if(n===0)K(`installPluginsForHeadless: no marketplaces declared`);else{let t=await Zr(`headless_marketplace_reconcile`,()=>Va({skip:e?(e,t)=>!gt(t):void 0,onProgress:e=>{e.type===`installed`?K(`installPluginsForHeadless: installed marketplace ${e.name}`):e.type===`failed`&&K(`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&&K(`installPluginsForHeadless: skipped ${t.skipped.length} marketplace(s) unsupported by zip cache: ${t.skipped.join(`, `)}`);let n=t.installed.length+t.updated.length;n>0&&(O(),ln(`headlessPluginInstall: marketplaces reconciled`),i=!0),r.marketplaces_installed=n}e&&await Fl();let t=await wa();return r.delisted_count=t.length,t.length>0&&(i=!0),i&&ln(`headlessPluginInstall: plugins changed`),e&&jr(Mn),i}catch(e){return J(e),!1}finally{Y(`tengu_headless_plugin_install`,r)}}si(),Ar(),Qr(),mt(),Ji(),ri(),Xr(),d(),ut(),Mr(),xr(),We(),hr(),ze(),ht(),$n(),Pr(),i(),Ua(),An(),f(),tr(),ft(),Tr();var Ll=(Ui(),e(ea)),Rl=1e4,zl=new Set,Bl=[];function Vl(e){if(zl.has(e))return!1;if(zl.add(e),Bl.push(e),Bl.length>Rl){let e=Bl.splice(0,Bl.length-Rl);for(let t of e)zl.delete(t)}return!0}function Hl(e){return typeof e==`string`?[{type:`text`,text:e}]:e}function Ul(e){return e.length===1?e[0]:e.every(e=>typeof e==`string`)?e.join(`
12
+ `):e.flatMap(Hl)}function Wl(e,t){return t!==void 0&&t.mode===`prompt`&&t.workload===e.workload&&t.isMeta===e.isMeta}async function Gl(e,t,n,i,a,o,s,c){if(Rn.subscribe(e=>{sn(e,n),Ti()&&n(e=>{let t=e.settings,n=t.fastMode===!0&&!t.fastModePerSessionOptIn;return{...e,fastMode:n}})}),Ll&&!Ll.isProactiveActive()&&r(process.env.CLAUDE_CODE_PROACTIVE)&&Ll.activateProactive(`command`),typeof Bun<`u`&&setInterval(()=>{process.memoryUsage.rss()>350*1024*1024?Bun.gc(!0):Bun.gc(!1)},1e3).unref(),Qt(),dn(`runHeadless_entry`),await ya()&&await ba(),dn(`after_grove_check`),c.resumeSessionAt&&!c.resume){process.stderr.write(`Error: --resume-session-at requires --resume
13
+ `),j(1);return}if(c.rewindFiles&&!c.resume){process.stderr.write(`Error: --rewind-files requires --resume
14
+ `),j(1);return}if(c.rewindFiles&&e){process.stderr.write(`Error: --rewind-files is a standalone operation and cannot be used with a prompt
15
+ `),j(1);return}let l=tu(e,c);c.outputFormat===`stream-json`&&ml();let u=It.getSandboxUnavailableReason();if(u){if(It.isSandboxRequired()){process.stderr.write(`\nError: sandbox required but unavailable: ${u}\n sandbox.failIfUnavailable is set — refusing to start without a working sandbox.\n\n`),j(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(It.isSandboxingEnabled())try{await It.initialize(l.createSandboxAskCallback())}catch(e){process.stderr.write(`\n❌ Sandbox Error: ${G(e)}\n`),j(1,`other`);return}c.outputFormat===`stream-json`&&c.verbose&&T(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:X(),session_id:W()};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:X(),session_id:W()};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:X(),session_id:W()}}})();l.write(t)}),c.setupTrigger&&await Ie(c.setupTrigger),dn(`before_loadInitialMessages`);let d=t(),{messages:f,turnInterruptionState:p,agentSetting:m}=await eu(n,{continue:c.continue,teleport:c.teleport,resume:c.resume,resumeSessionAt:c.resumeSessionAt,forkSession:c.forkSession,outputFormat:c.outputFormat,sessionStartHooksPromise:c.sessionStartHooksPromise,restoredWorkerState:l.restoredWorkerState}),h=ee();if(h&&l.prependUserMessage(h),!c.agent&&!gr()&&m){let{agentDefinition:e}=Ra(m,void 0,{activeAgents:s,allAgents:s});if(e){if(n(t=>({...t,agent:e.agentType})),!c.systemPrompt&&!wn(e)){let t=e.getSystemPrompt();t&&(c.systemPrompt=t)}cn(e.agentType)}}if(f.length===0&&process.exitCode!==void 0)return;if(c.rewindFiles){let e=f.find(e=>e.uuid===c.rewindFiles);if(!e||e.type!==`user`){process.stderr.write(`Error: --rewind-files requires a user message UUID, but ${c.rewindFiles} is not a user message in this session\n`),j(1);return}let r=t(),i=await Xl(c.rewindFiles,r,n,!1);if(!i.canRewind){process.stderr.write(`Error: ${i.error||`Unexpected error`}\n`),j(1);return}process.stdout.write(`Files rewound to state at message ${c.rewindFiles}\n`),j(0);return}let g=typeof c.resume==`string`&&(!!At(c.resume)||c.resume.endsWith(`.jsonl`)),_=!!c.sdkUrl;if(!e&&!g&&!_){process.stderr.write(`Error: Input must be provided either through stdin or as a prompt argument when using --print
16
+ `),j(1);return}if(c.outputFormat===`stream-json`&&!c.verbose){process.stderr.write(`Error: When using --print, --output-format=stream-json requires --verbose
17
+ `),j(1);return}let v=lt(d.mcp.tools,d.toolPermissionContext),y=[...a,...v],b=Jl(c.sdkUrl?`stdio`:c.permissionPromptToolName,l,()=>t().mcp.tools,e=>{n(e=>({...e,attribution:{...e.attribution,permissionPromptCount:e.attribution.permissionPromptCount+1}})),Yi(`requires_action`,e)});c.permissionPromptToolName&&(y=y.filter(e=>!Ri(e,c.permissionPromptToolName))),Yr(),dn(`after_loadInitialMessages`),await ui(),dn(`after_modelStrings`);let x=c.outputFormat===`json`&&c.verbose,S=[],C;dn(`before_runHeadlessStreaming`);for await(let e of Kl(l,d.mcp.clients,[...i,...d.mcp.commands],y,f,b,o,t,n,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`&&(x&&S.push(e),C=e);switch(c.outputFormat){case`json`:if(!C||C.type!==`result`)throw Error(`No messages returned`);if(c.verbose){q(Cr(S)+`
18
+ `);break}q(Cr(C)+`
19
+ `);break;case`stream-json`:break;default:if(!C||C.type!==`result`)throw Error(`No messages returned`);switch(C.subtype){case`success`:q(C.result.endsWith(`
20
+ `)?C.result:C.result+`
21
+ `);break;case`error_during_execution`:q(`Execution error`);break;case`error_max_turns`:q(`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`:q(`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`:q(`Error: Failed to provide valid structured output after maximum retries.
22
+ Tip: Simplify your schema or check if the output format matches the expected structure.`)}}if(Lt(),qr())try{let{drainPendingExtraction:e}=await import(`./extractMemories-6OnMgL2S.js`);await e()}catch{}j(C?.type===`result`&&C?.is_error?1:0)}function Kl(e,n,i,o,s,c,l,u,d,f,p,g){let _=!1,v,ee=!1,y=null,b,x=e.outbound;process.on(`SIGINT`,()=>{$r(`info`,`shutdown_signal`,{signal:`SIGINT`}),b&&!b.signal.aborted&&b.abort(),at(0)}),jr(async()=>{let t={};for(let e of je(u()))h(e)&&(t[e.type]=(t[e.type]??0)+1);$r(`info`,`run_state_at_shutdown`,{run_active:_,run_phase:v,worker_status:Qi(),internal_events_pending:e.internalEventsPending,bg_tasks:t})}),Xi(e=>{(e==="default"||e===`acceptEdits`||e===`bypassPermissions`||e===`plan`||e===`auto`||e===`dontAsk`)&&x.enqueue({type:`system`,subtype:`status`,status:null,permissionMode:e,uuid:X(),session_id:W()})});let S={abortController:null,inflightPromise:null,lastEmitted:null,pendingSuggestion:null,pendingLastEmittedEntry:null},C;p.enableAuthStatus&&(C=hi.getInstance().subscribe(e=>{x.enqueue({type:`auth_status`,isAuthenticating:e.isAuthenticating,output:e.output,error:e.error,uuid:X(),session_id:W()})}));let te=e=>{let t=ca(e);t&&x.enqueue({type:`rate_limit_event`,rate_limit_info:t,uuid:X(),session_id:W()})};se.add(te);let w=s,re=_n(s,$a(),100),ce=Yt(100),ue=process.env.CLAUDE_CODE_RESUME_INTERRUPTED_TURN;g&&g.kind!==`none`&&ue&&(K(`[print.ts] Auto-resuming interrupted turn (kind: ${g.kind})`),$l(w,g.message),Cn({mode:`prompt`,value:g.message.message.content,uuid:X()}));let de=La().map(e=>{let t=e.value===null?`default`:e.value,n=t==="default"?Si():li(t),r=Pt(n),i=bi(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}}}),fe=p.userSpecifiedModel;function me(e,t){let n=Pn(e,ji(t));w.push(...n);for(let e of n)typeof e.message.content==`string`&&e.message.content.includes(`<local-command-stdout>`)&&x.enqueue({type:`user`,content:e.message.content,message:e.message,session_id:W(),parent_tool_use_id:null,uuid:e.uuid,timestamp:e.timestamp,isReplay:!0})}let T=[],ge=[],ve=new Set;function ye(t){for(let n of t){if(n.type!==`connected`||ve.has(n.name)||n.config.type===`sdk`)continue;let t=n.name;try{n.client.setRequestHandler(m,async(n,r)=>{ti(t,`Elicitation request received in print mode: ${Cr(n)}`);let i=n.params.mode===`url`?`url`:`form`;Y(`tengu_mcp_elicitation_shown`,{mode:i});let a=await he(t,n.params,r.signal);if(a)return ti(t,`Elicitation resolved by hook: ${Cr(a)}`),Y(`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 e.handleElicitation(t,n.params.message,s,r.signal,i,o,c),u=await rt(t,l,r.signal,i,c);return Y(`tengu_mcp_elicitation_response`,{mode:i,action:u.action}),u}),n.client.setNotificationHandler(le,e=>{let{elicitationId:n}=e.params;ti(t,`Elicitation completion notification: ${n}`),Ye({message:`MCP server "${t}" confirmed elicitation ${n} complete`,notificationType:`elicitation_complete`}),x.enqueue({type:`system`,subtype:`elicitation_complete`,mcp_server_name:t,elicitation_id:n,uuid:X(),session_id:W()})}),ve.add(t)}catch{}}}async function be(){let t=new Set(Object.keys(l)),n=new Set(T.map(e=>e.name)),r=Array.from(t).some(e=>!n.has(e)),i=Array.from(n).some(e=>!t.has(e)),a=T.some(e=>e.type===`pending`),o=T.some(e=>e.type===`failed`);if(r||i||a||o){for(let e of T)t.has(e.name)||e.type===`connected`&&await e.cleanup();let r=await ie(l,(t,n)=>e.sendMcpMessage(t,n));T=r.clients,ge=r.tools;let i=Fr([...n,...t]);d(e=>({...e,mcp:{...e.mcp,tools:[...e.mcp.tools.filter(e=>!i.some(t=>e.name.startsWith(Wr(t)))),...ge]}})),gn(T)}}be();let E={clients:[],tools:[],configs:{}},Se=e=>{let t=tt(e.toolPermissionContext,e.mcp.tools),n=Kt(Ea([...o,...ge,...E.tools],t,e.toolPermissionContext.mode),`name`);p.permissionPromptToolName&&(n=n.filter(e=>!Ri(e,p.permissionPromptToolName)));let r=mr();if(r&&!p.jsonSchema){let e=Mi(r);`tool`in e&&(n=[...n,e.tool])}return n},O=null,we=0;function Ee(){if(!O)return;let e=Math.min(we,w.length),t=w.slice(e).filter(e=>e.type===`user`||e.type===`assistant`);we=w.length,t.length>0&&O.writeMessages(t)}let De=Promise.resolve({response:{added:[],removed:[],errors:{}},sdkServersChanged:!1});function Oe(e){let t=async()=>{let t=new Set(T.map(e=>e.name)),n=await iu(e,{configs:l,clients:T,tools:ge},E,d);for(let e of Object.keys(l))delete l[e];if(Object.assign(l,n.newSdkState.configs),T=n.newSdkState.clients,ge=n.newSdkState.tools,E=n.newDynamicState,n.sdkServersChanged){let e=new Set(T.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)))),...ge]}}))}return{response:n.response,sdkServersChanged:n.sdkServersChanged}};return De=De.then(t,t),De}function Ne(){let e=u(),t=e.mcp.clients,n=Kt([...e.mcp.tools,...E.tools],`name`),r=new Set([...t.map(e=>e.name),...T.map(e=>e.name)]);return[...t,...T,...E.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`?Gt(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 Pe(){try{await Promise.all([Promise.resolve(),Zr(`headless_managed_settings_wait`,()=>xa())]),await Il()&&await He()}catch(e){J(e)}}let Ie=null;a()||(r(process.env.CLAUDE_CODE_SYNC_PLUGIN_INSTALL)?Ie=Pe():Pe());let Re=hl(()=>!_),ze=i,Be=f;async function Ve(){let{agentDefinitions:e}=await Ha(d);ze=await Te($a());let t=Be.filter(e=>e.source===`flagSettings`);Be=[...e.allAgents,...t]}async function He(){let{servers:e}=await pe(),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 Oe(t);r&&be(),K(`Headless MCP refresh: added=${n.added.length}, removed=${n.removed.length}`)}let Ue=Ba.subscribe(()=>{Jt(),Te($a()).then(e=>{ze=e})}),We=()=>{setTimeout(()=>{!Ll?.isProactiveActive()||Ll.isProactivePaused()||ee||(async()=>{let e=await zn({basePrompt:`<${ei}>${new Date().toLocaleTimeString()}</${ei}>`,currentDir:$a(),shouldCreate:()=>!ee});if(ee){await xt({commands:e});return}for(let t of e)Cn({...t,uuid:X()});Ge()})().catch(e=>{J(e),K(`[Proactive] failed to create headless tick: ${e}`,{level:`error`})})},0)};zt(()=>{b&&Tt(`now`).length>0&&b.abort(`interrupt`)});let Ge=async()=>{if(_)return;if(_=!0,v=void 0,Yi(`running`),Re.stop(),dn(`run_entry`),await be(),dn(`after_updateSdkMcp`),Ie){let e=parseInt(process.env.CLAUDE_CODE_SYNC_PLUGIN_INSTALL_TIMEOUT_MS||``,10);if(e>0){let t=ki(e).then(()=>`timeout`);await Promise.race([Ie,t])===`timeout`&&(J(Error(`CLAUDE_CODE_SYNC_PLUGIN_INSTALL: plugin installation timed out after ${e}ms`)),Y(`tengu_sync_plugin_install_timeout`,{timeout_ms:e}))}else await Ie;Ie=null,await Ve();let{setupPluginHookHotReload:t}=await import(`./loadPluginHooks-CWI0RMUx.js`);t()}let n=e=>e.agentId===void 0;try{let r,i=!1,a=async()=>{for(;r=Dn(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(;Wl(r,mn(n));)i.push(Dn(n));let a=await Un(i);if(i=a.attachmentCommands,i.length===0)continue;r=i[0],r.mode===`prompt`&&i.length>1&&(r={...r,value:Ul(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(p.replayUserMessages&&i.length>1)for(let e of i)e.uuid&&e.uuid!==r.uuid&&x.enqueue({type:`user`,content:e.value,message:{role:`user`,content:e.value},session_id:W(),parent_tool_use_id:null,uuid:e.uuid,isReplay:!0});let s=u(),l=[...s.mcp.clients,...T,...E.clients];ye(l);let f=Se(s);for(let e of o)In(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&&x.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:W(),uuid:X()})}let m=r.value,g=a.claimedCommands;if(e instanceof ll&&r.mode===`prompt`&&Y(`tengu_bridge_message_received`,{is_repl:!1}),S.abortController?.abort(),S.abortController=null,S.pendingSuggestion=null,S.pendingLastEmittedEntry=null,S.lastEmitted&&r.mode===`prompt`){let e=typeof m==`string`?m:m.find(e=>e.type===`text`)?.text;typeof e==`string`&&bn(S.lastEmitted.text,e,S.lastEmitted.emittedAt,S.lastEmitted.promptId,S.lastEmitted.generationRequestId),S.lastEmitted=null}b=et(),dn(`before_ask`),hn();let _=r,v=!1;try{if(await yi(_.workload??p.workload,async()=>{for await(let t of ka({commands:Kt([...ze,...s.mcp.commands],`name`),prompt:m,promptUuid:_.uuid,isMeta:_.isMeta,cwd:$a(),tools:f,verbose:p.verbose,mcpClients:l,thinkingConfig:p.thinkingConfig,maxTurns:p.maxTurns,maxBudgetUsd:p.maxBudgetUsd,taskBudget:p.taskBudget,canUseTool:c,userSpecifiedModel:fe,fallbackModel:p.fallbackModel,jsonSchema:mr()??p.jsonSchema,mutableMessages:w,getReadFileCache:()=>ce.size===0?re:Et(re,ce),setReadFileCache:e=>{re=e;for(let[e,t]of ce.entries()){let n=re.get(e);(!n||t.timestamp>n.timestamp)&&re.set(e,t)}ce.clear()},customSystemPrompt:p.systemPrompt,appendSystemPrompt:p.appendSystemPrompt,getAppState:u,setAppState:d,abortController:b,replayUserMessages:p.replayUserMessages,includePartialMessages:p.includePartialMessages,handleElicitation:(t,n,r)=>e.handleElicitation(t,n.message,void 0,r,n.mode,n.url,`elicitationId`in n?n.elicitationId:void 0),agents:Be,orphanedPermission:_.orphanedPermission,setSDKStatus:e=>{x.enqueue({type:`system`,subtype:`status`,status:e,session_id:W(),uuid:X()})}}))if(Ee(),t.type===`result`){v=!!t.is_error;for(let e of $i())x.enqueue(e);je(u()).some(e=>(e.type===`local_agent`||e.type===`local_workflow`)&&h(e))?y=t:(y=null,x.enqueue(t))}else{for(let e of $i())x.enqueue(e);x.enqueue(t)}}),v)await Le({commands:g,outcome:{type:`failed`,message:`ask() returned an error result`},currentDir:$a(),priority:`later`,workload:_.workload??p.workload});else{let e=await Le({commands:g,outcome:{type:`completed`},currentDir:$a(),priority:`later`,workload:_.workload??p.workload});for(let t of e)Cn({...t,uuid:X()})}}catch(e){throw await Le({commands:g,outcome:{type:`failed`,error:e},currentDir:$a(),priority:`later`,workload:_.workload??p.workload}),e}for(let e of o)In(e,`completed`);if(Ee(),O?.sendResult(),p.promptSuggestions&&!t(process.env.CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION)){S.abortController?.abort();let e=new AbortController;S.abortController=e;let t=kn();if(!t)Ht(`sdk_no_params`,void 0,void 0,`sdk`);else{let n={promise:null};n.promise=(async()=>{try{let n=await an(e,w,u,t,`sdk`);if(!n||e.signal.aborted)return;let r={type:`prompt_suggestion`,suggestion:n.suggestion,uuid:X(),session_id:W()},i={text:n.suggestion,emittedAt:Date.now(),promptId:n.promptId,generationRequestId:n.generationRequestId};y?(S.pendingSuggestion=r,S.pendingLastEmittedEntry={text:i.text,promptId:i.promptId,generationRequestId:i.generationRequestId}):(S.lastEmitted=i,x.enqueue(r))}catch(e){if(e instanceof Error&&(e.name===`AbortError`||e.name===`APIUserAbortError`)){Ht(`aborted`,void 0,void 0,`sdk`);return}J(Dr(e))}finally{S.inflightPromise===n.promise&&(S.inflightPromise=null)}})(),S.inflightPromise=n.promise}}Lt(),ae(),Qt()}};do{for(let e of $i())x.enqueue(e);v=`draining_commands`,await a(),i=!1;{let e=je(u()).some(e=>h(e)),t=mn(n)!==void 0;(e||t)&&(i=!0,t||(v=`waiting_for_agents`,await ki(100)))}}while(i);y&&(x.enqueue(y),y=null,S.pendingSuggestion&&(x.enqueue(S.pendingSuggestion),S.pendingLastEmittedEntry&&(S.lastEmitted={...S.pendingLastEmittedEntry,emittedAt:Date.now()},S.pendingLastEmittedEntry=null),S.pendingSuggestion=null))}catch(t){try{await e.write({type:`result`,subtype:`error_during_execution`,duration_ms:0,duration_api_ms:0,is_error:!0,num_turns:0,stop_reason:null,session_id:W(),total_cost_usd:0,usage:Zi,modelUsage:{},permission_denials:[],uuid:X(),errors:[G(t),...ni().map(e=>e.error)]})}catch{}S.abortController?.abort(),j(1);return}finally{if(v=`finally_flush`,await e.flushInternalEvents(),v=`finally_post_flush`,!ke()){Yi(`idle`);for(let e of $i())x.enqueue(e)}_=!1,Re.start()}if(Ll?.isProactiveActive()&&!Ll.isProactivePaused()&&mn(n)===void 0&&!ee){We();return}if(mn(n)!==void 0){Ge();return}ee&&(S.inflightPromise&&await Promise.race([S.inflightPromise,ki(5e3)]),S.abortController?.abort(),S.abortController=null,await Ce(),Ue(),C?.(),se.delete(te),x.done())},k=function(e,t){x.enqueue({type:`control_response`,response:{subtype:`success`,request_id:e.request_id,response:t}})},A=function(e,t){x.enqueue({type:`control_response`,response:{subtype:`error`,request_id:e.request_id,error:t}})},qe=new Set;e.setUnexpectedResponseCallback(async e=>{await nu({message:e,setAppState:d,handledToolUseIds:qe,onEnqueued:()=>{Ge()}})});let Xe=new Map,Qe=new Map,$e=new Set,it=new Map,ot=null;return(async()=>{let t=!1;$r(`info`,`cli_message_loop_started`);for await(let r of e.structuredInput){let a=`uuid`in r?r.uuid:void 0;if(a&&r.type!==`user`&&r.type!==`control_response`&&In(a,`completed`),r.type===`control_request`){let a=r,o=a.request;if(a.request.subtype===`interrupt`)d(e=>({...e,attribution:{...e.attribution,escapeCount:e.attribution.escapeCount+1}})),b&&b.abort(),S.abortController?.abort(),S.abortController=null,S.lastEmitted=null,S.pendingSuggestion=null,k(a);else if(o.subtype===`end_session`){K(`[print.ts] end_session received, reason=${o.reason??`unspecified`}`),b&&b.abort(),S.abortController?.abort(),S.abortController=null,S.lastEmitted=null,S.pendingSuggestion=null,k(a);break}else if(a.request.subtype===`initialize`){if(a.request.sdkMcpServers&&a.request.sdkMcpServers.length>0)for(let e of a.request.sdkMcpServers)l[e]={type:`sdk`,name:e};await Yl(a.request,a.request_id,t,x,i,de,e,!!p.enableAuthStatus,p,f,u),a.request.promptSuggestions&&d(e=>e.promptSuggestionEnabled?e:{...e,promptSuggestionEnabled:!0}),a.request.agentProgressSummaries&&yr(!0),t=!0,Zt()&&Ge()}else if(a.request.subtype===`set_permission_mode`){let e=a.request;d(t=>({...t,toolPermissionContext:Zl(e,a.request_id,t.toolPermissionContext,x)}))}else if(a.request.subtype===`set_model`){let e=a.request.model??`default`,t=e==="default"?Si():e;fe=t,fr(t),Wi({model:t}),me(e,t),k(a)}else if(a.request.subtype===`set_max_thinking_tokens`)a.request.max_thinking_tokens===null?p.thinkingConfig=void 0:a.request.max_thinking_tokens===0?p.thinkingConfig={type:`disabled`}:p.thinkingConfig={type:`enabled`,budgetTokens:a.request.max_thinking_tokens},k(a);else if(a.request.subtype===`mcp_status`)k(a,{mcpServers:Ne()});else if(a.request.subtype===`get_context_usage`)try{let e=u(),t=await Pa({messages:w,getAppState:u,options:{mainLoopModel:Oi(),tools:Se(e),agentDefinitions:e.agentDefinitions,customSystemPrompt:p.systemPrompt,appendSystemPrompt:p.appendSystemPrompt}});k(a,{...t})}catch(e){A(a,G(e))}else if(a.request.subtype===`mcp_message`){let e=a.request,t=T.find(t=>t.name===e.server_name);t&&t.type===`connected`&&t.client?.transport?.onmessage&&t.client.transport.onmessage(e.message),k(a)}else if(a.request.subtype===`rewind_files`){let e=u(),t=await Xl(a.request.user_message_id,e,d,a.request.dry_run??!1);t.canRewind||a.request.dry_run?k(a,t):A(a,t.error??`Unexpected error`)}else if(a.request.subtype===`cancel_async_message`){let e=a.request.message_uuid,t=nn(t=>t.uuid===e);k(a,{cancelled:t.length>0})}else if(a.request.subtype===`seed_read_state`){try{let e=Gr(a.request.path),t=Math.floor((await Xa(e)).mtimeMs);if(t<=a.request.mtime){let n=await Ya(e,`utf-8`),r=(n.charCodeAt(0)===65279?n.slice(1):n).replaceAll(`\r
23
+ `,`
24
+ `);ce.set(e,{content:r,timestamp:t,offset:void 0,limit:void 0})}}catch{}k(a)}else if(a.request.subtype===`mcp_set_servers`){let{response:e,sdkServersChanged:t}=await Oe(a.request.servers);k(a,e),t&&be()}else if(a.request.subtype===`reload_plugins`)try{let e=await Ha(d),t=Be.filter(e=>e.source===`flagSettings`);Be=[...e.agentDefinitions.allAgents,...t];let n=[],[r,i,o]=await Promise.allSettled([Te($a()),He(),Nt()]);r.status===`fulfilled`?ze=r.value:J(r.reason),i.status===`rejected`&&J(i.reason),o.status===`fulfilled`?n=o.value.enabled.map(e=>({name:e.name,path:e.path,source:e.source})):J(o.reason),k(a,{commands:ze.filter(e=>e.userInvocable!==!1).map(e=>({name:Je(e),description:xe(e),argumentHint:e.argumentHint||``})),agents:Be.map(e=>({name:e.agentType,description:e.whenToUse,model:e.model===`inherit`?void 0:e.model})),plugins:n,mcpServers:Ne(),error_count:e.error_count})}catch(e){A(a,G(e))}else if(a.request.subtype===`mcp_reconnect`){let e=u(),{serverName:t}=a.request;ve.delete(t);let r=Ke(t)??n.find(e=>e.name===t)?.config??T.find(e=>e.name===t)?.config??E.clients.find(e=>e.name===t)?.config??e.mcp.clients.find(e=>e.name===t)?.config??null;if(!r)A(a,`Server not found: ${t}`);else{let e=await Ze(t,r),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=>Kn(e,t)),...e.commands],resources:e.resources&&e.resources.length>0?{...r.mcp.resources,[t]:e.resources}:ta(r.mcp.resources,t)}})),E={...E,clients:[...E.clients.filter(e=>e.name!==t),e.client],tools:[...E.tools.filter(e=>!e.name?.startsWith(n)),...e.tools]},e.client.type===`connected`)ye([e.client]),k(a);else{let t=e.client.type===`failed`?e.client.error??`Connection failed`:`Server status: ${e.client.type}`;A(a,t)}}}else if(a.request.subtype===`mcp_toggle`){let e=u(),{serverName:t,enabled:r}=a.request;ve.delete(t);let i=Ke(t)??n.find(e=>e.name===t)?.config??T.find(e=>e.name===t)?.config??E.clients.find(e=>e.name===t)?.config??e.mcp.clients.find(e=>e.name===t)?.config??null;if(!i)A(a,`Server not found: ${t}`);else if(r){Me(t,!0);let e=await Ze(t,i),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=>Kn(e,t)),...e.commands],resources:e.resources&&e.resources.length>0?{...r.mcp.resources,[t]:e.resources}:ta(r.mcp.resources,t)}})),e.client.type===`connected`)ye([e.client]),k(a);else{let t=e.client.type===`failed`?e.client.error??`Connection failed`:`Server status: ${e.client.type}`;A(a,t)}}else{Me(t,!1);let r=[...n,...T,...E.clients,...e.mcp.clients].find(e=>e.name===t);r&&r.type===`connected`&&await ne(t,i);let o=Wr(t);d(e=>({...e,mcp:{...e.mcp,clients:e.mcp.clients.map(e=>e.name===t?{name:t,type:`disabled`,config:i}:e),tools:D(e.mcp.tools,e=>e.name?.startsWith(o)),commands:D(e.mcp.commands,e=>Kn(e,t)),resources:ta(e.mcp.resources,t)}})),k(a)}}else if(o.subtype===`mcp_authenticate`){let e=o.serverName,t=u(),r=Ke(e)??n.find(t=>t.name===e)?.config??t.mcp.clients.find(t=>t.name===e)?.config??null;if(!r)A(a,`Server not found: ${e}`);else if(r.type!==`sse`&&r.type!==`http`)A(a,`Server type "${r.type}" does not support OAuth authentication`);else try{Xe.get(e)?.abort();let t=new AbortController;Xe.set(e,t);let n,i=new Promise(e=>{n=e}),o=un(e,r,e=>n(e),t.signal,{skipBrowserOpen:!0,onWaitingForCallback:t=>{Qe.set(e,t)}}),s=await Promise.race([i,o.then(()=>null)]);s?k(a,{authUrl:s,requiresUserAction:!0}):k(a,{requiresUserAction:!1}),it.set(e,o),o.then(async()=>{if(_e(e)||$e.has(e))return;let t=await Ze(e,r),n=Wr(e);d(r=>({...r,mcp:{...r.mcp,clients:r.mcp.clients.map(n=>n.name===e?t.client:n),tools:[...D(r.mcp.tools,e=>e.name?.startsWith(n)),...t.tools],commands:[...D(r.mcp.commands,t=>Kn(t,e)),...t.commands],resources:t.resources&&t.resources.length>0?{...r.mcp.resources,[e]:t.resources}:ta(r.mcp.resources,e)}})),E={...E,clients:[...E.clients.filter(t=>t.name!==e),t.client],tools:[...E.tools.filter(e=>!e.name?.startsWith(n)),...t.tools]}}).catch(t=>{K(`MCP OAuth failed for ${e}: ${t}`,{level:`error`})}).finally(()=>{Xe.get(e)===t&&(Xe.delete(e),Qe.delete(e),$e.delete(e),it.delete(e))})}catch(e){A(a,G(e))}}else if(o.subtype===`mcp_oauth_callback_url`){let e=o.serverName,t=o.callbackUrl,n=Qe.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(a,`Invalid callback URL: missing authorization code. Please paste the full redirect URL including the code parameter.`);else{$e.add(e),n(t);let r=it.get(e);if(r)try{await r,k(a)}catch(e){A(a,e instanceof Error?e.message:`OAuth authentication failed`)}else k(a)}}else A(a,`No active OAuth flow for server: ${e}`)}else if(o.subtype===`claude_authenticate`){let e=o.loginWithClaudeAi;ot?.service.cleanup(),Y(`tengu_oauth_flow_start`,{loginWithClaudeAi:e??!0});let t=new Sa,n,r=new Promise(e=>{n=e}),i=t.startOAuthFlow(async(e,t)=>{n({manualUrl:e,automaticUrl:t})},{loginWithClaudeAi:e??!0,skipBrowserOpen:!0}).then(async t=>{await Ca(t),Y(`tengu_oauth_success`,{loginWithClaudeAi:e??!0})}).finally(()=>{t.cleanup(),ot?.service===t&&(ot=null)});ot={service:t,flow:i},i.catch(e=>K(`claude_authenticate flow ended: ${e}`,{level:`info`}));try{let{manualUrl:e,automaticUrl:t}=await Promise.race([r,i.then(()=>{throw Error(`OAuth flow completed without producing auth URLs`)})]);k(a,{manualUrl:e,automaticUrl:t})}catch(e){A(a,G(e))}}else if(o.subtype===`claude_oauth_callback`||o.subtype===`claude_oauth_wait_for_completion`)if(!ot)A(a,`No active claude_authenticate flow`);else{o.subtype===`claude_oauth_callback`&&ot.service.handleManualAuthCodeInput({authorizationCode:o.authorizationCode,state:o.state});let{flow:e}=ot;e.then(()=>{let e=_i();k(a,{account:{email:e?.email,organization:e?.organization,subscriptionType:e?.subscription,tokenSource:e?.tokenSource,apiKeySource:e?.apiKeySource,apiProvider:gi()}})},e=>A(a,G(e)))}else if(o.subtype===`mcp_clear_auth`){let e=o.serverName,t=u(),r=Ke(e)??n.find(t=>t.name===e)?.config??t.mcp.clients.find(t=>t.name===e)?.config??null;if(!r)A(a,`Server not found: ${e}`);else if(r.type!==`sse`&&r.type!==`http`)A(a,`Cannot clear auth for server type "${r.type}"`);else{await wt(e,r);let t=await Ze(e,r),n=Wr(e);d(r=>({...r,mcp:{...r.mcp,clients:r.mcp.clients.map(n=>n.name===e?t.client:n),tools:[...D(r.mcp.tools,e=>e.name?.startsWith(n)),...t.tools],commands:[...D(r.mcp.commands,t=>Kn(t,e)),...t.commands],resources:t.resources&&t.resources.length>0?{...r.mcp.resources,[e]:t.resources}:ta(r.mcp.resources,e)}})),k(a,{})}}else if(a.request.subtype===`apply_flag_settings`){let e=Oi(),t=dr()??{},n=a.request.settings,r={...t,...n};for(let e of Object.keys(r))r[e]===null&&delete r[e];_r(r),Rn.notifyChange(`flagSettings`),`model`in n&&(n.model==null?fr(void 0):fr(String(n.model)));let i=Oi();if(i!==e){fe=i;let e=n.model?String(n.model):`default`;Wi({model:i}),me(e,i)}k(a)}else if(a.request.subtype===`get_settings`){let e=Oi();k(a,{...zr(),applied:{model:e}})}else if(a.request.subtype===`stop_task`){let{task_id:e}=a.request;try{await Ae(e,{getAppState:u,setAppState:d}),k(a,{})}catch(e){A(a,G(e))}}else if(o.subtype===`generate_session_title`){let e=o.description,t=o.persist,n=(b&&!b.signal.aborted?b:et()).signal;(async()=>{try{let r=await la(e,n);if(r&&t)try{En(W(),r)}catch(e){J(e)}k(a,{title:r})}catch(e){A(a,G(e))}})()}else if(o.subtype===`side_question`){let e=o.question;(async()=>{try{let t=kn(),n=t?{...t,toolUseContext:{...t.toolUseContext,abortController:et()}}:await Aa({tools:Se(u()),commands:ze,mcpClients:[...u().mcp.clients,...T,...E.clients],messages:w,readFileState:re,getAppState:u,setAppState:d,customSystemPrompt:p.systemPrompt,appendSystemPrompt:p.appendSystemPrompt,thinkingConfig:p.thinkingConfig,agents:Be}),r=await Na({question:e,cacheSafeParams:n});k(a,{response:r.response})}catch(e){A(a,G(e))}})()}else if(a.request.subtype===`set_proactive`)a.request.enabled?Ll.isProactiveActive()||(Ll.activateProactive(`command`),We()):Ll.deactivateProactive(),k(a);else if(o.subtype===`remote_control`)if(o.enabled)if(O)k(a,{session_url:Fe(O.bridgeSessionId,O.sessionIngressUrl),connect_url:ja(O.environmentId,O.sessionIngressUrl),environment_id:O.environmentId});else{let t;try{let{initReplBridge:n}=await import(`./initReplBridge-DyScxedy.js`),r=await n({onInboundMessage(e){let t=gl(e);if(!t)return;let{content:n,uuid:r}=t;Cn({value:n,mode:`prompt`,uuid:r,skipSlashCommands:!0}),Ge()},onPermissionResponse(t){e.injectControlResponse(t)},onInterrupt(){b?.abort()},onSetModel(e){let t=e==="default"?Si():e;fe=t,fr(t)},onSetMaxThinkingTokens(e){e===null?p.thinkingConfig=void 0:e===0?p.thinkingConfig={type:`disabled`}:p.thinkingConfig={type:`enabled`,budgetTokens:e}},onStateChange(e,n){e===`failed`&&(t=n),K(`[bridge:sdk] State change: ${e}${n?` — ${n}`:``}`),x.enqueue({type:`system`,subtype:`bridge_state`,state:e,detail:n,uuid:X(),session_id:W()})},initialMessages:w.length>0?w:void 0});r?(O=r,we=w.length,e.setOnControlRequestSent(e=>{r.sendControlRequest(e)}),e.setOnControlRequestResolved(e=>{r.sendControlCancelRequest(e)}),k(a,{session_url:Fe(r.bridgeSessionId,r.sessionIngressUrl),connect_url:ja(r.environmentId,r.sessionIngressUrl),environment_id:r.environmentId})):A(a,t??`Remote Control initialization failed`)}catch(e){A(a,G(e))}}else O&&(e.setOnControlRequestSent(void 0),e.setOnControlRequestResolved(void 0),await O.teardown(),O=null),k(a);else A(a,`Unsupported control request subtype: ${a.request.subtype}`);continue}else if(r.type===`control_response`){p.replayUserMessages&&x.enqueue(r);continue}else if(r.type===`keep_alive`)continue;else if(r.type===`update_environment_variables`)continue;else if(r.type===`assistant`||r.type===`system`){let e=oa([r]);w.push(...e),r.type===`assistant`&&p.replayUserMessages&&x.enqueue(r);continue}if(r.type!==`user`)continue;let o=r;if(t=!0,o.uuid){let e=W(),t=await nt(e,o.uuid);if(t||zl.has(o.uuid)){K(`Skipping duplicate user message: ${o.uuid}`),p.replayUserMessages&&(K(`Sending acknowledgment for duplicate user message: ${o.uuid}`),x.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&&In(o.uuid,`completed`);continue}Vl(o.uuid)}Cn({mode:`prompt`,value:await kl(o,o.message.content),uuid:o.uuid,priority:o.priority}),d(e=>({...e,attribution:qt(e.attribution,e=>{oe(e).catch(e=>{K(`Attribution: Failed to save snapshot: ${e}`)})})})),Ge()}ee=!0,_||(S.inflightPromise&&await Promise.race([S.inflightPromise,ki(5e3)]),S.abortController?.abort(),S.abortController=null,await Ce(),Ue(),C?.(),se.delete(te),x.done())})(),x}function ql(e){let t=async(n,r,i,a,o,s)=>{let c=s??await ce(n,r,i,a,o);if(c.behavior===`allow`||c.behavior===`deny`)return c;let{signal:l,cleanup:u}=Wn(i.abortController.signal);if(l.aborted)return u(),{behavior:`deny`,message:`Permission prompt was aborted.`,decisionReason:{type:`permissionPromptTool`,permissionPromptToolName:n.name,toolResult:void 0}};let d=new Promise(e=>{l.addEventListener(`abort`,()=>e(`aborted`),{once:!0})}),f=e.call({tool_name:n.name,input:r,tool_use_id:o},i,t,a),p=await Promise.race([f,d]);if(u(),p===`aborted`||l.aborted)return{behavior:`deny`,message:`Permission prompt was aborted.`,decisionReason:{type:`permissionPromptTool`,permissionPromptToolName:n.name,toolResult:void 0}};let m=p,h=e.mapToolResultToToolResultBlockParam(m.data,`1`);if(!h.content||!Array.isArray(h.content)||!h.content[0]||h.content[0].type!==`text`||typeof h.content[0].text!=`string`)throw Error(`Permission prompt tool returned an invalid result. Expected a single text block param with type="text" and a string text value.`);return Zc(Xc().parse(oi(h.content[0].text)),e,r,i)};return t}function Jl(e,t,n,r){if(e===`stdio`)return t.createCanUseTool(r);if(!e)return async(e,t,n,r,i,a)=>a??await ce(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=>Ri(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`),j(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`),j(1),Error(t)}i=ql(r)}return i(t,r,a,o,s,c)}}async function Yl(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=Mt(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 Sn(Sr()),p=_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 m={commands:i.filter(e=>e.userInvocable!==!1).map(e=>({name:Je(e),description:xe(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:p?.email,organization:p?.organization,subscriptionType:p?.subscription,tokenSource:p?.tokenSource,apiKeySource:p?.apiKeySource,apiProvider:gi()},pid:process.pid};if(Ti()&&Di()){let e=u();m.fast_mode_state=fi(c.userSpecifiedModel??null,e.fastMode)}if(r.enqueue({type:`control_response`,response:{subtype:`success`,request_id:t,response:m}}),s){let e=hi.getInstance().getStatus();e&&r.enqueue({type:`auth_status`,isAuthenticating:e.isAuthenticating,output:e.output,error:e.error,uuid:X(),session_id:W()})}}async function Xl(e,t,n,r){if(!bt())return{canRewind:!1,error:`File rewinding is not enabled.`,filesChanged:[]};if(!Yn(t.fileHistory,e))return{canRewind:!1,error:`No file checkpoint found for this message.`,filesChanged:[]};if(r){let n=await Hn(t.fileHistory,e);return{canRewind:!0,filesChanged:n?.filesChanged??[],insertions:n?.insertions,deletions:n?.deletions}}try{await He(e=>n(t=>({...t,fileHistory:e(t.fileHistory)})),e)}catch(e){return{canRewind:!1,error:`Failed to rewind: ${G(e)}`,filesChanged:[]}}return{canRewind:!0,filesChanged:[]}}function Zl(e,t,n,r){if(e.mode===`bypassPermissions`){if(C())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`&&!Ve()){let e=vt();return r.enqueue({type:`control_response`,response:{subtype:`error`,request_id:t,error:e?`Cannot set permission mode to auto: ${qn(e)}`:`Cannot set permission mode to auto`}}),n}return r.enqueue({type:`control_response`,response:{subtype:`success`,request_id:t,response:{mode:e.mode}}}),{...be(n.mode,e.mode,n),mode:e.mode}}function Ql(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:W(),total_cost_usd:0,usage:Zi,modelUsage:{},permission_denials:[],uuid:X(),errors:[e]};process.stdout.write(Cr(t)+`
25
+ `)}else process.stderr.write(e+`
26
+ `)}function $l(e,t){let n=e.findIndex(e=>e.uuid===t.uuid);n!==-1&&e.splice(n,2)}async function eu(e,t){let n=!ur();if(t.continue)try{Y(`tengu_continue_print`,{});let r=await x(void 0,void 0);if(r)return t.forkSession||r.sessionId&&(vr(fe(r.sessionId),r.fullPath?Ga(r.fullPath):null),n&&await xn()),za(r,e),Ut(t.forkSession?{...r,worktreeSession:void 0}:r),{messages:r.messages,turnInterruptionState:r.turnInterruptionState,agentSetting:r.agentSetting}}catch(e){return J(e),j(1),{messages:[]}}if(t.teleport)try{if(!Ct(`allow_remote_sessions`))throw Error(`Remote sessions are disabled by your organization's policy.`);if(Y(`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-C9KRE4X8.js`);await i();let a=await r(t.teleport),{branchError:o}=await e(a.branch);return{messages:n(a.log,o)}}catch(e){return J(e),j(1),{messages:[]}}if(t.resume)try{Y(`tengu_resume_print`,{});let i=Al(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`),Ql(e,t.outputFormat),j(1),{messages:[]}}if(r(process.env.CLAUDE_CODE_USE_CCR_V2)){let[,n]=await Promise.all([St(i.sessionId),t.restoredWorkerState]);n&&(e(Oa(n)),typeof n.model==`string`&&fr(n.model))}else i.isUrl&&i.ingressUrl&&r(process.env.ENABLE_SESSION_PERSISTENCE)&&await Gn(i.sessionId,i.ingressUrl);let a=await x(i.sessionId,i.jsonlFile||void 0);if(!a||a.messages.length===0)return i.isUrl||r(process.env.CLAUDE_CODE_USE_CCR_V2)?{messages:await(t.sessionStartHooksPromise??Vn(`startup`))}:(Ql(`No conversation found with session ID: ${i.sessionId}`,t.outputFormat),j(1),{messages:[]});if(t.resumeSessionAt){let e=a.messages.findIndex(e=>e.uuid===t.resumeSessionAt);if(e<0)return Ql(`No message found with message.uuid of: ${t.resumeSessionAt}`,t.outputFormat),j(1),{messages:[]};a.messages=e>=0?a.messages.slice(0,e+1):[]}return!t.forkSession&&a.sessionId&&(vr(fe(a.sessionId),a.fullPath?Ga(a.fullPath):null),n&&await xn()),za(a,e),Ut(t.forkSession?{...a,worktreeSession:void 0}:a),{messages:a.messages,turnInterruptionState:a.turnInterruptionState,agentSetting:a.agentSetting}}catch(e){return J(e),Ql(e instanceof Error?`Failed to resume session: ${e.message}`:`Failed to resume session with --print mode`,t.outputFormat),j(1),{messages:[]}}return{messages:await(t.sessionStartHooksPromise??Vn(`startup`))}}function tu(e,t){let n;return n=typeof e==`string`?e.trim()===``?qe([]):qe([Cr({type:`user`,content:e,uuid:``,session_id:``,message:{role:`user`,content:e},parent_tool_use_id:null})]):e,t.sdkUrl?new ll(t.sdkUrl,n,t.replayUserMessages):new al(n,t.replayUserMessages)}async function nu({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(K(`handleOrphanedPermissionResponse: received orphaned control_response for toolUseID=${t} request_id=${i.request_id}`),r.has(t))return K(`handleOrphanedPermissionResponse: skipping duplicate orphaned permission for toolUseID=${t} (already handled)`),!1;let a=await jt(t);return a?(r.add(t),K(`handleOrphanedPermissionResponse: enqueuing orphaned permission for toolUseID=${t} messageID=${a.message.id}`),Cn({mode:`orphaned-permission`,value:[],orphanedPermission:{permissionResult:e,assistantMessage:a}}),n?.(),!0):(K(`handleOrphanedPermissionResponse: no unresolved tool_use found for toolUseID=${t} (already resolved in transcript)`),!1)}return!1}function ru(e){return{...e,scope:`dynamic`}}async function iu(e,t,n,r){let{allowed:i,blocked:a}=Xe(e),o={};for(let e of a)o[e]=`Blocked by enterprise policy (allowedMcpServers/deniedMcpServers)`;let s={},c={};for(let[e,t]of Object.entries(i))t.type===`sdk`?s[e]=t:c[e]=t;let l=new Set(Object.keys(t.configs)),u=new Set(Object.keys(s)),d=[],f=[],p={...t.configs},m=[...t.clients],h=[...t.tools];for(let e of l)if(!u.has(e)){let t=m.find(t=>t.name===e);t&&t.type===`connected`&&await t.cleanup(),m=m.filter(t=>t.name!==e);let n=`mcp__${e}__`;h=h.filter(e=>!e.name.startsWith(n)),delete p[e],f.push(e)}for(let[e,t]of Object.entries(s))if(!l.has(e)){p[e]=t;let n={type:`pending`,name:e,config:{...t,scope:`dynamic`}};m=[...m,n],d.push(e)}let g=await au(c,n,r);return{response:{added:[...d,...g.response.added],removed:[...f,...g.response.removed],errors:{...o,...g.response.errors}},newSdkState:{configs:p,clients:m,tools:h},newDynamicState:g.newState,sdkServersChanged:d.length>0||f.length>0}}async function au(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||!Se(r,ru(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){J(e)}await ne(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=ru(n);if(n.type===`sdk`){l.push(t);continue}try{let e=await me(t,r);if(d.push(e),e.type===`connected`){let t=await er(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,J(n)}}let p={};for(let t of i){let n=e[t];n&&(p[t]=ru(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{Gl as runHeadless};
@@ -0,0 +1 @@
1
+ import{a as e}from"./rolldown-runtime-DaDcL9Zw.js";import{Ca as t,Gg as n,Jm as r,RC as i,Wg as a,Xm as o,Ya as s,Ym as c,_p as l,ba as u,gp as d,nl as f,qm as p,rl as m,wa as h,zC as g,za as _}from"./loadAgentsDir-mcRW90aq.js";import{I as v,fi as y,t as b}from"./src-P_wYS_NJ2.js";import{t as x}from"./jsx-runtime-Bb4Xn-E0.js";import{A as S,P as C,R as w}from"./debug-Dr1SjdXn.js";import{g as T,n as E}from"./settings-DiBMs2gM.js";import{n as D,r as O}from"./analytics-DJobLaWP.js";import{bt as k,xt as A}from"./prompt-DIlq8NTy.js";import{randomUUID as j}from"crypto";y(),b(),r(),l(),o();var M=x();function N({input:e,progress:t,verbose:n}){return(0,M.jsxs)(v,{flexDirection:`column`,marginTop:1,children:[(0,M.jsx)(d,{addMargin:!1,param:{text:`<bash-input>${e}</bash-input>`,type:`text`}}),t?(0,M.jsx)(c,{fullOutput:t.fullOutput,output:t.output,elapsedTimeSeconds:t.elapsedTimeSeconds,totalLines:t.totalLines,verbose:n}):p.renderToolUseProgressMessage?.([],{verbose:n,tools:[],terminalSize:void 0})]})}w(),D(),i(),_(),T();function P(){return E().defaultShell??`bash`}r(),k(),n();async function F(n,r,i,o,c){let l=A()&&P()===`powershell`;O(`tengu_input_bash`,{powershell:l});let d=h({content:s({inputString:`<bash-input>${n}</bash-input>`,precedingInputBlocks:r})}),_;c({jsx:(0,M.jsx)(N,{input:n,progress:null,verbose:o.options.verbose}),shouldHidePromptInput:!1});try{let t={...o,setToolJSX:e=>{_=e?.jsx}},r=e=>{c({jsx:(0,M.jsxs)(M.Fragment,{children:[(0,M.jsx)(N,{input:n,progress:e.data,verbose:o.options.verbose}),_]}),shouldHidePromptInput:!1,showSpinner:!1})},s=null;l&&(s=(m(),e(f)).PowerShellTool);let v=s??p,y=(s?await s.call({command:n,dangerouslyDisableSandbox:!0},t,void 0,void 0,r):await p.call({command:n,dangerouslyDisableSandbox:!0},t,void 0,void 0,r)).data;if(!y)throw Error(`No result received from shell command`);let b=y.stderr,x=await g(v,{...y,stderr:``},j()),S=typeof x.content==`string`?x.content:a(y.stdout);return{messages:[u(),d,...i,h({content:`<bash-stdout>${S}</bash-stdout><bash-stderr>${a(b)}</bash-stderr>`})],shouldQuery:!1}}catch(e){return e instanceof S?e.interrupted?{messages:[u(),d,t({toolUse:!1}),...i],shouldQuery:!1}:{messages:[u(),d,...i,h({content:`<bash-stdout>${a(e.stdout)}</bash-stdout><bash-stderr>${a(e.stderr)}</bash-stderr>`})],shouldQuery:!1}:{messages:[u(),d,...i,h({content:`<bash-stderr>Command failed: ${a(C(e))}</bash-stderr>`})],shouldQuery:!1}}finally{c(null)}}export{F as processBashCommand};
@@ -0,0 +1,5 @@
1
+ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{$p as t,Ba as n,Ca as r,Cf as i,Di as a,Dm as o,Ds as s,Em as c,Es as l,Fp as u,Gw as d,H as f,Hc as p,Ip as m,Kw as h,Mf as g,Mp as _,Ni as v,Np as y,O as b,Oa as x,Of as S,Pp as C,Pv as w,Qp as T,Ri as ee,S as E,Tf as D,Tm as O,U as k,Uc as A,Vi as j,Wa as te,Ww as ne,Xb as re,Xh as ie,Ya as M,Yh as ae,Zb as oe,_a as N,ba as P,cv as se,dc as ce,fc as le,g_ as ue,iy as de,jf as fe,ji as pe,jv as me,ks as he,lc as F,m_ as I,nT as L,nw as R,ov as ge,qa as _e,rw as ve,ry as ye,tT as be,tw as xe,uy as Se,wa as z,wf as Ce,xa as we,za as Te,zi as Ee}from"./loadAgentsDir-mcRW90aq.js";import{Gn as De,Wt as Oe,pt as ke,t as Ae}from"./state-BPFYBqm1.js";import{E as je,R as Me,c as B,f as Ne,i as V,k as H,u as Pe}from"./debug-Dr1SjdXn.js";import{Dt as Fe,Ot as Ie}from"./settings-DiBMs2gM.js";import{T as U,o as Le,q as Re,s as W,w as G}from"./log-27kCA_9u.js";import{n as ze,r as K}from"./analytics-DJobLaWP.js";import{_n as Be,ni as Ve,ri as He,vn as Ue}from"./model-C29_32BD.js";import{ct as We,ot as Ge}from"./esm-CtQkOk5D.js";import{E as Ke,T as qe,w as Je}from"./sessionTracing-CEsm8pZL.js";import{randomUUID as q}from"crypto";function Ye(e,t,n,r,i){let a=0;for(let o of Ie){let s=n[o];if(s)for(let n of s)for(let s of n.hooks){let c=s.once?()=>{B(`Removing one-shot hook for event ${o} in skill '${r}'`),m(e,t,o,s)}:void 0;C(e,t,o,n.matcher||``,s,c,i),a++}}a>0&&B(`Registered ${a} hooks from skill '${r}'`)}var Xe=e((()=>{Fe(),V(),u()}));function Ze(e){let t=e.trim();if(!t.startsWith(`/`))return null;let n=t.slice(1).split(` `);if(!n[0])return null;let r=n[0],i=!1,a=1;n.length>1&&n[1]===`(MCP)`&&(r+=` (MCP)`,i=!0,a=2);let o=n.slice(a).join(` `);return{commandName:r,args:o,isMcp:i}}var Qe=e((()=>{}));function $e(){return!1}function J(){if(!$e())throw Error(`ToolUseContext.options.allowBackgroundForkedSlashCommands is test-only and cannot be enabled outside NODE_ENV=test.`)}async function et(e,t,n,r,i,a,o){let s=T(),l=e.pluginInfo?h(e.pluginInfo.repository).marketplace:void 0;K(`tengu_slash_command_forked`,{command_name:e.name,invocation_trigger:`user-slash`,...e.pluginInfo&&{_PROTO_plugin_name:e.pluginInfo.pluginManifest.name,...l&&{_PROTO_marketplace_name:l},...D(e.pluginInfo)}});let{skillContent:u,modifiedGetAppState:d,baseAgent:f,promptMessages:p}=await le(e,t,n);B(`Executing forked slash command /${e.name} with agent ${f.agentType}`);let m=n.options.allowBackgroundForkedSlashCommands===!0;if(m&&J(),m){let t=re(),r=j(e),i=Ve(),l=e=>de({value:e,mode:`prompt`,priority:`later`,isMeta:!0,skipSlashCommands:!0,workload:i}),u=async()=>{if(!o?.runId)return;let e=await O({runId:o.runId,rootDir:o.rootDir,priority:`later`,workload:i});for(let t of e)ye(t)},m=async e=>{o?.runId&&await c({runId:o.runId,rootDir:o.rootDir,error:e instanceof Error?e.message:String(e)})};return(async()=>{let i=Date.now()+$;for(;Date.now()<i&&n.getAppState().mcp.clients.some(e=>e.type===`pending`);)await Ue(Q);let o=n.options.refreshTools?.()??n.options.tools,c=[];for await(let r of y({agentDefinition:f,promptMessages:p,toolUseContext:{...n,getAppState:d,abortController:t},canUseTool:a,isAsync:!0,querySource:`agent:custom`,model:e.model,availableTools:o,override:{agentId:s}}))c.push(r);let m=F(c,`Command completed`);B(`Background forked command /${r} completed (agent ${s})`),l(`<scheduled-task-result command="/${r}">\n${m}\n</scheduled-task-result>`);try{await u()}catch(e){W(e)}})().catch(async e=>{W(e),l(`<scheduled-task-result command="/${r}" status="failed">\n${e instanceof Error?e.message:String(e)}\n</scheduled-task-result>`),await m(e)}),{messages:[],shouldQuery:!1,command:e,deferAutonomyCompletion:!!o?.runId}}let _=[],v=[],b=`forked-command-${e.name}`,x=0,S=e=>(x++,{type:`progress`,data:{message:e,type:`agent_progress`,prompt:u,agentId:s},parentToolUseID:b,toolUseID:`${b}-${x}`,timestamp:new Date().toISOString(),uuid:q()}),C=()=>{i({jsx:g(v,{tools:n.options.tools,verbose:!1}),shouldHidePromptInput:!1,shouldContinueAnimation:!0,showSpinner:!0})};C();try{for await(let t of y({agentDefinition:f,promptMessages:p,toolUseContext:{...n,getAppState:d},canUseTool:a,isAsync:!1,querySource:`agent:custom`,model:e.model,availableTools:n.options.tools})){_.push(t);let e=_e([t]);if(t.type===`assistant`){let r=me(t);r>0&&n.setResponseLength(e=>e+r);let i=e[0];i&&i.type===`assistant`&&(v.push(S(t)),C())}if(t.type===`user`){let t=e[0];t&&t.type===`user`&&(v.push(S(t)),C())}}}finally{i(null)}let w=F(_,`Command completed`);return B(`Forked slash command /${e.name} completed with agent ${s}`),{messages:[z({content:M({inputString:`/${j(e)} ${t}`.trim(),precedingInputBlocks:r})}),z({content:`<local-command-stdout>\n${w}\n</local-command-stdout>`})],shouldQuery:!1,command:e,resultText:w}}function tt(e){return!/[^a-zA-Z0-9:\-_]/.test(e)}async function nt(e,t,r,i,o,s,c,l,u,f){let p=Ze(e);if(!p){K(`tengu_input_slash_missing`,{});let e="Commands are in the form `/command [args]`";return{messages:[P(),...i,z({content:M({inputString:e,precedingInputBlocks:t})})],shouldQuery:!1,resultText:e}}let{commandName:m,args:g,isMcp:_}=p,v=_?`mcp`:a().has(m)?m:`custom`;if(!ee(m,o.options.commands)){let n=!1;try{await Pe().stat(`/${m}`),n=!0}catch{}if(tt(m)&&!n){K(`tengu_input_slash_invalid`,{input:m});let e=`Unknown skill: ${m}`;return{messages:[P(),...i,z({content:M({inputString:e,precedingInputBlocks:t})}),...g?[we(`Args from unknown skill: ${g}`,`warning`)]:[]],shouldQuery:!1,resultText:e}}let r=q();return De(r),K(`tengu_input_prompt`,{}),qe(`user_prompt`,{prompt_length:String(e.length),prompt:Ke(e),"prompt.id":r}),{messages:[z({content:M({inputString:e,precedingInputBlocks:t}),uuid:c}),...i],shouldQuery:!0}}let{messages:y,shouldQuery:b,allowedTools:x,model:S,command:C,resultText:w,nextInput:T,submitNextInput:E,deferAutonomyCompletion:O}=await rt(m,g,s,o,t,r,l,u,c,f);if(y.length===0){let e={input:v};if(C.type===`prompt`&&C.pluginInfo){let{pluginManifest:t,repository:n}=C.pluginInfo,{marketplace:r}=h(n),i=d(r);e._PROTO_plugin_name=t.name,r&&(e._PROTO_marketplace_name=r),e.plugin_repository=i?n:`third-party`,e.plugin_name=i?t.name:`third-party`,i&&t.version&&(e.plugin_version=t.version),Object.assign(e,D(C.pluginInfo))}return K(`tengu_input_command`,{...e,invocation_trigger:`user-slash`}),{messages:[],shouldQuery:!1,model:S,nextInput:T,submitNextInput:E,deferAutonomyCompletion:O}}if(y.length===2&&y[1].type===`user`&&typeof y[1].message.content==`string`&&y[1].message.content.startsWith(`Unknown command:`))return e.startsWith(`/var`)||e.startsWith(`/tmp`)||e.startsWith(`/private`)||K(`tengu_input_slash_invalid`,{input:m}),{messages:[P(),...y],shouldQuery:b,allowedTools:x,model:S};let k={input:v};if(C.type===`prompt`&&C.pluginInfo){let{pluginManifest:e,repository:t}=C.pluginInfo,{marketplace:n}=h(t),r=d(n);k._PROTO_plugin_name=e.name,n&&(k._PROTO_marketplace_name=n),k.plugin_repository=r?t:`third-party`,k.plugin_name=r?e.name:`third-party`,r&&e.version&&(k.plugin_version=e.version),Object.assign(k,D(C.pluginInfo))}K(`tengu_input_command`,{...k,invocation_trigger:`user-slash`});let A=y.length>0&&y[0]&&n(y[0]);return{messages:b||y.every(te)||A?y:[P(),...y],shouldQuery:b,allowedTools:x,model:S,resultText:w,nextInput:T,submitNextInput:E,deferAutonomyCompletion:O}}async function rt(e,t,n,i,a,o,s,c,l,u){let d=v(e,i.options.commands);if(d.type===`prompt`&&d.userInvocable!==!1&&Ce(e),d.userInvocable===!1)return{messages:[z({content:M({inputString:`/${e}`,precedingInputBlocks:a})}),z({content:`This skill can only be invoked by Claude, not directly by users. Ask Claude to use the "${e}" skill for you.`})],shouldQuery:!1,command:d};try{switch(d.type){case`local-jsx`:return new Promise(e=>{let r=!1,o=(n,i)=>{if(r=!0,i?.display===`skip`){e({messages:[],shouldQuery:!1,command:d,nextInput:i?.nextInput,submitNextInput:i?.submitNextInput});return}let o=(i?.metaMessages??[]).map(e=>z({content:e,isMeta:!0})),s=ie()&&typeof n==`string`&&n.endsWith(` dismissed`),c=i?.displayArgs??t;e({messages:i?.display===`system`?s?o:[N(Y(d,c)),N(`<local-command-stdout>${n}</local-command-stdout>`),...o]:[z({content:M({inputString:Y(d,c),precedingInputBlocks:a})}),z(n?{content:`<local-command-stdout>${n}</local-command-stdout>`}:{content:`<local-command-stdout>${be}</local-command-stdout>`}),...o],shouldQuery:i?.shouldQuery??!1,command:d,nextInput:i?.nextInput,submitNextInput:i?.submitNextInput})};d.load().then(e=>e.call(o,{...i,canUseTool:c},t)).then(t=>{if(t!=null){if(i.options.isNonInteractiveSession){e({messages:[],shouldQuery:!1,command:d});return}r||n({jsx:t,shouldHidePromptInput:!0,showSpinner:!1,isLocalJSXCommand:!0,isImmediate:d.immediate===!0})}}).catch(t=>{W(t),!r&&(r=!0,n({jsx:null,shouldHidePromptInput:!1,clearLocalJSX:!0}),e({messages:[],shouldQuery:!1,command:d}))})});case`local`:{let e=z({content:M({inputString:Y(d,d.isSensitive&&t.trim()?`***`:t),precedingInputBlocks:a})});try{let n=P(),r=await(await d.load()).call(t,i);if(r.type===`skip`)return{messages:[],shouldQuery:!1,command:d};if(r.type===`compact`){let t=[n,e,...r.displayText?[z({content:`<local-command-stdout>${r.displayText}</local-command-stdout>`,timestamp:new Date(Date.now()+100).toISOString()})]:[]],i={...r.compactionResult,messagesToKeep:[...r.compactionResult.messagesToKeep??[],...t]};return se(),{messages:I(i),shouldQuery:!1,command:d}}return{messages:[e,N(`<local-command-stdout>${r.value}</local-command-stdout>`)],shouldQuery:!1,command:d,resultText:r.value}}catch(t){return W(t),{messages:[e,N(`<local-command-stderr>${String(t)}</local-command-stderr>`)],shouldQuery:!1,command:d}}}case`prompt`:try{return d.context===`fork`?await et(d,t,i,a,n,c??f,u):await Z(d,t,i,a,o,l)}catch(e){return e instanceof je?{messages:[z({content:M({inputString:Y(d,t),precedingInputBlocks:a})}),r({toolUse:!1})],shouldQuery:!1,command:d}:{messages:[z({content:M({inputString:Y(d,t),precedingInputBlocks:a})}),z({content:`<local-command-stderr>${String(e)}</local-command-stderr>`})],shouldQuery:!1,command:d}}}}catch(e){if(e instanceof H)return{messages:[z({content:M({inputString:e.message,precedingInputBlocks:a})})],shouldQuery:!1,command:d};throw e}}function Y(e,t){return x(j(e),t)}function X(e,t=`loading`){return[`<${G}>${e}</${G}>`,`<${U}>${e}</${U}>`,`<skill-format>true</skill-format>`].join(`
2
+ `)}function it(e,t){return[`<${G}>${e}</${G}>`,`<${U}>/${e}</${U}>`,t?`<command-args>${t}</command-args>`:null].filter(Boolean).join(`
3
+ `)}function at(e,t){return e.userInvocable===!1&&(e.loadedFrom===`skills`||e.loadedFrom===`plugin`||e.loadedFrom===`mcp`)?X(e.name,e.progressMessage):it(e.name,t)}async function ot(e,t,n,r,i=[]){let a=pe(e,n);if(!a)throw new H(`Unknown command: ${e}`);if(a.type!==`prompt`)throw Error(`Unexpected ${a.type} command. Expected 'prompt' command. Use /${e} directly in the main conversation.`);return Z(a,t,r,[],i)}async function Z(e,t,n,r=[],i=[],a){let o=await e.getPromptForCommand(t,n),c=!R(`hooks`)||ve(e.source);if(e.hooks&&c){let t=ke();Ye(n.setAppState,t,e.hooks,e.name,e.type===`prompt`?e.skillRoot:void 0)}let u=e.source?`${e.source}:${e.name}`:e.name,d=o.filter(e=>e.type===`text`).map(e=>e.text).join(`
4
+
5
+ `);Ae(e.name,u,d,Ge()?.agentId??null);let f=at(e,t),p=b(e.allowedTools??[]),m=i.length>0||r.length>0?[...i,...r,...o]:o,h=await A(s(o.filter(e=>e.type===`text`).map(e=>e.text).join(` `),n,null,[],n.messages,`repl_main_thread`,{skipSkillDiscovery:!0}));return{messages:[z({content:f,uuid:a}),z({content:m,isMeta:!0}),...h,l({type:`command_permissions`,allowedTools:p,model:e.model})],shouldQuery:!0,allowedTools:p,model:e.model,command:e}}var Q,$;e((()=>{Oe(),Ee(),L(),Re(),ze(),ue(),ge(),_(),fe(),oe(),We(),he(),V(),Me(),ce(),Ne(),ae(),p(),Xe(),Le(),Se(),Te(),E(),k(),ne(),xe(),Qe(),Be(),i(),Je(),S(),w(),t(),o(),He(),Q=200,$=1e4}))();export{X as formatSkillLoadingMetadata,ot as processPromptSlashCommand,nt as processSlashCommand};
@@ -1 +1 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{n as t,o as n}from"./envUtils-BDhHQY0-.js";import{basename as r,join as i,resolve as a}from"path";import{existsSync as o,mkdirSync as s,readFileSync as c,realpathSync as l,writeFileSync as u}from"fs";import{createHash as d}from"crypto";import{execFileSync as f}from"child_process";function p(){return i(t(),`skill-learning`)}function m(){return i(p(),`projects.json`)}function h(e){return e===j?i(p(),`global`):i(p(),`projects`,e)}function g(e){return i(h(e),`project.json`)}function _(e,t){if(F.has(e)&&F.delete(e),F.set(e,t),F.size>N){let e=F.size-P,t=F.keys();for(let n=0;n<e;n++){let e=t.next();if(e.done)break;F.delete(e.value)}}}function v(e=process.cwd()){let t=F.get(e);if(t){F.delete(e),F.set(e,t);let n=Date.now();return n-L>I&&(L=n,S(t)),t}let n=b(e);return _(e,n),S(n),L=Date.now(),n}function y(){let e=C(m());return Object.values(e.projects).sort((e,t)=>e.projectName.localeCompare(t.projectName))}function b(e){let t=process.env.CLAUDE_PROJECT_DIR?.trim();if(t){let n=E(t);return x({source:`claude_project_dir`,scope:`project`,cwd:e,projectRoot:n,identity:`claude-project-dir:${n}`,projectName:r(n)||`project`})}let n=T([`remote`,`get-url`,`origin`],e);if(n){let t=T([`rev-parse`,`--show-toplevel`],e),r=D(n);return x({source:`git_remote`,scope:`project`,cwd:e,projectRoot:E(t||e),gitRemote:r,identity:`git-remote:${r}`,projectName:O(r)})}let i=T([`rev-parse`,`--show-toplevel`],e);if(i){let t=E(i);return x({source:`git_root`,scope:`project`,cwd:e,projectRoot:t,identity:`git-root:${t}`,projectName:r(t)||`project`})}return x({source:`global`,scope:`global`,cwd:e,projectRoot:void 0,identity:`global`,projectName:M})}function x(e){let t=e.scope===`global`?j:k(e.identity);return{projectId:t,projectName:e.projectName,scope:e.scope,source:e.source,cwd:E(e.cwd),projectRoot:e.projectRoot,gitRemote:e.gitRemote,storageDir:h(t)}}function S(e){let t=new Date().toISOString(),n=m(),r=C(n),i=r.projects[e.projectId],a={...e,firstSeenAt:i?.firstSeenAt??t,lastSeenAt:t};r.projects[e.projectId]=a,r.updatedAt=t,s(e.storageDir,{recursive:!0}),s(p(),{recursive:!0}),w(n,r),w(g(e.projectId),a)}function C(e){if(!o(e))return{version:A,updatedAt:new Date(0).toISOString(),projects:{}};try{let t=JSON.parse(c(e,`utf8`));if(t.version===A&&typeof t.projects==`object`&&t.projects)return{version:A,updatedAt:typeof t.updatedAt==`string`?t.updatedAt:new Date(0).toISOString(),projects:t.projects}}catch{}return{version:A,updatedAt:new Date(0).toISOString(),projects:{}}}function w(e,t){u(e,`${JSON.stringify(t,null,2)}\n`,`utf8`)}function T(e,t){try{return f(`git`,[`-C`,t,...e],{encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]}).trim()||null}catch{return null}}function E(e){let t=a(e);try{return l.native(t).normalize(`NFC`)}catch{return t.normalize(`NFC`)}}function D(e){let t=e.trim().replace(/\\/g,`/`);return t=t.replace(/\.git$/i,``),t=t.replace(/\/+$/g,``),t.toLowerCase()}function O(e){return e.match(/[:/]([^/:]+?)(?:\.git)?$/)?.[1]||`project`}function k(e){return`project-${d(`sha256`).update(e).digest(`hex`).slice(0,16)}`}var A,j,M,N,P,F,I,L,R=e((()=>{n(),A=1,j=`global`,M=`Global`,N=32,P=24,F=new Map,I=300*1e3,L=0}));export{R as a,p as i,h as n,y as o,m as r,v as s,g as t};
1
+ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{i as t,o as n}from"./envUtils-DcaKZlRU.js";import{basename as r,join as i,resolve as a}from"path";import{existsSync as o,mkdirSync as s,readFileSync as c,realpathSync as l,writeFileSync as u}from"fs";import{createHash as d}from"crypto";import{execFileSync as f}from"child_process";function p(){return i(t(),`skill-learning`)}function m(){return i(p(),`projects.json`)}function h(e){return e===j?i(p(),`global`):i(p(),`projects`,e)}function g(e){return i(h(e),`project.json`)}function _(e,t){if(F.has(e)&&F.delete(e),F.set(e,t),F.size>N){let e=F.size-P,t=F.keys();for(let n=0;n<e;n++){let e=t.next();if(e.done)break;F.delete(e.value)}}}function v(e=process.cwd()){let t=F.get(e);if(t){F.delete(e),F.set(e,t);let n=Date.now();return n-L>I&&(L=n,S(t)),t}let n=b(e);return _(e,n),S(n),L=Date.now(),n}function y(){let e=C(m());return Object.values(e.projects).sort((e,t)=>e.projectName.localeCompare(t.projectName))}function b(e){let t=process.env.CLAUDE_PROJECT_DIR?.trim();if(t){let n=E(t);return x({source:`claude_project_dir`,scope:`project`,cwd:e,projectRoot:n,identity:`claude-project-dir:${n}`,projectName:r(n)||`project`})}let n=T([`remote`,`get-url`,`origin`],e);if(n){let t=T([`rev-parse`,`--show-toplevel`],e),r=D(n);return x({source:`git_remote`,scope:`project`,cwd:e,projectRoot:E(t||e),gitRemote:r,identity:`git-remote:${r}`,projectName:O(r)})}let i=T([`rev-parse`,`--show-toplevel`],e);if(i){let t=E(i);return x({source:`git_root`,scope:`project`,cwd:e,projectRoot:t,identity:`git-root:${t}`,projectName:r(t)||`project`})}return x({source:`global`,scope:`global`,cwd:e,projectRoot:void 0,identity:`global`,projectName:M})}function x(e){let t=e.scope===`global`?j:k(e.identity);return{projectId:t,projectName:e.projectName,scope:e.scope,source:e.source,cwd:E(e.cwd),projectRoot:e.projectRoot,gitRemote:e.gitRemote,storageDir:h(t)}}function S(e){let t=new Date().toISOString(),n=m(),r=C(n),i=r.projects[e.projectId],a={...e,firstSeenAt:i?.firstSeenAt??t,lastSeenAt:t};r.projects[e.projectId]=a,r.updatedAt=t,s(e.storageDir,{recursive:!0}),s(p(),{recursive:!0}),w(n,r),w(g(e.projectId),a)}function C(e){if(!o(e))return{version:A,updatedAt:new Date(0).toISOString(),projects:{}};try{let t=JSON.parse(c(e,`utf8`));if(t.version===A&&typeof t.projects==`object`&&t.projects)return{version:A,updatedAt:typeof t.updatedAt==`string`?t.updatedAt:new Date(0).toISOString(),projects:t.projects}}catch{}return{version:A,updatedAt:new Date(0).toISOString(),projects:{}}}function w(e,t){u(e,`${JSON.stringify(t,null,2)}\n`,`utf8`)}function T(e,t){try{return f(`git`,[`-C`,t,...e],{encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]}).trim()||null}catch{return null}}function E(e){let t=a(e);try{return l.native(t).normalize(`NFC`)}catch{return t.normalize(`NFC`)}}function D(e){let t=e.trim().replace(/\\/g,`/`);return t=t.replace(/\.git$/i,``),t=t.replace(/\/+$/g,``),t.toLowerCase()}function O(e){return e.match(/[:/]([^/:]+?)(?:\.git)?$/)?.[1]||`project`}function k(e){return`project-${d(`sha256`).update(e).digest(`hex`).slice(0,16)}`}var A,j,M,N,P,F,I,L,R=e((()=>{n(),A=1,j=`global`,M=`Global`,N=32,P=24,F=new Map,I=300*1e3,L=0}));export{R as a,p as i,h as n,y as o,m as r,v as s,g as t};
@@ -1 +1 @@
1
- import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./projectContext-CIxul6vA.js";e();export{o as getProjectContextPath,n as getProjectStorageDir,i as getProjectsRegistryPath,t as getSkillLearningRootDir,r as listKnownProjects,a as resolveProjectContext};
1
+ import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./projectContext-BN2ZWzOG.js";e();export{o as getProjectContextPath,n as getProjectStorageDir,i as getProjectsRegistryPath,t as getSkillLearningRootDir,r as listKnownProjects,a as resolveProjectContext};
@@ -1,4 +1,4 @@
1
- import{a as e,n as t,o as n,r,t as i}from"./rolldown-runtime-DaDcL9Zw.js";import{l as a,o}from"./envUtils-BDhHQY0-.js";import{n as s,t as c}from"./defineProperty-C-QyHrDq.js";import{A as l,C as u,M as d,w as f}from"./external-CEp-aPkt.js";import{n as p,r as m,t as h}from"./lazySchema-B4D4qJVE.js";import{C as g,R as _,j as v,x as y}from"./debug-BecbSVoN.js";import{G as b,J as x,K as S,Q as C,W as w,q as T}from"./settings-D4CpDv2y.js";import{H as E,q as D}from"./log-Dauqle-Z.js";import{i as O,o as k}from"./platform-B0uTQc9P.js";import{_ as A,u as j}from"./model-Bgh_r4lg.js";import{join as M,parse as N,resolve as P,sep as ee}from"node:path";import{createHash as F}from"node:crypto";import{appendFile as I,mkdir as te,readFile as L,readdir as ne,rm as re,writeFile as ie}from"node:fs/promises";function ae(e){return e.filter(e=>e.data?.type!==`hook_progress`)}function oe(e,t){return e.name===t||(e.aliases?.includes(t)??!1)}function se(e,t){return e.find(e=>oe(e,t))}function ce(e){return{...ue,userFacingName:()=>e.name,...e}}var le,ue,de=t((()=>{le=()=>({mode:`default`,additionalWorkingDirectories:new Map,alwaysAllowRules:{},alwaysDenyRules:{},alwaysAskRules:{},isBypassPermissionsModeAvailable:!0}),ue={isEnabled:()=>!0,isConcurrencySafe:e=>!1,isReadOnly:e=>!1,isDestructive:e=>!1,checkPermissions:(e,t)=>Promise.resolve({behavior:`allow`,updatedInput:e}),toAutoClassifierInput:e=>``,userFacingName:e=>``}})),fe,pe,me,he,ge=t((()=>{fe=`Edit`,pe=`/.claude/**`,me=`~/.claude/**`,he=`File has been unexpectedly modified. Read it again before attempting to write it.`}));function _e(e){let t=e.trim();if(!t)return null;if(t.endsWith(`-`)){let e=parseInt(t.slice(0,-1),10);return isNaN(e)||e<1?null:{firstPage:e,lastPage:1/0}}let n=t.indexOf(`-`);if(n===-1){let e=parseInt(t,10);return isNaN(e)||e<1?null:{firstPage:e,lastPage:e}}let r=parseInt(t.slice(0,n),10),i=parseInt(t.slice(n+1),10);return isNaN(r)||isNaN(i)||r<1||i<1||i<r?null:{firstPage:r,lastPage:i}}function ve(){return!j().toLowerCase().includes(`claude-3-haiku`)}function ye(e){let t=e.startsWith(`.`)?e.slice(1):e;return be.has(t.toLowerCase())}var be,xe=t((()=>{A(),be=new Set([`pdf`])})),R,Se=t((()=>{R=`Bash`}));function Ce(e,t,n){return`Reads a file from the local filesystem. You can access any file directly by using this tool.
1
+ import{a as e,n as t,o as n,r,t as i}from"./rolldown-runtime-DaDcL9Zw.js";import{l as a,o}from"./envUtils-DcaKZlRU.js";import{n as s,t as c}from"./defineProperty-C-QyHrDq.js";import{A as l,C as u,M as d,w as f}from"./external-CEp-aPkt.js";import{n as p,r as m,t as h}from"./lazySchema-B4D4qJVE.js";import{C as g,R as _,j as v,x as y}from"./debug-Dr1SjdXn.js";import{G as b,J as x,K as S,Q as C,W as w,q as T}from"./settings-DiBMs2gM.js";import{H as E,q as D}from"./log-27kCA_9u.js";import{i as O,o as k}from"./platform-Dg1c9F_1.js";import{_ as A,u as j}from"./model-C29_32BD.js";import{join as M,parse as N,resolve as P,sep as ee}from"node:path";import{createHash as F}from"node:crypto";import{appendFile as I,mkdir as te,readFile as L,readdir as ne,rm as re,writeFile as ie}from"node:fs/promises";function ae(e){return e.filter(e=>e.data?.type!==`hook_progress`)}function oe(e,t){return e.name===t||(e.aliases?.includes(t)??!1)}function se(e,t){return e.find(e=>oe(e,t))}function ce(e){return{...ue,userFacingName:()=>e.name,...e}}var le,ue,de=t((()=>{le=()=>({mode:`default`,additionalWorkingDirectories:new Map,alwaysAllowRules:{},alwaysDenyRules:{},alwaysAskRules:{},isBypassPermissionsModeAvailable:!0}),ue={isEnabled:()=>!0,isConcurrencySafe:e=>!1,isReadOnly:e=>!1,isDestructive:e=>!1,checkPermissions:(e,t)=>Promise.resolve({behavior:`allow`,updatedInput:e}),toAutoClassifierInput:e=>``,userFacingName:e=>``}})),fe,pe,me,he,ge=t((()=>{fe=`Edit`,pe=`/.workmate/**`,me=`~/.workmate/**`,he=`File has been unexpectedly modified. Read it again before attempting to write it.`}));function _e(e){let t=e.trim();if(!t)return null;if(t.endsWith(`-`)){let e=parseInt(t.slice(0,-1),10);return isNaN(e)||e<1?null:{firstPage:e,lastPage:1/0}}let n=t.indexOf(`-`);if(n===-1){let e=parseInt(t,10);return isNaN(e)||e<1?null:{firstPage:e,lastPage:e}}let r=parseInt(t.slice(0,n),10),i=parseInt(t.slice(n+1),10);return isNaN(r)||isNaN(i)||r<1||i<1||i<r?null:{firstPage:r,lastPage:i}}function ve(){return!j().toLowerCase().includes(`claude-3-haiku`)}function ye(e){let t=e.startsWith(`.`)?e.slice(1):e;return be.has(t.toLowerCase())}var be,xe=t((()=>{A(),be=new Set([`pdf`])})),R,Se=t((()=>{R=`Bash`}));function Ce(e,t,n){return`Reads a file from the local filesystem. You can access any file directly by using this tool.
2
2
  Assume this tool is able to read all files on the machine. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.
3
3
 
4
4
  Usage:
@@ -95,12 +95,12 @@ All operations require:
95
95
  - line: The line number (1-based, as shown in editors)
96
96
  - character: The character offset (1-based, as shown in editors)
97
97
 
98
- Note: LSP servers must be configured for the file type. If no server is available, an error will be returned.`})),rr,ir=t((()=>{rr=`VerifyPlanExecution`})),ar,or=t((()=>{ar=`ExecuteExtraTool`})),sr,cr=t((()=>{sr=`EnterWorktree`})),lr,ur=t((()=>{lr=`ExitWorktree`})),dr=t((()=>{})),q,J,fr,pr,mr,hr,Y=t((()=>{q=`Workflow`,J=`.claude/workflows`,fr=`.claude/workflow-runs`,pr=[`.ts`,`.js`,`.mjs`],mr=1e3,hr=4096}));function gr(e){return{[yr]:e}}function _r(e){return typeof e==`object`&&!!e&&yr in e}function vr(e){return e[yr]}var yr,br=t((()=>{yr=Symbol(`workflow.hostHandle`)}));function xr(e,t){return e.kind===`agentType`?t.agentType===e.agentType:e.kind===`model`?typeof t.model==`string`&&t.model.startsWith(e.pattern):e.match(t)}var Sr,Cr,wr=t((()=>{s(),Sr=class extends Error{constructor(e){super(e),this.name=`AdapterNotFoundError`}},Cr=class{constructor(){c(this,`adapters`,new Map),c(this,`rules`,[]),c(this,`defaultId`,null)}register(e){return this.adapters.set(e.id,e),this}default(e){return this.defaultId=e,this}route(e){return this.rules.push(e),this}has(e){return this.adapters.has(e)}get(e){return this.adapters.get(e)}resolve(e){for(let t of this.rules)if(xr(t,e)){let e=this.adapters.get(t.adapter);if(e)return e}if(this.defaultId){let e=this.adapters.get(this.defaultId);if(e)return e}throw new Sr(`No adapter matched (rules=${this.rules.length}, default=${this.defaultId??`none`})`)}async initializeAll(){for(let e of this.adapters.values())await e.initialize?.()}async disposeAll(){for(let e of this.adapters.values())await e.dispose?.()}}}));function Tr(){return 3}function Er(e){return e===void 0||Number.isNaN(e)?3:Math.max(1,Math.min(Math.trunc(e),16))}var Dr,Or=t((()=>{Y(),s(),Dr=class{constructor(e){c(this,`available`,void 0),c(this,`waiters`,[]),this.available=Math.max(1,Math.floor(e))}async acquire(e){if(e?.aborted)throw Error(`Semaphore.acquire aborted (signal already aborted)`);return this.available>0?(--this.available,()=>this.release()):new Promise((t,n)=>{let r=()=>{let e=this.waiters.indexOf(i);e>=0&&this.waiters.splice(e,1),n(Error(`Semaphore.acquire aborted`))},i={wake:()=>{e?.removeEventListener(`abort`,r),t(()=>this.release())},cleanup:()=>e?.removeEventListener(`abort`,r)};e?.addEventListener(`abort`,r,{once:!0}),this.waiters.push(i)})}release(){let e=this.waiters.shift();e?e.wake():this.available+=1}}}));function kr(e){let t=Pr.exec(e);if(!t)return{meta:null,body:e};let n=t.index+t[0].length;for(;n<e.length&&/\s/.test(e[n]);)n++;if(e[n]!==`{`)throw new Z("meta must be an object literal `{ ... }`");let r=0,i=n,a=null;for(;n<e.length;n++){let t=e[n];if(a){if(t===`\\`){n++;continue}t===a&&(a=null);continue}if(t===`"`||t===`'`||t==="`"){a=t;continue}if(t===`{`)r++;else if(t===`}`&&(r--,r===0)){n++;break}}if(r!==0)throw new Z(`meta literal braces are not closed`);let o=e.slice(i,n),s;try{s=Function(`return (${o})`)()}catch(e){throw new Z(`meta must be a plain literal (no variable/function calls/interpolation): ${e.message}`)}return{meta:Ar(s),body:e.slice(0,t.index)+e.slice(n).replace(/^[ \t]*;[ \t]*\n/,`
98
+ Note: LSP servers must be configured for the file type. If no server is available, an error will be returned.`})),rr,ir=t((()=>{rr=`VerifyPlanExecution`})),ar,or=t((()=>{ar=`ExecuteExtraTool`})),sr,cr=t((()=>{sr=`EnterWorktree`})),lr,ur=t((()=>{lr=`ExitWorktree`})),dr=t((()=>{})),q,J,fr,pr,mr,hr,Y=t((()=>{q=`Workflow`,J=`.workmate/workflows`,fr=`.workmate/workflow-runs`,pr=[`.ts`,`.js`,`.mjs`],mr=1e3,hr=4096}));function gr(e){return{[yr]:e}}function _r(e){return typeof e==`object`&&!!e&&yr in e}function vr(e){return e[yr]}var yr,br=t((()=>{yr=Symbol(`workflow.hostHandle`)}));function xr(e,t){return e.kind===`agentType`?t.agentType===e.agentType:e.kind===`model`?typeof t.model==`string`&&t.model.startsWith(e.pattern):e.match(t)}var Sr,Cr,wr=t((()=>{s(),Sr=class extends Error{constructor(e){super(e),this.name=`AdapterNotFoundError`}},Cr=class{constructor(){c(this,`adapters`,new Map),c(this,`rules`,[]),c(this,`defaultId`,null)}register(e){return this.adapters.set(e.id,e),this}default(e){return this.defaultId=e,this}route(e){return this.rules.push(e),this}has(e){return this.adapters.has(e)}get(e){return this.adapters.get(e)}resolve(e){for(let t of this.rules)if(xr(t,e)){let e=this.adapters.get(t.adapter);if(e)return e}if(this.defaultId){let e=this.adapters.get(this.defaultId);if(e)return e}throw new Sr(`No adapter matched (rules=${this.rules.length}, default=${this.defaultId??`none`})`)}async initializeAll(){for(let e of this.adapters.values())await e.initialize?.()}async disposeAll(){for(let e of this.adapters.values())await e.dispose?.()}}}));function Tr(){return 3}function Er(e){return e===void 0||Number.isNaN(e)?3:Math.max(1,Math.min(Math.trunc(e),16))}var Dr,Or=t((()=>{Y(),s(),Dr=class{constructor(e){c(this,`available`,void 0),c(this,`waiters`,[]),this.available=Math.max(1,Math.floor(e))}async acquire(e){if(e?.aborted)throw Error(`Semaphore.acquire aborted (signal already aborted)`);return this.available>0?(--this.available,()=>this.release()):new Promise((t,n)=>{let r=()=>{let e=this.waiters.indexOf(i);e>=0&&this.waiters.splice(e,1),n(Error(`Semaphore.acquire aborted`))},i={wake:()=>{e?.removeEventListener(`abort`,r),t(()=>this.release())},cleanup:()=>e?.removeEventListener(`abort`,r)};e?.addEventListener(`abort`,r,{once:!0}),this.waiters.push(i)})}release(){let e=this.waiters.shift();e?e.wake():this.available+=1}}}));function kr(e){let t=Pr.exec(e);if(!t)return{meta:null,body:e};let n=t.index+t[0].length;for(;n<e.length&&/\s/.test(e[n]);)n++;if(e[n]!==`{`)throw new Z("meta must be an object literal `{ ... }`");let r=0,i=n,a=null;for(;n<e.length;n++){let t=e[n];if(a){if(t===`\\`){n++;continue}t===a&&(a=null);continue}if(t===`"`||t===`'`||t==="`"){a=t;continue}if(t===`{`)r++;else if(t===`}`&&(r--,r===0)){n++;break}}if(r!==0)throw new Z(`meta literal braces are not closed`);let o=e.slice(i,n),s;try{s=Function(`return (${o})`)()}catch(e){throw new Z(`meta must be a plain literal (no variable/function calls/interpolation): ${e.message}`)}return{meta:Ar(s),body:e.slice(0,t.index)+e.slice(n).replace(/^[ \t]*;[ \t]*\n/,`
99
99
  `)}}function Ar(e){if(typeof e!=`object`||!e||Array.isArray(e))throw new Z(`meta must be an object`);let t=e;if(typeof t.name!=`string`||typeof t.description!=`string`)throw new Z(`meta must include string name and description`);return t}function jr(){let e=function(...e){if(e.length===0)throw new Fr(`Date.now()/new Date()`);return new Date(...e)};return e.now=()=>{throw new Fr(`Date.now()`)},e.parse=Date.parse,e.UTC=Date.UTC,e}function Mr(){return new Proxy(Math,{get(e,t,n){return t===`random`?()=>{throw new Fr(`Math.random()`)}:Reflect.get(e,t,n)}})}function Nr(e){if(/^\s*import\b/m.test(e))throw new Z(`workflow scripts are the body of new AsyncFunction (not ESM modules); import is not supported. agent / parallel / pipeline / phase / log / workflow / args / budget are injected as parameters — use them directly.`);if(/\bimport\s*\(/m.test(e))throw new Z(`dynamic import(...) is forbidden in workflow scripts: it bypasses the Date/Math sandbox and breaks resume determinism. The sandbox does not guarantee security (same trust level as the LLM), but explicit escapes are prohibited. Inject external dependencies via args.`);if(/^\s*export\b/m.test(e))throw new Z(`workflow scripts allow only one export const meta = {...} (already extracted by the engine). Remove other export / export default statements; use top-level return for the result.`)}function X(e){let{meta:t,body:n}=kr(e);Nr(n);let r;try{r=new Ir(`agent`,`parallel`,`pipeline`,`phase`,`log`,`workflow`,`args`,`budget`,`Date`,`Math`,n)}catch(e){throw new Z(`Script syntax error: ${e.message}`)}let i=jr(),a=Mr();return{meta:t,async execute(e,t,n){return r(e.agent,e.parallel,e.pipeline,e.phase,e.log,e.workflow,t,n,i,a)}}}var Z,Pr,Fr,Ir,Lr=t((()=>{Z=class extends Error{constructor(e){super(e),this.name=`ScriptError`}},Pr=/export\s+const\s+meta\s*=\s*/,Fr=class extends Error{constructor(e){super(`${e} is not available in workflow scripts (would break resume determinism). Pass timestamps/random seeds via args.`),this.name=`NonDeterministicError`}},Ir=Object.getPrototypeOf(async function(){}).constructor}));function Rr(e){let{label:t,phase:n,...r}=e,i=Object.keys(r).sort(),a={};for(let e of i)a[e]=r[e];return JSON.stringify(a)}function zr(e,t){return F(`sha256`).update(e+`
100
100
  `+Rr(t)).digest(`hex`)}function Br(e){let t=t=>M(e,t,`journal.jsonl`);return{async read(e){try{return(await L(t(e),`utf-8`)).split(`
101
101
  `).filter(e=>e.trim().length>0).map(e=>JSON.parse(e)).sort((e,t)=>(e.seq??0)-(t.seq??0))}catch{return[]}},async append(n,r){await te(M(e,n),{recursive:!0}),await I(t(n),JSON.stringify(r)+`
102
- `,`utf-8`)},async truncate(t){await re(M(e,t),{recursive:!0,force:!0})}}}var Vr=t((()=>{})),Hr,Ur,Wr=t((()=>{s(),Hr=class extends Error{constructor(){super(`workflow token budget exhausted (budget.total reached the cap)`),this.name=`BudgetExhaustedError`}},Ur=class{constructor(e){c(this,`total`,void 0),c(this,`spentTokens`,0),this.total=e}spent(){return this.spentTokens}remaining(){return this.total==null?1/0:Math.max(0,this.total-this.spentTokens)}addOutputTokens(e){e>0&&(this.spentTokens+=e)}assertCanSpend(){if(this.total!=null&&this.spentTokens>=this.total)throw new Hr}}}));function Gr(e,t){let n=qr.get(t);n||(n=new Kr.Ajv({allErrors:!0,strict:!1}).compile(t),qr.set(t,n));let r=n(e);return{valid:r,errors:r?[]:(n.errors??[]).map(e=>e.message??`validation error`)}}var Kr,qr,Jr=t((()=>{Kr=n(fn(),1),qr=new WeakMap}));function Yr(e,t){let n=P(e),r=P(n,t);return r===n||r.startsWith(n+ee)}function Xr(e){return typeof e!=`string`||e.length===0||e.includes(`/`)||e.includes(`\\`)||e.includes(`\0`)||e===`.`||e===`..`?null:e}var Zr=t((()=>{}));function Qr(e){return pr.includes(e.toLowerCase())}async function $r(e,t){for(let n of pr){let r=P(e,t+n);if(!Yr(e,r))return null;try{return{path:r,content:await L(r,`utf-8`)}}catch{}}return null}async function ei(e){let t;try{t=await ne(e)}catch{return[]}return t.filter(e=>Qr(N(e).ext)).map(e=>N(e).name).sort()}var ti=t((()=>{Y(),Zr()})),Q,$,ni=t((()=>{Q=class extends Error{constructor(e){super(e),this.name=`WorkflowError`}},$=class extends Error{constructor(){super(`workflow has been aborted`),this.name=`WorkflowAbortedError`}}}));function ri(e,t){return{semaphore:new Dr(Er(t)),budget:new Ur(e),agentCountBox:{value:0},agentIdSeq:{value:0},depth:0}}function ii(e){let t=ri(e.budgetTotal,e.maxConcurrency);return{ports:e.ports,host:e.host,signal:e.signal,runId:e.runId,workflowName:e.workflowName,cwd:e.cwd,resources:t,journal:e.journal?[...e.journal]:[],journalIndex:0,journalInvalidated:!1,currentPhase:null}}var ai=t((()=>{Wr(),Or()}));function oi(e,t){let n=t=>{e.ports.progressEmitter.emit({runId:e.runId,...t})};return{agent:async(t,r={})=>{let i=e.resources;if(i.agentCountBox.value>=1e3)throw new Q(`workflow exceeds total agent cap (${mr})`);let a=i.agentIdSeq.value++,o={prompt:t,...r},s=zr(t,o),c=r.label,l=r.phase??e.currentPhase??void 0;if(!e.journalInvalidated&&e.journalIndex<e.journal.length){let t=e.journal[e.journalIndex];if(t.key===s)return e.journalIndex++,n({type:`agent_done`,agentId:a,label:c,phase:l,result:t.result}),si(t.result);e.journalInvalidated=!0,e.journal=e.journal.slice(0,e.journalIndex),await e.ports.journalStore.truncate(e.runId)}let u;try{u=await e.resources.semaphore.acquire(e.signal)}catch{throw new $}try{if(e.signal.aborted)throw new $;if(i.budget.assertCanSpend(),e.ports.taskRegistrar.pendingAction(e.runId)?.kind===`skip`)return n({type:`agent_done`,agentId:a,label:c,phase:l,result:{kind:`skipped`}}),null;e.resources.agentCountBox.value++,n({type:`agent_started`,agentId:a,label:c,phase:l});let t=e.ports.agentAdapterRegistry,r=t?{host:e.host,signal:e.signal,runId:e.runId,agentId:a,onProgress:e=>{n({type:`agent_progress`,agentId:a,label:c,phase:l,...e})},...e.ports.taskRegistrar.registerAgentAbort?{registerAgentAbort:(t,n)=>{e.ports.taskRegistrar.registerAgentAbort?.(e.runId,t,n)}}:{},...e.ports.taskRegistrar.unregisterAgentAbort?{unregisterAgentAbort:t=>{e.ports.taskRegistrar.unregisterAgentAbort?.(e.runId,t)}}:{}}:null,u=t?t.resolve(o):null,d=()=>u?u.run(o,r):e.ports.agentRunner.runAgentToResult(o,e.host),f;try{if(f=await d(),f.kind===`dead`){let t=typeof f.detail==`string`?f.detail:``;e.ports.logger.warn?.(`agent "${c??`#${a}`}" returned dead`+(f.reason?` (${f.reason})`:``)+(t?`: ${t.slice(0,150)}`:``)+`; retrying once`),f=await d()}}catch(t){if(t instanceof $)throw t;let n=t instanceof Error?t.message:String(t);e.ports.logger.warn?.(`agent "${c??`#${a}`}" threw (${n}); retrying once`);try{f=await d()}catch(e){if(e instanceof $)throw e;f={kind:`dead`,reason:`runagent-threw`,detail:e instanceof Error?e.message:String(e)}}}f.kind===`ok`&&e.resources.budget.addOutputTokens(f.usage.outputTokens),n({type:`agent_done`,agentId:a,label:c,phase:l,result:f});let p={key:s,seq:a,result:f};return e.journal.push(p),e.journalIndex++,await e.ports.journalStore.append(e.runId,p),si(f)}finally{u()}},parallel:async t=>{if(t.length>4096)throw new Q(`parallel exceeds the per-call items cap (${hr})`);return Promise.all(t.map(async(t,n)=>{try{return await t()}catch(t){return e.ports.logger.warn?.(`parallel thunk #${n} failed: ${t.message}`),null}}))},pipeline:async(t,...n)=>{if(t.length>4096)throw new Q(`pipeline exceeds the per-call items cap (${hr})`);return Promise.all(t.map(async(t,r)=>{try{let e=t;for(let i of n)e=await i(e,t,r);return e}catch(t){return e.ports.logger.warn?.(`pipeline item #${r} failed: ${t.message}`),null}}))},phase:t=>{e.currentPhase&&n({type:`phase_done`,phase:e.currentPhase}),e.currentPhase=t,n({type:`phase_started`,phase:t})},log:e=>{n({type:`log`,message:e})},workflow:async(n,r)=>{if(e.resources.depth>=1)throw new Q(`workflow() nesting allows only one level`);return t({...typeof n==`string`?{name:n}:{scriptPath:n.scriptPath},args:r})}}}function si(e){return e.kind===`ok`?e.output:null}var ci=t((()=>{Y(),ni(),Vr()}));async function li(e){let{ports:t}=e,n;try{n=X(e.script)}catch(n){let r=n.message;return t.progressEmitter.emit({type:`run_done`,runId:e.runId,status:`failed`,error:r}),{status:`failed`,error:r}}let r=e.workflowName??n.meta?.name??`workflow`,i=[],a=!1;e.resume&&!e.scriptChanged?i=await t.journalStore.read(e.runId):e.scriptChanged&&(await t.journalStore.truncate(e.runId),a=!0);let o=ii({ports:t,host:e.host,signal:e.signal,runId:e.runId,workflowName:r,cwd:e.cwd,budgetTotal:e.budgetTotal,maxConcurrency:e.maxConcurrency,journal:i});a&&(o.journalInvalidated=!0),t.progressEmitter.emit({type:`run_started`,runId:e.runId,workflowName:r,meta:n.meta});let s=async t=>{let n=await ui(t,e.cwd),r;try{r=X(n)}catch(e){throw new Q(`Sub-workflow script error: ${e.message}`)}let i=o.resources.depth;o.resources.depth+=1;try{let e=oi(o,s);return await r.execute(e,t.args,o.resources.budget)}finally{o.resources.depth=i}},c=oi(o,s),l=()=>{o.currentPhase&&t.progressEmitter.emit({type:`phase_done`,runId:e.runId,phase:o.currentPhase})},u;try{u={status:`completed`,returnValue:await n.execute(c,e.args,o.resources.budget)}}catch(e){u=e instanceof $?{status:`killed`}:{status:`failed`,error:e.message}}return l(),t.progressEmitter.emit({type:`run_done`,runId:e.runId,...u}),u}async function ui(e,t){if(e.script)return e.script;if(e.scriptPath)return await L(e.scriptPath,`utf-8`);if(e.name){let n=await $r(M(t,J),e.name);if(!n)throw new Q(`Sub-workflow "${e.name}" not found`);return n.content}throw new Q(`workflow() requires name or scriptPath`)}var di=t((()=>{Y(),ai(),ni(),ci(),ti(),Lr()}));function fi(e){return{emit:e}}function pi(){let e=[];return{emitter:{emit:t=>void e.push(t)},events:e}}var mi=t((()=>{})),hi,gi=t((()=>{m(),hi=f({script:l().optional().describe(`Self-contained workflow script source (inline)`),name:l().optional().describe(`Named workflow, resolved to .claude/workflows/<name>.ts|js|mjs`),scriptPath:l().optional().describe(`Absolute path to an existing script file`),args:d().optional().describe(`The args global variable passed through to the script. Pass a real JSON value (object/array/string), not a JSON string.`),resumeFromRunId:l().optional().describe(`Resume the specified run, replaying the journal`),description:l().optional().describe(`A short description of this invocation (3-5 words)`),title:l().optional().describe(`Progress viewer title`),maxConcurrency:u().int().min(1).max(16).optional().describe(`Concurrency cap for agent(). Defaults to 3 (max 16). When the workflow contains heavy parallel/pipeline fan-out, you may confirm the desired concurrency with the user via AskUserQuestion before launching.`)})}));async function _i(e,t,n){let r=M(n,fr,t);await te(r,{recursive:!0});let i=M(r,`script.js`);return await ie(i,e,`utf-8`),i}var vi=t((()=>{Y()}));function yi(e){return{name:q,inputSchema:hi,isEnabled:()=>!0,isReadOnly:()=>!1,async description(){return`Execute a workflow script that orchestrates multiple subagents to complete a task`},async prompt(){return wi},renderToolUseMessage(e){return e.resumeFromRunId?`Workflow resume: ${e.resumeFromRunId}`:`Workflow: ${e.name??e.scriptPath??(e.script?`inline`:`unknown`)}`},async call(t,n,r,i){let a=e.hostFactory({context:n,canUseTool:r,parentMessage:i}),o,s;try{let e=await Ci(t,a.cwd);o=e.script,s=e.workflowFile}catch(e){return{data:{output:`Error: ${e.message}`}}}try{X(o)}catch(e){return{data:{output:`Error: script validation failed: ${e.message}`}}}let c=t.name??t.title??`workflow`,{runId:l,signal:u}=e.taskRegistrar.register({workflowName:c,...s?{workflowFile:s}:{},...t.description?{summary:t.description}:{},...a.toolUseId?{toolUseId:a.toolUseId}:{},...t.resumeFromRunId?{runId:t.resumeFromRunId}:{}},a.handle);if(!s&&t.script)try{s=await _i(t.script,l,a.cwd)}catch(t){e.logger.warn?.(`inline script persist failed: ${t.message}`)}li({script:o,...t.args===void 0?{}:{args:Si(t.args)},runId:l,workflowName:c,ports:e,host:a.handle,signal:u,cwd:a.cwd,budgetTotal:a.budgetTotal,...t.maxConcurrency===void 0?{}:{maxConcurrency:t.maxConcurrency},...t.resumeFromRunId?{resume:!0}:{}}).then(t=>bi(e,t,l)).catch(t=>e.taskRegistrar.fail(l,t.message));let d=s??`<inline run ${l}>`;return{data:{output:[`Workflow started (running in the background).`,`run_id: ${l}`,`workflow: ${c}`,`script: ${d}`,``,`You will be notified on completion. Use /workflows to view live progress.`].join(`
103
- `)}}},mapToolResultToToolResultBlockParam(e,t){return{tool_use_id:t,type:`tool_result`,content:[{type:`text`,text:e.output}]}}}}function bi(e,t,n){if(t.status===`completed`){let r=t.returnValue==null?`(no return value)`:xi(t.returnValue);e.taskRegistrar.complete(n,r)}else t.status===`failed`?e.taskRegistrar.fail(n,t.error??`workflow failed`):e.taskRegistrar.kill(n)}function xi(e){if(typeof e==`string`)return e.slice(0,500);try{return JSON.stringify(e).slice(0,500)}catch{return String(e)}}function Si(e){if(typeof e!=`string`)return e;try{let t=JSON.parse(e);return typeof t==`object`&&t?t:e}catch{return e}}async function Ci(e,t){if(e.script)return{script:e.script};if(e.scriptPath){let n=P(t,e.scriptPath);if(!Yr(t,n))throw Error(`scriptPath "${e.scriptPath}" is out of bounds (after resolve, ${n} is not within cwd ${t})`);return{script:await L(n,`utf-8`),workflowFile:n}}if(e.name){if(Xr(e.name)===null)throw Error(`Named workflow name "${e.name}" is invalid (contains path separators or is . / ..)`);let n=await $r(M(t,J),e.name);if(!n)throw Error(`Named workflow "${e.name}" not found (looked in ${J}/)`);return{script:n.content,workflowFile:n.path}}throw Error(`One of script, name, or scriptPath must be provided`)}var wi,Ti=t((()=>{Y(),ti(),di(),Lr(),Zr(),gi(),vi(),wi='Use the Workflow tool to execute a workflow script that orchestrates multiple subagents deterministically. The script runs in the background; you receive a run_id immediately and are notified on completion.\n\nProvide the script inline via "script", or reference a named workflow via "name" (resolved from .claude/workflows/), or an existing file via "scriptPath". Pass "args" as a real JSON value (object/array/string), not a stringified string.\n\nUse "resumeFromRunId" to resume a prior run — completed agent() calls replay from the journal instantly.\n\nConcurrency: default is 3 (hard ceiling 16). OMIT maxConcurrency to use 3. To set maxConcurrency to ANY value other than 3, you MUST first ask the user via AskUserQuestion — propose 3 / 6 / 9 (or other tiers matching the fan-out width) with 3 marked "(Recommended)". The ONLY exception: the user has ALREADY specified a concurrency number in this session ("use 6", "maxConcurrency 9") — then honor it without re-asking. Never silently raise concurrency above 3 just because the workflow fans out; 3 is the recommended default.\n\nScript execution model (common pitfalls — getting these wrong is the #1 cause of script errors): the script is the body of `new AsyncFunction` — NOT an ESM module, and TypeScript is NOT transpiled. Therefore:\n- Do NOT use `import` — `agent`, `parallel`, `pipeline`, `phase`, `log`, `workflow`, `args`, and `budget` are injected as parameters; reference them directly.\n- Do NOT use TS type annotations, `interface`, `enum`, `as`, or generics — the engine does not transpile, so even a .ts file with type syntax fails to parse.\n- Keep EXACTLY ONE `export const meta = {...}` (plain literal) and remove every other `export` / `export default`.\n- Return the result with a top-level `return`.\nPrefer .js / .mjs. See /ultracode for the full playbook and quality patterns.'})),Ei=r({AdapterNotFoundError:()=>Sr,AgentAdapterRegistry:()=>Cr,Budget:()=>Ur,BudgetExhaustedError:()=>Hr,DEFAULT_MAX_CONCURRENCY:()=>3,MAX_CONCURRENCY_CAP:()=>16,MAX_ITEMS_PER_CALL:()=>hr,MAX_TOTAL_AGENTS:()=>mr,ScriptError:()=>Z,Semaphore:()=>Dr,WORKFLOW_DIR_NAME:()=>J,WORKFLOW_RUNS_DIR:()=>fr,WORKFLOW_SCRIPT_EXTENSIONS:()=>pr,WORKFLOW_TOOL_NAME:()=>q,WorkflowAbortedError:()=>$,WorkflowError:()=>Q,agentCallKey:()=>zr,clampMaxConcurrency:()=>Er,createBufferingEmitter:()=>pi,createEngineContext:()=>ii,createFileJournalStore:()=>Br,createHostHandle:()=>gr,createProgressEmitter:()=>fi,createSharedResources:()=>ri,createWorkflowTool:()=>yi,extractMeta:()=>kr,isHostHandle:()=>_r,listNamedWorkflows:()=>ei,makeHooks:()=>oi,maxConcurrency:()=>Tr,parseScript:()=>X,persistInlineScript:()=>_i,resolveNamedWorkflow:()=>$r,runWorkflow:()=>li,unwrapHostHandle:()=>vr,validateAgainstSchema:()=>Gr,workflowInputSchema:()=>hi}),Di=t((()=>{dr(),Y(),br(),wr(),Or(),Lr(),Vr(),Wr(),Jr(),ti(),ni(),ai(),ci(),di(),mi(),Ti(),gi(),vi()})),Oi,ki,Ai,ji,Mi,Ni,Pi=t((()=>{Oi=`LocalMemoryRecall`,ki=100*1024,Ai=2*1024,ji=50*1024,Mi=4*1024,Ni=8*1024})),Fi,Ii,Li,Ri,zi=t((()=>{T(),Me(),_n(),C(),Sn(),b(),Ae(),Pe(),wn(),hn(),kn(),ge(),Nn(),Fn(),Be(),Ie(),Ln(),zn(),Re(),Vn(),Xn(),er(),nr(),ir(),or(),cr(),ur(),Di(),Pi(),Fi=new Set([S,je,gn,x,vn,w,q,Oi]),Ii=new Set([...Fi]),Li=new Set([z,Ne,G,pn,...On,fe,Mn,Pn,ze,K,Bn,ar,sr,lr]),Ri=new Set([...On,z,fe,Mn,pn,G,Pn,x,vn,S,w,Fe,In,Rn,Le,Ne,gn,je,rr,`LSP`,ze,q,Zn,Bn,ar,K])}));function Bi(){return`Deferred tools appear by name in <available-deferred-tools> messages.`}function Vi(e){return!(e.alwaysLoad===!0||Ri.has(e.name))}function Hi(e){return e.name}function Ui(){return Wi+Bi()+Gi}var Wi,Gi,Ki=t((()=>{zi(),Vn(),Wi=`Search for deferred tools by name or keyword. LOW PRIORITY — only use this tool when no core tool can accomplish the task. Core tools (Read, Edit, Write, Bash, Glob, Grep, Agent, WebFetch, WebSearch, Skill) are always available and should be used directly. This tool is for discovering additional capabilities like MCP tools, worktree management, agent teams (TeamCreate, TeamDelete, SendMessage), etc.
102
+ `,`utf-8`)},async truncate(t){await re(M(e,t),{recursive:!0,force:!0})}}}var Vr=t((()=>{})),Hr,Ur,Wr=t((()=>{s(),Hr=class extends Error{constructor(){super(`workflow token budget exhausted (budget.total reached the cap)`),this.name=`BudgetExhaustedError`}},Ur=class{constructor(e){c(this,`total`,void 0),c(this,`spentTokens`,0),this.total=e}spent(){return this.spentTokens}remaining(){return this.total==null?1/0:Math.max(0,this.total-this.spentTokens)}addOutputTokens(e){e>0&&(this.spentTokens+=e)}assertCanSpend(){if(this.total!=null&&this.spentTokens>=this.total)throw new Hr}}}));function Gr(e,t){let n=qr.get(t);n||(n=new Kr.Ajv({allErrors:!0,strict:!1}).compile(t),qr.set(t,n));let r=n(e);return{valid:r,errors:r?[]:(n.errors??[]).map(e=>e.message??`validation error`)}}var Kr,qr,Jr=t((()=>{Kr=n(fn(),1),qr=new WeakMap}));function Yr(e,t){let n=P(e),r=P(n,t);return r===n||r.startsWith(n+ee)}function Xr(e){return typeof e!=`string`||e.length===0||e.includes(`/`)||e.includes(`\\`)||e.includes(`\0`)||e===`.`||e===`..`?null:e}var Zr=t((()=>{}));function Qr(e){return pr.includes(e.toLowerCase())}async function $r(e,t){for(let n of pr){let r=P(e,t+n);if(!Yr(e,r))return null;try{return{path:r,content:await L(r,`utf-8`)}}catch{}}return null}async function ei(e){let t;try{t=await ne(e)}catch{return[]}return t.filter(e=>Qr(N(e).ext)).map(e=>N(e).name).sort()}var ti=t((()=>{Y(),Zr()})),Q,$,ni=t((()=>{Q=class extends Error{constructor(e){super(e),this.name=`WorkflowError`}},$=class extends Error{constructor(){super(`workflow has been aborted`),this.name=`WorkflowAbortedError`}}}));function ri(e,t){return{semaphore:new Dr(Er(t)),budget:new Ur(e),agentCountBox:{value:0},agentIdSeq:{value:0},depth:0}}function ii(e){let t=ri(e.budgetTotal,e.maxConcurrency);return{ports:e.ports,host:e.host,signal:e.signal,runId:e.runId,workflowName:e.workflowName,cwd:e.cwd,resources:t,journal:e.journal?[...e.journal]:[],journalIndex:0,journalInvalidated:!1,currentPhase:null}}var ai=t((()=>{Wr(),Or()}));function oi(e,t){let n=t=>{e.ports.progressEmitter.emit({runId:e.runId,...t})};return{agent:async(t,r={})=>{let i=e.resources;if(i.agentCountBox.value>=1e3)throw new Q(`workflow exceeds total agent cap (${mr})`);let a=i.agentIdSeq.value++,o={prompt:t,...r},s=zr(t,o),c=r.label,l=r.phase??e.currentPhase??void 0;if(!e.journalInvalidated&&e.journalIndex<e.journal.length){let t=e.journal[e.journalIndex];if(t.key===s)return e.journalIndex++,n({type:`agent_done`,agentId:a,label:c,phase:l,result:t.result}),si(t.result);e.journalInvalidated=!0,e.journal=e.journal.slice(0,e.journalIndex),await e.ports.journalStore.truncate(e.runId)}let u;try{u=await e.resources.semaphore.acquire(e.signal)}catch{throw new $}try{if(e.signal.aborted)throw new $;if(i.budget.assertCanSpend(),e.ports.taskRegistrar.pendingAction(e.runId)?.kind===`skip`)return n({type:`agent_done`,agentId:a,label:c,phase:l,result:{kind:`skipped`}}),null;e.resources.agentCountBox.value++,n({type:`agent_started`,agentId:a,label:c,phase:l});let t=e.ports.agentAdapterRegistry,r=t?{host:e.host,signal:e.signal,runId:e.runId,agentId:a,onProgress:e=>{n({type:`agent_progress`,agentId:a,label:c,phase:l,...e})},...e.ports.taskRegistrar.registerAgentAbort?{registerAgentAbort:(t,n)=>{e.ports.taskRegistrar.registerAgentAbort?.(e.runId,t,n)}}:{},...e.ports.taskRegistrar.unregisterAgentAbort?{unregisterAgentAbort:t=>{e.ports.taskRegistrar.unregisterAgentAbort?.(e.runId,t)}}:{}}:null,u=t?t.resolve(o):null,d=()=>u?u.run(o,r):e.ports.agentRunner.runAgentToResult(o,e.host),f;try{if(f=await d(),f.kind===`dead`){let t=typeof f.detail==`string`?f.detail:``;e.ports.logger.warn?.(`agent "${c??`#${a}`}" returned dead`+(f.reason?` (${f.reason})`:``)+(t?`: ${t.slice(0,150)}`:``)+`; retrying once`),f=await d()}}catch(t){if(t instanceof $)throw t;let n=t instanceof Error?t.message:String(t);e.ports.logger.warn?.(`agent "${c??`#${a}`}" threw (${n}); retrying once`);try{f=await d()}catch(e){if(e instanceof $)throw e;f={kind:`dead`,reason:`runagent-threw`,detail:e instanceof Error?e.message:String(e)}}}f.kind===`ok`&&e.resources.budget.addOutputTokens(f.usage.outputTokens),n({type:`agent_done`,agentId:a,label:c,phase:l,result:f});let p={key:s,seq:a,result:f};return e.journal.push(p),e.journalIndex++,await e.ports.journalStore.append(e.runId,p),si(f)}finally{u()}},parallel:async t=>{if(t.length>4096)throw new Q(`parallel exceeds the per-call items cap (${hr})`);return Promise.all(t.map(async(t,n)=>{try{return await t()}catch(t){return e.ports.logger.warn?.(`parallel thunk #${n} failed: ${t.message}`),null}}))},pipeline:async(t,...n)=>{if(t.length>4096)throw new Q(`pipeline exceeds the per-call items cap (${hr})`);return Promise.all(t.map(async(t,r)=>{try{let e=t;for(let i of n)e=await i(e,t,r);return e}catch(t){return e.ports.logger.warn?.(`pipeline item #${r} failed: ${t.message}`),null}}))},phase:t=>{e.currentPhase&&n({type:`phase_done`,phase:e.currentPhase}),e.currentPhase=t,n({type:`phase_started`,phase:t})},log:e=>{n({type:`log`,message:e})},workflow:async(n,r)=>{if(e.resources.depth>=1)throw new Q(`workflow() nesting allows only one level`);return t({...typeof n==`string`?{name:n}:{scriptPath:n.scriptPath},args:r})}}}function si(e){return e.kind===`ok`?e.output:null}var ci=t((()=>{Y(),ni(),Vr()}));async function li(e){let{ports:t}=e,n;try{n=X(e.script)}catch(n){let r=n.message;return t.progressEmitter.emit({type:`run_done`,runId:e.runId,status:`failed`,error:r}),{status:`failed`,error:r}}let r=e.workflowName??n.meta?.name??`workflow`,i=[],a=!1;e.resume&&!e.scriptChanged?i=await t.journalStore.read(e.runId):e.scriptChanged&&(await t.journalStore.truncate(e.runId),a=!0);let o=ii({ports:t,host:e.host,signal:e.signal,runId:e.runId,workflowName:r,cwd:e.cwd,budgetTotal:e.budgetTotal,maxConcurrency:e.maxConcurrency,journal:i});a&&(o.journalInvalidated=!0),t.progressEmitter.emit({type:`run_started`,runId:e.runId,workflowName:r,meta:n.meta});let s=async t=>{let n=await ui(t,e.cwd),r;try{r=X(n)}catch(e){throw new Q(`Sub-workflow script error: ${e.message}`)}let i=o.resources.depth;o.resources.depth+=1;try{let e=oi(o,s);return await r.execute(e,t.args,o.resources.budget)}finally{o.resources.depth=i}},c=oi(o,s),l=()=>{o.currentPhase&&t.progressEmitter.emit({type:`phase_done`,runId:e.runId,phase:o.currentPhase})},u;try{u={status:`completed`,returnValue:await n.execute(c,e.args,o.resources.budget)}}catch(e){u=e instanceof $?{status:`killed`}:{status:`failed`,error:e.message}}return l(),t.progressEmitter.emit({type:`run_done`,runId:e.runId,...u}),u}async function ui(e,t){if(e.script)return e.script;if(e.scriptPath)return await L(e.scriptPath,`utf-8`);if(e.name){let n=await $r(M(t,J),e.name);if(!n)throw new Q(`Sub-workflow "${e.name}" not found`);return n.content}throw new Q(`workflow() requires name or scriptPath`)}var di=t((()=>{Y(),ai(),ni(),ci(),ti(),Lr()}));function fi(e){return{emit:e}}function pi(){let e=[];return{emitter:{emit:t=>void e.push(t)},events:e}}var mi=t((()=>{})),hi,gi=t((()=>{m(),hi=f({script:l().optional().describe(`Self-contained workflow script source (inline)`),name:l().optional().describe(`Named workflow, resolved to .workmate/workflows/<name>.ts|js|mjs`),scriptPath:l().optional().describe(`Absolute path to an existing script file`),args:d().optional().describe(`The args global variable passed through to the script. Pass a real JSON value (object/array/string), not a JSON string.`),resumeFromRunId:l().optional().describe(`Resume the specified run, replaying the journal`),description:l().optional().describe(`A short description of this invocation (3-5 words)`),title:l().optional().describe(`Progress viewer title`),maxConcurrency:u().int().min(1).max(16).optional().describe(`Concurrency cap for agent(). Defaults to 3 (max 16). When the workflow contains heavy parallel/pipeline fan-out, you may confirm the desired concurrency with the user via AskUserQuestion before launching.`)})}));async function _i(e,t,n){let r=M(n,fr,t);await te(r,{recursive:!0});let i=M(r,`script.js`);return await ie(i,e,`utf-8`),i}var vi=t((()=>{Y()}));function yi(e){return{name:q,inputSchema:hi,isEnabled:()=>!0,isReadOnly:()=>!1,async description(){return`Execute a workflow script that orchestrates multiple subagents to complete a task`},async prompt(){return wi},renderToolUseMessage(e){return e.resumeFromRunId?`Workflow resume: ${e.resumeFromRunId}`:`Workflow: ${e.name??e.scriptPath??(e.script?`inline`:`unknown`)}`},async call(t,n,r,i){let a=e.hostFactory({context:n,canUseTool:r,parentMessage:i}),o,s;try{let e=await Ci(t,a.cwd);o=e.script,s=e.workflowFile}catch(e){return{data:{output:`Error: ${e.message}`}}}try{X(o)}catch(e){return{data:{output:`Error: script validation failed: ${e.message}`}}}let c=t.name??t.title??`workflow`,{runId:l,signal:u}=e.taskRegistrar.register({workflowName:c,...s?{workflowFile:s}:{},...t.description?{summary:t.description}:{},...a.toolUseId?{toolUseId:a.toolUseId}:{},...t.resumeFromRunId?{runId:t.resumeFromRunId}:{}},a.handle);if(!s&&t.script)try{s=await _i(t.script,l,a.cwd)}catch(t){e.logger.warn?.(`inline script persist failed: ${t.message}`)}li({script:o,...t.args===void 0?{}:{args:Si(t.args)},runId:l,workflowName:c,ports:e,host:a.handle,signal:u,cwd:a.cwd,budgetTotal:a.budgetTotal,...t.maxConcurrency===void 0?{}:{maxConcurrency:t.maxConcurrency},...t.resumeFromRunId?{resume:!0}:{}}).then(t=>bi(e,t,l)).catch(t=>e.taskRegistrar.fail(l,t.message));let d=s??`<inline run ${l}>`;return{data:{output:[`Workflow started (running in the background).`,`run_id: ${l}`,`workflow: ${c}`,`script: ${d}`,``,`You will be notified on completion. Use /workflows to view live progress.`].join(`
103
+ `)}}},mapToolResultToToolResultBlockParam(e,t){return{tool_use_id:t,type:`tool_result`,content:[{type:`text`,text:e.output}]}}}}function bi(e,t,n){if(t.status===`completed`){let r=t.returnValue==null?`(no return value)`:xi(t.returnValue);e.taskRegistrar.complete(n,r)}else t.status===`failed`?e.taskRegistrar.fail(n,t.error??`workflow failed`):e.taskRegistrar.kill(n)}function xi(e){if(typeof e==`string`)return e.slice(0,500);try{return JSON.stringify(e).slice(0,500)}catch{return String(e)}}function Si(e){if(typeof e!=`string`)return e;try{let t=JSON.parse(e);return typeof t==`object`&&t?t:e}catch{return e}}async function Ci(e,t){if(e.script)return{script:e.script};if(e.scriptPath){let n=P(t,e.scriptPath);if(!Yr(t,n))throw Error(`scriptPath "${e.scriptPath}" is out of bounds (after resolve, ${n} is not within cwd ${t})`);return{script:await L(n,`utf-8`),workflowFile:n}}if(e.name){if(Xr(e.name)===null)throw Error(`Named workflow name "${e.name}" is invalid (contains path separators or is . / ..)`);let n=await $r(M(t,J),e.name);if(!n)throw Error(`Named workflow "${e.name}" not found (looked in ${J}/)`);return{script:n.content,workflowFile:n.path}}throw Error(`One of script, name, or scriptPath must be provided`)}var wi,Ti=t((()=>{Y(),ti(),di(),Lr(),Zr(),gi(),vi(),wi='Use the Workflow tool to execute a workflow script that orchestrates multiple subagents deterministically. The script runs in the background; you receive a run_id immediately and are notified on completion.\n\nProvide the script inline via "script", or reference a named workflow via "name" (resolved from .workmate/workflows/), or an existing file via "scriptPath". Pass "args" as a real JSON value (object/array/string), not a stringified string.\n\nUse "resumeFromRunId" to resume a prior run — completed agent() calls replay from the journal instantly.\n\nConcurrency: default is 3 (hard ceiling 16). OMIT maxConcurrency to use 3. To set maxConcurrency to ANY value other than 3, you MUST first ask the user via AskUserQuestion — propose 3 / 6 / 9 (or other tiers matching the fan-out width) with 3 marked "(Recommended)". The ONLY exception: the user has ALREADY specified a concurrency number in this session ("use 6", "maxConcurrency 9") — then honor it without re-asking. Never silently raise concurrency above 3 just because the workflow fans out; 3 is the recommended default.\n\nScript execution model (common pitfalls — getting these wrong is the #1 cause of script errors): the script is the body of `new AsyncFunction` — NOT an ESM module, and TypeScript is NOT transpiled. Therefore:\n- Do NOT use `import` — `agent`, `parallel`, `pipeline`, `phase`, `log`, `workflow`, `args`, and `budget` are injected as parameters; reference them directly.\n- Do NOT use TS type annotations, `interface`, `enum`, `as`, or generics — the engine does not transpile, so even a .ts file with type syntax fails to parse.\n- Keep EXACTLY ONE `export const meta = {...}` (plain literal) and remove every other `export` / `export default`.\n- Return the result with a top-level `return`.\nPrefer .js / .mjs. See /ultracode for the full playbook and quality patterns.'})),Ei=r({AdapterNotFoundError:()=>Sr,AgentAdapterRegistry:()=>Cr,Budget:()=>Ur,BudgetExhaustedError:()=>Hr,DEFAULT_MAX_CONCURRENCY:()=>3,MAX_CONCURRENCY_CAP:()=>16,MAX_ITEMS_PER_CALL:()=>hr,MAX_TOTAL_AGENTS:()=>mr,ScriptError:()=>Z,Semaphore:()=>Dr,WORKFLOW_DIR_NAME:()=>J,WORKFLOW_RUNS_DIR:()=>fr,WORKFLOW_SCRIPT_EXTENSIONS:()=>pr,WORKFLOW_TOOL_NAME:()=>q,WorkflowAbortedError:()=>$,WorkflowError:()=>Q,agentCallKey:()=>zr,clampMaxConcurrency:()=>Er,createBufferingEmitter:()=>pi,createEngineContext:()=>ii,createFileJournalStore:()=>Br,createHostHandle:()=>gr,createProgressEmitter:()=>fi,createSharedResources:()=>ri,createWorkflowTool:()=>yi,extractMeta:()=>kr,isHostHandle:()=>_r,listNamedWorkflows:()=>ei,makeHooks:()=>oi,maxConcurrency:()=>Tr,parseScript:()=>X,persistInlineScript:()=>_i,resolveNamedWorkflow:()=>$r,runWorkflow:()=>li,unwrapHostHandle:()=>vr,validateAgainstSchema:()=>Gr,workflowInputSchema:()=>hi}),Di=t((()=>{dr(),Y(),br(),wr(),Or(),Lr(),Vr(),Wr(),Jr(),ti(),ni(),ai(),ci(),di(),mi(),Ti(),gi(),vi()})),Oi,ki,Ai,ji,Mi,Ni,Pi=t((()=>{Oi=`LocalMemoryRecall`,ki=100*1024,Ai=2*1024,ji=50*1024,Mi=4*1024,Ni=8*1024})),Fi,Ii,Li,Ri,zi=t((()=>{T(),Me(),_n(),C(),Sn(),b(),Ae(),Pe(),wn(),hn(),kn(),ge(),Nn(),Fn(),Be(),Ie(),Ln(),zn(),Re(),Vn(),Xn(),er(),nr(),ir(),or(),cr(),ur(),Di(),Pi(),Fi=new Set([S,je,gn,x,vn,w,q,Oi]),Ii=new Set([...Fi]),Li=new Set([z,Ne,G,pn,...On,fe,Mn,Pn,ze,K,Bn,ar,sr,lr]),Ri=new Set([...On,z,fe,Mn,pn,G,Pn,x,vn,S,w,Fe,In,Rn,Le,Ne,gn,je,rr,`LSP`,ze,q,Zn,Bn,ar,K])}));function Bi(){return`Deferred tools appear by name in <available-deferred-tools> messages.`}function Vi(e){return!(e.alwaysLoad===!0||Ri.has(e.name))}function Hi(e){return e.name}function Ui(){return Wi+Bi()+Gi}var Wi,Gi,Ki=t((()=>{zi(),Vn(),Wi=`Search for deferred tools by name or keyword. LOW PRIORITY — only use this tool when no core tool can accomplish the task. Core tools (Read, Edit, Write, Bash, Glob, Grep, Agent, WebFetch, WebSearch, Skill) are always available and should be used directly. This tool is for discovering additional capabilities like MCP tools, worktree management, agent teams (TeamCreate, TeamDelete, SendMessage), etc.
104
104
 
105
105
  `,Gi=` Returns matching tool names.
106
106
 
@@ -0,0 +1 @@
1
+ import{i as e,r as t}from"./prompt-DIlq8NTy.js";t();export{e as isDeferredTool};
@@ -0,0 +1 @@
1
+ import{Tw as e,yw as t}from"./loadAgentsDir-mcRW90aq.js";e();export{t as clearPromptCache};
@@ -1,4 +1,4 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{n as t,t as n}from"./memoize-BK3gG5ob.js";import{Id as r,Ld as i,Md as a,Pd as o,bu as s,qb as c,xu as l,zb as u}from"./loadAgentsDir-BL93ulMm.js";import{Rn as d,t as f}from"./src-P_wYS_NJ2.js";import{T as p,c as m,f as h,i as g,u as _,x as v}from"./debug-BecbSVoN.js";import{n as y,t as b}from"./execSyncWrapper-CDzB0BM1.js";import{r as x,t as S}from"./which-BRWBO7Gu.js";import{basename as C}from"path";import{spawn as w,spawnSync as T}from"child_process";function E(e){return!!x(e)}function D(e){let t=C(e.split(` `)[0]??``);return A.find(e=>t.includes(e))}function O(e,t,n){return n?M.has(e)?[`-g`,`${t}:${n}`]:e===`subl`?[`${t}:${n}`]:[t]:[t]}function k(e,t){let n=N();if(!n)return!1;let r=n.split(` `),i=r[0]??n,a=r.slice(1),o=D(n);if(o){let r=O(o,e,t),s={detached:!0,stdio:`ignore`},c;return c=process.platform===`win32`?w(`${n} ${r.map(e=>`"${e}"`).join(` `)}`,{...s,shell:!0}):w(i,[...a,...r],s),c.on(`error`,e=>m(`editor spawn failed: ${e}`,{level:`error`})),c.unref(),!0}let s=d.get(process.stdout);if(!s)return!1;let c=t&&j.test(C(i));s.enterAlternateScreen();try{let r={stdio:`inherit`},o;return o=process.platform===`win32`?T(`${n} ${c?`+${t} `:``}"${e}"`,{...r,shell:!0}):T(i,[...a,...c?[`+${t}`,e]:[e]],r),o.error?(m(`editor spawn failed: ${o.error}`,{level:`error`}),!1):!0}finally{s.exitAlternateScreen()}}var A,j,M,N,P=e((()=>{n(),f(),g(),S(),A=[`code`,`cursor`,`windsurf`,`codium`,`subl`,`atom`,`gedit`,`notepad++`,`notepad`],j=/\b(vi|vim|nvim|nano|emacs|pico|micro|helix|hx)\b/,M=new Set([`code`,`cursor`,`windsurf`,`codium`]),N=t(()=>process.env.VISUAL?.trim()?process.env.VISUAL.trim():process.env.EDITOR?.trim()?process.env.EDITOR.trim():process.platform===`win32`?`start /wait notepad`:[`code`,`vi`,`nano`].find(e=>E(e)))}));function F(e){return D(e)!==void 0}function I(e){let t=_(),n=d.get(process.stdout);if(!n)throw Error(`Ink instance not found - cannot pause rendering`);let r=N();if(!r)return{content:null};try{t.statSync(e)}catch{return{content:null}}let i=!F(r);i?n.enterAlternateScreen():(n.pause(),n.suspendStdin());try{return b(`${z[r]??r} "${e}"`,{stdio:`inherit`}),{content:t.readFileSync(e,{encoding:`utf-8`})}}catch(e){if(typeof e==`object`&&e&&`status`in e&&typeof e.status==`number`){let t=e.status;if(t!==0)return{content:null,error:`${c(r)} exited with code ${t}`}}return{content:null}}finally{i?n.exitAlternateScreen():(n.resumeStdin(),n.resume())}}function L(e,t,n){let i=e;for(let[e,t]of Object.entries(n))if(t.type===`text`){let n=parseInt(e,10),a=t.content,s=i.indexOf(a);if(s!==-1){let e=o(n,r(a));i=i.slice(0,s)+e+i.slice(s+a.length)}}return i}function R(e,t){let n=_(),r=s();try{p(r,t?a(e,t):e,{encoding:`utf-8`,flush:!0});let n=I(r);if(n.content===null)return n;let i=n.content;return i.endsWith(`
1
+ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{n as t,t as n}from"./memoize-BK3gG5ob.js";import{Ad as r,Md as i,Nd as a,Ob as o,Od as s,_u as c,bb as l,gu as u}from"./loadAgentsDir-mcRW90aq.js";import{Rn as d,t as f}from"./src-P_wYS_NJ2.js";import{T as p,c as m,f as h,i as g,u as _,x as v}from"./debug-Dr1SjdXn.js";import{n as y,t as b}from"./execSyncWrapper-Ne33rRiD.js";import{r as x,t as S}from"./which-mplwBbc0.js";import{basename as C}from"path";import{spawn as w,spawnSync as T}from"child_process";function E(e){return!!x(e)}function D(e){let t=C(e.split(` `)[0]??``);return A.find(e=>t.includes(e))}function O(e,t,n){return n?M.has(e)?[`-g`,`${t}:${n}`]:e===`subl`?[`${t}:${n}`]:[t]:[t]}function k(e,t){let n=N();if(!n)return!1;let r=n.split(` `),i=r[0]??n,a=r.slice(1),o=D(n);if(o){let r=O(o,e,t),s={detached:!0,stdio:`ignore`},c;return c=process.platform===`win32`?w(`${n} ${r.map(e=>`"${e}"`).join(` `)}`,{...s,shell:!0}):w(i,[...a,...r],s),c.on(`error`,e=>m(`editor spawn failed: ${e}`,{level:`error`})),c.unref(),!0}let s=d.get(process.stdout);if(!s)return!1;let c=t&&j.test(C(i));s.enterAlternateScreen();try{let r={stdio:`inherit`},o;return o=process.platform===`win32`?T(`${n} ${c?`+${t} `:``}"${e}"`,{...r,shell:!0}):T(i,[...a,...c?[`+${t}`,e]:[e]],r),o.error?(m(`editor spawn failed: ${o.error}`,{level:`error`}),!1):!0}finally{s.exitAlternateScreen()}}var A,j,M,N,P=e((()=>{n(),f(),g(),S(),A=[`code`,`cursor`,`windsurf`,`codium`,`subl`,`atom`,`gedit`,`notepad++`,`notepad`],j=/\b(vi|vim|nvim|nano|emacs|pico|micro|helix|hx)\b/,M=new Set([`code`,`cursor`,`windsurf`,`codium`]),N=t(()=>process.env.VISUAL?.trim()?process.env.VISUAL.trim():process.env.EDITOR?.trim()?process.env.EDITOR.trim():process.platform===`win32`?`start /wait notepad`:[`code`,`vi`,`nano`].find(e=>E(e)))}));function F(e){return D(e)!==void 0}function I(e){let t=_(),n=d.get(process.stdout);if(!n)throw Error(`Ink instance not found - cannot pause rendering`);let r=N();if(!r)return{content:null};try{t.statSync(e)}catch{return{content:null}}let i=!F(r);i?n.enterAlternateScreen():(n.pause(),n.suspendStdin());try{return b(`${z[r]??r} "${e}"`,{stdio:`inherit`}),{content:t.readFileSync(e,{encoding:`utf-8`})}}catch(e){if(typeof e==`object`&&e&&`status`in e&&typeof e.status==`number`){let t=e.status;if(t!==0)return{content:null,error:`${o(r)} exited with code ${t}`}}return{content:null}}finally{i?n.exitAlternateScreen():(n.resumeStdin(),n.resume())}}function L(e,t,n){let a=e;for(let[e,t]of Object.entries(n))if(t.type===`text`){let n=parseInt(e,10),o=t.content,s=a.indexOf(o);if(s!==-1){let e=r(n,i(o));a=a.slice(0,s)+e+a.slice(s+o.length)}}return a}function R(e,t){let n=_(),r=u();try{p(r,t?s(e,t):e,{encoding:`utf-8`,flush:!0});let n=I(r);if(n.content===null)return n;let i=n.content;return i.endsWith(`
2
2
  `)&&!i.endsWith(`
3
3
 
4
- `)&&(i=i.slice(0,-1)),t&&(i=L(i,e,t)),{content:i}}finally{try{n.unlinkSync(r)}catch{}}}var z,B=e((()=>{i(),f(),P(),y(),h(),u(),v(),l(),z={code:`code -w`,subl:`subl --wait`}}));export{P as a,N as i,R as n,k as o,B as r,I as t};
4
+ `)&&(i=i.slice(0,-1)),t&&(i=L(i,e,t)),{content:i}}finally{try{n.unlinkSync(r)}catch{}}}var z,B=e((()=>{a(),f(),P(),y(),h(),l(),v(),c(),z={code:`code -w`,subl:`subl --wait`}}));export{P as a,N as i,R as n,k as o,B as r,I as t};
@@ -1,4 +1,4 @@
1
- import{C as e,c as t,i as n,x as r}from"./debug-BecbSVoN.js";import{c as i,h as a}from"./config-aRiTrtCv.js";import{r as o,t as s}from"./execFileNoThrow-DHyW8FMX.js";import{n as c,t as l}from"./which-BRWBO7Gu.js";import{n as u,t as d}from"./githubRepoPathMapping-CK56bUDe.js";import{n as f}from"./banner-1Wyeyawe.js";import{a as p,i as m,n as h}from"./registerProtocol-E0Iu5hEx.js";import{homedir as g}from"os";import{basename as _}from"path";import{spawn as v}from"child_process";r(),m(),h(),a(),n(),o(),l();var y=[{name:`iTerm2`,bundleId:`com.googlecode.iterm2`,app:`iTerm`},{name:`Ghostty`,bundleId:`com.mitchellh.ghostty`,app:`Ghostty`},{name:`Kitty`,bundleId:`net.kovidgoyal.kitty`,app:`kitty`},{name:`Alacritty`,bundleId:`org.alacritty`,app:`Alacritty`},{name:`WezTerm`,bundleId:`com.github.wez.wezterm`,app:`WezTerm`},{name:`Terminal.app`,bundleId:`com.apple.Terminal`,app:`Terminal`}],b=[`ghostty`,`kitty`,`alacritty`,`wezterm`,`gnome-terminal`,`konsole`,`xfce4-terminal`,`mate-terminal`,`tilix`,`xterm`];async function x(){let e=i().deepLinkTerminal;if(e){let t=y.find(t=>t.app===e);if(t)return{name:t.name,command:t.app}}let t=process.env.TERM_PROGRAM;if(t){let e=t.replace(/\.app$/i,``).toLowerCase(),n=y.find(t=>t.app.toLowerCase()===e||t.name.toLowerCase()===e);if(n)return{name:n.name,command:n.app}}for(let e of y){let{code:t,stdout:n}=await s(`mdfind`,[`kMDItemCFBundleIdentifier == "${e.bundleId}"`],{timeout:5e3,useCwd:!1});if(t===0&&n.trim().length>0)return{name:e.name,command:e.app}}for(let e of y){let{code:t}=await s(`ls`,[`/Applications/${e.app}.app`],{timeout:1e3,useCwd:!1});if(t===0)return{name:e.name,command:e.app}}return{name:`Terminal.app`,command:`Terminal`}}async function S(){let e=process.env.TERMINAL;if(e){let t=await c(e);if(t)return{name:_(e),command:t}}let t=await c(`x-terminal-emulator`);if(t)return{name:`x-terminal-emulator`,command:t};for(let e of b){let t=await c(e);if(t)return{name:e,command:t}}return null}async function C(){let e=await c(`wt.exe`);if(e)return{name:`Windows Terminal`,command:e};let t=await c(`pwsh.exe`);if(t)return{name:`PowerShell`,command:t};let n=await c(`powershell.exe`);return n?{name:`PowerShell`,command:n}:{name:`Command Prompt`,command:`cmd.exe`}}async function w(){switch(process.platform){case`darwin`:return x();case`linux`:return S();case`win32`:return C();default:return null}}async function T(e,n){let r=await w();if(!r)return t(`No terminal emulator detected`,{level:`error`}),!1;t(`Launching in terminal: ${r.name} (${r.command})`);let i=[`--deep-link-origin`];switch(n.repo&&(i.push(`--deep-link-repo`,n.repo),n.lastFetchMs!==void 0&&i.push(`--deep-link-last-fetch`,String(n.lastFetchMs))),n.query&&i.push(`--prefill`,n.query),process.platform){case`darwin`:return E(r,e,i,n.cwd);case`linux`:return D(r,e,i,n.cwd);case`win32`:return O(r,e,i,n.cwd);default:return!1}}async function E(e,n,r,i){switch(e.command){case`iTerm`:{let{code:e}=await s(`osascript`,[`-e`,`tell application "iTerm"
1
+ import{C as e,c as t,i as n,x as r}from"./debug-Dr1SjdXn.js";import{c as i,h as a}from"./config-9rLTDOYW.js";import{r as o,t as s}from"./execFileNoThrow-mXq4K0rl.js";import{n as c,t as l}from"./which-mplwBbc0.js";import{n as u,t as d}from"./githubRepoPathMapping-CmpEaQoo.js";import{n as f}from"./banner-BcAM7iSx.js";import{a as p,i as m,n as h}from"./registerProtocol-DduKPsn_.js";import{homedir as g}from"os";import{basename as _}from"path";import{spawn as v}from"child_process";r(),m(),h(),a(),n(),o(),l();var y=[{name:`iTerm2`,bundleId:`com.googlecode.iterm2`,app:`iTerm`},{name:`Ghostty`,bundleId:`com.mitchellh.ghostty`,app:`Ghostty`},{name:`Kitty`,bundleId:`net.kovidgoyal.kitty`,app:`kitty`},{name:`Alacritty`,bundleId:`org.alacritty`,app:`Alacritty`},{name:`WezTerm`,bundleId:`com.github.wez.wezterm`,app:`WezTerm`},{name:`Terminal.app`,bundleId:`com.apple.Terminal`,app:`Terminal`}],b=[`ghostty`,`kitty`,`alacritty`,`wezterm`,`gnome-terminal`,`konsole`,`xfce4-terminal`,`mate-terminal`,`tilix`,`xterm`];async function x(){let e=i().deepLinkTerminal;if(e){let t=y.find(t=>t.app===e);if(t)return{name:t.name,command:t.app}}let t=process.env.TERM_PROGRAM;if(t){let e=t.replace(/\.app$/i,``).toLowerCase(),n=y.find(t=>t.app.toLowerCase()===e||t.name.toLowerCase()===e);if(n)return{name:n.name,command:n.app}}for(let e of y){let{code:t,stdout:n}=await s(`mdfind`,[`kMDItemCFBundleIdentifier == "${e.bundleId}"`],{timeout:5e3,useCwd:!1});if(t===0&&n.trim().length>0)return{name:e.name,command:e.app}}for(let e of y){let{code:t}=await s(`ls`,[`/Applications/${e.app}.app`],{timeout:1e3,useCwd:!1});if(t===0)return{name:e.name,command:e.app}}return{name:`Terminal.app`,command:`Terminal`}}async function S(){let e=process.env.TERMINAL;if(e){let t=await c(e);if(t)return{name:_(e),command:t}}let t=await c(`x-terminal-emulator`);if(t)return{name:`x-terminal-emulator`,command:t};for(let e of b){let t=await c(e);if(t)return{name:e,command:t}}return null}async function C(){let e=await c(`wt.exe`);if(e)return{name:`Windows Terminal`,command:e};let t=await c(`pwsh.exe`);if(t)return{name:`PowerShell`,command:t};let n=await c(`powershell.exe`);return n?{name:`PowerShell`,command:n}:{name:`Command Prompt`,command:`cmd.exe`}}async function w(){switch(process.platform){case`darwin`:return x();case`linux`:return S();case`win32`:return C();default:return null}}async function T(e,n){let r=await w();if(!r)return t(`No terminal emulator detected`,{level:`error`}),!1;t(`Launching in terminal: ${r.name} (${r.command})`);let i=[`--deep-link-origin`];switch(n.repo&&(i.push(`--deep-link-repo`,n.repo),n.lastFetchMs!==void 0&&i.push(`--deep-link-last-fetch`,String(n.lastFetchMs))),n.query&&i.push(`--prefill`,n.query),process.platform){case`darwin`:return E(r,e,i,n.cwd);case`linux`:return D(r,e,i,n.cwd);case`win32`:return O(r,e,i,n.cwd);default:return!1}}async function E(e,n,r,i){switch(e.command){case`iTerm`:{let{code:e}=await s(`osascript`,[`-e`,`tell application "iTerm"
2
2
  if running then
3
3
  create window with default profile
4
4
  else
@@ -1,4 +1,4 @@
1
- import{i as e,n as t,o as n,t as r}from"./rolldown-runtime-DaDcL9Zw.js";import{n as i,t as a}from"./memoize-BK3gG5ob.js";import{a as o,l as s,o as c}from"./envUtils-BDhHQY0-.js";import{i as l,n as u,r as d,t as f}from"./defineProperty-C-QyHrDq.js";import{a as p,c as m,i as h,n as g,o as _,r as v,s as y,t as b}from"./classPrivateFieldSet2-D4U5K-I3.js";import{n as x,t as S}from"./classPrivateMethodInitSpec-BXQD0Vh4.js";import{t as C}from"./src-DCUgdrYl.js";import{n as w,t as T}from"./axios-DaWTGg7G.js";import{c as E,f as D,i as O,u as k}from"./debug-BecbSVoN.js";import A from"assert";import{Agent as j}from"https";import*as M from"http";import{URL as N}from"url";import*as P from"net";import*as F from"tls";var I=t((()=>{})),L,R,z=t((()=>{I(),L=Symbol(`AgentBaseInternalState`),R=class extends M.Agent{constructor(e){super(e),this[L]={}}isSecureEndpoint(e){if(e){if(typeof e.secureEndpoint==`boolean`)return e.secureEndpoint;if(typeof e.protocol==`string`)return e.protocol===`https:`}let{stack:t}=Error();return typeof t==`string`&&t.split(`
1
+ import{i as e,n as t,o as n,t as r}from"./rolldown-runtime-DaDcL9Zw.js";import{n as i,t as a}from"./memoize-BK3gG5ob.js";import{a as o,l as s,o as c}from"./envUtils-DcaKZlRU.js";import{i as l,n as u,r as d,t as f}from"./defineProperty-C-QyHrDq.js";import{a as p,c as m,i as h,n as g,o as _,r as v,s as y,t as b}from"./classPrivateFieldSet2-D4U5K-I3.js";import{n as x,t as S}from"./classPrivateMethodInitSpec-BXQD0Vh4.js";import{t as C}from"./src-DCUgdrYl.js";import{n as w,t as T}from"./axios-DaWTGg7G.js";import{c as E,f as D,i as O,u as k}from"./debug-Dr1SjdXn.js";import A from"assert";import{Agent as j}from"https";import*as M from"http";import{URL as N}from"url";import*as P from"net";import*as F from"tls";var I=t((()=>{})),L,R,z=t((()=>{I(),L=Symbol(`AgentBaseInternalState`),R=class extends M.Agent{constructor(e){super(e),this[L]={}}isSecureEndpoint(e){if(e){if(typeof e.secureEndpoint==`boolean`)return e.secureEndpoint;if(typeof e.protocol==`string`)return e.protocol===`https:`}let{stack:t}=Error();return typeof t==`string`&&t.split(`
2
2
  `).some(e=>e.indexOf(`(https.js:`)!==-1||e.indexOf(`node:https:`)!==-1)}incrementSockets(e){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;this.sockets[e]||(this.sockets[e]=[]);let t=new P.Socket({writable:!1});return this.sockets[e].push(t),this.totalSocketCount++,t}decrementSockets(e,t){if(!this.sockets[e]||t===null)return;let n=this.sockets[e],r=n.indexOf(t);r!==-1&&(n.splice(r,1),this.totalSocketCount--,n.length===0&&delete this.sockets[e])}getName(e){return this.isSecureEndpoint(e)?j.prototype.getName.call(this,e):super.getName(e)}createSocket(e,t,n){let r={...t,secureEndpoint:this.isSecureEndpoint(t)},i=this.getName(r),a=this.incrementSockets(i);Promise.resolve().then(()=>this.connect(e,r)).then(o=>{if(this.decrementSockets(i,a),o instanceof M.Agent)try{return o.addRequest(e,r)}catch(e){return n(e)}this[L].currentSocket=o,super.createSocket(e,t,n)},e=>{this.decrementSockets(i,a),n(e)})}createConnection(){let e=this[L].currentSocket;if(this[L].currentSocket=void 0,!e)throw Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[L].defaultPort??(this.protocol===`https:`?443:80)}set defaultPort(e){this[L]&&(this[L].defaultPort=e)}get protocol(){return this[L].protocol??(this.isSecureEndpoint()?`https:`:`http:`)}set protocol(e){this[L]&&(this[L].protocol=e)}}}));function B(e){return new Promise((t,n)=>{let r=0,i=[];function a(){let t=e.read();t?l(t):e.once(`readable`,a)}function o(){e.removeListener(`end`,s),e.removeListener(`error`,c),e.removeListener(`readable`,a)}function s(){o(),H(`onend`),n(Error(`Proxy connection ended before receiving CONNECT response`))}function c(e){o(),H(`onerror %o`,e),n(e)}function l(s){i.push(s),r+=s.length;let c=Buffer.concat(i,r),l=c.indexOf(`\r
3
3
  \r
4
4
  `);if(l===-1){H(`have not received end of HTTP headers yet...`),a();return}let u=c.slice(0,l).toString(`ascii`).split(`\r
@@ -0,0 +1 @@
1
+ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{join as t}from"node:path";import{appendFileSync as n,existsSync as r,mkdirSync as i}from"node:fs";import{homedir as a}from"node:os";function o(){let e=t(a(),`.workmate`);r(e)||i(e,{recursive:!0})}function s(e){try{l||(o(),n(c,`\n===== RC-DEBUG session ${new Date().toISOString()} =====\n`),l=!0);let t=new Date().toISOString().slice(11,23);n(c,`[${t}] ${e}\n`)}catch{}}var c,l,u=e((()=>{c=t(a(),`.workmate`,`rc-debug.log`),l=!1}));export{s as n,u as t};
@@ -0,0 +1 @@
1
+ import{Mo as e,Po as t,Ro as n,zo as r}from"./loadAgentsDir-mcRW90aq.js";import{Wt as i,et as a}from"./state-BPFYBqm1.js";import{P as o,R as s,c,i as l}from"./debug-Dr1SjdXn.js";import{kn as u,vt as d,wn as f,yt as p}from"./settings-DiBMs2gM.js";import{m,n as h}from"./git-CoQQ6YEf.js";import{o as g,s as _}from"./log-27kCA_9u.js";import{ar as v,ir as y}from"./model-C29_32BD.js";import{isAbsolute as b,resolve as x}from"path";y(),i(),l(),s(),f(),m(),g(),n(),d();function S(e,t,n){let r=[],i=[],a=[];for(let[o,s]of Object.entries(e)){let e=t[o],c=w(s.source,n?.projectRoot);e?s.sourceIsFallback||v(c,e.source)?a.push(o):i.push({name:o,declaredSource:c,materializedSource:e.source}):r.push(o)}return{missing:r,sourceChanged:i,upToDate:a}}async function C(n){let i=t();if(Object.keys(i).length===0)return{installed:[],updated:[],failed:[],upToDate:[],skipped:[]};let s;try{s=await r()}catch(e){_(e),s={}}let l=S(i,s,{projectRoot:a()}),d=[...l.missing.map(e=>({name:e,source:w(i[e].source),action:`install`})),...l.sourceChanged.map(({name:e,declaredSource:t})=>({name:e,source:t,action:`update`}))],f=[],m=[];for(let e of d){if(n?.skip?.(e.name,e.source)){f.push(e.name);continue}if(e.action===`update`&&p(e.source)&&!await u(e.source.path)){c(`[reconcile] '${e.name}' declared path does not exist; keeping materialized entry`),f.push(e.name);continue}m.push(e)}if(m.length===0)return{installed:[],updated:[],failed:[],upToDate:l.upToDate,skipped:f};c(`[reconcile] ${m.length} marketplace(s): ${m.map(e=>`${e.name}(${e.action})`).join(`, `)}`);let h=[],g=[],v=[];for(let t=0;t<m.length;t++){let{name:r,source:i,action:a}=m[t];n?.onProgress?.({type:`installing`,name:r,action:a,index:t+1,total:m.length});try{let t=await e(i);a===`install`?h.push(r):g.push(r),n?.onProgress?.({type:`installed`,name:r,alreadyMaterialized:t.alreadyMaterialized})}catch(e){let t=o(e);v.push({name:r,error:t}),n?.onProgress?.({type:`failed`,name:r,error:t}),_(e)}}return{installed:h,updated:g,failed:v,upToDate:l.upToDate,skipped:f}}function w(e,t){if((e.source===`directory`||e.source===`file`)&&!b(e.path)){let n=t??a(),r=h(n);return{...e,path:x(r??n,e.path)}}return e}export{C as n,S as t};
@@ -0,0 +1 @@
1
+ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{Ch as t,D_ as n,E_ as r,aS as i,bs as a,do as o,fh as s,i as c,iS as l,mh as u,o as d,os as f,ss as p,uo as m,wh as h,xh as g,yh as _,ys as v}from"./loadAgentsDir-mcRW90aq.js";import{Wt as y,et as b}from"./state-BPFYBqm1.js";import{P as x,R as S,c as C,i as w}from"./debug-Dr1SjdXn.js";import{o as T,s as E}from"./log-27kCA_9u.js";async function D(e){C(`refreshActivePlugins: clearing all plugin caches`),f(),s();let t=await o(),[r,a]=await Promise.all([v(),c(b())]),{enabled:l,disabled:u,errors:d}=t,[p,m]=await Promise.all([Promise.all(l.map(async e=>{if(e.mcpServers)return Object.keys(e.mcpServers).length;let t=await i(e,d);return t&&(e.mcpServers=t),t?Object.keys(t).length:0})),Promise.all(l.map(async e=>{if(e.lspServers)return Object.keys(e.lspServers).length;let t=await h(e,d);return t&&(e.lspServers=t),t?Object.keys(t).length:0}))]),_=p.reduce((e,t)=>e+t,0),y=m.reduce((e,t)=>e+t,0);e(e=>({...e,plugins:{...e.plugins,enabled:l,disabled:u,commands:r,errors:O(e.plugins.errors,d),needsRefresh:!1},agentDefinitions:a,mcp:{...e.mcp,pluginReconnectKey:e.mcp.pluginReconnectKey+1}})),g();let S=!1;try{await n()}catch(e){S=!0,E(e),C(`refreshActivePlugins: loadPluginHooks failed: ${x(e)}`)}let w=l.reduce((e,t)=>t.hooksConfig?e+Object.values(t.hooksConfig).reduce((e,t)=>e+(t?.reduce((e,t)=>e+t.hooks.length,0)??0),0):e,0);return C(`refreshActivePlugins: ${l.length} enabled, ${r.length} commands, ${a.allAgents.length} agents, ${w} hooks, ${_} MCP, ${y} LSP`),{enabled_count:l.length,disabled_count:u.length,command_count:r.length,agent_count:a.allAgents.length,hook_count:w,mcp_count:_,lsp_count:y,error_count:d.length+ +!!S,agentDefinitions:a,pluginCommands:r}}function O(e,t){let n=e.filter(e=>e.source===`lsp-manager`||e.source.startsWith(`plugin:`)),r=new Set(t.map(k));return[...n.filter(e=>!r.has(k(e))),...t]}function k(e){return e.type===`generic-error`?`generic-error:${e.source}:${e.error}`:`${e.type}:${e.source}`}var A=e((()=>{y(),_(),d(),w(),S(),T(),p(),a(),r(),t(),l(),u(),m()}));export{D as n,A as t};
@@ -1,4 +1,4 @@
1
- import{n as e,r as t}from"./rolldown-runtime-DaDcL9Zw.js";import{o as n}from"./envUtils-BDhHQY0-.js";import{F as r,R as i,c as a,i as o}from"./debug-BecbSVoN.js";import{g as s,n as c}from"./settings-D4CpDv2y.js";import{r as l,t as u}from"./execFileNoThrow-DHyW8FMX.js";import{n as d,t as f}from"./which-BRWBO7Gu.js";import{a as p,r as m,t as h}from"./xdg-DcF9ejUM.js";import*as g from"os";import*as _ from"path";import{promises as v}from"fs";function y(e){let t=e,n=``,r=0;for(;t!==n&&r<10;)n=t,t=t.normalize(`NFKC`),t=t.replace(/[\p{Cf}\p{Co}\p{Cn}]/gu,``),t=t.replace(/[\u200B-\u200F]/g,``).replace(/[\u202A-\u202E]/g,``).replace(/[\u2066-\u2069]/g,``).replace(/[\uFEFF]/g,``).replace(/[\uE000-\uF8FF]/g,``),r++;if(r>=10)throw Error(`Unicode sanitization reached maximum iterations (10) for input: ${e.slice(0,100)}`);return t}var b=e((()=>{}));function x(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<=31||n===127)return!0}return!1}function S(e){let t=e.startsWith(`claude-cli://`)?e:e.startsWith(`claude-cli:`)?e.replace(`${C}:`,`${C}://`):null;if(!t)throw Error(`Invalid deep link: expected ${C}:// scheme, got "${e}"`);let n;try{n=new URL(t)}catch{throw Error(`Invalid deep link URL: "${e}"`)}if(n.hostname!==`open`)throw Error(`Unknown deep link action: "${n.hostname}"`);let r=n.searchParams.get(`cwd`)??void 0,i=n.searchParams.get(`repo`)??void 0,a=n.searchParams.get(`q`);if(r&&!r.startsWith(`/`)&&!/^[a-zA-Z]:[/\\]/.test(r))throw Error(`Invalid cwd in deep link: must be an absolute path, got "${r}"`);if(r&&x(r))throw Error(`Deep link cwd contains disallowed control characters`);if(r&&r.length>E)throw Error(`Deep link cwd exceeds ${E} characters (got ${r.length})`);if(i&&!w.test(i))throw Error(`Invalid repo in deep link: expected "owner/repo", got "${i}"`);let o;if(a&&a.trim().length>0){if(o=y(a.trim()),x(o))throw Error(`Deep link query contains disallowed control characters`);if(o.length>T)throw Error(`Deep link query exceeds ${T} characters (got ${o.length})`)}return{query:o,cwd:r,repo:i}}var C,w,T,E,D=e((()=>{b(),C=`claude-cli`,w=/^[\w.-]+\/[\w.-]+$/,T=5e3,E=4096})),O=t({MACOS_BUNDLE_ID:()=>z,ensureDeepLinkProtocolRegistered:()=>R,isProtocolHandlerCurrent:()=>L,registerProtocolHandler:()=>F});function k(){return _.join(m(),`applications`,V)}function A(e){return`Exec="${e}" --handle-uri %u`}function j(e){return`"${e}" --handle-uri "%1"`}async function M(e){let t=_.join(H,`Contents`);try{await v.rm(H,{recursive:!0})}catch(e){if(r(e)!==`ENOENT`)throw e}await v.mkdir(_.dirname(U),{recursive:!0});let n=`<?xml version="1.0" encoding="UTF-8"?>
1
+ import{n as e,r as t}from"./rolldown-runtime-DaDcL9Zw.js";import{o as n}from"./envUtils-DcaKZlRU.js";import{F as r,R as i,c as a,i as o}from"./debug-Dr1SjdXn.js";import{g as s,n as c}from"./settings-DiBMs2gM.js";import{r as l,t as u}from"./execFileNoThrow-mXq4K0rl.js";import{n as d,t as f}from"./which-mplwBbc0.js";import{a as p,r as m,t as h}from"./xdg-DcF9ejUM.js";import*as g from"os";import*as _ from"path";import{promises as v}from"fs";function y(e){let t=e,n=``,r=0;for(;t!==n&&r<10;)n=t,t=t.normalize(`NFKC`),t=t.replace(/[\p{Cf}\p{Co}\p{Cn}]/gu,``),t=t.replace(/[\u200B-\u200F]/g,``).replace(/[\u202A-\u202E]/g,``).replace(/[\u2066-\u2069]/g,``).replace(/[\uFEFF]/g,``).replace(/[\uE000-\uF8FF]/g,``),r++;if(r>=10)throw Error(`Unicode sanitization reached maximum iterations (10) for input: ${e.slice(0,100)}`);return t}var b=e((()=>{}));function x(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<=31||n===127)return!0}return!1}function S(e){let t=e.startsWith(`claude-cli://`)?e:e.startsWith(`claude-cli:`)?e.replace(`${C}:`,`${C}://`):null;if(!t)throw Error(`Invalid deep link: expected ${C}:// scheme, got "${e}"`);let n;try{n=new URL(t)}catch{throw Error(`Invalid deep link URL: "${e}"`)}if(n.hostname!==`open`)throw Error(`Unknown deep link action: "${n.hostname}"`);let r=n.searchParams.get(`cwd`)??void 0,i=n.searchParams.get(`repo`)??void 0,a=n.searchParams.get(`q`);if(r&&!r.startsWith(`/`)&&!/^[a-zA-Z]:[/\\]/.test(r))throw Error(`Invalid cwd in deep link: must be an absolute path, got "${r}"`);if(r&&x(r))throw Error(`Deep link cwd contains disallowed control characters`);if(r&&r.length>E)throw Error(`Deep link cwd exceeds ${E} characters (got ${r.length})`);if(i&&!w.test(i))throw Error(`Invalid repo in deep link: expected "owner/repo", got "${i}"`);let o;if(a&&a.trim().length>0){if(o=y(a.trim()),x(o))throw Error(`Deep link query contains disallowed control characters`);if(o.length>T)throw Error(`Deep link query exceeds ${T} characters (got ${o.length})`)}return{query:o,cwd:r,repo:i}}var C,w,T,E,D=e((()=>{b(),C=`claude-cli`,w=/^[\w.-]+\/[\w.-]+$/,T=5e3,E=4096})),O=t({MACOS_BUNDLE_ID:()=>z,ensureDeepLinkProtocolRegistered:()=>R,isProtocolHandlerCurrent:()=>L,registerProtocolHandler:()=>F});function k(){return _.join(m(),`applications`,V)}function A(e){return`Exec="${e}" --handle-uri %u`}function j(e){return`"${e}" --handle-uri "%1"`}async function M(e){let t=_.join(H,`Contents`);try{await v.rm(H,{recursive:!0})}catch(e){if(r(e)!==`ENOENT`)throw e}await v.mkdir(_.dirname(U),{recursive:!0});let n=`<?xml version="1.0" encoding="UTF-8"?>
2
2
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
3
  <plist version="1.0">
4
4
  <dict>
@@ -1 +1 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{o as t}from"./envUtils-BDhHQY0-.js";import{HT as n}from"./loadAgentsDir-BL93ulMm.js";import{Wt as r}from"./state-BemZdQIl.js";import{l as i,o as a}from"./stringUtils-C8PaYpQF.js";import{t as o}from"./settingsSync-BSrpnyqo.js";import{n as s,t as c}from"./refresh-B84H2Ezd.js";function l(e,t){return`${e} ${i(e,t)}`}var u;e((()=>{r(),o(),t(),c(),n(),a(),u=async(e,t)=>{let n=await s(t.setAppState),r=`Reloaded: ${[l(n.enabled_count,`plugin`),l(n.command_count,`skill`),l(n.agent_count,`agent`),l(n.hook_count,`hook`),l(n.mcp_count,`plugin MCP server`),l(n.lsp_count,`plugin LSP server`)].join(` · `)}`;return n.error_count>0&&(r+=`\n${l(n.error_count,`error`)} during load. Run /doctor for details.`),{type:`text`,value:r}}}))();export{u as call};
1
+ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{o as t}from"./envUtils-DcaKZlRU.js";import{CT as n}from"./loadAgentsDir-mcRW90aq.js";import{Wt as r}from"./state-BPFYBqm1.js";import{l as i,o as a}from"./stringUtils-Df-Lnjxd.js";import{t as o}from"./settingsSync-eHaSngKo.js";import{n as s,t as c}from"./refresh-ysrhoWCo.js";function l(e,t){return`${e} ${i(e,t)}`}var u;e((()=>{r(),o(),t(),c(),n(),a(),u=async(e,t)=>{let n=await s(t.setAppState),r=`Reloaded: ${[l(n.enabled_count,`plugin`),l(n.command_count,`skill`),l(n.agent_count,`agent`),l(n.hook_count,`hook`),l(n.mcp_count,`plugin MCP server`),l(n.lsp_count,`plugin LSP server`)].join(` · `)}`;return n.error_count>0&&(r+=`\n${l(n.error_count,`error`)} during load. Run /doctor for details.`),{type:`text`,value:r}}}))();export{u as call};