@readmagic/workmate 0.0.12 → 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 (312) hide show
  1. package/dist/chunks/{AddWorkspaceDirectory-CtRxzRny.js → AddWorkspaceDirectory-BzNj9rS6.js} +1 -1
  2. package/dist/chunks/AgentsMdExternalIncludesDialog-CDZPR488.js +1 -0
  3. package/dist/chunks/{AgentsMdExternalIncludesDialog-_yJJ0wqu.js → AgentsMdExternalIncludesDialog-CH9x1Ngp.js} +1 -1
  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-COI_V57z.js → BypassPermissionsModeDialog-B0BizN_J.js} +1 -1
  9. package/dist/chunks/{DiffDialog-CRWtQ1R5.js → DiffDialog-mQ-5_TSv.js} +3 -3
  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-DRZrhbF0.js → Grove-D0nn8zOV.js} +2 -2
  14. package/dist/chunks/{HybridTransport-BadJQe6u.js → HybridTransport-BQNLZNa_.js} +2 -2
  15. package/dist/chunks/InvalidConfigDialog-C5CIiSIE.js +1 -0
  16. package/dist/chunks/{InvalidSettingsDialog-ISzcIGPU.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-xv0RZCSL.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-8-awCxOn.js → PromptInputFooterSuggestions-R12fbdmp.js} +1 -1
  24. package/dist/chunks/PromptInputHelpMenu-BgADIzRj.js +1 -0
  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-je346ofV.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-zmdAsogZ.js → TeleportProgress-3hmIApkj.js} +1 -1
  34. package/dist/chunks/{TeleportRepoMismatchDialog-CG32I4cO.js → TeleportRepoMismatchDialog-BA1a66RK.js} +1 -1
  35. package/dist/chunks/{TeleportResumeWrapper-2Yjr74Lq.js → TeleportResumeWrapper-BT4O-Wsi.js} +1 -1
  36. package/dist/chunks/{ThemePicker-p7_hHk1V.js → ThemePicker-DUlhcoso.js} +1 -1
  37. package/dist/chunks/{TrustDialog-BVcny9vs.js → TrustDialog-Dpk03V1Y.js} +1 -1
  38. package/dist/chunks/add-dir-BUr0z-VU.js +1 -0
  39. package/dist/chunks/{agentDisplay-CfMLGPGH.js → agentDisplay-D7bdOOG7.js} +1 -1
  40. package/dist/chunks/{agents-BT82hwBN.js → agents-22wiC58F.js} +1 -1
  41. package/dist/chunks/agents-8ELI8RJo.js +103 -0
  42. package/dist/chunks/{allErrors-CS77lRvU.js → allErrors-C1eMbHSv.js} +1 -1
  43. package/dist/chunks/api-DgjIFdMn.js +1 -0
  44. package/dist/chunks/{api-DAubp5q9.js → api-f3GN2I_J.js} +1 -1
  45. package/dist/chunks/auth-B73a4Cob.js +1 -0
  46. package/dist/chunks/{auth-yDsvFcM7.js → auth-Czy7GoRh.js} +1 -1
  47. package/dist/chunks/auth-D_0waidQ.js +1 -0
  48. package/dist/chunks/backgroundHousekeeping-C_ArdTFX.js +17 -0
  49. package/dist/chunks/backgroundHousekeeping-YJhvZ0dh.js +1 -0
  50. package/dist/chunks/{branch-DJiMa8td.js → branch-bb4-bErF.js} +2 -2
  51. package/dist/chunks/{bridgeConfig-BB6Hgali.js → bridgeConfig-B80T_lw7.js} +1 -1
  52. package/dist/chunks/bridgeConfig-DywkIo_k.js +1 -0
  53. package/dist/chunks/{bridgeMessaging-C9D0Lly2.js → bridgeMessaging-DyvHd16Z.js} +1 -1
  54. package/dist/chunks/{bridgeStatusUtil-D8UbcVrZ.js → bridgeStatusUtil-DStiD05t.js} +1 -1
  55. package/dist/chunks/{btw-BO2B23f-.js → btw-BRmV51bR.js} +1 -1
  56. package/dist/chunks/caches-C5DIVdvI.js +1 -0
  57. package/dist/chunks/caches-zDZEgNKq.js +1 -0
  58. package/dist/chunks/{ccrClient-BG9HU_fW.js → ccrClient-BALhzhPF.js} +1 -1
  59. package/dist/chunks/{clear-B4XN2fib.js → clear-B_yVyJXP.js} +1 -1
  60. package/dist/chunks/client-DVg8PpFX.js +1 -0
  61. package/dist/chunks/commands-ByFXqW43.js +1 -0
  62. package/dist/chunks/compact-BUShp2eQ.js +2 -0
  63. package/dist/chunks/config-BwHNU_pI.js +1 -0
  64. package/dist/chunks/{context-BY5oO5is.js → context-6Pk3iVhh.js} +1 -1
  65. package/dist/chunks/{context-noninteractive-mAQt1p9l.js → context-noninteractive-CHzerxnH.js} +2 -2
  66. package/dist/chunks/context-noninteractive-DFwRQyFE.js +1 -0
  67. package/dist/chunks/conversation-5zb5XkSA.js +1 -0
  68. package/dist/chunks/conversation-JP2ZXrwu.js +1 -0
  69. package/dist/chunks/{createSSHSession-DjLSGm-0.js → createSSHSession-XkHMiGRN.js} +1 -1
  70. package/dist/chunks/{createSession-CftIZ3aq.js → createSession-BNGm9fL4.js} +1 -1
  71. package/dist/chunks/createSession-VTqzWAu6.js +1 -0
  72. package/dist/chunks/crossProjectResume-DxgQVYSi.js +40 -0
  73. package/dist/chunks/{datadog-BGati3aQ.js → datadog-3WUWcCFn.js} +1 -1
  74. package/dist/chunks/{diff-1HsxKGBh.js → diff-CKlLimGq.js} +1 -1
  75. package/dist/chunks/doctor-Bvx0u0sO.js +1 -0
  76. package/dist/chunks/entry-DCbq734V.js +14 -0
  77. package/dist/chunks/{esm-BkOWaWVb.js → esm-CtQkOk5D.js} +1 -1
  78. package/dist/chunks/exit-DTsz5Lcb.js +1 -0
  79. package/dist/chunks/{extraUsage-0pUcYexI.js → extraUsage-C86bZVgt.js} +1 -1
  80. package/dist/chunks/extractMemories-6OnMgL2S.js +1 -0
  81. package/dist/chunks/fast-B2ziqJEA.js +1 -0
  82. package/dist/chunks/{fast-VOu2FUlV.js → fast-BkhjaTkZ.js} +1 -1
  83. package/dist/chunks/{fileSuggestions-Be-pyLLq.js → fileSuggestions-BalHmi1-.js} +2 -2
  84. package/dist/chunks/{firstPartyEventLogger-aFhcruXA.js → firstPartyEventLogger-1RTgXHSz.js} +2 -2
  85. package/dist/chunks/firstPartyEventLogger-CXMzhLrF.js +1 -0
  86. package/dist/chunks/{flushGate-BUSrMj_6.js → flushGate-DWL05x7v.js} +1 -1
  87. package/dist/chunks/{gemini-DB4M-MYv.js → gemini-BLpLJyli.js} +1 -1
  88. package/dist/chunks/generateSessionName-CdbMksHi.js +1 -0
  89. package/dist/chunks/goal-V3qix-i1.js +3 -0
  90. package/dist/chunks/grok-BLLATotv.js +1 -0
  91. package/dist/chunks/{grove-BnzBbGsX.js → grove-b9gGKgu4.js} +2 -2
  92. package/dist/chunks/{help-C5ankDi4.js → help-BR7UEr5R.js} +1 -1
  93. package/dist/chunks/{hooks-BZS105Rd.js → hooks-C-QMGvCg.js} +2 -2
  94. package/dist/chunks/hooks-D6wtd0Qq.js +1 -0
  95. package/dist/chunks/{initReplBridge-DL4klK0C.js → initReplBridge-DyScxedy.js} +1 -1
  96. package/dist/chunks/{install-NZvHd_40.js → install-DGH_bjUh.js} +1 -1
  97. package/dist/chunks/{instrumentation-CjBlVlFq.js → instrumentation-DQ705pC7.js} +3 -3
  98. package/dist/chunks/{job-D502Zf8J.js → job-BaMT6Lb2.js} +1 -1
  99. package/dist/chunks/keybindings-CG292HS1.js +2 -0
  100. package/dist/chunks/{launchLocalMemory-DxC3LojF.js → launchLocalMemory-CtZrkmaw.js} +2 -2
  101. package/dist/chunks/{launchOnboarding-BLp5k_H4.js → launchOnboarding-CyOtdZkT.js} +1 -1
  102. package/dist/chunks/loadAgentsDir-4UC4yLg1.js +1 -0
  103. package/dist/chunks/{loadAgentsDir-BXtV2jiO.js → loadAgentsDir-mcRW90aq.js} +389 -390
  104. package/dist/chunks/loadPluginHooks-CWI0RMUx.js +1 -0
  105. package/dist/chunks/{localSearch-CeP4ef0a.js → localSearch-CCCDKpYx.js} +1 -1
  106. package/dist/chunks/localSearch-D4hVR7-d.js +1 -0
  107. package/dist/chunks/{logoV2Utils-CEnU8qad.js → logoV2Utils--8OUQQPd.js} +1 -1
  108. package/dist/chunks/{magicDocs-YtfrqVC6.js → magicDocs-26J_l1De.js} +2 -2
  109. package/dist/chunks/main-DUjtDK1Q.js +513 -0
  110. package/dist/chunks/managedEnv-BuCurT_S.js +1 -0
  111. package/dist/chunks/{managedEnv-B-BNY0xC.js → managedEnv-Ds6MlFQE.js} +1 -1
  112. package/dist/chunks/{mappers-IuJeXgvr.js → mappers-DwZw084m.js} +1 -1
  113. package/dist/chunks/mcp-CEKR7PjL.js +6 -0
  114. package/dist/chunks/mcp-DCAf2hHD.js +1 -0
  115. package/dist/chunks/mcp-mCuc8dNe.js +2 -0
  116. package/dist/chunks/memory-B5SkpC7u.js +1 -0
  117. package/dist/chunks/{mode-GzBwK--u.js → mode-B80CHkqo.js} +2 -2
  118. package/dist/chunks/model-BqaneI4D.js +1 -0
  119. package/dist/chunks/{model-CDnVaVDR.js → model-C29_32BD.js} +1 -1
  120. package/dist/chunks/{model-BydaMaPr.js → model-NG8fvuT2.js} +1 -1
  121. package/dist/chunks/{modelOptions-ut0xePEe.js → modelOptions-CiZgZxZC.js} +1 -1
  122. package/dist/chunks/{nativeInstaller-fgCMR_c0.js → nativeInstaller-DqbEfGSX.js} +1 -1
  123. package/dist/chunks/{omit-D4Udf-p-.js → omit-KEhe84f4.js} +1 -1
  124. package/dist/chunks/{onChangeAppState-WbvtqDtk.js → onChangeAppState-Dq1tIEJI.js} +1 -1
  125. package/dist/chunks/{openai-DaVFXyBB.js → openai-BvnsYTpQ.js} +3 -3
  126. package/dist/chunks/{partition-CzW_31Y1.js → partition-DeT341qu.js} +1 -1
  127. package/dist/chunks/permissions-BPpeHxpk.js +3 -0
  128. package/dist/chunks/pidLock-DQGDoFQP.js +3 -0
  129. package/dist/chunks/{plan-M9DG3AqN.js → plan-BRiC5ujG.js} +1 -1
  130. package/dist/chunks/plugin-Dcg_GGR9.js +17 -0
  131. package/dist/chunks/{pluginAutoupdate-B5lel6s5.js → pluginAutoupdate-ByH9IPC9.js} +1 -1
  132. package/dist/chunks/pluginBlocklist-BfoLN9a-.js +1 -0
  133. package/dist/chunks/pluginCliCommands-Bc2Iybhz.js +1 -0
  134. package/dist/chunks/{pluginFlagging-CXSSOj4J.js → pluginFlagging-Cr0d0hBA.js} +1 -1
  135. package/dist/chunks/pluginOperations-CKNyYjS-.js +2 -0
  136. package/dist/chunks/pluginStartupCheck-B48_cGgo.js +1 -0
  137. package/dist/chunks/{pluginStartupCheck-BEd0VeQC.js → pluginStartupCheck-DiCDQQlr.js} +1 -1
  138. package/dist/chunks/plugins-BP_36tOl.js +4 -0
  139. package/dist/chunks/print-2uavraPq.js +26 -0
  140. package/dist/chunks/processBashCommand-g3sAMpHt.js +1 -0
  141. package/dist/chunks/processSlashCommand-tIbeCrv5.js +5 -0
  142. package/dist/chunks/{prompt-CRc2QEZ5.js → prompt-DIlq8NTy.js} +1 -1
  143. package/dist/chunks/prompt-DLv-Cd67.js +1 -0
  144. package/dist/chunks/prompt-DV5tCLRh.js +1 -0
  145. package/dist/chunks/{promptEditor-Bo1d8ZLq.js → promptEditor-BILqOGl1.js} +2 -2
  146. package/dist/chunks/{reconciler-BGav_ezX.js → reconciler-CDq6XgAS.js} +1 -1
  147. package/dist/chunks/refresh-ysrhoWCo.js +1 -0
  148. package/dist/chunks/{reload-plugins-DNEgQ5vo.js → reload-plugins-CGb0HTsH.js} +1 -1
  149. package/dist/chunks/{remoteBridgeCore-BGOqHADF.js → remoteBridgeCore-BmteXmI9.js} +1 -1
  150. package/dist/chunks/{remoteManagedSettings-26nhzuca.js → remoteManagedSettings-CwDGxL5p.js} +1 -1
  151. package/dist/chunks/rename-1GLIUlYk.js +1 -0
  152. package/dist/chunks/resume-DWtlUiHW.js +2 -0
  153. package/dist/chunks/{runtimeObserver-BZrF3GnQ.js → runtimeObserver-4ZqaCXYy.js} +4 -4
  154. package/dist/chunks/{runtimeObserver-CBV-7-w7.js → runtimeObserver-CtNY8Al2.js} +1 -1
  155. package/dist/chunks/sandbox-adapter-BzjRQh_r.js +1 -0
  156. package/dist/chunks/{sandbox-toggle-D61gVqcT.js → sandbox-toggle-Bz49-F6e.js} +1 -1
  157. package/dist/chunks/searchExtraTools-D6vj8qJ-.js +1 -0
  158. package/dist/chunks/{session-Dy-_R7KP.js → session-wb6X4Wrq.js} +1 -1
  159. package/dist/chunks/sessionFileAccessHooks-Da97UA2n.js +1 -0
  160. package/dist/chunks/{sessionObserver-CyLpHSkw.js → sessionObserver-BJQ5hwjU.js} +2 -2
  161. package/dist/chunks/sessionObserver-DXO4trhk.js +1 -0
  162. package/dist/chunks/{sessionState-DSWN4tMV.js → sessionState-Bn3ESS5f.js} +1 -1
  163. package/dist/chunks/sessionStorage-DlPVsQn9.js +1 -0
  164. package/dist/chunks/{sessionTitle-L5tyJgdU.js → sessionTitle-Cbzrb9jT.js} +2 -2
  165. package/dist/chunks/{sessionTracing-DpHGGIZm.js → sessionTracing-CEsm8pZL.js} +1 -1
  166. package/dist/chunks/{settingsSync-dBqlrbcU.js → settingsSync-eHaSngKo.js} +1 -1
  167. package/dist/chunks/setup-DeyiuGNX.js +3 -0
  168. package/dist/chunks/{shadowedRuleDetection-DZ0AA2Rw.js → shadowedRuleDetection-D5X5fhzj.js} +1 -1
  169. package/dist/chunks/{sideQuestion-BYT8FdPF.js → sideQuestion-BHRtwhyj.js} +3 -3
  170. package/dist/chunks/{sinks-mFsijQ_S.js → sinks-Bgy2UNK-.js} +2 -2
  171. package/dist/chunks/sinks-CgzLmim2.js +1 -0
  172. package/dist/chunks/skillChangeDetector-BlSP16j6.js +1 -0
  173. package/dist/chunks/{skillGapStore-DQXHqoP7.js → skillGapStore-BjQSSz2E.js} +2 -2
  174. package/dist/chunks/{skillLifecycle-BG_RnGSh.js → skillLifecycle-Sp8strFv.js} +2 -2
  175. package/dist/chunks/{skillSearchPanel-DxYP4Q6R.js → skillSearchPanel-3sYRez_Q.js} +4 -4
  176. package/dist/chunks/{skills-BD-2ofXA.js → skills-CJhWI8t1.js} +1 -1
  177. package/dist/chunks/{status-BmHu-c7I.js → status-CDCurOqs.js} +2 -2
  178. package/dist/chunks/{status-CrmnCDIE.js → status-yoQIQ2Ni.js} +1 -1
  179. package/dist/chunks/statusNoticeHelpers-Sl4jjauz.js +1 -0
  180. package/dist/chunks/switcher-C-m6MUwE.js +1 -0
  181. package/dist/chunks/{switcher-sYTxnJQA.js → switcher-uoQMHmEZ.js} +1 -1
  182. package/dist/chunks/{syncCache-BofuFJEe.js → syncCache-BooMjgU6.js} +1 -1
  183. package/dist/chunks/{tasks-NpI1iEem.js → tasks-CHG_6sXQ.js} +1 -1
  184. package/dist/chunks/teleport-C9KRE4X8.js +1 -0
  185. package/dist/chunks/{templateJobs-C94jEE6O.js → templateJobs-BYYfF4m5.js} +1 -1
  186. package/dist/chunks/{theme-CEi3b_8f.js → theme-MvX7hojJ.js} +1 -1
  187. package/dist/chunks/{toolEventObserver-DlL9CHmI.js → toolEventObserver-BFEl47bq.js} +1 -1
  188. package/dist/chunks/toolPool-Cq74Cvjp.js +1 -0
  189. package/dist/chunks/trustedDevice-BGwujSqc.js +1 -0
  190. package/dist/chunks/{trustedDevice-Bzz03jCy.js → trustedDevice-BLiKbGpG.js} +1 -1
  191. package/dist/chunks/{updateCCB-CzBxsuJe.js → updateCCB-CfckOy7T.js} +6 -6
  192. package/dist/chunks/{useExitOnCtrlCDWithKeybindings-BHQfwlAl.js → useExitOnCtrlCDWithKeybindings-CPLBDluY.js} +1 -1
  193. package/dist/chunks/useMainLoopModel-C00PbZ1Q.js +1 -0
  194. package/dist/chunks/useManagePlugins-DFaGntzJ.js +1 -0
  195. package/dist/chunks/{useMergedTools-CHxnwR7R.js → useMergedTools-DYobZ5N4.js} +1 -1
  196. package/dist/chunks/{useSearchInput-q2CFPU4W.js → useSearchInput-KFKh2ozY.js} +1 -1
  197. package/dist/chunks/useSettingsErrors-BRgjvaHd.js +1 -0
  198. package/dist/chunks/{userAgent-B7WkjI6I.js → userAgent-DUrr02yh.js} +1 -1
  199. package/dist/chunks/util-D7uwPgF1.js +1 -0
  200. package/dist/chunks/validatePlugin-VukX52bx.js +1 -0
  201. package/dist/chunks/{workerRegistry-Cfo7bKlm.js → workerRegistry-BA37PVbv.js} +3 -3
  202. package/dist/chunks/worktree-Lik8xuKd.js +1 -0
  203. package/dist/cli.js +1 -1
  204. package/package.json +1 -1
  205. package/dist/chunks/AgentsMdExternalIncludesDialog-_bI4jo_P.js +0 -1
  206. package/dist/chunks/App-DoAZ7CYS.js +0 -1
  207. package/dist/chunks/ApproveApiKey-C8LwmDM2.js +0 -1
  208. package/dist/chunks/ApproveApiKey-DQP3qmb0.js +0 -1
  209. package/dist/chunks/BackgroundTasksDialog-CDA2noEk.js +0 -2
  210. package/dist/chunks/ConsoleOAuthFlow-Dn8fO-o_.js +0 -1
  211. package/dist/chunks/Doctor-CZ513Df9.js +0 -3
  212. package/dist/chunks/Doctor-CzPvNZzF.js +0 -1
  213. package/dist/chunks/ExitFlow-BFeftDv0.js +0 -2
  214. package/dist/chunks/InvalidConfigDialog-DQaT6aen.js +0 -1
  215. package/dist/chunks/MCPConnectionManager-BpjC7CEo.js +0 -1
  216. package/dist/chunks/MCPToolListView-Rb1Q--jG.js +0 -1
  217. package/dist/chunks/MessageSelector-BHB55sZb.js +0 -3
  218. package/dist/chunks/Messages-CPX-nIdA.js +0 -11
  219. package/dist/chunks/Onboarding-CymgipoF.js +0 -1
  220. package/dist/chunks/PromptInputHelpMenu-BP3UgCdi.js +0 -1
  221. package/dist/chunks/QueryEngine-HkswHUNv.js +0 -1
  222. package/dist/chunks/REPL-CZfg65kg.js +0 -133
  223. package/dist/chunks/REPL-eZsYNBfl.js +0 -1
  224. package/dist/chunks/RemoteSessionManager-B4jqKVd3.js +0 -2
  225. package/dist/chunks/ResumeConversation-B03XN_SP.js +0 -1
  226. package/dist/chunks/SearchExtraToolsTool-C85Sanww.js +0 -1
  227. package/dist/chunks/Settings-C8GKWod1.js +0 -2
  228. package/dist/chunks/WelcomeV2-BnSYhyfu.js +0 -1
  229. package/dist/chunks/add-dir-Bd7pilVx.js +0 -1
  230. package/dist/chunks/agents-qR6r94-F.js +0 -103
  231. package/dist/chunks/api-C4VflFau.js +0 -1
  232. package/dist/chunks/auth-CNCehj7y.js +0 -1
  233. package/dist/chunks/auth-DrD9DW6X.js +0 -1
  234. package/dist/chunks/autoMode-C2lnBot9.js +0 -45
  235. package/dist/chunks/backgroundHousekeeping-DbpTGbwl.js +0 -1
  236. package/dist/chunks/backgroundHousekeeping-SpTxViUq.js +0 -17
  237. package/dist/chunks/bridgeConfig-Ccm79Jze.js +0 -1
  238. package/dist/chunks/caches-BQmbXerw.js +0 -1
  239. package/dist/chunks/caches-Dtjmjm6G.js +0 -1
  240. package/dist/chunks/client-B-2ccQZk.js +0 -1
  241. package/dist/chunks/commands-D_-v6_A0.js +0 -1
  242. package/dist/chunks/compact-kM0ETtB2.js +0 -2
  243. package/dist/chunks/config-Crf6Mzu3.js +0 -1
  244. package/dist/chunks/connectHeadless-CqRoEtrg.js +0 -1
  245. package/dist/chunks/context-noninteractive-tc4KTYfI.js +0 -1
  246. package/dist/chunks/conversation-CFIn-KsW.js +0 -1
  247. package/dist/chunks/conversation-DPI7VKBL.js +0 -1
  248. package/dist/chunks/createSession-CjdLcRec.js +0 -1
  249. package/dist/chunks/crossProjectResume-BJqXBzkf.js +0 -40
  250. package/dist/chunks/dangerousBackend-DwcP0P08.js +0 -1
  251. package/dist/chunks/doctor-CJfvt9zR.js +0 -1
  252. package/dist/chunks/entry-CrZCZQQC.js +0 -14
  253. package/dist/chunks/exit-B8MA4Ltm.js +0 -1
  254. package/dist/chunks/extractMemories-DqhN0lba.js +0 -1
  255. package/dist/chunks/fast-DT5WDe3L.js +0 -1
  256. package/dist/chunks/firstPartyEventLogger-B8RVGBQB.js +0 -1
  257. package/dist/chunks/generateSessionName-DhCypqJ_.js +0 -1
  258. package/dist/chunks/goal-TxXtfkQ6.js +0 -3
  259. package/dist/chunks/grok-D2a_J5wE.js +0 -1
  260. package/dist/chunks/hooks-D-twhU_z.js +0 -1
  261. package/dist/chunks/keybindings-D9Boc8FD.js +0 -2
  262. package/dist/chunks/loadAgentsDir-BjsAQWqt.js +0 -1
  263. package/dist/chunks/loadPluginHooks-Dt3XQ-3N.js +0 -1
  264. package/dist/chunks/localSearch-Cz8Ot7k2.js +0 -1
  265. package/dist/chunks/lockfile-D5-j7HOZ.js +0 -1
  266. package/dist/chunks/main-CkjTzYj1.js +0 -513
  267. package/dist/chunks/managedEnv-K9Si1UuL.js +0 -1
  268. package/dist/chunks/mcp-DMBoeQzm.js +0 -6
  269. package/dist/chunks/mcp-TMOPfLcW.js +0 -1
  270. package/dist/chunks/mcp-x5rgv-uv.js +0 -2
  271. package/dist/chunks/memory-DDUoR63T.js +0 -1
  272. package/dist/chunks/model-CIvbC7rW.js +0 -1
  273. package/dist/chunks/parseConnectUrl-BiyKR5-x.js +0 -1
  274. package/dist/chunks/permissions-BT3lxYBM.js +0 -3
  275. package/dist/chunks/pidLock-d1VPd6CG.js +0 -3
  276. package/dist/chunks/plugin-BiNHuq3h.js +0 -17
  277. package/dist/chunks/pluginBlocklist-CNGmIlwU.js +0 -1
  278. package/dist/chunks/pluginCliCommands-WLOEhb2M.js +0 -1
  279. package/dist/chunks/pluginOperations-BFbty6WT.js +0 -2
  280. package/dist/chunks/pluginStartupCheck-Bcdxg484.js +0 -1
  281. package/dist/chunks/plugins-BMZ3aYKP.js +0 -4
  282. package/dist/chunks/print-DmoLcwVq.js +0 -26
  283. package/dist/chunks/processBashCommand-B-VqME9O.js +0 -1
  284. package/dist/chunks/processSlashCommand-D6zEooTy.js +0 -5
  285. package/dist/chunks/prompt-C3RRe4kW.js +0 -1
  286. package/dist/chunks/prompt-EtAanewG.js +0 -1
  287. package/dist/chunks/refresh-DumNiLvM.js +0 -1
  288. package/dist/chunks/rename-BPknfVGF.js +0 -1
  289. package/dist/chunks/resume-DGz04xDh.js +0 -2
  290. package/dist/chunks/sandbox-adapter-DUqeqkQD.js +0 -1
  291. package/dist/chunks/searchExtraTools-CgsV6kb1.js +0 -1
  292. package/dist/chunks/server-LdbAb0sV.js +0 -1
  293. package/dist/chunks/serverBanner-BdExKFHT.js +0 -1
  294. package/dist/chunks/serverLog-BFmvyJ93.js +0 -1
  295. package/dist/chunks/sessionFileAccessHooks-BJlrZaRD.js +0 -1
  296. package/dist/chunks/sessionManager-CPa049BO.js +0 -1
  297. package/dist/chunks/sessionObserver-BGYoLRGx.js +0 -1
  298. package/dist/chunks/sessionStorage-zJ1esSCE.js +0 -1
  299. package/dist/chunks/setup-zf3v3ICe.js +0 -3
  300. package/dist/chunks/sinks-DppGvgz1.js +0 -1
  301. package/dist/chunks/skillChangeDetector-D-iq09Xs.js +0 -1
  302. package/dist/chunks/statusNoticeHelpers-DakAVtQO.js +0 -1
  303. package/dist/chunks/switcher-Dm646gO5.js +0 -1
  304. package/dist/chunks/teleport-Bs3kEipi.js +0 -1
  305. package/dist/chunks/toolPool-DIT_uhtD.js +0 -1
  306. package/dist/chunks/trustedDevice-BokywSKL.js +0 -1
  307. package/dist/chunks/useMainLoopModel-BkyIIW9t.js +0 -1
  308. package/dist/chunks/useManagePlugins-BWROoGDs.js +0 -1
  309. package/dist/chunks/useSettingsErrors-CPVQbsqq.js +0 -1
  310. package/dist/chunks/util-BfqXOA-P.js +0 -1
  311. package/dist/chunks/validatePlugin-jrcrYEIu.js +0 -1
  312. package/dist/chunks/worktree-D0k_pCEz.js +0 -1
@@ -1,26 +0,0 @@
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{$b as u,$d as d,$g as f,$l as p,Ag as m,Ai as h,Ba as g,Bb as _,Bf as ee,Bi as v,C as te,CT as ne,Cg as re,Cm as y,Cn as b,Cr as x,Cu as ie,D as ae,DS as S,DT as oe,D_ as se,Dm as ce,Dn as le,E as ue,ES as de,E_ as fe,Em as pe,En as C,Fi as me,Fo as he,Fs as ge,Fx as _e,Gc as ve,Gx as ye,Hc as w,Hi as be,Ht as xe,IT as Se,Is as T,Jb as Ce,Jc as we,Js as Te,Jv as Ee,KS as De,Kb as Oe,Kc as ke,Kg as Ae,Kr as je,Kx as Me,LT as E,Lb as Ne,Ls as Pe,MT as Fe,N as Ie,NT as Le,Nh as Re,Ni as ze,OT as Be,Om as Ve,Ph as He,Po as Ue,Ps as We,Qb as Ge,Qc as Ke,Qd as qe,Ql as Je,Qx as Ye,Rx as Xe,Sm as Ze,Sn as Qe,Sr as $e,T_ as D,Tg as O,Tm as et,Tn as tt,Tx as nt,U as rt,Ub as it,Uc as at,Vf as ot,Vo as st,W as ct,WS as lt,Wo as ut,Wt as dt,Xb as ft,Xc as pt,Xd as mt,Xg as ht,Xs as gt,Yb as _t,Yc as vt,Yv as yt,Zc as bt,Zd as k,Zg as xt,Zn as St,Zx as Ct,_m as wt,_s as Tt,_w as Et,_y as Dt,ac as Ot,ai as kt,ao as At,ay as jt,b as Mt,bT as Nt,bi as Pt,bm as Ft,bu as It,by as Lt,ci as Rt,dc as zt,dg as Bt,do as Vt,dp as Ht,ds as Ut,ex as Wt,f as Gt,fc as Kt,fs as qt,fx as Jt,fy as Yt,gs as Xt,hb as Zt,hs as Qt,ic as $t,ii as en,im as tn,io as nn,jm as rn,kg as an,lf as on,lx as sn,mb as cn,ms as ln,my as un,nS as dn,ny as fn,o as pn,oy as mn,pb as hn,po as gn,pp as _n,ps as vn,py as yn,qg as bn,qx as xn,r_ as Sn,rc as Cn,rm as wn,ry as Tn,s as En,sC as Dn,sc as On,sf as kn,si as An,so as jn,sy as Mn,t_ as Nn,tl as Pn,tr as Fn,tx as In,ug as Ln,us as Rn,ux as zn,vm as Bn,vn as Vn,vs as Hn,vw as Un,w_ as Wn,wg as Gn,wm as Kn,wn as qn,wu as Jn,x as Yn,xE as Xn,xm as Zn,xr as Qn,ya as $n,yi as er,ym as tr,ys as nr,zb as rr,zo as ir}from"./loadAgentsDir-BXtV2jiO.js";import{A,C as j,M,O as N,b as P,f as ar,g as or,j as F,l as I,m as L,p as R,u as sr,w as z,y as cr}from"./external-CEp-aPkt.js";import{i as B,n as V,r as lr,t as ur}from"./lazySchema-B4D4qJVE.js";import{$t as dr,Gt as fr,M as pr,Mn as mr,Nn as hr,P as gr,Wt as _r,Y as vr,hn as yr,or as br,pt as H,qn as xr,yn as Sr}from"./state-BPFYBqm1.js";import{n as Cr,t as wr}from"./cwd-Besi3Os3.js";import{C as U,E as Tr,P as W,R as Er,S as Dr,U as Or,a as kr,c as G,f as Ar,i as jr,nt as Mr,tt as Nr,u as Pr,x as Fr}from"./debug-Dr1SjdXn.js";import{Bn as Ir,G as Lr,Rn as Rr,cr as zr,d as Br,dt as Vr,f as Hr,g as Ur,it as Wr,nt as Gr,or as Kr,vt as qr}from"./settings-DiBMs2gM.js";import{F as Jr,M as Yr}from"./config-9rLTDOYW.js";import{i as Xr,n as Zr,o as K}from"./process-gEbdy6uY.js";import{A as Qr,O as $r,k as ei}from"./git-CoQQ6YEf.js";import{H as ti,c as ni,i as ri,o as ii,q as ai,s as q}from"./log-27kCA_9u.js";import{s as oi,u as si}from"./types-BJ7qTz75.js";import{n as ci,r as J}from"./analytics-DJobLaWP.js";import{Bt as li,C as ui,Gr as di,Mn as fi,Y as pi,_ as mi,_n as hi,_r as gi,ai as _i,bt as vi,et as yi,ii as bi,it as xi,jn as Si,o as Ci,qr as wi,ri as Ti,rt as Ei,si as Di,tt as Oi,u as ki,vn as Ai,vr as ji,x as Mi}from"./model-CDnVaVDR.js";import{at as Ni,bn as Pi,bt as Fi,ot as Ii,rn as Li,vt as Ri,xn as zi,yt as Bi}from"./prompt-CRc2QEZ5.js";import{A as Vi,D as Hi,M as Ui,_ as Wi,a as Gi,c as Ki,k as qi,l as Ji,n as Yi,o as Xi,s as Zi,st as Qi,t as $i,w as ea,x as ta}from"./sessionState-DSWN4tMV.js";import{n as na,t as ra}from"./omit-D4Udf-p-.js";import{a as ia,n as aa,t as oa}from"./bridgeConfig-BB6Hgali.js";import{i as sa,n as ca,s as la}from"./mappers-IuJeXgvr.js";import{n as ua,r as da}from"./sessionTitle-L5tyJgdU.js";import{t as fa}from"./pollConfig-BgpfHQPJ.js";import{t as pa}from"./controlMessageCompat-IFu4Gc1y.js";import{n as ma,t as ha}from"./ccrClient-BG9HU_fW.js";import{n as ga,t as _a}from"./HybridTransport-BadJQe6u.js";import{n as va,t as ya}from"./SSETransport-je346ofV.js";import{a as ba,n as xa}from"./grove-BnzBbGsX.js";import{o as Sa}from"./remoteManagedSettings-26nhzuca.js";import{i as Ca,r as wa}from"./auth-yDsvFcM7.js";import{t as Ta}from"./pluginBlocklist-CNGmIlwU.js";import{t as Ea}from"./onChangeAppState-WbvtqDtk.js";import{t as Da}from"./settingsSync-dBqlrbcU.js";import{n as Oa,t as ka}from"./toolPool-DIT_uhtD.js";import{n as Aa,r as ja}from"./QueryEngine-HkswHUNv.js";import{r as Ma}from"./bridgeStatusUtil-D8UbcVrZ.js";import{n as Na,r as Pa}from"./sideQuestion-BYT8FdPF.js";import{n as Fa,r as Ia}from"./context-noninteractive-mAQt1p9l.js";import{n as La,t as Ra}from"./modelOptions-ut0xePEe.js";import{a as za,o as Ba,t as Va}from"./skillChangeDetector-D-iq09Xs.js";import{n as Ha}from"./reconciler-BGav_ezX.js";import{n as Ua,t as Wa}from"./refresh-DumNiLvM.js";import{basename as Ga,dirname as Ka,join as qa}from"path";import{PassThrough as Ja}from"stream";import{randomUUID as Y}from"crypto";import{mkdir as Ya,readFile as Xa,stat as Za,writeFile as Qa}from"fs/promises";import{URL as $a}from"url";import{cwd as eo}from"process";i(),o(),l(),_r(),Nr(),Er(),Fr(),Ar(),Zr(),jr(),$r(),ai(),ii(),Rr(),oi(),Ur(),Di(),wi(),ji(),Si(),hi(),li(),mi(),Da(),lr(),ur();var to=V(()=>z({inputTokens:j(),outputTokens:j(),cacheReadInputTokens:j(),cacheCreationInputTokens:j(),webSearchRequests:j(),costUSD:j(),contextWindow:j(),maxOutputTokens:j()})),no=V(()=>P(`json_schema`));V(()=>z({type:no()}));var ro=V(()=>z({type:P(`json_schema`),schema:N(A(),M())}));V(()=>ro());var io=V(()=>I([`user`,`project`,`org`,`temporary`,`oauth`]));V(()=>I([`local`,`user`,`project`]).describe(`Config scope for settings.`)),V(()=>P(`context-1m-2025-08-07`));var ao=V(()=>z({type:P(`adaptive`)}).describe(`Claude decides when and how much to think (Opus 4.6+).`)),oo=V(()=>z({type:P(`enabled`),budgetTokens:j().optional()}).describe(`Fixed thinking token budget (older models)`)),so=V(()=>z({type:P(`disabled`)}).describe(`No extended thinking`));V(()=>F([ao(),oo(),so()]).describe(`Controls Claude's thinking/reasoning behavior. When set, takes precedence over the deprecated maxThinkingTokens.`));var co=V(()=>z({type:P(`stdio`).optional(),command:A(),args:R(A()).optional(),env:N(A(),A()).optional()})),lo=V(()=>z({type:P(`sse`),url:A(),headers:N(A(),A()).optional()})),uo=V(()=>z({type:P(`http`),url:A(),headers:N(A(),A()).optional()})),fo=V(()=>z({type:P(`sdk`),name:A()})),po=V(()=>F([co(),lo(),uo(),fo()])),mo=V(()=>z({type:P(`claudeai-proxy`),url:A(),id:A()})),ho=V(()=>F([po(),mo()])),go=V(()=>z({name:A().describe(`Server name as configured`),status:I([`connected`,`failed`,`needs-auth`,`pending`,`disabled`]).describe(`Current connection status`),serverInfo:z({name:A(),version:A()}).optional().describe(`Server information (available when connected)`),error:A().optional().describe(`Error message (available when status is 'failed')`),config:ho().optional().describe(`Server configuration (includes URL for HTTP/SSE servers)`),scope:A().optional().describe(`Configuration scope (e.g., project, user, local, claudeai, managed)`),tools:R(z({name:A(),description:A().optional(),annotations:z({readOnly:L().optional(),destructive:L().optional(),openWorld:L().optional()}).optional()})).optional().describe(`Tools provided by this server (available when connected)`),capabilities:z({experimental:N(A(),M()).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.`));V(()=>z({added:R(A()).describe(`Names of servers that were added`),removed:R(A()).describe(`Names of servers that were removed`),errors:N(A(),A()).describe(`Map of server names to error messages for servers that failed to connect`)}).describe(`Result of a setMcpServers operation.`));var _o=V(()=>I([`userSettings`,`projectSettings`,`localSettings`,`session`,`cliArg`])),vo=V(()=>I([`allow`,`deny`,`ask`])),yo=V(()=>z({toolName:A(),ruleContent:A().optional()})),bo=V(()=>or(`type`,[z({type:P(`addRules`),rules:R(yo()),behavior:vo(),destination:_o()}),z({type:P(`replaceRules`),rules:R(yo()),behavior:vo(),destination:_o()}),z({type:P(`removeRules`),rules:R(yo()),behavior:vo(),destination:_o()}),z({type:P(`setMode`),mode:cr(()=>So()),destination:_o()}),z({type:P(`addDirectories`),directories:R(A()),destination:_o()}),z({type:P(`removeDirectories`),directories:R(A()),destination:_o()})])),xo=V(()=>I([`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).`));V(()=>F([z({behavior:P(`allow`),updatedInput:N(A(),M()).optional(),updatedPermissions:R(bo()).optional(),toolUseID:A().optional(),decisionClassification:xo().optional()}),z({behavior:P(`deny`),message:A(),interrupt:L().optional(),toolUseID:A().optional(),decisionClassification:xo().optional()})]));var So=V(()=>I([`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).`)),Co=`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(`.`),wo=V(()=>I(Co)),X=V(()=>z({session_id:A(),transcript_path:A(),cwd:A(),permission_mode:A().optional(),agent_id:A().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:A().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).`)})),To=V(()=>X().and(z({hook_event_name:P(`PreToolUse`),tool_name:A(),tool_input:M(),tool_use_id:A()}))),Eo=V(()=>X().and(z({hook_event_name:P(`PermissionRequest`),tool_name:A(),tool_input:M(),permission_suggestions:R(bo()).optional()}))),Do=V(()=>X().and(z({hook_event_name:P(`PostToolUse`),tool_name:A(),tool_input:M(),tool_response:M(),tool_use_id:A()}))),Oo=V(()=>X().and(z({hook_event_name:P(`PostToolUseFailure`),tool_name:A(),tool_input:M(),tool_use_id:A(),error:A(),is_interrupt:L().optional()}))),ko=V(()=>X().and(z({hook_event_name:P(`PermissionDenied`),tool_name:A(),tool_input:M(),tool_use_id:A(),reason:A()}))),Ao=V(()=>X().and(z({hook_event_name:P(`Notification`),message:A(),title:A().optional(),notification_type:A()}))),jo=V(()=>X().and(z({hook_event_name:P(`UserPromptSubmit`),prompt:A()}))),Mo=V(()=>X().and(z({hook_event_name:P(`SessionStart`),source:I([`startup`,`resume`,`clear`,`compact`]),agent_type:A().optional(),model:A().optional()}))),No=V(()=>X().and(z({hook_event_name:P(`Setup`),trigger:I([`init`,`maintenance`])}))),Po=V(()=>X().and(z({hook_event_name:P(`Stop`),stop_hook_active:L(),last_assistant_message:A().optional().describe(`Text content of the last assistant message before stopping. Avoids the need to read and parse the transcript file.`)}))),Fo=V(()=>X().and(z({hook_event_name:P(`StopFailure`),error:Ms(),error_details:A().optional(),last_assistant_message:A().optional()}))),Io=V(()=>X().and(z({hook_event_name:P(`SubagentStart`),agent_id:A(),agent_type:A()}))),Lo=V(()=>X().and(z({hook_event_name:P(`SubagentStop`),stop_hook_active:L(),agent_id:A(),agent_transcript_path:A(),agent_type:A(),last_assistant_message:A().optional().describe(`Text content of the last assistant message before stopping. Avoids the need to read and parse the transcript file.`)}))),Ro=V(()=>X().and(z({hook_event_name:P(`PreCompact`),trigger:I([`manual`,`auto`]),custom_instructions:A().nullable()}))),zo=V(()=>X().and(z({hook_event_name:P(`PostCompact`),trigger:I([`manual`,`auto`]),compact_summary:A().describe(`The conversation summary produced by compaction`)}))),Bo=V(()=>X().and(z({hook_event_name:P(`TeammateIdle`),teammate_name:A(),team_name:A()}))),Vo=V(()=>X().and(z({hook_event_name:P(`TaskCreated`),task_id:A(),task_subject:A(),task_description:A().optional(),teammate_name:A().optional(),team_name:A().optional()}))),Ho=V(()=>X().and(z({hook_event_name:P(`TaskCompleted`),task_id:A(),task_subject:A(),task_description:A().optional(),teammate_name:A().optional(),team_name:A().optional()}))),Uo=V(()=>X().and(z({hook_event_name:P(`Elicitation`),mcp_server_name:A(),message:A(),mode:I([`form`,`url`]).optional(),url:A().optional(),elicitation_id:A().optional(),requested_schema:N(A(),M()).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.`)),Wo=V(()=>X().and(z({hook_event_name:P(`ElicitationResult`),mcp_server_name:A(),elicitation_id:A().optional(),mode:I([`form`,`url`]).optional(),action:I([`accept`,`decline`,`cancel`]),content:N(A(),M()).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.`)),Go=[`user_settings`,`project_settings`,`local_settings`,`policy_settings`,`skills`],Ko=V(()=>X().and(z({hook_event_name:P(`ConfigChange`),source:I(Go),file_path:A().optional()}))),qo=[`session_start`,`nested_traversal`,`path_glob_match`,`include`,`compact`],Jo=[`User`,`Project`,`Local`,`Managed`],Yo=V(()=>X().and(z({hook_event_name:P(`InstructionsLoaded`),file_path:A(),memory_type:I(Jo),load_reason:I(qo),globs:R(A()).optional(),trigger_file_path:A().optional(),parent_file_path:A().optional()}))),Xo=V(()=>X().and(z({hook_event_name:P(`WorktreeCreate`),name:A()}))),Zo=V(()=>X().and(z({hook_event_name:P(`WorktreeRemove`),worktree_path:A()}))),Qo=V(()=>X().and(z({hook_event_name:P(`CwdChanged`),old_cwd:A(),new_cwd:A()}))),$o=V(()=>X().and(z({hook_event_name:P(`FileChanged`),file_path:A(),event:I([`change`,`add`,`unlink`])}))),es=[`clear`,`resume`,`logout`,`prompt_input_exit`,`other`,`bypass_permissions_disabled`],ts=V(()=>I(es)),ns=V(()=>X().and(z({hook_event_name:P(`SessionEnd`),reason:ts()}))),rs=V(()=>F([To(),Do(),Oo(),ko(),Ao(),jo(),Mo(),ns(),Po(),Fo(),Io(),Lo(),Ro(),zo(),Eo(),No(),Bo(),Vo(),Ho(),Uo(),Wo(),Ko(),Yo(),Xo(),Zo(),Qo(),$o()])),is=V(()=>z({async:P(!0),asyncTimeout:j().optional()})),as=V(()=>z({hookEventName:P(`PreToolUse`),permissionDecision:vo().optional(),permissionDecisionReason:A().optional(),updatedInput:N(A(),M()).optional(),additionalContext:A().optional()})),os=V(()=>z({hookEventName:P(`UserPromptSubmit`),additionalContext:A().optional()})),ss=V(()=>z({hookEventName:P(`SessionStart`),additionalContext:A().optional(),initialUserMessage:A().optional(),watchPaths:R(A()).optional()})),cs=V(()=>z({hookEventName:P(`Setup`),additionalContext:A().optional()})),ls=V(()=>z({hookEventName:P(`SubagentStart`),additionalContext:A().optional()})),us=V(()=>z({hookEventName:P(`PostToolUse`),additionalContext:A().optional(),updatedMCPToolOutput:M().optional()})),ds=V(()=>z({hookEventName:P(`PostToolUseFailure`),additionalContext:A().optional()})),fs=V(()=>z({hookEventName:P(`PermissionDenied`),retry:L().optional()})),ps=V(()=>z({hookEventName:P(`Notification`),additionalContext:A().optional()})),ms=V(()=>z({hookEventName:P(`PermissionRequest`),decision:F([z({behavior:P(`allow`),updatedInput:N(A(),M()).optional(),updatedPermissions:R(bo()).optional()}),z({behavior:P(`deny`),message:A().optional(),interrupt:L().optional()})])})),hs=V(()=>z({hookEventName:P(`CwdChanged`),watchPaths:R(A()).optional()})),gs=V(()=>z({hookEventName:P(`FileChanged`),watchPaths:R(A()).optional()})),_s=V(()=>z({continue:L().optional(),suppressOutput:L().optional(),stopReason:A().optional(),decision:I([`approve`,`block`]).optional(),systemMessage:A().optional(),reason:A().optional(),hookSpecificOutput:F([as(),os(),ss(),cs(),ls(),us(),ds(),fs(),ps(),ms(),vs(),ys(),hs(),gs(),bs()]).optional()})),vs=V(()=>z({hookEventName:P(`Elicitation`),action:I([`accept`,`decline`,`cancel`]).optional(),content:N(A(),M()).optional()}).describe(`Hook-specific output for the Elicitation event. Return this to programmatically accept or decline an MCP elicitation request.`)),ys=V(()=>z({hookEventName:P(`ElicitationResult`),action:I([`accept`,`decline`,`cancel`]).optional(),content:N(A(),M()).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.`)),bs=V(()=>z({hookEventName:P(`WorktreeCreate`),worktreePath:A()}).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.`));V(()=>F([is(),_s()]));var xs=V(()=>z({key:A().describe(`Unique key for this option, returned in the response`),label:A().describe(`Display text for this option`),description:A().optional().describe(`Optional description shown below the label`)}));V(()=>z({prompt:A().describe(`Request ID. Presence of this key marks the line as a prompt request.`),message:A().describe(`The prompt message to display to the user`),options:R(xs()).describe(`Available options for the user to choose from`)})),V(()=>z({prompt_response:A().describe(`The request ID from the corresponding prompt request`),selected:A().describe(`The key of the selected option`)}));var Ss=V(()=>z({name:A().describe(`Skill name (without the leading slash)`),description:A().describe(`Description of what the skill does`),argumentHint:A().describe(`Hint for skill arguments (e.g., "<file>")`)}).describe(`Information about an available skill (invoked via /command syntax).`)),Cs=V(()=>z({name:A().describe(`Agent type identifier (e.g., "Explore")`),description:A().describe(`Description of when to use this agent`),model:A().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.`)),ws=V(()=>z({value:A().describe(`Model identifier to use in API calls`),displayName:A().describe(`Human-readable display name`),description:A().describe(`Description of the model's capabilities`),supportsAdaptiveThinking:L().optional().describe(`Whether this model supports adaptive thinking (Claude decides when and how much to think)`),supportsFastMode:L().optional().describe(`Whether this model supports fast mode`),supportsAutoMode:L().optional().describe(`Whether this model supports auto mode`)}).describe(`Information about an available model.`)),Ts=V(()=>z({email:A().optional(),organization:A().optional(),subscriptionType:A().optional(),tokenSource:A().optional(),apiKeySource:A().optional(),apiProvider:I([`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.`)),Es=V(()=>F([A(),N(A(),po())])),Ds=V(()=>z({description:A().describe(`Natural language description of when to use this agent`),tools:R(A()).optional().describe(`Array of allowed tool names. If omitted, inherits all tools from parent`),disallowedTools:R(A()).optional().describe(`Array of tool names to explicitly disallow for this agent`),prompt:A().describe(`The agent's system prompt`),model:A().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:R(Es()).optional(),criticalSystemReminder_EXPERIMENTAL:A().optional().describe(`Experimental: Critical reminder added to system prompt`),skills:R(A()).optional().describe(`Array of skill names to preload into the agent context`),initialPrompt:A().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:j().int().positive().optional().describe(`Maximum number of agentic turns (API round-trips) before stopping`),background:L().optional().describe(`Run this agent as a background task (non-blocking, fire-and-forget) when invoked`),memory:I([`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:So().optional().describe(`Permission mode controlling how tool executions are handled`)}).describe(`Definition for a custom subagent that can be invoked via the Agent tool.`));V(()=>I([`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).`)),V(()=>z({type:P(`local`).describe(`Plugin type. Currently only 'local' is supported`),path:A().describe(`Absolute or relative path to the plugin directory`)}).describe(`Configuration for loading a plugin.`)),V(()=>z({canRewind:L(),error:A().optional(),filesChanged:R(A()).optional(),insertions:j().optional(),deletions:j().optional()}).describe(`Result of a rewindFiles operation.`));var Os=V(()=>M()),ks=V(()=>M()),As=V(()=>M()),Z=V(()=>A()),js=V(()=>M()),Ms=V(()=>I([`authentication_failed`,`billing_error`,`rate_limit`,`invalid_request`,`server_error`,`unknown`,`max_output_tokens`])),Ns=V(()=>F([P(`compacting`),sr()])),Ps=V(()=>z({type:P(`user`),message:Os(),parent_tool_use_id:A().nullable(),isSynthetic:L().optional(),tool_use_result:M().optional(),priority:I([`now`,`next`,`later`]).optional(),timestamp:A().optional().describe(`ISO timestamp when the message was created on the originating process. Older emitters omit it; consumers should fall back to receive time.`)})),Fs=V(()=>Ps().extend({uuid:Z().optional(),session_id:A().optional()})),Is=V(()=>Ps().extend({uuid:Z(),session_id:A(),isReplay:P(!0)})),Ls=V(()=>z({status:I([`allowed`,`allowed_warning`,`rejected`]),resetsAt:j().optional(),rateLimitType:I([`five_hour`,`seven_day`,`seven_day_opus`,`seven_day_sonnet`,`overage`]).optional(),utilization:j().optional(),overageStatus:I([`allowed`,`allowed_warning`,`rejected`]).optional(),overageResetsAt:j().optional(),overageDisabledReason:I([`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:L().optional(),surpassedThreshold:j().optional()}).describe(`Rate limit information for claude.ai subscription users.`)),Rs=V(()=>z({type:P(`assistant`),message:ks(),parent_tool_use_id:A().nullable(),error:Ms().optional(),uuid:Z(),session_id:A()})),zs=V(()=>z({type:P(`rate_limit_event`),rate_limit_info:Ls(),uuid:Z(),session_id:A()}).describe(`Rate limit event emitted when rate limit info changes.`)),Bs=V(()=>z({type:P(`streamlined_text`),text:A().describe(`Text content preserved from the assistant message`),session_id:A(),uuid:Z()}).describe(`@internal Streamlined text message - replaces SDKAssistantMessage in streamlined output. Text content preserved, thinking and tool_use blocks removed.`)),Vs=V(()=>z({type:P(`streamlined_tool_use_summary`),tool_summary:A().describe(`Summary of tool calls (e.g., "Read 2 files, wrote 1 file")`),session_id:A(),uuid:Z()}).describe(`@internal Streamlined tool use summary - replaces tool_use blocks in streamlined output with a cumulative summary string.`)),Hs=V(()=>z({tool_name:A(),tool_use_id:A(),tool_input:N(A(),M())})),Us=V(()=>z({type:P(`result`),subtype:P(`success`),duration_ms:j(),duration_api_ms:j(),is_error:L(),num_turns:j(),result:A(),stop_reason:A().nullable(),total_cost_usd:j(),usage:js(),modelUsage:N(A(),to()),permission_denials:R(Hs()),structured_output:M().optional(),fast_mode_state:pc().optional(),uuid:Z(),session_id:A()})),Ws=V(()=>z({type:P(`result`),subtype:I([`error_during_execution`,`error_max_turns`,`error_max_budget_usd`,`error_max_structured_output_retries`]),duration_ms:j(),duration_api_ms:j(),is_error:L(),num_turns:j(),stop_reason:A().nullable(),total_cost_usd:j(),usage:js(),modelUsage:N(A(),to()),permission_denials:R(Hs()),errors:R(A()),fast_mode_state:pc().optional(),uuid:Z(),session_id:A()})),Gs=V(()=>F([Us(),Ws()])),Ks=V(()=>z({type:P(`system`),subtype:P(`init`),agents:R(A()).optional(),apiKeySource:io(),betas:R(A()).optional(),claude_code_version:A(),cwd:A(),tools:R(A()),mcp_servers:R(z({name:A(),status:A()})),model:A(),permissionMode:So(),slash_commands:R(A()),output_style:A(),skills:R(A()),plugins:R(z({name:A(),path:A(),source:A().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:pc().optional(),uuid:Z(),session_id:A()})),qs=V(()=>z({type:P(`stream_event`),event:As(),parent_tool_use_id:A().nullable(),uuid:Z(),session_id:A()})),Js=V(()=>z({type:P(`system`),subtype:P(`compact_boundary`),compact_metadata:z({trigger:I([`manual`,`auto`]),pre_tokens:j(),preserved_segment:z({head_uuid:Z(),anchor_uuid:Z(),tail_uuid:Z()}).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:Z(),session_id:A()})),Ys=V(()=>z({type:P(`system`),subtype:P(`status`),status:Ns(),permissionMode:So().optional(),uuid:Z(),session_id:A()})),Xs=V(()=>z({type:P(`system`),subtype:P(`post_turn_summary`),summarizes_uuid:A(),status_category:I([`blocked`,`waiting`,`completed`,`review_ready`,`failed`]),status_detail:A(),is_noteworthy:L(),title:A(),description:A(),recent_action:A(),needs_action:A(),artifact_urls:R(A()),uuid:Z(),session_id:A()}).describe(`@internal Background post-turn summary emitted after each assistant turn. summarizes_uuid points to the assistant message this summarizes.`)),Zs=V(()=>z({type:P(`system`),subtype:P(`api_retry`),attempt:j(),max_retries:j(),retry_delay_ms:j(),error_status:j().nullable(),error:Ms(),uuid:Z(),session_id:A()}).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.`)),Qs=V(()=>z({type:P(`system`),subtype:P(`local_command_output`),content:A(),uuid:Z(),session_id:A()}).describe(`Output from a local slash command (e.g. /voice, /cost). Displayed as assistant-style text in the transcript.`)),$s=V(()=>z({type:P(`system`),subtype:P(`hook_started`),hook_id:A(),hook_name:A(),hook_event:A(),uuid:Z(),session_id:A()})),ec=V(()=>z({type:P(`system`),subtype:P(`hook_progress`),hook_id:A(),hook_name:A(),hook_event:A(),stdout:A(),stderr:A(),output:A(),uuid:Z(),session_id:A()})),tc=V(()=>z({type:P(`system`),subtype:P(`hook_response`),hook_id:A(),hook_name:A(),hook_event:A(),output:A(),stdout:A(),stderr:A(),exit_code:j().optional(),outcome:I([`success`,`error`,`cancelled`]),uuid:Z(),session_id:A()})),nc=V(()=>z({type:P(`tool_progress`),tool_use_id:A(),tool_name:A(),parent_tool_use_id:A().nullable(),elapsed_time_seconds:j(),task_id:A().optional(),uuid:Z(),session_id:A()})),rc=V(()=>z({type:P(`auth_status`),isAuthenticating:L(),output:R(A()),error:A().optional(),uuid:Z(),session_id:A()})),ic=V(()=>z({type:P(`system`),subtype:P(`files_persisted`),files:R(z({filename:A(),file_id:A()})),failed:R(z({filename:A(),error:A()})),processed_at:A(),uuid:Z(),session_id:A()})),ac=V(()=>z({type:P(`system`),subtype:P(`task_notification`),task_id:A(),tool_use_id:A().optional(),status:I([`completed`,`failed`,`stopped`]),output_file:A(),summary:A(),usage:z({total_tokens:j(),tool_uses:j(),duration_ms:j()}).optional(),uuid:Z(),session_id:A()})),oc=V(()=>z({type:P(`system`),subtype:P(`task_started`),task_id:A(),tool_use_id:A().optional(),description:A(),task_type:A().optional(),workflow_name:A().optional().describe(`meta.name from the workflow script (e.g. 'spec'). Only set when task_type is 'local_workflow'.`),prompt:A().optional(),uuid:Z(),session_id:A()})),sc=V(()=>z({type:P(`system`),subtype:P(`session_state_changed`),state:I([`idle`,`running`,`requires_action`]),uuid:Z(),session_id:A()}).describe(`Mirrors notifySessionStateChanged. 'idle' fires after heldBackResult flushes and the bg-agent do-while exits — authoritative turn-over signal.`)),cc=V(()=>z({type:P(`system`),subtype:P(`task_progress`),task_id:A(),tool_use_id:A().optional(),description:A(),usage:z({total_tokens:j(),tool_uses:j(),duration_ms:j()}),last_tool_name:A().optional(),summary:A().optional(),uuid:Z(),session_id:A()})),lc=V(()=>z({type:P(`tool_use_summary`),summary:A(),preceding_tool_use_ids:R(A()),uuid:Z(),session_id:A()})),uc=V(()=>z({type:P(`system`),subtype:P(`elicitation_complete`),mcp_server_name:A(),elicitation_id:A(),uuid:Z(),session_id:A()}).describe(`Emitted when an MCP server confirms that a URL-mode elicitation is complete.`)),dc=V(()=>z({type:P(`prompt_suggestion`),suggestion:A(),uuid:Z(),session_id:A()}).describe(`Predicted next user prompt, emitted after each turn when promptSuggestions is enabled.`));V(()=>z({sessionId:A().describe(`Unique session identifier (UUID).`),summary:A().describe(`Display title for the session: custom title, auto-generated summary, or first prompt.`),lastModified:j().describe(`Last modified time in milliseconds since epoch.`),fileSize:j().optional().describe(`File size in bytes. Only populated for local JSONL storage.`),customTitle:A().optional().describe(`User-set session title via /rename.`),firstPrompt:A().optional().describe(`First meaningful user prompt in the session.`),gitBranch:A().optional().describe(`Git branch at the end of the session.`),cwd:A().optional().describe(`Working directory for the session.`),tag:A().optional().describe(`User-set session tag.`),createdAt:j().optional().describe(`Creation time in milliseconds since epoch, extracted from the first entry's timestamp.`)}).describe(`Session metadata returned by listSessions and getSessionInfo.`));var fc=V(()=>F([Rs(),Fs(),Is(),Gs(),Ks(),qs(),Js(),Ys(),Zs(),Qs(),$s(),ec(),tc(),nc(),rc(),ac(),oc(),cc(),sc(),ic(),lc(),zs(),uc(),dc()])),pc=V(()=>I([`off`,`cooldown`,`on`]).describe(`Fast mode state: off, in cooldown after rate limit, or actively enabled.`));lr(),ur();var mc=V(()=>M()),hc=V(()=>z({matcher:A().optional(),hookCallbackIds:R(A()),timeout:j().optional()}).describe(`Configuration for matching and routing hook callbacks.`)),gc=V(()=>z({subtype:P(`initialize`),hooks:N(wo(),R(hc())).optional(),sdkMcpServers:R(A()).optional(),jsonSchema:N(A(),M()).optional(),systemPrompt:A().optional(),appendSystemPrompt:A().optional(),agents:N(A(),Ds()).optional(),promptSuggestions:L().optional(),agentProgressSummaries:L().optional()}).describe(`Initializes the SDK session with hooks, MCP servers, and agent configuration.`));V(()=>z({commands:R(Ss()),agents:R(Cs()),output_style:A(),available_output_styles:R(A()),models:R(ws()),account:Ts(),pid:j().optional().describe(`@internal CLI process PID for tmux socket isolation`),fast_mode_state:pc().optional()}).describe(`Response from session initialization with available commands, models, and account info.`));var _c=V(()=>z({subtype:P(`interrupt`)}).describe(`Interrupts the currently running conversation turn.`)),vc=V(()=>z({subtype:P(`can_use_tool`),tool_name:A(),input:N(A(),M()),permission_suggestions:R(bo()).optional(),blocked_path:A().optional(),decision_reason:A().optional(),title:A().optional(),display_name:A().optional(),tool_use_id:A(),agent_id:A().optional(),description:A().optional()}).describe(`Requests permission to use a tool with the given input.`)),yc=V(()=>z({subtype:P(`set_permission_mode`),mode:So()}).describe(`Sets the permission mode for tool execution handling.`)),bc=V(()=>z({subtype:P(`set_model`),model:A().optional()}).describe(`Sets the model to use for subsequent conversation turns.`)),xc=V(()=>z({subtype:P(`set_max_thinking_tokens`),max_thinking_tokens:j().nullable()}).describe(`Sets the maximum number of thinking tokens for extended thinking.`)),Sc=V(()=>z({subtype:P(`mcp_status`)}).describe(`Requests the current status of all MCP server connections.`));V(()=>z({mcpServers:R(go())}).describe(`Response containing the current status of all MCP server connections.`));var Cc=V(()=>z({subtype:P(`get_context_usage`)}).describe(`Requests a breakdown of current context window usage by category.`)),wc=V(()=>z({name:A(),tokens:j(),color:A(),isDeferred:L().optional()})),Tc=V(()=>z({color:A(),isFilled:L(),categoryName:A(),tokens:j(),percentage:j(),squareFullness:j()}));V(()=>z({categories:R(wc()),totalTokens:j(),maxTokens:j(),rawMaxTokens:j(),percentage:j(),gridRows:R(R(Tc())),model:A(),memoryFiles:R(z({path:A(),type:A(),tokens:j()})),mcpTools:R(z({name:A(),serverName:A(),tokens:j(),isLoaded:L().optional()})),deferredBuiltinTools:R(z({name:A(),tokens:j(),isLoaded:L()})).optional(),systemTools:R(z({name:A(),tokens:j()})).optional(),systemPromptSections:R(z({name:A(),tokens:j()})).optional(),agents:R(z({agentType:A(),source:A(),tokens:j()})),slashCommands:z({totalCommands:j(),includedCommands:j(),tokens:j()}).optional(),skills:z({totalSkills:j(),includedSkills:j(),tokens:j(),skillFrontmatter:R(z({name:A(),source:A(),tokens:j()}))}).optional(),autoCompactThreshold:j().optional(),isAutoCompactEnabled:L(),messageBreakdown:z({toolCallTokens:j(),toolResultTokens:j(),attachmentTokens:j(),assistantMessageTokens:j(),userMessageTokens:j(),toolCallsByType:R(z({name:A(),callTokens:j(),resultTokens:j()})),attachmentsByType:R(z({name:A(),tokens:j()}))}).optional(),apiUsage:z({input_tokens:j(),output_tokens:j(),cache_creation_input_tokens:j(),cache_read_input_tokens:j()}).nullable()}).describe(`Breakdown of current context window usage by category (system prompt, tools, messages, etc.).`));var Ec=V(()=>z({subtype:P(`rewind_files`),user_message_id:A(),dry_run:L().optional()}).describe(`Rewinds file changes made since a specific user message.`));V(()=>z({canRewind:L(),error:A().optional(),filesChanged:R(A()).optional(),insertions:j().optional(),deletions:j().optional()}).describe(`Result of a rewindFiles operation.`));var Dc=V(()=>z({subtype:P(`cancel_async_message`),message_uuid:A()}).describe(`Drops a pending async user message from the command queue by uuid. No-op if already dequeued for execution.`));V(()=>z({cancelled:L()}).describe(`Result of a cancel_async_message operation. cancelled=false means the message was not in the queue (already dequeued or never enqueued).`));var Oc=V(()=>z({subtype:P(`seed_read_state`),path:A(),mtime:j()}).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.`)),kc=V(()=>z({subtype:P(`hook_callback`),callback_id:A(),input:rs(),tool_use_id:A().optional()}).describe(`Delivers a hook callback with its input data.`)),Ac=V(()=>z({subtype:P(`mcp_message`),server_name:A(),message:mc()}).describe(`Sends a JSON-RPC message to a specific MCP server.`)),jc=V(()=>z({subtype:P(`mcp_set_servers`),servers:N(A(),po())}).describe(`Replaces the set of dynamically managed MCP servers.`));V(()=>z({added:R(A()),removed:R(A()),errors:N(A(),A())}).describe(`Result of replacing the set of dynamically managed MCP servers.`));var Mc=V(()=>z({subtype:P(`reload_plugins`)}).describe(`Reloads plugins from disk and returns the refreshed session components.`));V(()=>z({commands:R(Ss()),agents:R(Cs()),plugins:R(z({name:A(),path:A(),source:A().optional()})),mcpServers:R(go()),error_count:j()}).describe(`Refreshed commands, agents, plugins, and MCP server status after reload.`));var Nc=V(()=>z({subtype:P(`mcp_reconnect`),serverName:A()}).describe(`Reconnects a disconnected or failed MCP server.`)),Pc=V(()=>z({subtype:P(`mcp_toggle`),serverName:A(),enabled:L()}).describe(`Enables or disables an MCP server.`)),Fc=V(()=>z({subtype:P(`stop_task`),task_id:A()}).describe(`Stops a running task.`)),Ic=V(()=>z({subtype:P(`apply_flag_settings`),settings:N(A(),M())}).describe(`Merges the provided settings into the flag settings layer, updating the active configuration.`)),Lc=V(()=>z({subtype:P(`get_settings`)}).describe(`Returns the effective merged settings and the raw per-source settings.`));V(()=>z({effective:N(A(),M()),sources:R(z({source:I([`userSettings`,`projectSettings`,`localSettings`,`flagSettings`,`policySettings`]),settings:N(A(),M())})).describe(`Ordered low-to-high priority — later entries override earlier ones.`),applied:z({model:A()}).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 Rc=V(()=>z({subtype:P(`elicitation`),mcp_server_name:A(),message:A(),mode:I([`form`,`url`]).optional(),url:A().optional(),elicitation_id:A().optional(),requested_schema:N(A(),M()).optional()}).describe(`Requests the SDK consumer to handle an MCP elicitation (user input request).`)),zc=V(()=>z({action:I([`accept`,`decline`,`cancel`]),content:N(A(),M()).optional()}).describe(`Response from the SDK consumer for an elicitation request.`)),Bc=V(()=>F([_c(),vc(),gc(),yc(),bc(),xc(),Sc(),Cc(),kc(),Ac(),Ec(),Dc(),Oc(),jc(),Mc(),Nc(),Pc(),Fc(),Ic(),Lc(),Rc()])),Vc=V(()=>z({type:P(`control_request`),request_id:A(),request:Bc()})),Hc=V(()=>z({subtype:P(`success`),request_id:A(),response:N(A(),M()).optional()})),Uc=V(()=>z({subtype:P(`error`),request_id:A(),error:A(),pending_permission_requests:R(cr(()=>Vc())).optional()})),Wc=V(()=>z({type:P(`control_response`),response:F([Hc(),Uc()])})),Gc=V(()=>z({type:P(`control_cancel_request`),request_id:A()}).describe(`Cancels a currently open control request.`)),Kc=V(()=>z({type:P(`keep_alive`)}).describe(`Keep-alive message to maintain WebSocket connection.`)),qc=V(()=>z({type:P(`update_environment_variables`),variables:N(A(),A())}).describe(`Updates environment variables at runtime.`));V(()=>F([fc(),Bs(),Vs(),Xs(),Wc(),Vc(),Gc(),Kc()])),V(()=>F([Fs(),Vc(),Wc(),Kc(),qc()])),tt(),lr(),ur(),Nn(),C(),V(()=>B.object({tool_name:B.string().describe(`The name of the tool requesting permission`),input:B.record(B.string(),B.unknown()).describe(`The input for the tool`),tool_use_id:B.string().optional().describe(`The unique tool use request ID`)}));var Jc=V(()=>B.enum([`user_temporary`,`user_permanent`,`user_reject`]).optional().catch(void 0)),Yc=V(()=>B.object({behavior:B.literal(`allow`),updatedInput:B.record(B.string(),B.unknown()),updatedPermissions:B.array(le()).optional().catch(e=>{G(`Malformed updatedPermissions from SDK host ignored: ${e.error.issues[0]?.message??`unknown`}`,{level:`warn`})}),toolUseID:B.string().optional(),decisionClassification:Jc()})),Xc=V(()=>B.object({behavior:B.literal(`deny`),message:B.string(),interrupt:B.boolean().optional(),toolUseID:B.string().optional(),decisionClassification:Jc()})),Zc=V(()=>B.union([Yc(),Xc()]));function Qc(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:f(e.toolPermissionContext,t)})),Sn(t));let a=Object.keys(e.updatedInput).length>0?e.updatedInput:n;return{...e,updatedInput:a,decisionReason:i}}else e.behavior===`deny`&&e.interrupt&&(G(`SDK permission prompt deny+interrupt: tool=${t.name} message=${e.message}`),r.abortController.abort());return{...e,decisionReason:i}}Cr(),zr(),qr(),Wr(),Pi(),Li(),oe(),ne(),In(),un(),Hi(),bn(),Zn(),wn(),qe(),Yi(),pt(),at(),T(),ge(),At(),g(),v(),x(),b(),Vn(),ct();var $c=/\u2028|\u2029/g;function el(e){return e.replace($c,e=>e===`\u2028`?`\\u2028`:`\\u2029`)}function tl(e){return el(U(e))}jr(),Fr(),lr(),Nn();var nl=`SandboxNetworkAccess`;function rl(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 il(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 al=1e3,ol=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 vt),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>al)){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(U({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&&(ei(`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=pa(Dr(e));if(t.type===`keep_alive`)return;if(t.type===`update_environment_variables`){let e=t.variables??{},n=Object.keys(e);for(let[t,n]of Object.entries(e))process.env[t]=n;G(`[structuredIO] applied update_environment_variables: ${n.join(`, `)}`);return}if(t.type===`control_response`){let e=`uuid`in t&&typeof t.uuid==`string`?t.uuid:void 0;e&&Ze(e,`completed`);let n=t.response,r=this.pendingRequests.get(n.request_id);if(!r){let e=(n.subtype===`success`?n.response:void 0)?.toolUseID;if(typeof e==`string`&&this.resolvedToolUseIds.has(e)){G(`Ignoring duplicate control_response for already-resolved toolUseID=${e} request_id=${n.request_id}`);return}this.unexpectedResponseCallback&&await this.unexpectedResponseCallback(t);return}if(this.trackResolvedToolUseId(r.request),this.pendingRequests.delete(n.request_id),r.request.request.subtype===`can_use_tool`&&this.onControlRequestResolved&&this.onControlRequestResolved(n.request_id),n.subtype===`error`){r.reject(Error(n.error??`Unknown error`));return}let i=n.response;if(r.schema)try{r.resolve(r.schema.parse(i))}catch(e){r.reject(e)}else r.resolve({});return this.replayUserMessages?t:void 0}if(t.type!==`user`&&t.type!==`control_request`&&t.type!==`assistant`&&t.type!==`system`){G(`Ignoring unknown message type: ${t.type}`,{level:`warn`});return}return t.type===`control_request`?(t.request||sl(`Error: Missing request on control_request`),t):(t.type===`assistant`||t.type===`system`||t.message?.role!==`user`&&sl(`Error: Expected message role 'user', got '${t.message?.role}'`),t)}catch(t){console.error(`Error parsing streaming input line: ${e}: ${t}`),process.exit(1)}}async write(e){K(tl(e)+`
4
- `)}async sendRequest(e,t,n,r=Y()){let i={type:`control_request`,request_id:r,request:e};if(this.inputClosed)throw Error(`Stream closed`);if(n?.aborted)throw Error(`Request aborted`);this.outbound.enqueue(i),e.subtype===`can_use_tool`&&this.onControlRequestSent&&this.onControlRequestSent(i);let a=()=>{this.outbound.enqueue({type:`control_cancel_request`,request_id:r});let e=this.pendingRequests.get(r);e&&(this.trackResolvedToolUseId(e.request),e.reject(new Tr))};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 rt(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=cl(t.name,a,n,r,s.suggestions).then(e=>({source:`hook`,decision:e})),o=Y();e?.(il(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:rl(s.decisionReason),tool_use_id:a,agent_id:r.agentId},Zc(),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):Qc((await l).result,t,n,r):Qc(u.result,t,n,r)}catch(e){return Qc({behavior:`deny`,message:`Tool permission request failed: ${e}`,toolUseID:a},t,n,r)}finally{this.getPendingPermissionRequests().length===0&&Xi(`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},qn(),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},zc(),r)}catch{return{action:`cancel`}}}createSandboxAskCallback(){return async e=>{try{return(await this.sendRequest({subtype:`can_use_tool`,tool_name:nl,input:{host:e.host},tool_use_id:Y(),description:`Allow network connection to ${e.host}?`},Zc())).behavior===`allow`}catch{return!1}}}async sendMcpMessage(e,t){return(await this.sendRequest({subtype:`mcp_message`,server_name:e,message:t},z({mcp_response:ar()}))).mcp_response}};function sl(e){console.error(e),process.exit(1)}async function cl(e,t,n,r,i){let a=r.getAppState().toolPermissionContext.mode,o=dt(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){Sn(i);let e=f(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`}}}}Vi(),va();function ll(e,t={},n,i){if(r(process.env.CLAUDE_CODE_USE_CCR_V2)){let r=new $a(e.href);return r.protocol===`wss:`?r.protocol=`https:`:r.protocol===`ws:`&&(r.protocol=`http:`),r.pathname=r.pathname.replace(/\/$/,``)+`/worker/events/stream`,new ya(r,t,n,i)}if(e.protocol===`ws:`||e.protocol===`wss:`)return r(process.env.CLAUDE_CODE_POST_FOR_SESSION_INGRESS_V2)?new _a(e,t,n,i):new ga(e,t,n,i);throw Error(`Unsupported protocol: ${e.protocol}`)}Zn(),jr(),$r(),i(),Er(),Zr(),Yi(),va(),o();var ul=class extends ol{constructor(e,t,n){let i=new Ja({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 $a(e);let a={},o=qi();o?a.Authorization=`Bearer ${o}`:G(`[remote-io] No session ingress token available`,{level:`error`});let c=process.env.CLAUDE_CODE_ENVIRONMENT_RUNNER_VERSION;c&&(a[`x-environment-runner-version`]=c);let l=()=>{let e={},t=qi();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=ll(this.url,a,H(),l),this.isBridge=process.env.CLAUDE_CODE_ENVIRONMENT_KIND===`bridge`,this.isDebug=kr(),this.transport.setOnData(e=>{this.inputStream.write(e),this.isBridge&&this.isDebug&&K(e.endsWith(`
5
- `)?e:e+`
6
- `)}),this.transport.setOnClose(()=>{this.inputStream.end()}),r(process.env.CLAUDE_CODE_USE_CCR_V2)){if(!(this.transport instanceof ya))throw Error(`CCR v2 requires SSETransport; check getTransportForUrl`);this.ccrClient=new ha(this.transport,this.url);let e=this.ccrClient.initialize();this.restoredWorkerState=e.catch(()=>null),e.catch(e=>{ei(`error`,`cli_worker_lifecycle_init_failed`,{reason:e instanceof ma?e.reason:`unknown`}),q(Error(`CCRClient initialization failed: ${W(e)}`)),mt(1,`other`)}),Mr(async()=>this.ccrClient?.close()),Pt((e,t,n)=>this.ccrClient.writeInternalEvent(e,t,n)),er(()=>this.ccrClient.readInternalEvents(),()=>this.ccrClient.readSubagentInternalEvents());let t={started:`processing`,completed:`processed`};y((e,n)=>{this.ccrClient?.reportDelivery(e,t[n])}),Ji((e,t)=>{this.ccrClient?.reportState(e,t)}),Ki(e=>{this.ccrClient?.reportMetadata(e)},{replayCurrent:!0})}this.transport.connect();let u=fa().session_keepalive_interval_v2_ms;if(this.isBridge&&u>0&&(this.keepAliveTimer=setInterval(()=>{G(`[remote-io] keep_alive sent`),this.write({type:`keep_alive`}).catch(e=>{G(`[remote-io] keep_alive write failed: ${W(e)}`)})},u),this.keepAliveTimer.unref?.()),Mr(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)&&K(tl(e)+`
8
- `)}close(){this.keepAliveTimer&&(clearInterval(this.keepAliveTimer),this.keepAliveTimer=null),this.transport.close(),this.inputStream.end()}};Ri(),Lr(),Fi(),[...Bi],Nr(),jr();var dl=`[stdout-guard]`,fl=!1,Q=``,pl=null;function ml(e){if(e.length===0)return!0;try{return JSON.parse(e),!0}catch{return!1}}function hl(){fl||(fl=!0,pl=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`);Q+=r;let i,a=!0;for(;(i=Q.indexOf(`
9
- `))!==-1;){let e=Q.slice(0,i);Q=Q.slice(i+1),ml(e)?a=pl(e+`
10
- `):(process.stderr.write(`${dl} ${e}\n`),G(`streamJsonStdoutGuard diverted non-JSON stdout line: ${e.slice(0,200)}`))}let o=typeof t==`function`?t:n;return o&&queueMicrotask(()=>o()),a},Mr(async()=>{Q.length>0&&(pl&&ml(Q)?pl(Q+`
11
- `):process.stderr.write(`${dl} ${Q}\n`),Q=``),pl&&(process.stdout.write=pl,pl=null),fl=!1}))}Yr(),Fe(),Ui(),Ct(),Xe(),cn(),Ii(),Wn(),ht(),m(),ie(),Pn(),gt(),Tt(),ir(),Vt(),pn(),ka(),It(),Er(),ii(),Vi(),Xn(),jr(),qe();function gl(e){let t=process.env.CLAUDE_CODE_EXIT_AFTER_STOP_DELAY,n=t?parseInt(t,10):null,r=n&&!isNaN(n)&&n>0,i=null,a=0;return{start(){i&&(clearTimeout(i),i=null),r&&(a=Date.now(),i=setTimeout(()=>{let t=Date.now()-a;e()&&t>=n&&(G(`Exiting after ${n}ms of idle time`),k())},n))},stop(){i&&(clearTimeout(i),i=null)}}}ra(),Se(),S(),kn(),Un();function _l(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)?vl(t):t,uuid:n}}function vl(e){return e.some(yl)?e.map(e=>{if(!yl(e))return e;let t=e.source,n=typeof t.mediaType==`string`&&t.mediaType?t.mediaType:Et(e.source.data);return{...e,source:{type:`base64`,media_type:n,data:e.source.data}}}):e}function yl(e){return e.type!==`image`||e.source?.type!==`base64`?!1:!e.source.media_type}lr(),_r(),jr(),i(),ur(),ia();var bl=3e4;function xl(e){G(`[bridge:inbound-attach] ${e}`)}var Sl=V(()=>z({file_uuid:A(),file_name:A()})),Cl=V(()=>R(Sl()));function wl(e){if(typeof e!=`object`||!e||!(`file_attachments`in e))return[];let t=Cl().safeParse(e.file_attachments);return t.success?t.data:[]}function Tl(e){return Ga(e).replace(/[^a-zA-Z0-9._-]/g,`_`)||`attachment`}function El(){return qa(n(),`uploads`,H())}async function Dl(e){let t=oa();if(!t){xl(`skip: no oauth token`);return}let n;try{let r=`${aa()}/api/oauth/files/${encodeURIComponent(e.file_uuid)}/content`,i=await c.get(r,{headers:{Authorization:`Bearer ${t}`},responseType:`arraybuffer`,timeout:bl,validateStatus:()=>!0});if(i.status!==200){xl(`fetch ${e.file_uuid} failed: status=${i.status}`);return}n=Buffer.from(i.data)}catch(t){xl(`fetch ${e.file_uuid} threw: ${t}`);return}let r=Tl(e.file_name),i=(e.file_uuid.slice(0,8)||Y().slice(0,8)).replace(/[^a-zA-Z0-9_-]/g,`_`),a=El(),o=qa(a,`${i}-${r}`);try{await Ya(a,{recursive:!0}),await Qa(o,n)}catch(e){xl(`write ${o} failed: ${e}`);return}return xl(`resolved ${e.file_uuid} → ${o} (${n.length} bytes)`),o}async function Ol(e){if(e.length===0)return``;xl(`resolving ${e.length} attachment(s)`);let t=(await Promise.all(e.map(Dl))).filter(e=>e!==void 0);return t.length===0?``:t.map(e=>`@"${e}"`).join(` `)+` `}function kl(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 Al(e,t){let n=wl(e);return n.length===0?t:kl(t,await Ol(n))}yi(),Ee(),Bt(),Kt(),Cn(),te(),da(),Na();function jl(e){if(e.toLowerCase().endsWith(`.jsonl`))return{sessionId:Y(),ingressUrl:null,isUrl:!1,jsonlFile:e,isJsonlFile:!0};if(tn(e))return{sessionId:e,ingressUrl:null,isUrl:!1,jsonlFile:null,isJsonlFile:!1};try{let t=new URL(e);return{sessionId:Y(),ingressUrl:t.href,isUrl:!0,jsonlFile:null,isJsonlFile:!1}}catch{}return null}Ti(),Dn(),sn(),ft(),Oe(),He(),rn(),ce(),tr(),Ht(),ve(),ca(),Ia(),La(),jr(),Fr();async function Ml(){try{let e=await Xa(ln(),`utf-8`),t=Vr().safeParse(Dr(e));return t.success?t.data:(G(`Invalid known_marketplaces.json in zip cache: ${t.error.message}`,{level:`error`}),{})}catch{return{}}}async function Nl(e){await Rn(ln(),U(e,null,2))}async function Pl(e,t){let n=vn();if(!n)return;let r=await Fl(t);r!==null&&await Rn(qa(n,qt(e)),r)}async function Fl(e){let t=[qa(e,`.claude-plugin`,`marketplace.json`),qa(e,`marketplace.json`),e];for(let e of t)try{return await Xa(e,`utf-8`)}catch{}return null}async function Il(){let e=await st();for(let[t,n]of Object.entries(e))if(n.installLocation)try{await Pl(t,n.installLocation)}catch(e){G(`Failed to save marketplace JSON for ${t}: ${e}`)}await Nl({...await Ml(),...e})}ci(),Nr(),jr(),$r(),ii(),ir(),Tt();async function Ll(){let e=nr();G(`installPluginsForHeadless: starting${e?` (zip cache mode)`:``}`);let t=await ut();t&&(Ue(),jn(`headlessPluginInstall: seed marketplaces registered`)),e&&(await Pr().mkdir(Qt()),await Pr().mkdir(Xt()));let n=Object.keys(he()).length,r={marketplaces_installed:0,delisted_count:0},i=t;try{if(n===0)G(`installPluginsForHeadless: no marketplaces declared`);else{let t=await Qr(`headless_marketplace_reconcile`,()=>Ha({skip:e?(e,t)=>!Hn(t):void 0,onProgress:e=>{e.type===`installed`?G(`installPluginsForHeadless: installed marketplace ${e.name}`):e.type===`failed`&&G(`installPluginsForHeadless: failed to install marketplace ${e.name}: ${e.error}`)}}),e=>({installed_count:e.installed.length,updated_count:e.updated.length,failed_count:e.failed.length,skipped_count:e.skipped.length}));t.skipped.length>0&&G(`installPluginsForHeadless: skipped ${t.skipped.length} marketplace(s) unsupported by zip cache: ${t.skipped.join(`, `)}`);let n=t.installed.length+t.updated.length;n>0&&(Ue(),jn(`headlessPluginInstall: marketplaces reconciled`),i=!0),r.marketplaces_installed=n}e&&await Il();let t=await Ta();return r.delisted_count=t.length,t.length>0&&(i=!0),i&&jn(`headlessPluginInstall: plugins changed`),e&&Mr(Ut),i}catch(e){return q(e),!1}finally{J(`tengu_headless_plugin_install`,r)}}ci(),jr(),$r(),Zn(),Yi(),ii(),Zr(),wn(),qe(),Nr(),Cr(),ct(),_r(),x(),Vn(),g(),Fr(),i(),Wa(),Vt(),Tn(),ee(),Je(),Er();var $=(Wi(),e(ta)),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(Be.subscribe(e=>{Ln(e,n),Ei()&&n(e=>{let t=e.settings,n=t.fastMode===!0&&!t.fastModePerSessionOptIn;return{...e,fastMode:n}})}),$&&!$.isProactiveActive()&&r(process.env.CLAUDE_CODE_PROACTIVE)&&$.activateProactive(`command`),typeof Bun<`u`&&setInterval(()=>{process.memoryUsage.rss()>350*1024*1024?Bun.gc(!0):Bun.gc(!1)},1e3).unref(),Bn(),wt(`runHeadless_entry`),await ba()&&await xa(),wt(`after_grove_check`),c.resumeSessionAt&&!c.resume){process.stderr.write(`Error: --resume-session-at requires --resume
13
- `),k(1);return}if(c.rewindFiles&&!c.resume){process.stderr.write(`Error: --rewind-files requires --resume
14
- `),k(1);return}if(c.rewindFiles&&e){process.stderr.write(`Error: --rewind-files is a standalone operation and cannot be used with a prompt
15
- `),k(1);return}let l=tu(e,c);c.outputFormat===`stream-json`&&hl();let u=Nt.getSandboxUnavailableReason();if(u){if(Nt.isSandboxRequired()){process.stderr.write(`\nError: sandbox required but unavailable: ${u}\n sandbox.failIfUnavailable is set — refusing to start without a working sandbox.\n\n`),k(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(Nt.isSandboxingEnabled())try{await Nt.initialize(l.createSandboxAskCallback())}catch(e){process.stderr.write(`\n❌ Sandbox Error: ${W(e)}\n`),k(1,`other`);return}c.outputFormat===`stream-json`&&c.verbose&&Pe(e=>{let t=(()=>{switch(e.type){case`started`:return{type:`system`,subtype:`hook_started`,hook_id:e.hookId,hook_name:e.hookName,hook_event:e.hookEvent,uuid:Y(),session_id:H()};case`progress`:return{type:`system`,subtype:`hook_progress`,hook_id:e.hookId,hook_name:e.hookName,hook_event:e.hookEvent,stdout:e.stdout,stderr:e.stderr,output:e.output,uuid:Y(),session_id:H()};case`response`:return{type:`system`,subtype:`hook_response`,hook_id:e.hookId,hook_name:e.hookName,hook_event:e.hookEvent,output:e.output,stdout:e.stdout,stderr:e.stderr,exit_code:e.exitCode,outcome:e.outcome,uuid:Y(),session_id:H()}}})();l.write(t)}),c.setupTrigger&&await fe(c.setupTrigger),wt(`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=se();if(h&&l.prependUserMessage(h),!c.agent&&!vr()&&m){let{agentDefinition:e}=za(m,void 0,{activeAgents:s,allAgents:s});if(e){if(n(t=>({...t,agent:e.agentType})),!c.systemPrompt&&!En(e)){let t=e.getSystemPrompt();t&&(c.systemPrompt=t)}An(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`),k(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`),k(1);return}process.stdout.write(`Files rewound to state at message ${c.rewindFiles}\n`),k(0);return}let g=typeof c.resume==`string`&&(!!tn(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
- `),k(1);return}if(c.outputFormat===`stream-json`&&!c.verbose){process.stderr.write(`Error: When using --print, --output-format=stream-json requires --verbose
17
- `),k(1);return}let ee=Ke(d.mcp.tools,d.toolPermissionContext),v=[...a,...ee],te=Jl(c.sdkUrl?`stdio`:c.permissionPromptToolName,l,()=>t().mcp.tools,e=>{n(e=>({...e,attribution:{...e.attribution,permissionPromptCount:e.attribution.permissionPromptCount+1}})),Xi(`requires_action`,e)});c.permissionPromptToolName&&(v=v.filter(e=>!zi(e,c.permissionPromptToolName))),Xr(),wt(`after_loadInitialMessages`),await di(),wt(`after_modelStrings`);let ne=c.outputFormat===`json`&&c.verbose,re=[],y;wt(`before_runHeadlessStreaming`);for await(let e of Kl(l,d.mcp.clients,[...i,...d.mcp.commands],v,f,te,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`&&(ne&&re.push(e),y=e);switch(c.outputFormat){case`json`:if(!y||y.type!==`result`)throw Error(`No messages returned`);if(c.verbose){K(U(re)+`
18
- `);break}K(U(y)+`
19
- `);break;case`stream-json`:break;default:if(!y||y.type!==`result`)throw Error(`No messages returned`);switch(y.subtype){case`success`:K(y.result.endsWith(`
20
- `)?y.result:y.result+`
21
- `);break;case`error_during_execution`:K(`Execution error`);break;case`error_max_turns`:K(`Error: Reached max turns (${c.maxTurns}).\nTip: Increase the limit with --max-turns or continue in a new session.`);break;case`error_max_budget_usd`:K(`Error: Exceeded USD budget ($${c.maxBudgetUsd}).\nTip: Increase the limit with --max-budget-usd or start a new session to continue.`);break;case`error_max_structured_output_retries`:K(`Error: Failed to provide valid structured output after maximum retries.
22
- Tip: Simplify your schema or check if the output format matches the expected structure.`)}}if(Ft(),Jr())try{let{drainPendingExtraction:e}=await import(`./extractMemories-DqhN0lba.js`);await e()}catch{}k(y?.type===`result`&&y?.is_error?1:0)}function Kl(e,n,i,o,s,c,l,f,m,g,_,ee){let v=!1,te,ne=!1,re=null,y,b=e.outbound;process.on(`SIGINT`,()=>{ei(`info`,`shutdown_signal`,{signal:`SIGINT`}),y&&!y.signal.aborted&&y.abort(),mt(0)}),Mr(async()=>{let t={};for(let e of fn(f()))ot(e)&&(t[e.type]=(t[e.type]??0)+1);ei(`info`,`run_state_at_shutdown`,{run_active:v,run_phase:te,worker_status:$i(),internal_events_pending:e.internalEventsPending,bg_tasks:t})}),Zi(e=>{(e==="default"||e===`acceptEdits`||e===`bypassPermissions`||e===`plan`||e===`auto`||e===`dontAsk`)&&b.enqueue({type:`system`,subtype:`status`,status:null,permissionMode:e,uuid:Y(),session_id:H()})});let x={abortController:null,inflightPromise:null,lastEmitted:null,pendingSuggestion:null,pendingLastEmittedEntry:null},ie;_.enableAuthStatus&&(ie=gi.getInstance().subscribe(e=>{b.enqueue({type:`auth_status`,isAuthenticating:e.isAuthenticating,output:e.output,error:e.error,uuid:Y(),session_id:H()})}));let ae=e=>{let t=la(e);t&&b.enqueue({type:`rate_limit_event`,rate_limit_info:t,uuid:Y(),session_id:H()})};yt.add(ae);let S=s,oe=Te(s,eo(),100),se=hn(100),ce=process.env.CLAUDE_CODE_RESUME_INTERRUPTED_TURN;ee&&ee.kind!==`none`&&ce&&(G(`[print.ts] Auto-resuming interrupted turn (kind: ${ee.kind})`),$l(S,ee.message),Mn({mode:`prompt`,value:ee.message.message.content,uuid:Y()}));let le=Ra().map(e=>{let t=e.value===null?`default`:e.value,n=t==="default"?Ci():ui(t),r=_n(n),i=xi(e.value),a=fi(n);return{name:t,value:t,displayName:e.label,description:e.description,...r&&{supportsAdaptiveThinking:!0},...i&&{supportsFastMode:!0},...a&&{supportsAutoMode:!0}}}),ue=_.userSpecifiedModel;function fe(e,t){let n=$n(e,Mi(t));S.push(...n);for(let e of n)typeof e.message.content==`string`&&e.message.content.includes(`<local-command-stdout>`)&&b.enqueue({type:`user`,content:e.message.content,message:e.message,session_id:H(),parent_tool_use_id:null,uuid:e.uuid,timestamp:e.timestamp,isReplay:!0})}let C=[],he=[],ge=new Set;function ve(t){for(let n of t){if(n.type!==`connected`||ge.has(n.name)||n.config.type===`sdk`)continue;let t=n.name;try{n.client.setRequestHandler(lt,async(n,r)=>{ni(t,`Elicitation request received in print mode: ${U(n)}`);let i=n.params.mode===`url`?`url`:`form`;J(`tengu_mcp_elicitation_shown`,{mode:i});let a=await Ge(t,n.params,r.signal);if(a)return ni(t,`Elicitation resolved by hook: ${U(a)}`),J(`tengu_mcp_elicitation_response`,{mode:i,action:a.action}),a;let o=`url`in n.params?n.params.url:void 0,s=`requestedSchema`in n.params?n.params.requestedSchema:void 0,c=`elicitationId`in n.params?n.params.elicitationId:void 0,l=await e.handleElicitation(t,n.params.message,s,r.signal,i,o,c),d=await u(t,l,r.signal,i,c);return J(`tengu_mcp_elicitation_response`,{mode:i,action:d.action}),d}),n.client.setNotificationHandler(De,e=>{let{elicitationId:n}=e.params;ni(t,`Elicitation completion notification: ${n}`),xe({message:`MCP server "${t}" confirmed elicitation ${n} complete`,notificationType:`elicitation_complete`}),b.enqueue({type:`system`,subtype:`elicitation_complete`,mcp_server_name:t,elicitation_id:n,uuid:Y(),session_id:H()})}),ge.add(t)}catch{}}}async function ye(){let t=new Set(Object.keys(l)),n=new Set(C.map(e=>e.name)),r=Array.from(t).some(e=>!n.has(e)),i=Array.from(n).some(e=>!t.has(e)),a=C.some(e=>e.type===`pending`),o=C.some(e=>e.type===`failed`);if(r||i||a||o){for(let e of C)t.has(e.name)||e.type===`connected`&&await e.cleanup();let r=await _t(l,(t,n)=>e.sendMcpMessage(t,n));C=r.clients,he=r.tools;let i=Ir([...n,...t]);m(e=>({...e,mcp:{...e.mcp,tools:[...e.mcp.tools.filter(e=>!i.some(t=>e.name.startsWith(Gr(t)))),...he]}})),xt(C)}}ye();let w={clients:[],tools:[],configs:{}},Se=e=>{let t=bt(e.toolPermissionContext,e.mcp.tools),n=Le(Oa([...o,...he,...w.tools],t,e.toolPermissionContext.mode),`name`);_.permissionPromptToolName&&(n=n.filter(e=>!zi(e,_.permissionPromptToolName)));let r=gr();if(r&&!_.jsonSchema){let e=Ni(r);`tool`in e&&(n=[...n,e.tool])}return n},T=null,Ee=0;function Oe(){if(!T)return;let e=Math.min(Ee,S.length),t=S.slice(e).filter(e=>e.type===`user`||e.type===`assistant`);Ee=S.length,t.length>0&&T.writeMessages(t)}let Ae=Promise.resolve({response:{added:[],removed:[],errors:{}},sdkServersChanged:!1});function Ne(e){let t=async()=>{let t=new Set(C.map(e=>e.name)),n=await iu(e,{configs:l,clients:C,tools:he},w,m);for(let e of Object.keys(l))delete l[e];if(Object.assign(l,n.newSdkState.configs),C=n.newSdkState.clients,he=n.newSdkState.tools,w=n.newDynamicState,n.sdkServersChanged){let e=new Set(C.map(e=>e.name)),n=Ir([...t,...e]);m(e=>({...e,mcp:{...e.mcp,tools:[...e.mcp.tools.filter(e=>!n.some(t=>e.name.startsWith(Gr(t)))),...he]}}))}return{response:n.response,sdkServersChanged:n.sdkServersChanged}};return Ae=Ae.then(t,t),Ae}function Pe(){let e=f(),t=e.mcp.clients,n=Le([...e.mcp.tools,...w.tools],`name`),r=new Set([...t.map(e=>e.name),...C.map(e=>e.name)]);return[...t,...C,...w.clients.filter(e=>!r.has(e.name))].map(e=>{let t;if(e.config.type===`sse`||e.config.type===`http`)t={type:e.config.type,url:e.config.url,headers:e.config.headers,oauth:e.config.oauth};else if(e.config.type===`claudeai-proxy`)t={type:`claudeai-proxy`,url:e.config.url,id:e.config.id};else if(e.config.type===`stdio`||e.config.type===void 0){let n=e.config;t={type:`stdio`,command:n.command,args:n.args}}let r=e.type===`connected`?_e(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 Fe(){try{await Promise.all([Promise.resolve(),Qr(`headless_managed_settings_wait`,()=>Sa())]),await Ll()&&await Je()}catch(e){q(e)}}let Ie=null;a()||(r(process.env.CLAUDE_CODE_SYNC_PLUGIN_INSTALL)?Ie=Fe():Fe());let He=gl(()=>!v),Ue=i,Ke=g;async function qe(){let{agentDefinitions:e}=await Ua(m);Ue=await me(eo());let t=Ke.filter(e=>e.source===`flagSettings`);Ke=[...e.allAgents,...t]}async function Je(){let{servers:e}=await Me(),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 Ne(t);r&&ye(),G(`Headless MCP refresh: added=${n.added.length}, removed=${n.removed.length}`)}let Xe=Va.subscribe(()=>{h(),me(eo()).then(e=>{Ue=e})}),Qe=()=>{setTimeout(()=>{!$?.isProactiveActive()||$.isProactivePaused()||ne||(async()=>{let e=await Ve({basePrompt:`<${ti}>${new Date().toLocaleTimeString()}</${ti}>`,currentDir:eo(),shouldCreate:()=>!ne});if(ne){await Kn({commands:e});return}for(let t of e)Mn({...t,uuid:Y()});$e()})().catch(e=>{q(e),G(`[Proactive] failed to create headless tick: ${e}`,{level:`error`})})},0)};Lt(()=>{y&&Yt(`now`).length>0&&y.abort(`interrupt`)});let $e=async()=>{if(v)return;if(v=!0,te=void 0,Xi(`running`),He.stop(),wt(`run_entry`),await ye(),wt(`after_updateSdkMcp`),Ie){let e=parseInt(process.env.CLAUDE_CODE_SYNC_PLUGIN_INSTALL_TIMEOUT_MS||``,10);if(e>0){let t=Ai(e).then(()=>`timeout`);await Promise.race([Ie,t])===`timeout`&&(q(Error(`CLAUDE_CODE_SYNC_PLUGIN_INSTALL: plugin installation timed out after ${e}ms`)),J(`tengu_sync_plugin_install_timeout`,{timeout_ms:e}))}else await Ie;Ie=null,await qe();let{setupPluginHookHotReload:t}=await import(`./loadPluginHooks-Dt3XQ-3N.js`);t()}let n=e=>e.agentId===void 0;try{let r,i=!1,a=async()=>{for(;r=jt(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,Dt(n));)i.push(jt(n));let a=await et(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(_.replayUserMessages&&i.length>1)for(let e of i)e.uuid&&e.uuid!==r.uuid&&b.enqueue({type:`user`,content:e.value,message:{role:`user`,content:e.value},session_id:H(),parent_tool_use_id:null,uuid:e.uuid,isReplay:!0});let s=f(),l=[...s.mcp.clients,...C,...w.clients];ve(l);let u=Se(s);for(let e of o)Ze(e,`started`);if(r.mode===`task-notification`){let e=typeof r.value==`string`?r.value:``,t=e.match(/<task-id>([^<]+)<\/task-id>/),n=e.match(/<tool-use-id>([^<]+)<\/tool-use-id>/),i=e.match(/<output-file>([^<]+)<\/output-file>/),a=e.match(/<status>([^<]+)<\/status>/),o=e.match(/<summary>([^<]+)<\/summary>/),s=e=>e===`completed`||e===`failed`||e===`stopped`||e===`killed`,c=a?.[1],l=s(c)?c===`killed`?`stopped`:c:`completed`,u=e.match(/<usage>([\s\S]*?)<\/usage>/)?.[1]??``,d=u.match(/<total_tokens>(\d+)<\/total_tokens>/),f=u.match(/<tool_uses>(\d+)<\/tool_uses>/),p=u.match(/<duration_ms>(\d+)<\/duration_ms>/);a&&b.enqueue({type:`system`,subtype:`task_notification`,task_id:t?.[1]??``,tool_use_id:n?.[1],status:l,output_file:i?.[1]??``,summary:o?.[1]??``,usage:d&&f?{total_tokens:parseInt(d[1],10),tool_uses:parseInt(f[1],10),duration_ms:p?parseInt(p[1],10):0}:void 0,session_id:H(),uuid:Y()})}let d=r.value,p=a.claimedCommands;if(e instanceof ul&&r.mode===`prompt`&&J(`tengu_bridge_message_received`,{is_repl:!1}),x.abortController?.abort(),x.abortController=null,x.pendingSuggestion=null,x.pendingLastEmittedEntry=null,x.lastEmitted&&r.mode===`prompt`){let e=typeof d==`string`?d:d.find(e=>e.type===`text`)?.text;typeof e==`string`&&$t(x.lastEmitted.text,e,x.lastEmitted.emittedAt,x.lastEmitted.promptId,x.lastEmitted.generationRequestId),x.lastEmitted=null}y=Wt(),wt(`before_ask`),we();let h=r,g=!1;try{if(await bi(h.workload??_.workload,async()=>{for await(let t of Aa({commands:Le([...Ue,...s.mcp.commands],`name`),prompt:d,promptUuid:h.uuid,isMeta:h.isMeta,cwd:eo(),tools:u,verbose:_.verbose,mcpClients:l,thinkingConfig:_.thinkingConfig,maxTurns:_.maxTurns,maxBudgetUsd:_.maxBudgetUsd,taskBudget:_.taskBudget,canUseTool:c,userSpecifiedModel:ue,fallbackModel:_.fallbackModel,jsonSchema:gr()??_.jsonSchema,mutableMessages:S,getReadFileCache:()=>se.size===0?oe:Zt(oe,se),setReadFileCache:e=>{oe=e;for(let[e,t]of se.entries()){let n=oe.get(e);(!n||t.timestamp>n.timestamp)&&oe.set(e,t)}se.clear()},customSystemPrompt:_.systemPrompt,appendSystemPrompt:_.appendSystemPrompt,getAppState:f,setAppState:m,abortController:y,replayUserMessages:_.replayUserMessages,includePartialMessages:_.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:Ke,orphanedPermission:h.orphanedPermission,setSDKStatus:e=>{b.enqueue({type:`system`,subtype:`status`,status:e,session_id:H(),uuid:Y()})}}))if(Oe(),t.type===`result`){g=!!t.is_error;for(let e of ea())b.enqueue(e);fn(f()).some(e=>(e.type===`local_agent`||e.type===`local_workflow`)&&ot(e))?re=t:(re=null,b.enqueue(t))}else{for(let e of ea())b.enqueue(e);b.enqueue(t)}}),g)await pe({commands:p,outcome:{type:`failed`,message:`ask() returned an error result`},currentDir:eo(),priority:`later`,workload:h.workload??_.workload});else{let e=await pe({commands:p,outcome:{type:`completed`},currentDir:eo(),priority:`later`,workload:h.workload??_.workload});for(let t of e)Mn({...t,uuid:Y()})}}catch(e){throw await pe({commands:p,outcome:{type:`failed`,error:e},currentDir:eo(),priority:`later`,workload:h.workload??_.workload}),e}for(let e of o)Ze(e,`completed`);if(Oe(),T?.sendResult(),_.promptSuggestions&&!t(process.env.CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION)){x.abortController?.abort();let e=new AbortController;x.abortController=e;let t=zt();if(!t)Ot(`sdk_no_params`,void 0,void 0,`sdk`);else{let n={promise:null};n.promise=(async()=>{try{let n=await On(e,S,f,t,`sdk`);if(!n||e.signal.aborted)return;let r={type:`prompt_suggestion`,suggestion:n.suggestion,uuid:Y(),session_id:H()},i={text:n.suggestion,emittedAt:Date.now(),promptId:n.promptId,generationRequestId:n.generationRequestId};re?(x.pendingSuggestion=r,x.pendingLastEmittedEntry={text:i.text,promptId:i.promptId,generationRequestId:i.generationRequestId}):(x.lastEmitted=i,b.enqueue(r))}catch(e){if(e instanceof Error&&(e.name===`AbortError`||e.name===`APIUserAbortError`)){Ot(`aborted`,void 0,void 0,`sdk`);return}q(Or(e))}finally{x.inflightPromise===n.promise&&(x.inflightPromise=null)}})(),x.inflightPromise=n.promise}}Ft(),ke(),Bn()}};do{for(let e of ea())b.enqueue(e);te=`draining_commands`,await a(),i=!1;{let e=fn(f()).some(e=>ot(e)),t=Dt(n)!==void 0;(e||t)&&(i=!0,t||(te=`waiting_for_agents`,await Ai(100)))}}while(i);re&&(b.enqueue(re),re=null,x.pendingSuggestion&&(b.enqueue(x.pendingSuggestion),x.pendingLastEmittedEntry&&(x.lastEmitted={...x.pendingLastEmittedEntry,emittedAt:Date.now()},x.pendingLastEmittedEntry=null),x.pendingSuggestion=null))}catch(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:H(),total_cost_usd:0,usage:Qi,modelUsage:{},permission_denials:[],uuid:Y(),errors:[W(t),...ri().map(e=>e.error)]})}catch{}x.abortController?.abort(),k(1);return}finally{if(te=`finally_flush`,await e.flushInternalEvents(),te=`finally_post_flush`,!d()){Xi(`idle`);for(let e of ea())b.enqueue(e)}v=!1,He.start()}if($?.isProactiveActive()&&!$.isProactivePaused()&&Dt(n)===void 0&&!ne){Qe();return}if(Dt(n)!==void 0){$e();return}ne&&(x.inflightPromise&&await Promise.race([x.inflightPromise,Ai(5e3)]),x.abortController?.abort(),x.abortController=null,await We(),Xe(),ie?.(),yt.delete(ae),b.done())},D=function(e,t){b.enqueue({type:`control_response`,response:{subtype:`success`,request_id:e.request_id,response:t}})},O=function(e,t){b.enqueue({type:`control_response`,response:{subtype:`error`,request_id:e.request_id,error:t}})},tt=new Set;e.setUnexpectedResponseCallback(async e=>{await nu({message:e,setAppState:m,handledToolUseIds:tt,onEnqueued:()=>{$e()}})});let rt=new Map,it=new Map,at=new Set,st=new Map,ct=null;return(async()=>{let t=!1;ei(`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`&&Ze(a,`completed`),r.type===`control_request`){let a=r,o=a.request;if(a.request.subtype===`interrupt`)m(e=>({...e,attribution:{...e.attribution,escapeCount:e.attribution.escapeCount+1}})),y&&y.abort(),x.abortController?.abort(),x.abortController=null,x.lastEmitted=null,x.pendingSuggestion=null,D(a);else if(o.subtype===`end_session`){G(`[print.ts] end_session received, reason=${o.reason??`unspecified`}`),y&&y.abort(),x.abortController?.abort(),x.abortController=null,x.lastEmitted=null,x.pendingSuggestion=null,D(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,b,i,le,e,!!_.enableAuthStatus,_,g,f),a.request.promptSuggestions&&m(e=>e.promptSuggestionEnabled?e:{...e,promptSuggestionEnabled:!0}),a.request.agentProgressSummaries&&xr(!0),t=!0,yn()&&$e()}else if(a.request.subtype===`set_permission_mode`){let e=a.request;m(t=>({...t,toolPermissionContext:Zl(e,a.request_id,t.toolPermissionContext,b)}))}else if(a.request.subtype===`set_model`){let e=a.request.model??`default`,t=e==="default"?Ci():e;ue=t,mr(t),Gi({model:t}),fe(e,t),D(a)}else if(a.request.subtype===`set_max_thinking_tokens`)a.request.max_thinking_tokens===null?_.thinkingConfig=void 0:a.request.max_thinking_tokens===0?_.thinkingConfig={type:`disabled`}:_.thinkingConfig={type:`enabled`,budgetTokens:a.request.max_thinking_tokens},D(a);else if(a.request.subtype===`mcp_status`)D(a,{mcpServers:Pe()});else if(a.request.subtype===`get_context_usage`)try{let e=f(),t=await Fa({messages:S,getAppState:f,options:{mainLoopModel:ki(),tools:Se(e),agentDefinitions:e.agentDefinitions,customSystemPrompt:_.systemPrompt,appendSystemPrompt:_.appendSystemPrompt}});D(a,{...t})}catch(e){O(a,W(e))}else if(a.request.subtype===`mcp_message`){let e=a.request,t=C.find(t=>t.name===e.server_name);t&&t.type===`connected`&&t.client?.transport?.onmessage&&t.client.transport.onmessage(e.message),D(a)}else if(a.request.subtype===`rewind_files`){let e=f(),t=await Xl(a.request.user_message_id,e,m,a.request.dry_run??!1);t.canRewind||a.request.dry_run?D(a,t):O(a,t.error??`Unexpected error`)}else if(a.request.subtype===`cancel_async_message`){let e=a.request.message_uuid,t=mn(t=>t.uuid===e);D(a,{cancelled:t.length>0})}else if(a.request.subtype===`seed_read_state`){try{let e=Kr(a.request.path),t=Math.floor((await Za(e)).mtimeMs);if(t<=a.request.mtime){let n=await Xa(e,`utf-8`),r=(n.charCodeAt(0)===65279?n.slice(1):n).replaceAll(`\r
23
- `,`
24
- `);se.set(e,{content:r,timestamp:t,offset:void 0,limit:void 0})}}catch{}D(a)}else if(a.request.subtype===`mcp_set_servers`){let{response:e,sdkServersChanged:t}=await Ne(a.request.servers);D(a,e),t&&ye()}else if(a.request.subtype===`reload_plugins`)try{let e=await Ua(m),t=Ke.filter(e=>e.source===`flagSettings`);Ke=[...e.agentDefinitions.allAgents,...t];let n=[],[r,i,o]=await Promise.allSettled([me(eo()),Je(),gn()]);r.status===`fulfilled`?Ue=r.value:q(r.reason),i.status===`rejected`&&q(i.reason),o.status===`fulfilled`?n=o.value.enabled.map(e=>({name:e.name,path:e.path,source:e.source})):q(o.reason),D(a,{commands:Ue.filter(e=>e.userInvocable!==!1).map(e=>({name:be(e),description:ze(e),argumentHint:e.argumentHint||``})),agents:Ke.map(e=>({name:e.agentType,description:e.whenToUse,model:e.model===`inherit`?void 0:e.model})),plugins:n,mcpServers:Pe(),error_count:e.error_count})}catch(e){O(a,W(e))}else if(a.request.subtype===`mcp_reconnect`){let e=f(),{serverName:t}=a.request;ge.delete(t);let r=xn(t)??n.find(e=>e.name===t)?.config??C.find(e=>e.name===t)?.config??w.clients.find(e=>e.name===t)?.config??e.mcp.clients.find(e=>e.name===t)?.config??null;if(!r)O(a,`Server not found: ${t}`);else{let e=await Ce(t,r),n=Gr(t);if(m(r=>({...r,mcp:{...r.mcp,clients:r.mcp.clients.map(n=>n.name===t?e.client:n),tools:[...E(r.mcp.tools,e=>e.name?.startsWith(n)),...e.tools],commands:[...E(r.mcp.commands,e=>nt(e,t)),...e.commands],resources:e.resources&&e.resources.length>0?{...r.mcp.resources,[t]:e.resources}:na(r.mcp.resources,t)}})),w={...w,clients:[...w.clients.filter(e=>e.name!==t),e.client],tools:[...w.tools.filter(e=>!e.name?.startsWith(n)),...e.tools]},e.client.type===`connected`)ve([e.client]),D(a);else{let t=e.client.type===`failed`?e.client.error??`Connection failed`:`Server status: ${e.client.type}`;O(a,t)}}}else if(a.request.subtype===`mcp_toggle`){let e=f(),{serverName:t,enabled:r}=a.request;ge.delete(t);let i=xn(t)??n.find(e=>e.name===t)?.config??C.find(e=>e.name===t)?.config??w.clients.find(e=>e.name===t)?.config??e.mcp.clients.find(e=>e.name===t)?.config??null;if(!i)O(a,`Server not found: ${t}`);else if(r){dn(t,!0);let e=await Ce(t,i),n=Gr(t);if(m(r=>({...r,mcp:{...r.mcp,clients:r.mcp.clients.map(n=>n.name===t?e.client:n),tools:[...E(r.mcp.tools,e=>e.name?.startsWith(n)),...e.tools],commands:[...E(r.mcp.commands,e=>nt(e,t)),...e.commands],resources:e.resources&&e.resources.length>0?{...r.mcp.resources,[t]:e.resources}:na(r.mcp.resources,t)}})),e.client.type===`connected`)ve([e.client]),D(a);else{let t=e.client.type===`failed`?e.client.error??`Connection failed`:`Server status: ${e.client.type}`;O(a,t)}}else{dn(t,!1);let r=[...n,...C,...w.clients,...e.mcp.clients].find(e=>e.name===t);r&&r.type===`connected`&&await rr(t,i);let o=Gr(t);m(e=>({...e,mcp:{...e.mcp,clients:e.mcp.clients.map(e=>e.name===t?{name:t,type:`disabled`,config:i}:e),tools:E(e.mcp.tools,e=>e.name?.startsWith(o)),commands:E(e.mcp.commands,e=>nt(e,t)),resources:na(e.mcp.resources,t)}})),D(a)}}else if(o.subtype===`mcp_authenticate`){let e=o.serverName,t=f(),r=xn(e)??n.find(t=>t.name===e)?.config??t.mcp.clients.find(t=>t.name===e)?.config??null;if(!r)O(a,`Server not found: ${e}`);else if(r.type!==`sse`&&r.type!==`http`)O(a,`Server type "${r.type}" does not support OAuth authentication`);else try{rt.get(e)?.abort();let t=new AbortController;rt.set(e,t);let n,i=new Promise(e=>{n=e}),o=zn(e,r,e=>n(e),t.signal,{skipBrowserOpen:!0,onWaitingForCallback:t=>{it.set(e,t)}}),s=await Promise.race([i,o.then(()=>null)]);s?D(a,{authUrl:s,requiresUserAction:!0}):D(a,{requiresUserAction:!1}),st.set(e,o),o.then(async()=>{if(Ye(e)||at.has(e))return;let t=await Ce(e,r),n=Gr(e);m(r=>({...r,mcp:{...r.mcp,clients:r.mcp.clients.map(n=>n.name===e?t.client:n),tools:[...E(r.mcp.tools,e=>e.name?.startsWith(n)),...t.tools],commands:[...E(r.mcp.commands,t=>nt(t,e)),...t.commands],resources:t.resources&&t.resources.length>0?{...r.mcp.resources,[e]:t.resources}:na(r.mcp.resources,e)}})),w={...w,clients:[...w.clients.filter(t=>t.name!==e),t.client],tools:[...w.tools.filter(e=>!e.name?.startsWith(n)),...t.tools]}}).catch(t=>{G(`MCP OAuth failed for ${e}: ${t}`,{level:`error`})}).finally(()=>{rt.get(e)===t&&(rt.delete(e),it.delete(e),at.delete(e),st.delete(e))})}catch(e){O(a,W(e))}}else if(o.subtype===`mcp_oauth_callback_url`){let e=o.serverName,t=o.callbackUrl,n=it.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)O(a,`Invalid callback URL: missing authorization code. Please paste the full redirect URL including the code parameter.`);else{at.add(e),n(t);let r=st.get(e);if(r)try{await r,D(a)}catch(e){O(a,e instanceof Error?e.message:`OAuth authentication failed`)}else D(a)}}else O(a,`No active OAuth flow for server: ${e}`)}else if(o.subtype===`claude_authenticate`){let e=o.loginWithClaudeAi;ct?.service.cleanup(),J(`tengu_oauth_flow_start`,{loginWithClaudeAi:e??!0});let t=new Ca,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 wa(t),J(`tengu_oauth_success`,{loginWithClaudeAi:e??!0})}).finally(()=>{t.cleanup(),ct?.service===t&&(ct=null)});ct={service:t,flow:i},i.catch(e=>G(`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`)})]);D(a,{manualUrl:e,automaticUrl:t})}catch(e){O(a,W(e))}}else if(o.subtype===`claude_oauth_callback`||o.subtype===`claude_oauth_wait_for_completion`)if(!ct)O(a,`No active claude_authenticate flow`);else{o.subtype===`claude_oauth_callback`&&ct.service.handleManualAuthCodeInput({authorizationCode:o.authorizationCode,state:o.state});let{flow:e}=ct;e.then(()=>{let e=vi();D(a,{account:{email:e?.email,organization:e?.organization,subscriptionType:e?.subscription,tokenSource:e?.tokenSource,apiKeySource:e?.apiKeySource,apiProvider:_i()}})},e=>O(a,W(e)))}else if(o.subtype===`mcp_clear_auth`){let e=o.serverName,t=f(),r=xn(e)??n.find(t=>t.name===e)?.config??t.mcp.clients.find(t=>t.name===e)?.config??null;if(!r)O(a,`Server not found: ${e}`);else if(r.type!==`sse`&&r.type!==`http`)O(a,`Cannot clear auth for server type "${r.type}"`);else{await Jt(e,r);let t=await Ce(e,r),n=Gr(e);m(r=>({...r,mcp:{...r.mcp,clients:r.mcp.clients.map(n=>n.name===e?t.client:n),tools:[...E(r.mcp.tools,e=>e.name?.startsWith(n)),...t.tools],commands:[...E(r.mcp.commands,t=>nt(t,e)),...t.commands],resources:t.resources&&t.resources.length>0?{...r.mcp.resources,[e]:t.resources}:na(r.mcp.resources,e)}})),D(a,{})}}else if(a.request.subtype===`apply_flag_settings`){let e=ki(),t=pr()??{},n=a.request.settings,r={...t,...n};for(let e of Object.keys(r))r[e]===null&&delete r[e];yr(r),Be.notifyChange(`flagSettings`),`model`in n&&(n.model==null?mr(void 0):mr(String(n.model)));let i=ki();if(i!==e){ue=i;let e=n.model?String(n.model):`default`;Gi({model:i}),fe(e,i)}D(a)}else if(a.request.subtype===`get_settings`){let e=ki();D(a,{...Br(),applied:{model:e}})}else if(a.request.subtype===`stop_task`){let{task_id:e}=a.request;try{await p(e,{getAppState:f,setAppState:m}),D(a,{})}catch(e){O(a,W(e))}}else if(o.subtype===`generate_session_title`){let e=o.description,t=o.persist,n=(y&&!y.signal.aborted?y:Wt()).signal;(async()=>{try{let r=await ua(e,n);if(r&&t)try{Rt(H(),r)}catch(e){q(e)}D(a,{title:r})}catch(e){O(a,W(e))}})()}else if(o.subtype===`side_question`){let e=o.question;(async()=>{try{let t=zt(),n=t?{...t,toolUseContext:{...t.toolUseContext,abortController:Wt()}}:await ja({tools:Se(f()),commands:Ue,mcpClients:[...f().mcp.clients,...C,...w.clients],messages:S,readFileState:oe,getAppState:f,setAppState:m,customSystemPrompt:_.systemPrompt,appendSystemPrompt:_.appendSystemPrompt,thinkingConfig:_.thinkingConfig,agents:Ke}),r=await Pa({question:e,cacheSafeParams:n});D(a,{response:r.response})}catch(e){O(a,W(e))}})()}else if(a.request.subtype===`set_proactive`)a.request.enabled?$.isProactiveActive()||($.activateProactive(`command`),Qe()):$.deactivateProactive(),D(a);else if(o.subtype===`remote_control`)if(o.enabled)if(T)D(a,{session_url:de(T.bridgeSessionId,T.sessionIngressUrl),connect_url:Ma(T.environmentId,T.sessionIngressUrl),environment_id:T.environmentId});else{let t;try{let{initReplBridge:n}=await import(`./initReplBridge-DL4klK0C.js`),r=await n({onInboundMessage(e){let t=_l(e);if(!t)return;let{content:n,uuid:r}=t;Mn({value:n,mode:`prompt`,uuid:r,skipSlashCommands:!0}),$e()},onPermissionResponse(t){e.injectControlResponse(t)},onInterrupt(){y?.abort()},onSetModel(e){let t=e==="default"?Ci():e;ue=t,mr(t)},onSetMaxThinkingTokens(e){e===null?_.thinkingConfig=void 0:e===0?_.thinkingConfig={type:`disabled`}:_.thinkingConfig={type:`enabled`,budgetTokens:e}},onStateChange(e,n){e===`failed`&&(t=n),G(`[bridge:sdk] State change: ${e}${n?` — ${n}`:``}`),b.enqueue({type:`system`,subtype:`bridge_state`,state:e,detail:n,uuid:Y(),session_id:H()})},initialMessages:S.length>0?S:void 0});r?(T=r,Ee=S.length,e.setOnControlRequestSent(e=>{r.sendControlRequest(e)}),e.setOnControlRequestResolved(e=>{r.sendControlCancelRequest(e)}),D(a,{session_url:de(r.bridgeSessionId,r.sessionIngressUrl),connect_url:Ma(r.environmentId,r.sessionIngressUrl),environment_id:r.environmentId})):O(a,t??`Remote Control initialization failed`)}catch(e){O(a,W(e))}}else T&&(e.setOnControlRequestSent(void 0),e.setOnControlRequestResolved(void 0),await T.teardown(),T=null),D(a);else O(a,`Unsupported control request subtype: ${a.request.subtype}`);continue}else if(r.type===`control_response`){_.replayUserMessages&&b.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=sa([r]);S.push(...e),r.type===`assistant`&&_.replayUserMessages&&b.enqueue(r);continue}if(r.type!==`user`)continue;let o=r;if(t=!0,o.uuid){let e=H(),t=await St(e,o.uuid);if(t||zl.has(o.uuid)){G(`Skipping duplicate user message: ${o.uuid}`),_.replayUserMessages&&(G(`Sending acknowledgment for duplicate user message: ${o.uuid}`),b.enqueue({type:`user`,content:o.message?.content??``,message:o.message,session_id:e,parent_tool_use_id:null,uuid:o.uuid,timestamp:o.timestamp,isReplay:!0})),t&&Ze(o.uuid,`completed`);continue}Vl(o.uuid)}Mn({mode:`prompt`,value:await Al(o,o.message.content),uuid:o.uuid,priority:o.priority}),m(e=>({...e,attribution:Re(e.attribution,e=>{je(e).catch(e=>{G(`Attribution: Failed to save snapshot: ${e}`)})})})),$e()}ne=!0,v||(x.inflightPromise&&await Promise.race([x.inflightPromise,Ai(5e3)]),x.abortController?.abort(),x.abortController=null,await We(),Xe(),ie?.(),yt.delete(ae),b.done())})(),b}function ql(e){let t=async(n,r,i,a,o,s)=>{let c=s??await rt(n,r,i,a,o);if(c.behavior===`allow`||c.behavior===`deny`)return c;let{signal:l,cleanup:u}=Qe(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 Qc(Zc().parse(si(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 rt(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=>zi(t,e));if(!r){let n=`Error: MCP tool ${e} (passed via --permission-prompt-tool) not found. Available MCP tools: ${t.map(e=>e.name).join(`, `)||`none`}`;throw process.stderr.write(`${n}\n`),k(1),Error(n)}if(!r.inputJSONSchema){let t=`Error: tool ${e} (passed via --permission-prompt-tool) must be an MCP tool`;throw process.stderr.write(`${t}\n`),k(1),Error(t)}i=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=Gt(e.agents,`flagSettings`);l.push(...t)}if(c.agent){let e=vr()===c.agent,t=l.find(e=>e.agentType===c.agent);if(t&&!e){if(hr(t.agentType),!c.systemPrompt&&!En(t)){let e=t.getSystemPrompt();e&&(c.systemPrompt=e)}!c.userSpecifiedModel&&t.model&&t.model!==`inherit`&&mr(ui(t.model)),t.initialPrompt&&o.prependUserMessage(t.initialPrompt)}else t?.initialPrompt&&o.prependUserMessage(t.initialPrompt)}let d=Hr()?.outputStyle||`default`,f=await nn(wr()),p=vi();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}});dr(t)}e.jsonSchema&&Sr(e.jsonSchema);let m={commands:i.filter(e=>e.userInvocable!==!1).map(e=>({name:be(e),description:ze(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:_i()},pid:process.pid};if(Ei()&&Oi()){let e=u();m.fast_mode_state=pi(c.userSpecifiedModel??null,e.fastMode)}if(r.enqueue({type:`control_response`,response:{subtype:`success`,request_id:t,response:m}}),s){let e=gi.getInstance().getStatus();e&&r.enqueue({type:`auth_status`,isAuthenticating:e.isAuthenticating,output:e.output,error:e.error,uuid:Y(),session_id:H()})}}async function Xl(e,t,n,r){if(!Gn())return{canRewind:!1,error:`File rewinding is not enabled.`,filesChanged:[]};if(!re(t.fileHistory,e))return{canRewind:!1,error:`No file checkpoint found for this message.`,filesChanged:[]};if(r){let n=await O(t.fileHistory,e);return{canRewind:!0,filesChanged:n?.filesChanged??[],insertions:n?.insertions,deletions:n?.deletions}}try{await an(e=>n(t=>({...t,fileHistory:e(t.fileHistory)})),e)}catch(e){return{canRewind:!1,error:`Failed to rewind: ${W(e)}`,filesChanged:[]}}return{canRewind:!0,filesChanged:[]}}function Zl(e,t,n,r){if(e.mode===`bypassPermissions`){if(ae())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`&&!ue()){let e=Yn();return r.enqueue({type:`control_response`,response:{subtype:`error`,request_id:t,error:e?`Cannot set permission mode to auto: ${Mt(e)}`:`Cannot set permission mode to auto`}}),n}return r.enqueue({type:`control_response`,response:{subtype:`success`,request_id:t,response:{mode:e.mode}}}),{...Ie(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:H(),total_cost_usd:0,usage:Qi,modelUsage:{},permission_denials:[],uuid:Y(),errors:[e]};process.stdout.write(U(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=!fr();if(t.continue)try{J(`tengu_continue_print`,{});let r=await Jn(void 0,void 0);if(r)return t.forkSession||r.sessionId&&(br(Ae(r.sessionId),r.fullPath?Ka(r.fullPath):null),n&&await en()),Ba(r,e),kt(t.forkSession?{...r,worktreeSession:void 0}:r),{messages:r.messages,turnInterruptionState:r.turnInterruptionState,agentSetting:r.agentSetting}}catch(e){return q(e),k(1),{messages:[]}}if(t.teleport)try{if(!on(`allow_remote_sessions`))throw Error(`Remote sessions are disabled by your organization's policy.`);if(J(`tengu_teleport_print`,{}),typeof t.teleport!=`string`)throw Error(`No session ID provided for teleport`);let{checkOutTeleportedSessionBranch:e,processMessagesForTeleportResume:n,teleportResumeCodeSession:r,validateGitState:i}=await import(`./teleport-Bs3kEipi.js`);await i();let a=await r(t.teleport),{branchError:o}=await e(a.branch);return{messages:n(a.log,o)}}catch(e){return q(e),k(1),{messages:[]}}if(t.resume)try{J(`tengu_resume_print`,{});let i=jl(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),k(1),{messages:[]}}if(r(process.env.CLAUDE_CODE_USE_CCR_V2)){let[,n]=await Promise.all([Qn(i.sessionId),t.restoredWorkerState]);n&&(e(Ea(n)),typeof n.model==`string`&&mr(n.model))}else i.isUrl&&i.ingressUrl&&r(process.env.ENABLE_SESSION_PERSISTENCE)&&await $e(i.sessionId,i.ingressUrl);let a=await Jn(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??D(`startup`))}:(Ql(`No conversation found with session ID: ${i.sessionId}`,t.outputFormat),k(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),k(1),{messages:[]};a.messages=e>=0?a.messages.slice(0,e+1):[]}return!t.forkSession&&a.sessionId&&(br(Ae(a.sessionId),a.fullPath?Ka(a.fullPath):null),n&&await en()),Ba(a,e),kt(t.forkSession?{...a,worktreeSession:void 0}:a),{messages:a.messages,turnInterruptionState:a.turnInterruptionState,agentSetting:a.agentSetting}}catch(e){return q(e),Ql(e instanceof Error?`Failed to resume session: ${e.message}`:`Failed to resume session with --print mode`,t.outputFormat),k(1),{messages:[]}}return{messages:await(t.sessionStartHooksPromise??D(`startup`))}}function tu(e,t){let n;return n=typeof e==`string`?e.trim()===``?w([]):w([U({type:`user`,content:e,uuid:``,session_id:``,message:{role:`user`,content:e},parent_tool_use_id:null})]):e,t.sdkUrl?new ul(t.sdkUrl,n,t.replayUserMessages):new ol(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(G(`handleOrphanedPermissionResponse: received orphaned control_response for toolUseID=${t} request_id=${i.request_id}`),r.has(t))return G(`handleOrphanedPermissionResponse: skipping duplicate orphaned permission for toolUseID=${t} (already handled)`),!1;let a=await Fn(t);return a?(r.add(t),G(`handleOrphanedPermissionResponse: enqueuing orphaned permission for toolUseID=${t} messageID=${a.message.id}`),Mn({mode:`orphaned-permission`,value:[],orphanedPermission:{permissionResult:e,assistantMessage:a}}),n?.(),!0):(G(`handleOrphanedPermissionResponse: no unresolved tool_use found for toolUseID=${t} (already resolved in transcript)`),!1)}return!1}function ru(e){return{...e,scope:`dynamic`}}async function iu(e,t,n,r){let{allowed:i,blocked:a}=ye(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||!Ne(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){q(e)}await rr(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 _(t,r);if(d.push(e),e.type===`connected`){let t=await it(e);f.push(...t)}else e.type===`failed`&&(u[t]=e.error||`Connection failed`);l.push(t)}catch(e){let n=Or(e);u[t]=n.message,q(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};
@@ -1 +0,0 @@
1
- import{a as e}from"./rolldown-runtime-DaDcL9Zw.js";import{$m as t,Ba as n,HC as r,Jg as i,Qm as a,Ta as o,UC as s,Xa as c,Yg as l,Zm as u,_p as d,eh as f,il as p,rl as m,vp as h,wa as g,xa as _}from"./loadAgentsDir-BXtV2jiO.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-CRc2QEZ5.js";import{randomUUID as j}from"crypto";y(),b(),a(),h(),f();var M=x();function N({input:e,progress:n,verbose:r}){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`}}),n?(0,M.jsx)(t,{fullOutput:n.fullOutput,output:n.output,elapsedTimeSeconds:n.elapsedTimeSeconds,totalLines:n.totalLines,verbose:r}):u.renderToolUseProgressMessage?.([],{verbose:r,tools:[],terminalSize:void 0})]})}w(),D(),r(),n(),T();function P(){return E().defaultShell??`bash`}a(),k(),l();async function F(t,n,r,a,l){let d=A()&&P()===`powershell`;O(`tengu_input_bash`,{powershell:d});let f=o({content:c({inputString:`<bash-input>${t}</bash-input>`,precedingInputBlocks:n})}),h;l({jsx:(0,M.jsx)(N,{input:t,progress:null,verbose:a.options.verbose}),shouldHidePromptInput:!1});try{let n={...a,setToolJSX:e=>{h=e?.jsx}},c=e=>{l({jsx:(0,M.jsxs)(M.Fragment,{children:[(0,M.jsx)(N,{input:t,progress:e.data,verbose:a.options.verbose}),h]}),shouldHidePromptInput:!1,showSpinner:!1})},g=null;d&&(g=(p(),e(m)).PowerShellTool);let v=g??u,y=(g?await g.call({command:t,dangerouslyDisableSandbox:!0},n,void 0,void 0,c):await u.call({command:t,dangerouslyDisableSandbox:!0},n,void 0,void 0,c)).data;if(!y)throw Error(`No result received from shell command`);let b=y.stderr,x=await s(v,{...y,stderr:``},j()),S=typeof x.content==`string`?x.content:i(y.stdout);return{messages:[_(),f,...r,o({content:`<bash-stdout>${S}</bash-stdout><bash-stderr>${i(b)}</bash-stderr>`})],shouldQuery:!1}}catch(e){return e instanceof S?e.interrupted?{messages:[_(),f,g({toolUse:!1}),...r],shouldQuery:!1}:{messages:[_(),f,...r,o({content:`<bash-stdout>${i(e.stdout)}</bash-stdout><bash-stderr>${i(e.stderr)}</bash-stderr>`})],shouldQuery:!1}:{messages:[_(),f,...r,o({content:`<bash-stderr>Command failed: ${i(C(e))}</bash-stderr>`})],shouldQuery:!1}}finally{l(null)}}export{F as processBashCommand};
@@ -1,5 +0,0 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{$h as t,Am as n,As as r,Ba as i,Bi as a,C as o,Ds as s,Ef as c,Fp as l,Fv as u,Ga as d,Hi as f,Ip as p,Ja as m,Jw as h,Lp as g,Mf as _,Mi as v,Nf as y,Np as b,Oi as x,Os as S,Pi as C,Pp as w,Rv as T,Sa as E,Ta as D,Tf as O,U as k,Uc as A,Va as ee,W as te,Wc as ne,Xa as j,Xw as M,Yw as N,aT as re,aw as ie,b_ as ae,cy as oe,eg as se,ex as ce,fc as le,fv as ue,jm as de,k as fe,ka as pe,kf as me,km as he,my as ge,nm as _e,oT as P,ow as F,pc as I,rm as ve,sw as ye,sy as be,tx as xe,uc as L,uv as Se,v_ as Ce,va as R,wa as we,wf as Te,xa as z,zi as Ee}from"./loadAgentsDir-BXtV2jiO.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-CDnVaVDR.js";import{ct as We,ot as Ge}from"./esm-BkOWaWVb.js";import{E as Ke,T as qe,w as Je}from"./sessionTracing-DpHGGIZm.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}'`),g(e,t,o,s)}:void 0;l(e,t,o,n.matcher||``,s,c,i),a++}}a>0&&B(`Registered ${a} hooks from skill '${r}'`)}var Xe=e((()=>{Fe(),V(),p()}));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,r,i,a,o,s){let l=_e(),d=e.pluginInfo?M(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,...d&&{_PROTO_marketplace_name:d},...c(e.pluginInfo)}});let{skillContent:p,modifiedGetAppState:h,baseAgent:g,promptMessages:_}=await I(e,t,r);B(`Executing forked slash command /${e.name} with agent ${g.agentType}`);let v=r.options.allowBackgroundForkedSlashCommands===!0;if(v&&J(),v){let t=ce(),i=f(e),a=Ve(),c=e=>oe({value:e,mode:`prompt`,priority:`later`,isMeta:!0,skipSlashCommands:!0,workload:a}),u=async()=>{if(!s?.runId)return;let e=await he({runId:s.runId,rootDir:s.rootDir,priority:`later`,workload:a});for(let t of e)be(t)},d=async e=>{s?.runId&&await n({runId:s.runId,rootDir:s.rootDir,error:e instanceof Error?e.message:String(e)})};return(async()=>{let n=Date.now()+$;for(;Date.now()<n&&r.getAppState().mcp.clients.some(e=>e.type===`pending`);)await Ue(Q);let a=r.options.refreshTools?.()??r.options.tools,s=[];for await(let n of w({agentDefinition:g,promptMessages:_,toolUseContext:{...r,getAppState:h,abortController:t},canUseTool:o,isAsync:!0,querySource:`agent:custom`,model:e.model,availableTools:a,override:{agentId:l}}))s.push(n);let d=L(s,`Command completed`);B(`Background forked command /${i} completed (agent ${l})`),c(`<scheduled-task-result command="/${i}">\n${d}\n</scheduled-task-result>`);try{await u()}catch(e){W(e)}})().catch(async e=>{W(e),c(`<scheduled-task-result command="/${i}" status="failed">\n${e instanceof Error?e.message:String(e)}\n</scheduled-task-result>`),await d(e)}),{messages:[],shouldQuery:!1,command:e,deferAutonomyCompletion:!!s?.runId}}let b=[],x=[],S=`forked-command-${e.name}`,C=0,T=e=>(C++,{type:`progress`,data:{message:e,type:`agent_progress`,prompt:p,agentId:l},parentToolUseID:S,toolUseID:`${S}-${C}`,timestamp:new Date().toISOString(),uuid:q()}),E=()=>{a({jsx:y(x,{tools:r.options.tools,verbose:!1}),shouldHidePromptInput:!1,shouldContinueAnimation:!0,showSpinner:!0})};E();try{for await(let t of w({agentDefinition:g,promptMessages:_,toolUseContext:{...r,getAppState:h},canUseTool:o,isAsync:!1,querySource:`agent:custom`,model:e.model,availableTools:r.options.tools})){b.push(t);let e=m([t]);if(t.type===`assistant`){let n=u(t);n>0&&r.setResponseLength(e=>e+n);let i=e[0];i&&i.type===`assistant`&&(x.push(T(t)),E())}if(t.type===`user`){let t=e[0];t&&t.type===`user`&&(x.push(T(t)),E())}}}finally{a(null)}let O=L(b,`Command completed`);return B(`Forked slash command /${e.name} completed with agent ${l}`),{messages:[D({content:j({inputString:`/${f(e)} ${t}`.trim(),precedingInputBlocks:i})}),D({content:`<local-command-stdout>\n${O}\n</local-command-stdout>`})],shouldQuery:!1,command:e,resultText:O}}function tt(e){return!/[^a-zA-Z0-9:\-_]/.test(e)}async function nt(e,t,n,r,i,a,o,s,l,u){let f=Ze(e);if(!f){K(`tengu_input_slash_missing`,{});let e="Commands are in the form `/command [args]`";return{messages:[z(),...r,D({content:j({inputString:e,precedingInputBlocks:t})})],shouldQuery:!1,resultText:e}}let{commandName:p,args:m,isMcp:h}=f,g=h?`mcp`:x().has(p)?p:`custom`;if(!Ee(p,i.options.commands)){let n=!1;try{await Pe().stat(`/${p}`),n=!0}catch{}if(tt(p)&&!n){K(`tengu_input_slash_invalid`,{input:p});let e=`Unknown skill: ${p}`;return{messages:[z(),...r,D({content:j({inputString:e,precedingInputBlocks:t})}),...m?[E(`Args from unknown skill: ${m}`,`warning`)]:[]],shouldQuery:!1,resultText:e}}let i=q();return De(i),K(`tengu_input_prompt`,{}),qe(`user_prompt`,{prompt_length:String(e.length),prompt:Ke(e),"prompt.id":i}),{messages:[D({content:j({inputString:e,precedingInputBlocks:t}),uuid:o}),...r],shouldQuery:!0}}let{messages:_,shouldQuery:v,allowedTools:y,model:b,command:S,resultText:C,nextInput:w,submitNextInput:T,deferAutonomyCompletion:O}=await rt(p,m,a,i,t,n,s,l,o,u);if(_.length===0){let e={input:g};if(S.type===`prompt`&&S.pluginInfo){let{pluginManifest:t,repository:n}=S.pluginInfo,{marketplace:r}=M(n),i=N(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,c(S.pluginInfo))}return K(`tengu_input_command`,{...e,invocation_trigger:`user-slash`}),{messages:[],shouldQuery:!1,model:b,nextInput:w,submitNextInput:T,deferAutonomyCompletion:O}}if(_.length===2&&_[1].type===`user`&&typeof _[1].message.content==`string`&&_[1].message.content.startsWith(`Unknown command:`))return e.startsWith(`/var`)||e.startsWith(`/tmp`)||e.startsWith(`/private`)||K(`tengu_input_slash_invalid`,{input:p}),{messages:[z(),..._],shouldQuery:v,allowedTools:y,model:b};let k={input:g};if(S.type===`prompt`&&S.pluginInfo){let{pluginManifest:e,repository:t}=S.pluginInfo,{marketplace:n}=M(t),r=N(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,c(S.pluginInfo))}K(`tengu_input_command`,{...k,invocation_trigger:`user-slash`});let A=_.length>0&&_[0]&&ee(_[0]);return{messages:v||_.every(d)||A?_:[z(),..._],shouldQuery:v,allowedTools:y,model:b,resultText:C,nextInput:w,submitNextInput:T,deferAutonomyCompletion:O}}async function rt(e,t,n,r,i,a,o,s,c,l){let u=C(e,r.options.commands);if(u.type===`prompt`&&u.userInvocable!==!1&&O(e),u.userInvocable===!1)return{messages:[D({content:j({inputString:`/${e}`,precedingInputBlocks:i})}),D({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:u};try{switch(u.type){case`local-jsx`:return new Promise(e=>{let a=!1,o=(n,r)=>{if(a=!0,r?.display===`skip`){e({messages:[],shouldQuery:!1,command:u,nextInput:r?.nextInput,submitNextInput:r?.submitNextInput});return}let o=(r?.metaMessages??[]).map(e=>D({content:e,isMeta:!0})),s=se()&&typeof n==`string`&&n.endsWith(` dismissed`),c=r?.displayArgs??t;e({messages:r?.display===`system`?s?o:[R(Y(u,c)),R(`<local-command-stdout>${n}</local-command-stdout>`),...o]:[D({content:j({inputString:Y(u,c),precedingInputBlocks:i})}),D(n?{content:`<local-command-stdout>${n}</local-command-stdout>`}:{content:`<local-command-stdout>${re}</local-command-stdout>`}),...o],shouldQuery:r?.shouldQuery??!1,command:u,nextInput:r?.nextInput,submitNextInput:r?.submitNextInput})};u.load().then(e=>e.call(o,{...r,canUseTool:s},t)).then(t=>{if(t!=null){if(r.options.isNonInteractiveSession){e({messages:[],shouldQuery:!1,command:u});return}a||n({jsx:t,shouldHidePromptInput:!0,showSpinner:!1,isLocalJSXCommand:!0,isImmediate:u.immediate===!0})}}).catch(t=>{W(t),!a&&(a=!0,n({jsx:null,shouldHidePromptInput:!1,clearLocalJSX:!0}),e({messages:[],shouldQuery:!1,command:u}))})});case`local`:{let e=D({content:j({inputString:Y(u,u.isSensitive&&t.trim()?`***`:t),precedingInputBlocks:i})});try{let n=z(),i=await(await u.load()).call(t,r);if(i.type===`skip`)return{messages:[],shouldQuery:!1,command:u};if(i.type===`compact`){let t=[n,e,...i.displayText?[D({content:`<local-command-stdout>${i.displayText}</local-command-stdout>`,timestamp:new Date(Date.now()+100).toISOString()})]:[]],r={...i.compactionResult,messagesToKeep:[...i.compactionResult.messagesToKeep??[],...t]};return ue(),{messages:Ce(r),shouldQuery:!1,command:u}}return{messages:[e,R(`<local-command-stdout>${i.value}</local-command-stdout>`)],shouldQuery:!1,command:u,resultText:i.value}}catch(t){return W(t),{messages:[e,R(`<local-command-stderr>${String(t)}</local-command-stderr>`)],shouldQuery:!1,command:u}}}case`prompt`:try{return u.context===`fork`?await et(u,t,r,i,n,s??k,l):await Z(u,t,r,i,a,c)}catch(e){return e instanceof je?{messages:[D({content:j({inputString:Y(u,t),precedingInputBlocks:i})}),we({toolUse:!1})],shouldQuery:!1,command:u}:{messages:[D({content:j({inputString:Y(u,t),precedingInputBlocks:i})}),D({content:`<local-command-stderr>${String(e)}</local-command-stderr>`})],shouldQuery:!1,command:u}}}}catch(e){if(e instanceof H)return{messages:[D({content:j({inputString:e.message,precedingInputBlocks:i})})],shouldQuery:!1,command:u};throw e}}function Y(e,t){return pe(f(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=v(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=!F(`hooks`)||ye(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 l=e.source?`${e.source}:${e.name}`:e.name,u=o.filter(e=>e.type===`text`).map(e=>e.text).join(`
4
-
5
- `);Ae(e.name,l,u,Ge()?.agentId??null);let d=at(e,t),f=fe(e.allowedTools??[]),p=i.length>0||r.length>0?[...i,...r,...o]:o,m=await ne(S(o.filter(e=>e.type===`text`).map(e=>e.text).join(` `),n,null,[],n.messages,`repl_main_thread`,{skipSkillDiscovery:!0}));return{messages:[D({content:d,uuid:a}),D({content:p,isMeta:!0}),...m,s({type:`command_permissions`,allowedTools:f,model:e.model})],shouldQuery:!0,allowedTools:f,model:e.model,command:e}}var Q,$;e((()=>{Oe(),a(),P(),Re(),ze(),ae(),Se(),b(),_(),xe(),We(),r(),V(),Me(),le(),Ne(),t(),A(),Xe(),Le(),ge(),i(),o(),te(),h(),ie(),Qe(),Be(),Te(),Je(),me(),T(),ve(),de(),He(),Q=200,$=1e4}))();export{X as formatSkillLoadingMetadata,ot as processPromptSlashCommand,nt as processSlashCommand};
@@ -1 +0,0 @@
1
- import{Cw as e,kw as t}from"./loadAgentsDir-BXtV2jiO.js";t();export{e as clearPromptCache};
@@ -1 +0,0 @@
1
- import{i as e,r as t}from"./prompt-CRc2QEZ5.js";t();export{e as isDeferredTool};
@@ -1 +0,0 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{A_ as t,Ch as n,Dh as r,Oh as i,Th as a,bs as o,cS as s,cs as c,do as l,fo as u,gh as d,i as f,j_ as p,lS as m,o as h,ss as g,vh as _,xs as v}from"./loadAgentsDir-BXtV2jiO.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`),g(),d();let t=await u(),[n,r]=await Promise.all([o(),f(b())]),{enabled:s,disabled:c,errors:l}=t,[h,_]=await Promise.all([Promise.all(s.map(async e=>{if(e.mcpServers)return Object.keys(e.mcpServers).length;let t=await m(e,l);return t&&(e.mcpServers=t),t?Object.keys(t).length:0})),Promise.all(s.map(async e=>{if(e.lspServers)return Object.keys(e.lspServers).length;let t=await i(e,l);return t&&(e.lspServers=t),t?Object.keys(t).length:0}))]),v=h.reduce((e,t)=>e+t,0),y=_.reduce((e,t)=>e+t,0);e(e=>({...e,plugins:{...e.plugins,enabled:s,disabled:c,commands:n,errors:O(e.plugins.errors,l),needsRefresh:!1},agentDefinitions:r,mcp:{...e.mcp,pluginReconnectKey:e.mcp.pluginReconnectKey+1}})),a();let S=!1;try{await p()}catch(e){S=!0,E(e),C(`refreshActivePlugins: loadPluginHooks failed: ${x(e)}`)}let w=s.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: ${s.length} enabled, ${n.length} commands, ${r.allAgents.length} agents, ${w} hooks, ${v} MCP, ${y} LSP`),{enabled_count:s.length,disabled_count:c.length,command_count:n.length,agent_count:r.allAgents.length,hook_count:w,mcp_count:v,lsp_count:y,error_count:l.length+ +!!S,agentDefinitions:r,pluginCommands:n}}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(),n(),h(),w(),S(),T(),c(),v(),t(),r(),s(),_(),l()}));export{D as n,A as t};
@@ -1 +0,0 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{Ba as t,Cr as n,Ma as r,li as i,oi as a,vr as o}from"./loadAgentsDir-BXtV2jiO.js";import{Wt as s,pt as c}from"./state-BPFYBqm1.js";import{a as l,i as u,r as d}from"./bridgeConfig-BB6Hgali.js";import{n as f,t as p}from"./generateSessionName-DhCypqJ_.js";async function m(e,t,n){let s;if(!n||n.trim()===``){let n=await p(r(t.messages),t.abortController.signal);if(!n)return e(`Could not generate a name: no conversation context yet. Usage: /rename <name>`,{display:`system`}),null;s=n}else s=n.trim();let l=c(),f=o();await i(l,s,f);let m=t.getAppState().replBridgeSessionId;if(m){let e=u();import(`./createSession-CjdLcRec.js`).then(({updateBridgeSessionTitle:t})=>t(m,s,{baseUrl:d(),getAccessToken:e?()=>e:void 0}).catch(()=>{}))}return await a(l,s,f),t.setAppState(e=>({...e,standaloneAgentContext:{...e.standaloneAgentContext,name:s}})),e(`Session renamed to: ${s}`,{display:`system`}),null}e((()=>{s(),l(),t(),n(),f()}))();export{m as call};
@@ -1,2 +0,0 @@
1
- import{n as e,o as t}from"./rolldown-runtime-DaDcL9Zw.js";import{n,t as r}from"./figures-5ThXQEtq.js";import{Cr as i,Dr as a,Ei as o,IC as s,Ir as c,Nr as l,Nu as u,Rr as d,Ti as f,Tr as p,cr as m,hi as h,hr as g,im as _,ju as v,rm as y,vC as b,yC as x}from"./loadAgentsDir-BXtV2jiO.js";import{I as S,P as C,di as w,dr as T,fi as E,ot as D,t as O,ui as k}from"./src-P_wYS_NJ2.js";import{t as A}from"./jsx-runtime-Bb4Xn-E0.js";import{Wt as j,et as M,pt as N}from"./state-BPFYBqm1.js";import{o as P,s as F}from"./log-27kCA_9u.js";import{n as I,r as L}from"./modalContext-CUThy6Ph.js";import{a as R,i as z,n as B,o as V,r as H,t as U}from"./crossProjectResume-BJqXBzkf.js";function W(e){switch(e.resultType){case`sessionNotFound`:return`Session ${k.bold(e.arg)} was not found. Run ${k.bold(`/resume`)} without arguments to browse all sessions.`;case`multipleMatches`:return`Found ${e.count} sessions matching ${k.bold(e.arg)}. Run ${k.bold(`/resume`)} to pick one from the list.`}}function G({message:e,args:t,onDone:n}){return J.useEffect(()=>{let e=setTimeout(n,0);return()=>clearTimeout(e)},[n]),(0,Y.jsxs)(S,{flexDirection:`column`,children:[(0,Y.jsxs)(C,{dimColor:!0,children:[r.pointer,` /resume `,t]}),(0,Y.jsx)(b,{children:(0,Y.jsx)(C,{children:e})})]})}function K({onDone:e,onResume:t}){let[n,r]=J.useState([]),[i,o]=J.useState([]),[s,u]=J.useState(!0),[p,m]=J.useState(!1),[h,y]=J.useState(!1),{rows:b}=D(),x=L(),w=J.useCallback(async(t,n)=>{u(!0);try{let i=q(t?await l():await d(n),N());if(i.length===0){e(`No conversations found to resume`);return}r(i)}catch{e(`Failed to load conversations`)}finally{u(!1)}},[e]);J.useEffect(()=>{async function e(){let e=await f(M());o(e),w(!1,e)}e()},[w]);let E=J.useCallback(()=>{let e=!h;y(e),w(e,i)},[h,w,i]);async function O(n){let r=_(g(n));if(!r){e(`Failed to resume conversation`);return}let i=a(n)?await c(n):n,o=U(i,h);if(o.isCrossProject){if(o.isSameRepoWorktree){m(!0),t(r,i,`slash_command_picker`);return}let n=await T(o.command);n&&process.stdout.write(n),e([``,`This conversation is from a different directory.`,``,`To resume, run:`,` ${o.command}`,``,`(Command copied to clipboard)`,``].join(`
2
- `),{display:`user`});return}m(!0),t(r,i,`slash_command_picker`)}function k(){e(`Resume cancelled`,{display:`system`})}return s?(0,Y.jsxs)(S,{children:[(0,Y.jsx)(v,{}),(0,Y.jsx)(C,{children:` Loading conversations…`})]}):p?(0,Y.jsxs)(S,{children:[(0,Y.jsx)(v,{}),(0,Y.jsx)(C,{children:` Resuming conversation…`})]}):(0,Y.jsx)(R,{logs:n,maxHeight:x?Math.floor(b/2):b-2,onCancel:k,onSelect:O,onLogsChanged:()=>w(h,i),showAllProjects:h,onToggleAllProjects:E,onAgenticSearch:H})}function q(e,t){return e.filter(e=>!e.isSidechain&&g(e)!==t)}var J,Y,X;e((()=>{w(),n(),J=t(E(),1),j(),V(),x(),u(),I(),s(),O(),z(),B(),o(),P(),i(),y(),Y=A(),X=async(e,t,n)=>{let r=async(n,r,i)=>{try{await t.resume?.(n,r,i),e(void 0,{display:`skip`})}catch(t){F(t),e(`Failed to resume: ${t.message}`)}},i=n?.trim();if(!i)return(0,Y.jsx)(K,{onDone:e,onResume:r},Date.now());let o=await d(await f(M()));if(o.length===0){let t=`No conversations found to resume.`;return(0,Y.jsx)(G,{message:t,args:i,onDone:()=>e(t)})}let s=_(i);if(s){let e=o.filter(e=>g(e)===s).sort((e,t)=>t.modified.getTime()-e.modified.getTime());if(e.length>0){let t=e[0];return r(s,a(t)?await c(t):t,`slash_command_session_id`),null}let t=await m(s);if(t)return r(s,t,`slash_command_session_id`),null}if(p()){let t=await h(i,{exact:!0});if(t.length===1){let e=t[0],n=g(e);if(n)return r(n,a(e)?await c(e):e,`slash_command_title`),null}if(t.length>1){let n=W({resultType:`multipleMatches`,arg:i,count:t.length});return(0,Y.jsx)(G,{message:n,args:i,onDone:()=>e(n)})}}let l=W({resultType:`sessionNotFound`,arg:i});return(0,Y.jsx)(G,{message:l,args:i,onDone:()=>e(l)})}}))();export{X as call,q as filterResumableSessions};
@@ -1 +0,0 @@
1
- import{CT as e,bT as t}from"./loadAgentsDir-BXtV2jiO.js";e();export{t as SandboxManager};
@@ -1 +0,0 @@
1
- import{G_ as e,U_ as t}from"./loadAgentsDir-BXtV2jiO.js";t();export{e as isSearchExtraToolsEnabled};
@@ -1 +0,0 @@
1
- var e=()=>({stop(){}});export{e as startServer};
@@ -1 +0,0 @@
1
- var e=()=>{};export{e as printBanner};
@@ -1 +0,0 @@
1
- var e=()=>({});export{e as createServerLogger};
@@ -1 +0,0 @@
1
- import{dh as e,uh as t}from"./loadAgentsDir-BXtV2jiO.js";t();export{e as registerSessionFileAccessHooks};
@@ -1 +0,0 @@
1
- var e=class{async destroyAll(){}};export{e as SessionManager};
@@ -1 +0,0 @@
1
- import{n as e,r as t}from"./sessionObserver-CyLpHSkw.js";t();export{e as heuristicObserverBackend};
@@ -1 +0,0 @@
1
- import{$r as e,Ar as t,Cr as n}from"./loadAgentsDir-BXtV2jiO.js";n();export{t as linkSessionToPR,e as recordTranscript};
@@ -1,3 +0,0 @@
1
- import{n as e,t}from"./memoize-BK3gG5ob.js";import{l as n,o as r,s as i}from"./envUtils-DcaKZlRU.js";import{$C as a,Av as o,Ba as s,Bi as c,Bm as l,Bv as u,Cr as d,Cv as f,Dv as p,Ev as m,Fi as ee,Fn as te,In as ne,Kg as re,Lv as ie,Nm as ae,Nt as h,Ov as oe,Pm as se,Pn as ce,Ra as g,Rm as le,Rv as ue,Sv as de,Ta as fe,Tt as pe,Tv as me,XC as _,YC as he,_E as ge,_n as v,bv as y,cc as b,ew as x,fc as S,gm as C,hC as w,hE as T,hm as E,iw as D,kv as O,lc as k,lt as A,mC as j,mc as M,mi as N,nb as P,nv as F,nw as I,ov as L,qg as _e,rw as ve,sb as ye,vn as be,vt as xe,vv as R,wv as Se,xt as z,xv as Ce,yt as we,yv as Te,zm as Ee}from"./loadAgentsDir-BXtV2jiO.js";import{di as De,ui as B}from"./src-P_wYS_NJ2.js";import{B as Oe,Bn as ke,Hn as Ae,Wt as V,it as je,or as Me,pt as Ne,z as H}from"./state-BPFYBqm1.js";import{n as Pe,t as U}from"./cwd-Besi3Os3.js";import{F as Fe,P as Ie,R as W,f as Le,u as Re}from"./debug-Dr1SjdXn.js";import{Kt as ze,Ln as Be,Rn as Ve,Yt as He}from"./settings-DiBMs2gM.js";import{h as Ue,o as We}from"./config-9rLTDOYW.js";import{O as Ge,k as G,l as Ke,m as qe,n as Je,r as Ye}from"./git-CoQQ6YEf.js";import{o as Xe,s as Ze}from"./log-27kCA_9u.js";import{n as K,r as q}from"./analytics-DJobLaWP.js";import{n as Qe,r as J}from"./startupProfiler-Dc5r6LgE.js";import{Bt as $e,ei as et,rn as tt,ti as nt}from"./model-CDnVaVDR.js";import{fn as Y,hn as rt}from"./prompt-CRc2QEZ5.js";import{h as it,l as at,p as ot,u as st}from"./terminalSetup-fwhFTxGi.js";import{ft as ct,ut as X}from"./esm-BkOWaWVb.js";import{c as lt,t as ut}from"./nativeInstaller-fgCMR_c0.js";import{l as dt,s as ft}from"./logoV2Utils-CEnU8qad.js";import{i as pt,r as mt}from"./runtimeObserver-BZrF3GnQ.js";import{t as ht}from"./sinks-mFsijQ_S.js";import{writeFile as Z}from"fs/promises";r(),De(),Pe(),Ge(),Xe(),qe(),He(),Ue(),$e(),ge(),ve(),a(),he(),_e(),c(),d(),be(),t(),V(),A(),L(),rt(),w(),Ve(),S(),Le(),E(),s(),ne(),et(),F(),ue(),K(),ae(),Ee(),f(),W();function gt(){return!1}function Q(){return{}}var $;function _t(e,t){let n=0,r=t==null;for(let i of e){if(!r){i.uuid===t&&(r=!0);continue}if(i.type===`assistant`){let e=i.message.content;Array.isArray(e)&&(n+=Be(e,e=>e.type===`tool_use`))}}return n}function vt(e){let t=u(e);if(!Se()){if(!Ce(t))return!1;p()}let n=de(t),r=_t(e,$)>=y(),i=g(e);if(n&&r||n&&!i){let t=e[e.length-1];return t?.uuid&&($=t.uuid),!0}return!1}async function yt(e){let t=Re(),n=ce();await t.mkdir(n,{mode:448});let r=te();try{await Z(r,``,{encoding:`utf-8`,mode:384,flag:`wx`}),await Z(r,await l(),{encoding:`utf-8`,mode:384})}catch(e){if(Fe(e)!==`EEXIST`)throw e}e.readFileState.delete(r);let i=await j.call({file_path:r},e),a=``,o=i.data;return o.type===`text`&&(a=o.file.content),q(`tengu_session_memory_file_read`,{content_length:a.length}),{memoryPath:r,currentMemory:a}}var bt=e(()=>{let e=Q();o({minimumMessageTokensToInit:e.minimumMessageTokensToInit&&e.minimumMessageTokensToInit>0?e.minimumMessageTokensToInit:R.minimumMessageTokensToInit,minimumTokensBetweenUpdate:e.minimumTokensBetweenUpdate&&e.minimumTokensBetweenUpdate>0?e.minimumTokensBetweenUpdate:R.minimumTokensBetweenUpdate,toolCallsBetweenUpdates:e.toolCallsBetweenUpdates&&e.toolCallsBetweenUpdates>0?e.toolCallsBetweenUpdates:R.toolCallsBetweenUpdates})}),xt=nt(async function(e){let{messages:t,toolUseContext:n,querySource:r}=e;if(r!==`repl_main_thread`)return;{let{isPoorModeActive:e}=await import(`./poorMode-Djw0P9Gu.js`);if(e())return}if(!gt()||(bt(),!vt(t)))return;m();let i=k(n),{memoryPath:a,currentMemory:o}=await yt(i);await M({promptMessages:[fe({content:await le(o,a)})],cacheSafeParams:b(e),canUseTool:Ct(a),querySource:`session_memory`,forkLabel:`session_memory`,overrides:{readFileState:i.readFileState}});let s=t[t.length-1],c=s?ie(s):void 0,l=Te();q(`tengu_session_memory_extraction`,{input_tokens:c?.input_tokens,output_tokens:c?.output_tokens,cache_read_input_tokens:c?.cache_read_input_tokens??void 0,cache_creation_input_tokens:c?.cache_creation_input_tokens??void 0,config_min_message_tokens_to_init:l.minimumMessageTokensToInit,config_min_tokens_between_update:l.minimumTokensBetweenUpdate,config_tool_calls_between_updates:l.toolCallsBetweenUpdates}),oe(u(t)),wt(t),me()});function St(){Oe()||se()&&C(xt)}function Ct(e){return async(t,n)=>{if(t.name===`Edit`&&typeof n==`object`&&n&&`file_path`in n){let t=n.file_path;if(typeof t==`string`&&t===e)return{behavior:`allow`,updatedInput:n}}return{behavior:`deny`,message:`only ${Y} on ${e} is allowed`,decisionReason:{type:`other`,reason:`only ${Y} on ${e} is allowed`}}}}function wt(e){if(!g(e)){let t=e[e.length-1];t?.uuid&&O(t.uuid)}}K(),V(),pt(),st(),ye(),ct(),W(),dt(),ut(),ot(),Qe(),pe();async function Tt(e,t,r,a,o,s,c,l,u){G(`info`,`setup_started`);let d=process.version.match(/^v(\d+)\./)?.[1];if((!d||parseInt(d,10)<18)&&(console.error(B.bold.red(`Error: Work Mate requires Node.js version 18 or higher.`)),process.exit(1)),c&&Me(re(c)),!H())try{let e=await at();e.status===`restored`?console.log(B.yellow(`Detected an interrupted Terminal.app setup. Your original settings have been restored. You may need to restart Terminal.app for the changes to take effect.`)):e.status===`failed`&&console.error(B.red(`Failed to restore Terminal.app settings. Please manually restore your original settings with: defaults import com.apple.Terminal ${e.backupPath}.`))}catch(e){Ze(e)}_(e);let f=Date.now();if(I(),G(`info`,`setup_hooks_captured`,{duration_ms:Date.now()-f}),x(e),a){let t=v(),n=await Ke();!t&&!n&&(process.stderr.write(B.red(`Error: Can only use --worktree in a git repository, but ${B.bold(e)} is not a git repository. Configure a WorktreeCreate hook in settings.json to use --worktree with other VCS systems.\n`)),process.exit(1));let r=l?`pr-${l}`:o??T(),i;if(n){let e=Je(U());e||(process.stderr.write(B.red(`Error: Could not determine the main git repository root.
2
- `)),process.exit(1)),e!==(Ye(U())??U())&&(G(`info`,`worktree_resolved_to_main_repo`),process.chdir(e),_(e)),i=s?z(e,h(r)):void 0}else i=s?z(U(),h(r)):void 0;let a;try{a=await we(Ne(),r,i,l?{prNumber:l}:void 0)}catch(e){process.stderr.write(B.red(`Error creating worktree: ${Ie(e)}\n`)),process.exit(1)}if(q(`tengu_worktree_created`,{tmux_enabled:s}),s&&i){let e=await xe(i,a.worktreePath);e.created?console.log(B.green(`Created tmux session: ${B.bold(i)}\nTo attach: ${B.bold(`tmux attach -t ${i}`)}`)):console.error(B.yellow(`Warning: Failed to create tmux session: ${e.error}`))}process.chdir(a.worktreePath),_(a.worktreePath),ke(U()),Ae(U()),N(a),P(),D()}G(`info`,`setup_background_jobs_starting`),i()||(St(),mt()),lt(),G(`info`,`setup_background_jobs_launched`),J(`setup_before_prefetch`),G(`info`,`setup_prefetch_starting`);let p=H()&&n(process.env.CLAUDE_CODE_SYNC_PLUGIN_INSTALL)||i();if(p||ee(je()),import(`./loadPluginHooks-Dt3XQ-3N.js`).then(e=>{p||(e.loadPluginHooks(),e.setupPluginHookHotReload())}),i()||(setImmediate(()=>{import(`./attributionHooks-CUAoGkU6.js`).then(({registerAttributionHooks:e})=>{e()})}),import(`./sessionFileAccessHooks-BJlrZaRD.js`).then(e=>e.registerSessionFileAccessHooks())),ht(),q(`tengu_started`,{}),tt(H()),J(`setup_after_prefetch`),!i()&&it()&&await ft(),t===`bypassPermissions`||r){if(process.platform!==`win32`&&typeof process.getuid==`function`&&process.getuid()===0&&process.env.IS_SANDBOX!==`1`&&!n(process.env.CLAUDE_CODE_BUBBLEWRAP))if(process.stdin.isTTY){console.error(B.bold.red(`WARNING: Running as root/sudo with bypass permissions mode is dangerous.`)),console.error(B.yellow(`Bypass mode skips ALL permission checks. Combined with root, any command (rm -rf /, chmod, dd) executes without review.`));let e=(await import(`readline`)).createInterface({input:process.stdin,output:process.stdout}),t=await new Promise(t=>{e.question(`
3
- I understand the risks. Continue? [y/N] `,t)});e.close(),t.trim().toLowerCase()!==`y`&&(console.error(`Aborted.`),process.exit(1))}else console.error(`--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons`),process.exit(1);if(process.env.CLAUDE_CODE_ENTRYPOINT!==`local-agent`&&process.env.CLAUDE_CODE_ENTRYPOINT!==`claude-desktop`){let[e,t]=await Promise.all([X.getIsDocker(),ze.hasInternetAccess()]),n=X.getIsBubblewrapSandbox(),r=process.env.IS_SANDBOX===`1`;(!(e||n||r)||t)&&(console.error(`--dangerously-skip-permissions can only be used in Docker/sandbox containers with no internet access but got Docker: ${e}, Bubblewrap: ${n}, IS_SANDBOX: ${r}, hasInternet: ${t}`),process.exit(1))}}let m=We();m.lastCost!==void 0&&m.lastDuration!==void 0&&q(`tengu_exit`,{last_session_cost:m.lastCost,last_session_api_duration:m.lastAPIDuration,last_session_tool_duration:m.lastToolDuration,last_session_duration:m.lastDuration,last_session_lines_added:m.lastLinesAdded,last_session_lines_removed:m.lastLinesRemoved,last_session_total_input_tokens:m.lastTotalInputTokens,last_session_total_output_tokens:m.lastTotalOutputTokens,last_session_total_cache_creation_input_tokens:m.lastTotalCacheCreationInputTokens,last_session_total_cache_read_input_tokens:m.lastTotalCacheReadInputTokens,last_session_fps_average:m.lastFpsAverage,last_session_fps_low_1_pct:m.lastFpsLow1Pct,last_session_id:m.lastSessionId,...m.lastSessionMetrics})}export{Tt as setup};
@@ -1 +0,0 @@
1
- import{t as e}from"./sinks-mFsijQ_S.js";export{e as initSinks};
@@ -1 +0,0 @@
1
- import{a as e}from"./rolldown-runtime-DaDcL9Zw.js";import{$i as t,Ag as n,Ai as r,As as i,Bi as a,Cc as ee,Cr as o,Fh as s,Ft as c,Fy as te,Iy as ne,Kg as re,Og as ie,Ph as ae,Qi as l,St as u,Tt as oe,Vn as se,XC as d,Xi as ce,YC as f,_E as p,_l as m,ai as h,cE as g,ch as _,di as le,ea as ue,fC as de,gE as v,gl as fe,h_ as pe,hn as me,ii as he,jh as ge,js as _e,jt as y,ki as ve,lE as ye,lh as be,m_ as b,mi as x,nb as S,pC as C,qg as w,qr as T,sb as E,vc as D,vn as O}from"./loadAgentsDir-BXtV2jiO.js";import{Bn as k,J as A,Mn as j,Nn as M,Wt as N,h as xe,lr as Se,or as Ce,pt as P,ur as we}from"./state-BPFYBqm1.js";import{n as Te,t as F}from"./cwd-Besi3Os3.js";import{c as I,f as Ee,i as L,nt as De,tt as Oe,u as R}from"./debug-Dr1SjdXn.js";import{n as ke,r as Ae}from"./analytics-DJobLaWP.js";import{C as je,_ as Me}from"./model-CDnVaVDR.js";import{Kt as Ne}from"./prompt-CRc2QEZ5.js";import*as z from"path";import{dirname as Pe}from"path";N(),pe(),te(),Ne(),w(),E(),ae(),D(),Te(),L(),n(),Me(),p(),f(),o(),de(),be(),oe();function Fe(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n?.type!==`assistant`)continue;let r=n.message.content.find(e=>e.type===`tool_use`&&e.name===`TodoWrite`);if(!r||r.type!==`tool_use`)continue;let i=r.input;if(typeof i!=`object`||!i)return[];let a=_().safeParse(i.todos);return a.success?a.data:[]}return[]}function Ie(e,t){if(e.fileHistorySnapshots&&e.fileHistorySnapshots.length>0&&ie(e.fileHistorySnapshots,e=>{t(t=>({...t,fileHistory:e}))}),e.attributionSnapshots&&e.attributionSnapshots.length>0&&ge(e.attributionSnapshots,e=>{t(t=>({...t,attribution:e}))}),!C()&&e.messages&&e.messages.length>0){let n=Fe(e.messages);if(n.length>0){let e=P();t(t=>({...t,todos:{...t.todos,[e]:n}}))}}}function Le(e){if(e.attributionSnapshots&&e.attributionSnapshots.length>0)return s(e.attributionSnapshots)}function B(e,t){if(!(!e&&!t))return{name:e??``,color:t==="default"?void 0:t}}function V(e,t,n){if(t)return{agentDefinition:t,agentType:void 0};if(!e)return M(void 0),{agentDefinition:void 0,agentType:void 0};let r=n.activeAgents.find(t=>t.agentType===e);return r?(M(r.agentType),!A()&&r.model&&r.model!==`inherit`&&j(je(r.model)),{agentDefinition:r,agentType:r.agentType}):(I(`Resumed session had agent "${e}" but it is no longer available. Using default behavior.`),M(void 0),{agentDefinition:void 0,agentType:void 0})}function H(e){let t=u();if(t){x(t);return}if(e){try{process.chdir(e.worktreePath)}catch{x(null);return}d(e.worktreePath),k(F()),y(e),S(),b(),v.cache.clear?.()}}function Re(){let e=u();if(e){y(null),S(),b(),v.cache.clear?.();try{process.chdir(e.originalCwd)}catch{return}d(e.originalCwd),k(F())}}async function ze(t,n,r){if(n.forkSession)t.contentReplacements?.length&&await T(t.contentReplacements);else{let e=n.sessionIdOverride??t.sessionId;e&&(Ce(re(e),n.transcriptPath?Pe(n.transcriptPath):null),await he(),ne(e))}if(h(n.forkSession?{...t,worktreeSession:void 0}:t),t.goal){let{hydrateGoalFromTranscript:r}=(m(),e(fe)),i=new Map,a=n.sessionIdOverride??t.sessionId??P();i.set(a,t.goal),r(i,a)}n.forkSession||(H(t.worktreeSession),se());let{agentDefinition:i,agentType:a}=V(t.agentSetting,r.mainThreadAgentDefinition,r.agentDefinitions);le(`normal`);let o=n.includeAttribution?Le(t):void 0,s=B(t.agentName,t.agentColor);ee(t.agentName);let c=r.agentDefinitions;return{messages:t.messages,fileHistorySnapshots:t.fileHistorySnapshots,contentReplacements:t.contentReplacements,agentName:t.agentName,agentColor:t.agentColor==="default"?void 0:t.agentColor,restoredAgentDef:i,initialState:{...r.initialState,...a&&{agent:a},...o&&{attribution:o},...s&&{standaloneAgentContext:s},agentDefinitions:c}}}ye(),N(),a(),ke(),t(),i(),Oe(),L(),Ee(),O(),we();var Be=1e3,Ve=500,He=300,Ue=2e3,We=typeof Bun<`u`,U=null,W=null,G=new Set,K=!1,q=!1,J=!1,Y=null,X=Se(),Z=null;async function Ge(){if(K||q)return;K=!0,J||(J=!0,ue(()=>{ve(),X.emit()}));let e=await qe();e.length!==0&&(I(`Watching for changes in skill/command directories: ${e.join(`, `)}...`),U=g.watch(e,{persistent:!0,ignoreInitial:!0,depth:2,awaitWriteFinish:{stabilityThreshold:Z?.stabilityThreshold??Be,pollInterval:Z?.pollInterval??Ve},ignored:(e,t)=>t&&!t.isFile()&&!t.isDirectory()?!0:e.split(z.sep).some(e=>e===`.git`),ignorePermissionErrors:!0,usePolling:We,interval:Z?.chokidarInterval??Ue,atomic:!0}),U.on(`add`,$),U.on(`change`,$),U.on(`unlink`,$),Y=De(async()=>{await Q()}))}function Q(){q=!0,Y&&(Y(),Y=null);let e=Promise.resolve();return U&&(e=U.close(),U=null),W&&(clearTimeout(W),W=null),G.clear(),X.clear(),e}var Ke=X.subscribe;async function qe(){let e=R(),t=[],n=l(`userSettings`,`skills`);if(n)try{await e.stat(n),t.push(n)}catch{}let r=l(`userSettings`,`commands`);if(r)try{await e.stat(r),t.push(r)}catch{}let i=l(`projectSettings`,`skills`);if(i)try{let n=z.resolve(i);await e.stat(n),t.push(n)}catch{}let a=l(`projectSettings`,`commands`);if(a)try{let n=z.resolve(a);await e.stat(n),t.push(n)}catch{}for(let n of xe()){let r=z.join(n,`.workmate`,`skills`);try{await e.stat(r),t.push(r)}catch{}}return t}function $(e){I(`Detected skill change: ${e}`),Ae(`tengu_skill_file_changed`,{source:`chokidar`}),Je(e)}function Je(e){G.add(e),W&&clearTimeout(W),W=setTimeout(async()=>{W=null;let e=[...G];if(G.clear(),me(await c(`skills`,e[0]))){I(`ConfigChange hook blocked skill reload (${e.length} paths)`);return}ce(),r(),_e(),X.emit()},Z?.reloadDebounce??He)}async function Ye(e){U&&(await U.close(),U=null),W&&(clearTimeout(W),W=null),G.clear(),X.clear(),K=!1,q=!1,Z=e??null}var Xe={initialize:Ge,dispose:Q,subscribe:Ke,resetForTesting:Ye};export{V as a,ze as i,B as n,Ie as o,Re as r,H as s,Xe as t};
@@ -1 +0,0 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{na as t,ta as n}from"./loadAgentsDir-BXtV2jiO.js";function r(e){return e?e.activeAgents.filter(e=>e.source!==`built-in`).reduce((e,n)=>e+t(`${n.agentType}: ${n.whenToUse}`),0):0}var i,a=e((()=>{n(),i=15e3}));export{r as n,a as r,i as t};
@@ -1 +0,0 @@
1
- import{n as e,r as t}from"./switcher-sYTxnJQA.js";e();export{t as restoreActiveProvider};
@@ -1 +0,0 @@
1
- import{cu as e,fu as t,hu as n,su as r,uu as i}from"./loadAgentsDir-BXtV2jiO.js";e();export{r as checkOutTeleportedSessionBranch,i as processMessagesForTeleportResume,t as teleportResumeCodeSession,n as validateGitState};
@@ -1 +0,0 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{MT as t,NT as n,Rx as r,zx as i}from"./loadAgentsDir-BXtV2jiO.js";import{n as a,t as o}from"./partition-CzW_31Y1.js";function s(e,t,r){let[o,s]=a(n([...e,...t],`name`),i),c=(e,t)=>e.name.localeCompare(t.name);return[...s.sort(c),...o.sort(c)]}var c=e((()=>{o(),t(),r()}));export{s as n,c as t};
@@ -1 +0,0 @@
1
- import{r as e,t}from"./trustedDevice-Bzz03jCy.js";export{t as clearTrustedDeviceToken,e as enrollTrustedDevice};
@@ -1 +0,0 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{og as t,sg as n}from"./loadAgentsDir-BXtV2jiO.js";import{C as r,_ as i,s as a}from"./model-CDnVaVDR.js";function o(){let e=n(e=>e.mainLoopModel);return r(n(e=>e.mainLoopModelForSession)??e??a())}var s=e((()=>{t(),i()}));export{o as n,s as t};
@@ -1 +0,0 @@
1
- import{o as e}from"./rolldown-runtime-DaDcL9Zw.js";import{A_ as t,Ch as n,Dh as r,Es as i,Jd as a,Oh as o,Th as s,Ts as c,Yd as l,bs as u,cS as d,do as f,fo as p,j_ as m,lS as h,lg as g,og as _,sg as v,xs as y}from"./loadAgentsDir-BXtV2jiO.js";import{fi as b}from"./src-P_wYS_NJ2.js";import{R as x,U as S,c as C,i as w}from"./debug-Dr1SjdXn.js";import{Ln as T,Rn as E}from"./settings-DiBMs2gM.js";import{O as D,k as O}from"./git-CoQQ6YEf.js";import{o as k,s as A}from"./log-27kCA_9u.js";import{n as j,r as M}from"./analytics-DJobLaWP.js";import{n as N,r as P}from"./pluginFlagging-CXSSOj4J.js";import{t as F}from"./pluginBlocklist-CNGmIlwU.js";var I=e(b(),1);a(),j(),n(),_(),E(),w(),D(),x(),k(),c(),y(),t(),r(),d(),P(),f();function L({enabled:e=!0}={}){let t=g(),n=v(e=>e.plugins.needsRefresh),{addNotification:r}=l(),a=(0,I.useCallback)(async()=>{try{let{enabled:e,disabled:n,errors:a}=await p();await F();let c=N();Object.keys(c).length>0&&r({key:`plugin-delisted-flagged`,text:`Plugins flagged. Check /plugins`,color:`warning`,priority:`high`});let l=[],d=[];try{l=await u()}catch(e){let t=e instanceof Error?e.message:String(e);a.push({type:`generic-error`,source:`plugin-commands`,error:`Failed to load plugin commands: ${t}`})}try{d=await i()}catch(e){let t=e instanceof Error?e.message:String(e);a.push({type:`generic-error`,source:`plugin-agents`,error:`Failed to load plugin agents: ${t}`})}try{await m()}catch(e){let t=e instanceof Error?e.message:String(e);a.push({type:`generic-error`,source:`plugin-hooks`,error:`Failed to load plugin hooks: ${t}`})}let f=(await Promise.all(e.map(async e=>{if(e.mcpServers)return Object.keys(e.mcpServers).length;let t=await h(e,a);return t&&(e.mcpServers=t),t?Object.keys(t).length:0}))).reduce((e,t)=>e+t,0),g=(await Promise.all(e.map(async e=>{if(e.lspServers)return Object.keys(e.lspServers).length;let t=await o(e,a);return t&&(e.lspServers=t),t?Object.keys(t).length:0}))).reduce((e,t)=>e+t,0);s(),t(t=>{let r=t.plugins.errors.filter(e=>e.source===`lsp-manager`||e.source.startsWith(`plugin:`)),i=new Set(a.map(e=>e.type===`generic-error`?`generic-error:${e.source}:${e.error}`:`${e.type}:${e.source}`)),o=[...r.filter(e=>{let t=e.type===`generic-error`?`generic-error:${e.source}:${e.error}`:`${e.type}:${e.source}`;return!i.has(t)}),...a];return{...t,plugins:{...t.plugins,enabled:e,disabled:n,commands:l,errors:o}}}),C(`Loaded plugins - Enabled: ${e.length}, Disabled: ${n.length}, Commands: ${l.length}, Agents: ${d.length}, Errors: ${a.length}`);let _=e.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{enabled_count:e.length,disabled_count:n.length,inline_count:T(e,e=>e.source.endsWith(`@inline`)),marketplace_count:T(e,e=>!e.source.endsWith(`@inline`)),error_count:a.length,skill_count:l.length,agent_count:d.length,hook_count:_,mcp_count:f,lsp_count:g}}catch(e){let n=S(e);return A(n),C(`Error loading plugins: ${e}`),t(e=>{let t=e.plugins.errors.filter(e=>e.source===`lsp-manager`||e.source.startsWith(`plugin:`)),r={type:`generic-error`,source:`plugin-system`,error:n.message};return{...e,plugins:{...e.plugins,enabled:[],disabled:[],commands:[],errors:[...t,r]}}}),{enabled_count:0,disabled_count:0,inline_count:0,marketplace_count:0,error_count:1,skill_count:0,agent_count:0,hook_count:0,mcp_count:0,lsp_count:0,load_failed:!0,ant_enabled_names:void 0}}},[t,r]);(0,I.useEffect)(()=>{e&&a().then(e=>{let{ant_enabled_names:t,...n}=e,r={...n,has_custom_plugin_cache_dir:!!process.env.CLAUDE_CODE_PLUGIN_CACHE_DIR};M(`tengu_plugins_loaded`,{...r,...t!==void 0&&{enabled_names:t}}),O(`info`,`tengu_plugins_loaded`,r)})},[a,e]),(0,I.useEffect)(()=>{!e||!n||r({key:`plugin-reload-pending`,text:`Plugins changed. Run /reload-plugins to activate.`,color:`suggestion`,priority:`low`})},[e,n,r])}export{L as t};
@@ -1 +0,0 @@
1
- import{n as e,o as t}from"./rolldown-runtime-DaDcL9Zw.js";import{Jd as n,Yd as r,fg as i,pg as a}from"./loadAgentsDir-BXtV2jiO.js";import{fi as o}from"./src-P_wYS_NJ2.js";import{B as s,Wt as c}from"./state-BPFYBqm1.js";import{n as l,t as u}from"./allErrors-CS77lRvU.js";function d(){let{addNotification:e,removeNotification:t}=r(),[n,i]=(0,f.useState)(()=>{let{errors:e}=u();return e});return a((0,f.useCallback)(()=>{let{errors:e}=u();i(e)},[])),(0,f.useEffect)(()=>{if(!s())if(n.length>0){let t=`Found ${n.length} settings ${n.length===1?`issue`:`issues`} · /doctor for details`;e({key:p,text:t,color:`warning`,priority:`high`,timeoutMs:6e4})}else t(p)},[n,e,t]),n}var f,p,m=e((()=>{f=t(o(),1),n(),c(),l(),i(),p=`settings-errors`}));export{d as n,m as t};
@@ -1 +0,0 @@
1
- import{o as e}from"./rolldown-runtime-DaDcL9Zw.js";import{Du as t,Ou as n,ag as r,og as i}from"./loadAgentsDir-BXtV2jiO.js";import{I as a,P as o,fi as s,t as c}from"./src-P_wYS_NJ2.js";import{t as l}from"./jsx-runtime-Bb4Xn-E0.js";import{n as u,r as d}from"./analytics-DJobLaWP.js";import{Bt as f,Ht as p}from"./model-CDnVaVDR.js";import{t as m}from"./WelcomeV2-BnSYhyfu.js";import{t as h}from"./useManagePlugins-BWROoGDs.js";import{n as g,t as _}from"./MCPConnectionManager-BpjC7CEo.js";import{n as v}from"./onChangeAppState-WbvtqDtk.js";import{cwd as y}from"process";var b=e(s(),1);c(),n(),u(),g(),i(),f();var x=l();async function S(e){d(`tengu_setup_token_command`,{});let n=!p(),{ConsoleOAuthFlow:i}=await import(`./ConsoleOAuthFlow-Dn8fO-o_.js`);await new Promise(s=>{e.render((0,x.jsx)(r,{onChangeAppState:v,children:(0,x.jsx)(t,{children:(0,x.jsxs)(a,{flexDirection:`column`,gap:1,children:[(0,x.jsx)(m,{}),n&&(0,x.jsxs)(a,{flexDirection:`column`,children:[(0,x.jsx)(o,{color:`warning`,children:`Warning: You already have authentication configured via environment variable or API key helper.`}),(0,x.jsx)(o,{color:`warning`,children:`The setup-token command will create a new OAuth token which you can use instead.`})]}),(0,x.jsx)(i,{onDone:()=>{s()}})]})})}))}),e.unmount(),process.exit(0)}var C=b.lazy(()=>import(`./Doctor-CzPvNZzF.js`).then(e=>({default:e.Doctor})));function w({onDone:e}){return h(),(0,x.jsx)(b.Suspense,{fallback:null,children:(0,x.jsx)(C,{onDone:e})})}async function T(e){d(`tengu_doctor_command`,{}),await new Promise(n=>{e.render((0,x.jsx)(r,{children:(0,x.jsx)(t,{children:(0,x.jsx)(_,{dynamicMcpConfig:void 0,isStrictMcpConfig:!1,children:(0,x.jsx)(w,{onDone:()=>{n()}})})})}))}),e.unmount(),process.exit(0)}async function E(e,t){let{setup:n}=await import(`./setup-zf3v3ICe.js`);await n(y(),`default`,!1,!1,void 0,!1);let{install:r}=await import(`./install-NZvHd_40.js`);await new Promise(n=>{let i=[];e&&i.push(e),t.force&&i.push(`--force`),r.call(e=>{n(),process.exit(+!!e.includes(`failed`))},{},i)})}export{T as doctorHandler,E as installHandler,S as setupTokenHandler};
@@ -1 +0,0 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{n as t,t as n}from"./axios-DaWTGg7G.js";import{Bw as r,ME as i,Nw as a,OE as o,Pw as s,Vw as c,jE as l,kE as u,zw as d}from"./loadAgentsDir-BXtV2jiO.js";import{p as f}from"./external-CEp-aPkt.js";import{r as ee}from"./lazySchema-B4D4qJVE.js";import{B as p,C as m,F as h,P as g,R as _,S as v,c as y,f as b,i as te,u as x,x as S}from"./debug-Dr1SjdXn.js";import{_t as C,gt as w,ht as T,pt as E,vt as D}from"./settings-DiBMs2gM.js";import{o as ne,s as O}from"./log-27kCA_9u.js";import{homedir as re}from"os";import*as k from"path";import{join as ie,resolve as ae}from"path";import{randomBytes as oe}from"crypto";import{readFile as A,readdir as j,rename as M,stat as N,unlink as P,writeFile as F}from"fs/promises";function I(){return ie(a(),U)}async function L(){let e=I();try{let t=v(await A(e,{encoding:`utf-8`}));if(typeof t!=`object`||!t||!(`version`in t)||!(`fetchedAt`in t)||!(`counts`in t))return y(`Install counts cache has invalid structure`),null;let n=t;if(n.version!==H)return y(`Install counts cache version mismatch (got ${n.version}, expected ${H})`),null;if(typeof n.fetchedAt!=`string`||!Array.isArray(n.counts))return y(`Install counts cache has invalid structure`),null;let r=new Date(n.fetchedAt).getTime();return Number.isNaN(r)?(y(`Install counts cache has invalid fetchedAt timestamp`),null):n.counts.every(e=>typeof e==`object`&&!!e&&typeof e.plugin==`string`&&typeof e.unique_installs==`number`)?Date.now()-r>G?(y(`Install counts cache is stale (>24h old)`),null):{version:n.version,fetchedAt:n.fetchedAt,counts:n.counts}:(y(`Install counts cache has malformed entries`),null)}catch(e){return h(e)!==`ENOENT`&&y(`Failed to load install counts cache: ${g(e)}`),null}}async function R(e){let t=I(),n=`${t}.${oe(8).toString(`hex`)}.tmp`;try{let r=a();await x().mkdir(r),await F(n,m(e,null,2),{encoding:`utf-8`,mode:384}),await M(n,t),y(`Install counts cache saved successfully`)}catch(e){O(e);try{await P(n)}catch{}}}async function z(){y(`Fetching install counts from ${W}`);let e=performance.now();try{let n=await t.get(W,{timeout:1e4});if(!n.data?.plugins||!Array.isArray(n.data.plugins))throw Error(`Invalid response format from install counts API`);return c(`install_counts`,W,`success`,performance.now()-e),n.data.plugins}catch(t){throw c(`install_counts`,W,`failure`,performance.now()-e,d(t)),t}}async function B(){let e=await L();if(e){y(`Using cached install counts`),c(`install_counts`,W,`cache_hit`,0);let t=new Map;for(let n of e.counts)t.set(n.plugin,n.unique_installs);return t}try{let e=await z();await R({version:H,fetchedAt:new Date().toISOString(),counts:e});let t=new Map;for(let n of e)t.set(n.plugin,n.unique_installs);return t}catch(e){return O(e),y(`Failed to fetch install counts: ${g(e)}`),null}}function V(e){if(e<1e3)return String(e);if(e<1e6){let t=(e/1e3).toFixed(1);return t.endsWith(`.0`)?`${t.slice(0,-2)}K`:`${t}K`}let t=(e/1e6).toFixed(1);return t.endsWith(`.0`)?`${t.slice(0,-2)}M`:`${t}M`}var H,U,W,G,K=e((()=>{n(),te(),_(),b(),ne(),S(),r(),s(),H=1,U=`install-counts-cache.json`,W=`https://raw.githubusercontent.com/anthropics/claude-plugins-official/refs/heads/stats/stats/plugin-installs.json`,G=1440*60*1e3}));async function se(e){let t=e.trim(),n=x(),r=t.match(/^([a-zA-Z0-9._-]+@[^:]+:.+?(?:\.git)?)(#(.+))?$/);if(r?.[1]){let e=r[1],t=r[3];return t?{source:`git`,url:e,ref:t}:{source:`git`,url:e}}if(t.startsWith(`http://`)||t.startsWith(`https://`)){let e=t.match(/^([^#]+)(#(.+))?$/),n=e?.[1]||t,r=e?.[3];if(n.endsWith(`.git`)||n.includes(`/_git/`))return r?{source:`git`,url:n,ref:r}:{source:`git`,url:n};let i;try{i=new URL(n)}catch{return{source:`url`,url:n}}if((i.hostname===`github.com`||i.hostname===`www.github.com`)&&i.pathname.match(/^\/([^/]+\/[^/]+?)(\/|\.git|$)/)?.[1]){let e=n.endsWith(`.git`)?n:`${n}.git`;return r?{source:`git`,url:e,ref:r}:{source:`git`,url:e}}return{source:`url`,url:n}}let i=process.platform===`win32`&&(t.startsWith(`.\\`)||t.startsWith(`..\\`)||/^[a-zA-Z]:[/\\]/.test(t));if(t.startsWith(`./`)||t.startsWith(`../`)||t.startsWith(`/`)||t.startsWith(`~`)||i){let e=ae(t.startsWith(`~`)?t.replace(/^~/,re()):t),r;try{r=await n.stat(e)}catch(t){let n=h(t);return{error:n===`ENOENT`?`Path does not exist: ${e}`:`Cannot access path: ${e} (${n??t})`}}return r.isFile()?e.endsWith(`.json`)?{source:`file`,path:e}:{error:`File path must point to a .json file (marketplace.json), but got: ${e}`}:r.isDirectory()?{source:`directory`,path:e}:{error:`Path is neither a file nor a directory: ${e}`}}if(t.includes(`/`)&&!t.startsWith(`@`)){if(t.includes(`:`))return null;let e=t.match(/^([^#@]+)(?:[#@](.+))?$/),n=e?.[1]||t,r=e?.[2];return r?{source:`github`,repo:n,ref:r}:{source:`github`,repo:n}}return null}var ce=e((()=>{_(),b()}));function le(e){let t=k.basename(e),n=k.basename(k.dirname(e));return t===`plugin.json`?`plugin`:t===`marketplace.json`?`marketplace`:n===`.claude-plugin`?`plugin`:`unknown`}function q(e){return e.issues.map(e=>({path:e.path.join(`.`)||`root`,message:e.message,code:e.code}))}function J(e,t,n,r){e.includes(`..`)&&n.push({path:t,message:r?`Path contains "..": ${e}. ${r}`:`Path contains ".." which could be a path traversal attempt: ${e}`})}function ue(e){let t=e.replace(/^(\.\.\/)+/,``);return`Plugin source paths are resolved relative to the marketplace root (the directory containing .claude-plugin/), not relative to marketplace.json. Use "${t===e?`./plugins/my-plugin`:`./${t}`}" instead of "${e}".`}async function Y(e){let t=[],n=[],r=k.resolve(e),i;try{i=await A(r,{encoding:`utf-8`})}catch(e){let t=h(e),n;return n=t===`ENOENT`?`File not found: ${r}`:t===`EISDIR`?`Path is not a file: ${r}`:`Failed to read file: ${g(e)}`,{success:!1,errors:[{path:`file`,message:n,code:t}],warnings:[],filePath:r,fileType:`plugin`}}let a;try{a=v(i)}catch(e){return{success:!1,errors:[{path:`json`,message:`Invalid JSON syntax: ${g(e)}`}],warnings:[],filePath:r,fileType:`plugin`}}if(a&&typeof a==`object`){let e=a;e.commands&&(Array.isArray(e.commands)?e.commands:[e.commands]).forEach((e,n)=>{typeof e==`string`&&J(e,`commands[${n}]`,t)}),e.agents&&(Array.isArray(e.agents)?e.agents:[e.agents]).forEach((e,n)=>{typeof e==`string`&&J(e,`agents[${n}]`,t)}),e.skills&&(Array.isArray(e.skills)?e.skills:[e.skills]).forEach((e,n)=>{typeof e==`string`&&J(e,`skills[${n}]`,t)})}let o=a;if(typeof a==`object`&&a){let e=a,t=Object.keys(e).filter(e=>$.has(e));if(t.length>0){let r={...e};for(let e of t)delete r[e],n.push({path:e,message:`Field '${e}' belongs in the marketplace entry (marketplace.json), not plugin.json. It's harmless here but unused — Work Mate ignores it at load time.`});o=r}}let s=T().strict().safeParse(o);if(s.success||t.push(...q(s.error)),s.success){let e=s.data;/^[a-z0-9]+(-[a-z0-9]+)*$/.test(e.name)||n.push({path:`name`,message:`Plugin name "${e.name}" is not kebab-case. Work Mate accepts it, but the Claude.ai marketplace sync requires kebab-case (lowercase letters, digits, and hyphens only, e.g., "my-plugin").`}),e.version||n.push({path:`version`,message:`No version specified. Consider adding a version following semver (e.g., "1.0.0")`}),e.description||n.push({path:`description`,message:`No description provided. Adding a description helps users understand what your plugin does`}),e.author||n.push({path:`author`,message:`No author information provided. Consider adding author details for plugin attribution`})}return{success:t.length===0,errors:t,warnings:n,filePath:r,fileType:`plugin`}}async function X(e){let t=[],n=[],r=k.resolve(e),i;try{i=await A(r,{encoding:`utf-8`})}catch(e){let t=h(e),n;return n=t===`ENOENT`?`File not found: ${r}`:t===`EISDIR`?`Path is not a file: ${r}`:`Failed to read file: ${g(e)}`,{success:!1,errors:[{path:`file`,message:n,code:t}],warnings:[],filePath:r,fileType:`marketplace`}}let a;try{a=v(i)}catch(e){return{success:!1,errors:[{path:`json`,message:`Invalid JSON syntax: ${g(e)}`}],warnings:[],filePath:r,fileType:`marketplace`}}if(a&&typeof a==`object`){let e=a;Array.isArray(e.plugins)&&e.plugins.forEach((e,n)=>{if(e&&typeof e==`object`&&`source`in e){let r=e.source;typeof r==`string`&&J(r,`plugins[${n}].source`,t,ue(r)),r&&typeof r==`object`&&`path`in r&&typeof r.path==`string`&&J(r.path,`plugins[${n}].source.path`,t)}})}let o=C().extend({plugins:f(w().strict())}).strict().safeParse(a);if(o.success||t.push(...q(o.error)),o.success){let e=o.data;if((!e.plugins||e.plugins.length===0)&&n.push({path:`plugins`,message:`Marketplace has no plugins defined`}),e.plugins){e.plugins.forEach((n,r)=>{e.plugins.filter(e=>e.name===n.name).length>1&&t.push({path:`plugins[${r}].name`,message:`Duplicate plugin name "${n.name}" found in marketplace`})});let i=k.dirname(r),a=k.basename(i)===`.claude-plugin`?k.dirname(i):i;for(let[t,r]of e.plugins.entries()){if(!r.version||typeof r.source!=`string`||!r.source.startsWith(`./`))continue;let e=k.join(a,r.source,`.claude-plugin`,`plugin.json`),i;try{let t=v(await A(e,{encoding:`utf-8`}));typeof t.version==`string`&&(i=t.version)}catch{continue}i&&i!==r.version&&n.push({path:`plugins[${t}].version`,message:`Entry declares version "${r.version}" but ${r.source}/.claude-plugin/plugin.json says "${i}". At install time, plugin.json wins (calculatePluginVersion precedence) — the entry version is silently ignored. Update this entry to "${i}" to match.`})}}e.metadata?.description||n.push({path:`metadata.description`,message:`No marketplace description provided. Adding a description helps users understand what this marketplace offers`})}return{success:t.length===0,errors:t,warnings:n,filePath:r,fileType:`marketplace`}}function de(e,t,n){let r=[],a=[],s=t.match(o);if(!s)return a.push({path:`frontmatter`,message:`No frontmatter block found. Add YAML frontmatter between --- delimiters at the top of the file to set description and other metadata.`}),{success:!0,errors:r,warnings:a,filePath:e,fileType:n};let c=s[1]||``,l;try{l=i(c)}catch(t){return r.push({path:`frontmatter`,message:`YAML frontmatter failed to parse: ${g(t)}. At runtime this ${n} loads with empty metadata (all frontmatter fields silently dropped).`}),{success:!1,errors:r,warnings:a,filePath:e,fileType:n}}if(typeof l!=`object`||!l||Array.isArray(l))return r.push({path:`frontmatter`,message:`Frontmatter must be a YAML mapping (key: value pairs), got ${Array.isArray(l)?`an array`:l===null?`null`:typeof l}.`}),{success:!1,errors:r,warnings:a,filePath:e,fileType:n};let u=l;if(u.description!==void 0){let e=u.description;typeof e!=`string`&&typeof e!=`number`&&typeof e!=`boolean`&&e!==null&&r.push({path:`description`,message:`description must be a string, got ${Array.isArray(e)?`array`:typeof e}. At runtime this value is dropped.`})}else a.push({path:`description`,message:`No description in frontmatter. A description helps users and Claude understand when to use this ${n}.`});u.name!==void 0&&u.name!==null&&typeof u.name!=`string`&&r.push({path:`name`,message:`name must be a string, got ${typeof u.name}.`});let d=u[`allowed-tools`];d!=null&&(typeof d!=`string`&&!Array.isArray(d)?r.push({path:`allowed-tools`,message:`allowed-tools must be a string or array of strings, got ${typeof d}.`}):Array.isArray(d)&&d.some(e=>typeof e!=`string`)&&r.push({path:`allowed-tools`,message:`allowed-tools array must contain only strings.`}));let f=u.shell;if(f!=null)if(typeof f!=`string`)r.push({path:`shell`,message:`shell must be a string, got ${typeof f}.`});else{let e=f.trim().toLowerCase();e!==`bash`&&e!==`powershell`&&r.push({path:`shell`,message:`shell must be 'bash' or 'powershell', got '${f}'.`})}return{success:r.length===0,errors:r,warnings:a,filePath:e,fileType:n}}async function Z(e){let t;try{t=await A(e,{encoding:`utf-8`})}catch(t){return h(t)===`ENOENT`?{success:!0,errors:[],warnings:[],filePath:e,fileType:`hooks`}:{success:!1,errors:[{path:`file`,message:`Failed to read file: ${g(t)}`}],warnings:[],filePath:e,fileType:`hooks`}}let n;try{n=v(t)}catch(t){return{success:!1,errors:[{path:`json`,message:`Invalid JSON syntax: ${g(t)}. At runtime this breaks the entire plugin load.`}],warnings:[],filePath:e,fileType:`hooks`}}let r=E().safeParse(n);return r.success?{success:!0,errors:[],warnings:[],filePath:e,fileType:`hooks`}:{success:!1,errors:q(r.error),warnings:[],filePath:e,fileType:`hooks`}}async function Q(e,t){let n;try{n=await j(e,{withFileTypes:!0})}catch(e){let t=h(e);if(t===`ENOENT`||t===`ENOTDIR`)return[];throw e}if(t)return n.filter(e=>e.isDirectory()).map(t=>k.join(e,t.name,`SKILL.md`));let r=[];for(let t of n){let n=k.join(e,t.name);t.isDirectory()?r.push(...await Q(n,!1)):t.isFile()&&t.name.toLowerCase().endsWith(`.md`)&&r.push(n)}return r}async function fe(e){let t=[],n=[[`skill`,k.join(e,`skills`)],[`agent`,k.join(e,`agents`)],[`command`,k.join(e,`commands`)]];for(let[e,r]of n){let n=await Q(r,e===`skill`);for(let r of n){let n;try{n=await A(r,{encoding:`utf-8`})}catch(n){if(p(n))continue;t.push({success:!1,errors:[{path:`file`,message:`Failed to read: ${g(n)}`}],warnings:[],filePath:r,fileType:e});continue}let i=de(r,n,e);(i.errors.length>0||i.warnings.length>0)&&t.push(i)}}let r=await Z(k.join(e,`hooks`,`hooks.json`));return(r.errors.length>0||r.warnings.length>0)&&t.push(r),t}async function pe(e){let t=k.resolve(e),n=null;try{n=await N(t)}catch(e){if(!p(e))throw e}if(n?.isDirectory()){let e=await X(k.join(t,`.claude-plugin`,`marketplace.json`));if(e.errors[0]?.code!==`ENOENT`)return e;let n=await Y(k.join(t,`.claude-plugin`,`plugin.json`));return n.errors[0]?.code===`ENOENT`?{success:!1,errors:[{path:`directory`,message:`No manifest found in directory. Expected .claude-plugin/marketplace.json or .claude-plugin/plugin.json`}],warnings:[],filePath:t,fileType:`plugin`}:n}switch(le(e)){case`plugin`:return Y(e);case`marketplace`:return X(e);case`unknown`:try{let n=v(await A(t,{encoding:`utf-8`}));if(Array.isArray(n.plugins))return X(e)}catch(e){if(h(e)===`ENOENT`)return{success:!1,errors:[{path:`file`,message:`File not found: ${t}`}],warnings:[],filePath:t,fileType:`plugin`}}return Y(e)}}var $,me=e((()=>{ee(),_(),u(),S(),l(),D(),$=new Set([`category`,`source`,`tags`,`strict`,`id`])}));export{se as a,K as c,ce as i,pe as n,V as o,fe as r,B as s,me as t};
@@ -1 +0,0 @@
1
- import{Tt as e,bt as t}from"./loadAgentsDir-BXtV2jiO.js";e();export{t as execIntoTmuxWorktree};