@readmagic/workmate 0.0.23 → 0.0.24

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 (210) hide show
  1. package/dist/chunks/{AddWorkspaceDirectory-OgcBcK5A.js → AddWorkspaceDirectory-Ch8IcWXO.js} +1 -1
  2. package/dist/chunks/AgentsMdExternalIncludesDialog-Cyia0s4g.js +1 -0
  3. package/dist/chunks/{AgentsMdExternalIncludesDialog-CNEifEyV.js → AgentsMdExternalIncludesDialog-LjI_H_Au.js} +1 -1
  4. package/dist/chunks/{App-B-3tPQ3k.js → App-BOqh_1tN.js} +1 -1
  5. package/dist/chunks/{BackgroundTasksDialog-COuhHcey.js → BackgroundTasksDialog-CSEuuoq9.js} +1 -1
  6. package/dist/chunks/{BypassPermissionsModeDialog-bJek4siJ.js → BypassPermissionsModeDialog-CwfCwUr9.js} +1 -1
  7. package/dist/chunks/CustomSelect-wmZ9jz0W.js +1 -0
  8. package/dist/chunks/{DiffDialog-B3X9FMpO.js → DiffDialog-BpXIEWiE.js} +1 -1
  9. package/dist/chunks/Doctor-CMpr7tdf.js +1 -0
  10. package/dist/chunks/{Doctor-6PXyjIi6.js → Doctor-DqW6j3_B.js} +1 -1
  11. package/dist/chunks/{ExitFlow-DgAZp_8U.js → ExitFlow-DacaBTlk.js} +1 -1
  12. package/dist/chunks/{Grove-CHatOzcE.js → Grove-CNqYPWI6.js} +1 -1
  13. package/dist/chunks/{InvalidConfigDialog-DXL92MN9.js → InvalidConfigDialog-0TMJItCC.js} +1 -1
  14. package/dist/chunks/{InvalidSettingsDialog-Dtmpzeps.js → InvalidSettingsDialog-iwh8H52b.js} +1 -1
  15. package/dist/chunks/{KeybindingProviderSetup-DA37QUFs.js → KeybindingProviderSetup-D49HHTXD.js} +1 -1
  16. package/dist/chunks/{MCPConnectionManager-thZd-xA_.js → MCPConnectionManager-Cie77ZAK.js} +1 -1
  17. package/dist/chunks/{MCPToolListView-CpY-YJg4.js → MCPToolListView-B4ehtkXd.js} +1 -1
  18. package/dist/chunks/{McpParsingWarnings-JvChf3xr.js → McpParsingWarnings-Bff66RtJ.js} +1 -1
  19. package/dist/chunks/{MessageSelector-C0_iw7SI.js → MessageSelector-Dpd6Iywp.js} +1 -1
  20. package/dist/chunks/{Messages-K4DDsDP9.js → Messages-DN7M3oS_.js} +1 -1
  21. package/dist/chunks/{Onboarding-C1UdzM-1.js → Onboarding-CQmE3rUf.js} +1 -1
  22. package/dist/chunks/{PromptInputFooterSuggestions-AyLog8p7.js → PromptInputFooterSuggestions-HI6HH3TP.js} +1 -1
  23. package/dist/chunks/{PromptInputHelpMenu-oyic20ip.js → PromptInputHelpMenu-3QNUC2Cg.js} +1 -1
  24. package/dist/chunks/{ProviderSetup-XcBHjUnd.js → ProviderSetup-BCSPsvfv.js} +1 -1
  25. package/dist/chunks/{QueryEngine-DYxBjJ4i.js → QueryEngine-DdLWvJv6.js} +1 -1
  26. package/dist/chunks/{REPL-CQBJRrT0.js → REPL-BqO9KcK_.js} +5 -5
  27. package/dist/chunks/REPL-CmZmypfF.js +1 -0
  28. package/dist/chunks/{ResumeConversation-Dl8H9Gfy.js → ResumeConversation-DBqX7gva.js} +1 -1
  29. package/dist/chunks/SearchExtraToolsTool-BsSoILFj.js +1 -0
  30. package/dist/chunks/{SelectMulti-Bc6l11_K.js → SelectMulti-BQRHed-d.js} +1 -1
  31. package/dist/chunks/{Settings-TGp3fPrS.js → Settings-B-7yBewS.js} +3 -3
  32. package/dist/chunks/{Spinner-zYPFVFHN.js → Spinner-ByQXTvAA.js} +1 -1
  33. package/dist/chunks/{TextInput-CD9iau2k.js → TextInput-B8ruWRf2.js} +1 -1
  34. package/dist/chunks/{ThemePicker-0F0hZYPX.js → ThemePicker-BQErFFW1.js} +1 -1
  35. package/dist/chunks/{TrustDialog-C76YiMKz.js → TrustDialog-BIhz6AZE.js} +1 -1
  36. package/dist/chunks/{_baseEach-4ff-vRlp.js → _baseEach-CsIRoaTH.js} +1 -1
  37. package/dist/chunks/{add-dir-JMsRLGfx.js → add-dir-CrUDs19x.js} +1 -1
  38. package/dist/chunks/{agentDisplay-BReJUBWg.js → agentDisplay-M4pfwbMC.js} +1 -1
  39. package/dist/chunks/{agents-9qQ8I6zW.js → agents-CGaCQeLw.js} +1 -1
  40. package/dist/chunks/{agents-B3x8yJ_r.js → agents-DddX7lLX.js} +1 -1
  41. package/dist/chunks/{allErrors-DfWylHSw.js → allErrors-BF73lon8.js} +1 -1
  42. package/dist/chunks/{backgroundHousekeeping-CVNIhQg8.js → backgroundHousekeeping-Bq3LMsVR.js} +2 -2
  43. package/dist/chunks/backgroundHousekeeping-Cl3Ox7Qh.js +1 -0
  44. package/dist/chunks/{branch-C4TsMEkx.js → branch-Yg_taNlT.js} +1 -1
  45. package/dist/chunks/{btw-Dn1eYFAz.js → btw-udbprVvu.js} +1 -1
  46. package/dist/chunks/caches-ChjIEcdd.js +1 -0
  47. package/dist/chunks/{caches-DArHxBgL.js → caches-DLJ6urv-.js} +1 -1
  48. package/dist/chunks/{clear-Bdhb6b39.js → clear-B8ZtFPOK.js} +1 -1
  49. package/dist/chunks/commands-CVCpJo7M.js +1 -0
  50. package/dist/chunks/{compact-Bu9BUpxV.js → compact-izk6RKHQ.js} +1 -1
  51. package/dist/chunks/config-CFqpXMFX.js +1 -0
  52. package/dist/chunks/{context-CY_yfdYa.js → context-BbVm4SWK.js} +1 -1
  53. package/dist/chunks/{context-noninteractive-Dd4xIoP1.js → context-noninteractive-C7wrRZnM.js} +1 -1
  54. package/dist/chunks/context-noninteractive-x0HAzWhc.js +1 -0
  55. package/dist/chunks/conversation-DouVzO0K.js +1 -0
  56. package/dist/chunks/{conversation-DUu9qBnq.js → conversation-DrVkifKy.js} +1 -1
  57. package/dist/chunks/{conversationRecovery-2ft8sCPE.js → conversationRecovery-DliPBo_z.js} +1 -1
  58. package/dist/chunks/{crossProjectResume-6boHMUBx.js → crossProjectResume-DxMy05_P.js} +1 -1
  59. package/dist/chunks/{datadog-BPuGcxxC.js → datadog-Cu3s7P48.js} +1 -1
  60. package/dist/chunks/{diff-BOAElpfQ.js → diff-DdpHThJ7.js} +1 -1
  61. package/dist/chunks/doctor-D_kV_D_l.js +1 -0
  62. package/dist/chunks/{entry-TNOoyy7_.js → entry-Bxseqbi_.js} +1 -1
  63. package/dist/chunks/{esm-eTAUP-La.js → esm-BXTZz3av.js} +1 -1
  64. package/dist/chunks/{exit-DXApFJIP.js → exit-C_R_FgzR.js} +1 -1
  65. package/dist/chunks/{extraUsage-CmQaLPV1.js → extraUsage-xMuDiNKh.js} +1 -1
  66. package/dist/chunks/extractMemories-D4Dl1itt.js +1 -0
  67. package/dist/chunks/{fast-eGx2IxD7.js → fast-DH-C5IZs.js} +1 -1
  68. package/dist/chunks/fast-bopOPrtf.js +1 -0
  69. package/dist/chunks/fetchModelList-DC4VQpqa.js +1 -0
  70. package/dist/chunks/{fetchModelList-CxLsVNsu.js → fetchModelList-FE8tzTDc.js} +1 -1
  71. package/dist/chunks/{fileSuggestions-DHxdwq28.js → fileSuggestions-C-9unnoJ.js} +1 -1
  72. package/dist/chunks/{firstPartyEventLogger-M6UMli2c.js → firstPartyEventLogger-QmjjQmgt.js} +2 -2
  73. package/dist/chunks/firstPartyEventLogger-lFeqhtfh.js +1 -0
  74. package/dist/chunks/{gemini-D_ORb_L6.js → gemini-C_ApXgwc.js} +1 -1
  75. package/dist/chunks/{generateSessionName-BQoDduyA.js → generateSessionName-CQ03xlYI.js} +1 -1
  76. package/dist/chunks/{goal-D7c2mSds.js → goal-CdL29Y8C.js} +1 -1
  77. package/dist/chunks/{grok-B2-ZbUiR.js → grok-C6WAslUT.js} +1 -1
  78. package/dist/chunks/{help-CZJdRviD.js → help-DxanITNN.js} +1 -1
  79. package/dist/chunks/{history-CQiUERTL.js → history-BMycjPTT.js} +1 -1
  80. package/dist/chunks/hooks-D9ApLkBp.js +1 -0
  81. package/dist/chunks/{hooks-DIvN6gdv.js → hooks-DR3IYPJ3.js} +1 -1
  82. package/dist/chunks/{install-T_CV1Slu.js → install-0D9u2dZw.js} +1 -1
  83. package/dist/chunks/{instrumentation-BjqUZ383.js → instrumentation-BFiGwntt.js} +3 -3
  84. package/dist/chunks/{job-R6c4-3c8.js → job-YhJQWgE0.js} +1 -1
  85. package/dist/chunks/{keybindings-CLRaiL_Z.js → keybindings-DZrF9iNd.js} +1 -1
  86. package/dist/chunks/{launchLocalMemory-DrbKrwXc.js → launchLocalMemory-DhJ56KDc.js} +1 -1
  87. package/dist/chunks/{launchOnboarding-tqsMD8ni.js → launchOnboarding-DmMoZwv5.js} +1 -1
  88. package/dist/chunks/{loadAgentsDir-DlPbtIsS.js → loadAgentsDir-B0Anodo0.js} +23 -23
  89. package/dist/chunks/loadAgentsDir-BbUR6pqH.js +1 -0
  90. package/dist/chunks/{loadPluginHooks-C_msxVIc.js → loadPluginHooks-BSwCtQ6T.js} +1 -1
  91. package/dist/chunks/{localSearch-CK-sFzPm.js → localSearch-BxLYi6w_.js} +1 -1
  92. package/dist/chunks/localSearch-zfn7jgrh.js +1 -0
  93. package/dist/chunks/{logoUtils-x2pHV-Nl.js → logoUtils-CRxTutvr.js} +1 -1
  94. package/dist/chunks/{magicDocs-BEF8D3if.js → magicDocs-Bkz7ZcmL.js} +1 -1
  95. package/dist/chunks/{main-kOVUGxOS.js → main-9ksgUUY_.js} +5 -5
  96. package/dist/chunks/{mcp-D0wAJrRT.js → mcp-ChF12reQ.js} +1 -1
  97. package/dist/chunks/{mcp-mgOlm1cY.js → mcp-DoEl5uah.js} +1 -1
  98. package/dist/chunks/{mcp-BNd29r6p.js → mcp-hp9qqjAy.js} +2 -2
  99. package/dist/chunks/{memory-DDLk9_LJ.js → memory-Qv-wGNQ5.js} +1 -1
  100. package/dist/chunks/{mode-CcNsWgK3.js → mode-bFXPCR2P.js} +1 -1
  101. package/dist/chunks/{model-DzCP4K-9.js → model-6lkW4o2c.js} +1 -1
  102. package/dist/chunks/{model-BwBG0V1u.js → model-BvQFFOf8.js} +1 -1
  103. package/dist/chunks/{modelOptions-DRaG3bo0.js → modelOptions-BBvF3wHK.js} +1 -1
  104. package/dist/chunks/{nativeInstaller-C3pVPqrZ.js → nativeInstaller-CdjmE9Zy.js} +1 -1
  105. package/dist/chunks/{notifications-4wP1Tx9Y.js → notifications-Bc6k-Ozy.js} +1 -1
  106. package/dist/chunks/{onChangeAppState-BlaoFbYF.js → onChangeAppState-DLjZ1x95.js} +1 -1
  107. package/dist/chunks/{openai-CDN71NdX.js → openai-D46QvESE.js} +1 -1
  108. package/dist/chunks/{overlayContext-BT2Lq8ei.js → overlayContext-8--_fbvY.js} +1 -1
  109. package/dist/chunks/{partition-CIl_ORUT.js → partition-DznN4XZH.js} +1 -1
  110. package/dist/chunks/{permissions-zSNOZSwr.js → permissions-DmGFViHI.js} +1 -1
  111. package/dist/chunks/{pidLock-BTqO-h7Y.js → pidLock-Cm4sW35f.js} +2 -2
  112. package/dist/chunks/{plan-Bs6em6lk.js → plan-CzGBz_87.js} +1 -1
  113. package/dist/chunks/{plugin-DDDxjBa0.js → plugin-CluR79xX.js} +1 -1
  114. package/dist/chunks/{pluginAutoupdate-8qugAFhb.js → pluginAutoupdate-ennb9k8_.js} +1 -1
  115. package/dist/chunks/{pluginBlocklist-q01ackCf.js → pluginBlocklist-9OrNEh--.js} +1 -1
  116. package/dist/chunks/{pluginCliCommands-DXZfCZsv.js → pluginCliCommands-CJv5uhOG.js} +1 -1
  117. package/dist/chunks/{pluginFlagging-BG2MHCQJ.js → pluginFlagging-js_-WmYj.js} +1 -1
  118. package/dist/chunks/{pluginOperations-hXYLrzM2.js → pluginOperations-CcUSHAIa.js} +1 -1
  119. package/dist/chunks/pluginStartupCheck-CRBUO9gP.js +1 -0
  120. package/dist/chunks/{pluginStartupCheck-DTMa6TgL.js → pluginStartupCheck-SRXOyqr7.js} +1 -1
  121. package/dist/chunks/{plugins-COoGBYk6.js → plugins-IwwaCDba.js} +1 -1
  122. package/dist/chunks/{print-BASybEtO.js → print-CgszM1ea.js} +2 -2
  123. package/dist/chunks/{processBashCommand-DDi_Pymt.js → processBashCommand-D098WsqY.js} +1 -1
  124. package/dist/chunks/{processSlashCommand-Cq9kaoSF.js → processSlashCommand-DOQFjJ88.js} +1 -1
  125. package/dist/chunks/prompt-BKPmDAuL.js +1 -0
  126. package/dist/chunks/{prompt-mM79EGnT.js → prompt-CJ1l3XXk.js} +1 -1
  127. package/dist/chunks/prompt-CgOklk7z.js +1 -0
  128. package/dist/chunks/{promptEditor-DLGN_eLu.js → promptEditor-DoGHJN_W.js} +1 -1
  129. package/dist/chunks/{reconciler-CeXqh95g.js → reconciler-ykkSPR-i.js} +1 -1
  130. package/dist/chunks/{refresh-Ce2yk28a.js → refresh-Dn_I1R4v.js} +1 -1
  131. package/dist/chunks/{reject-Bld5E-bn.js → reject-DtcCfuZV.js} +1 -1
  132. package/dist/chunks/{reload-plugins-C42xSB5l.js → reload-plugins-CQZFQLWP.js} +1 -1
  133. package/dist/chunks/{rename-CtBghpxZ.js → rename-DyEfsZiq.js} +1 -1
  134. package/dist/chunks/{resume-BWkaTDqd.js → resume-BcXEDUqZ.js} +1 -1
  135. package/dist/chunks/{runtimeObserver-1wQO8HSZ.js → runtimeObserver-DEuR8z0f.js} +1 -1
  136. package/dist/chunks/{runtimeObserver-XQrOux41.js → runtimeObserver-PJ1o8GRA.js} +2 -2
  137. package/dist/chunks/sandbox-adapter-DfB9kgQD.js +1 -0
  138. package/dist/chunks/{sandbox-toggle-Dir9Polo.js → sandbox-toggle-D9GDUsTl.js} +1 -1
  139. package/dist/chunks/searchExtraTools-D4gMMQv0.js +1 -0
  140. package/dist/chunks/{select-Bxf5-5sI.js → select-DIxfl_VN.js} +1 -1
  141. package/dist/chunks/sessionFileAccessHooks-lbgHnVvi.js +1 -0
  142. package/dist/chunks/{sessionObserver-DS4G6mb9.js → sessionObserver-BtKjvteq.js} +1 -1
  143. package/dist/chunks/sessionObserver-D6qzEdGJ.js +1 -0
  144. package/dist/chunks/sessionStorage-C_7gow_z.js +1 -0
  145. package/dist/chunks/{sessionTracing-BoDDYLxW.js → sessionTracing-CtbeAD0s.js} +1 -1
  146. package/dist/chunks/{setup-BRypY6iT.js → setup-qecdf-ES.js} +2 -2
  147. package/dist/chunks/{shadowedRuleDetection-BRxZjobz.js → shadowedRuleDetection-Bg_aIc5Z.js} +1 -1
  148. package/dist/chunks/{sideQuestion-DLJxyrlp.js → sideQuestion-D49GsfH7.js} +1 -1
  149. package/dist/chunks/sinks-C-lP7uyO.js +1 -0
  150. package/dist/chunks/{sinks-Cz2HfgMU.js → sinks-De-B1lPQ.js} +1 -1
  151. package/dist/chunks/{skillChangeDetector-xviGstqm.js → skillChangeDetector-DkOJoNhT.js} +1 -1
  152. package/dist/chunks/{skillGapStore-CKN_d3pO.js → skillGapStore-CcFoHNLl.js} +2 -2
  153. package/dist/chunks/{skillLifecycle-BMY2JGGG.js → skillLifecycle-Bnz_4wE5.js} +2 -2
  154. package/dist/chunks/{skillSearchPanel-D9trHULQ.js → skillSearchPanel-C_5yUhqn.js} +2 -2
  155. package/dist/chunks/{skills-CX_AvwLG.js → skills-BE5scC-g.js} +1 -1
  156. package/dist/chunks/status-Dw09WZLd.js +1 -0
  157. package/dist/chunks/{statusNoticeHelpers-vFVgIYuw.js → statusNoticeHelpers-BRQpUIlH.js} +1 -1
  158. package/dist/chunks/switcher-CgZVah7U.js +1 -0
  159. package/dist/chunks/{switcher-CAajZeNL.js → switcher-DZwUo5Ed.js} +1 -1
  160. package/dist/chunks/{tasks-BWNQr2d3.js → tasks-DdcUQEeD.js} +1 -1
  161. package/dist/chunks/{templateJobs-gUET39Ho.js → templateJobs-C8qsPrLj.js} +1 -1
  162. package/dist/chunks/{theme-B7fKI6E5.js → theme-f1h2QI8J.js} +1 -1
  163. package/dist/chunks/{tipRegistry-DamZr34w.js → tipRegistry-B71o4qWr.js} +1 -1
  164. package/dist/chunks/{toolEventObserver-BL06sDI4.js → toolEventObserver-7QP38x4t.js} +1 -1
  165. package/dist/chunks/{toolPool-CX5wDBi1.js → toolPool-V-7Yv0GA.js} +1 -1
  166. package/dist/chunks/{use-select-navigation-BiUJdWai.js → use-select-navigation-hWL5VHnL.js} +1 -1
  167. package/dist/chunks/{useExitOnCtrlCDWithKeybindings-C9BYG8Bo.js → useExitOnCtrlCDWithKeybindings-BKwzUpgb.js} +1 -1
  168. package/dist/chunks/useMainLoopModel-DxvV70Ru.js +1 -0
  169. package/dist/chunks/{useManagePlugins-BqfIVa6E.js → useManagePlugins-BXLXazrR.js} +1 -1
  170. package/dist/chunks/useMergedTools-CCgnBJzO.js +1 -0
  171. package/dist/chunks/{useSearchInput-B25K1RnK.js → useSearchInput-CzopttqC.js} +1 -1
  172. package/dist/chunks/{useSettingsErrors-DYQ44kX4.js → useSettingsErrors-SFPWfxsA.js} +1 -1
  173. package/dist/chunks/{util-CtlC2dsN.js → util-Cbb3S6SX.js} +1 -1
  174. package/dist/chunks/{validatePlugin-D6tFo87L.js → validatePlugin-BMSoeb_b.js} +1 -1
  175. package/dist/chunks/worktree-Vm-SNY5x.js +1 -0
  176. package/dist/cli.js +1 -1
  177. package/package.json +1 -1
  178. package/dist/chunks/AgentsMdExternalIncludesDialog-CDNd5-7E.js +0 -1
  179. package/dist/chunks/CustomSelect-DoeEXOIP.js +0 -1
  180. package/dist/chunks/Doctor-DNgkgYhB.js +0 -1
  181. package/dist/chunks/REPL-CrVuMQY2.js +0 -1
  182. package/dist/chunks/SearchExtraToolsTool-lv7VE50N.js +0 -1
  183. package/dist/chunks/backgroundHousekeeping-BGxHB_OX.js +0 -1
  184. package/dist/chunks/caches-BGzKwpnc.js +0 -1
  185. package/dist/chunks/commands-QepeBbFn.js +0 -1
  186. package/dist/chunks/config-D58C3_Lu.js +0 -1
  187. package/dist/chunks/context-noninteractive-BDDi3NLF.js +0 -1
  188. package/dist/chunks/conversation-B0wxBwzv.js +0 -1
  189. package/dist/chunks/doctor-CkLzqAMd.js +0 -1
  190. package/dist/chunks/extractMemories-xP63mv6R.js +0 -1
  191. package/dist/chunks/fast-C5nQH8rm.js +0 -1
  192. package/dist/chunks/fetchModelList-D24lRIgR.js +0 -1
  193. package/dist/chunks/firstPartyEventLogger-BVAogAX8.js +0 -1
  194. package/dist/chunks/hooks-BNuUlMzL.js +0 -1
  195. package/dist/chunks/loadAgentsDir-CcmY8zCj.js +0 -1
  196. package/dist/chunks/localSearch-DrUj0B-d.js +0 -1
  197. package/dist/chunks/pluginStartupCheck-HS1ZceZa.js +0 -1
  198. package/dist/chunks/prompt-CHobfCB1.js +0 -1
  199. package/dist/chunks/prompt-CMm6RHHc.js +0 -1
  200. package/dist/chunks/sandbox-adapter-8GO6eJxw.js +0 -1
  201. package/dist/chunks/searchExtraTools-BhDq8DTJ.js +0 -1
  202. package/dist/chunks/sessionFileAccessHooks-CozocHQE.js +0 -1
  203. package/dist/chunks/sessionObserver-DGEQM4cO.js +0 -1
  204. package/dist/chunks/sessionStorage-BcAscOGE.js +0 -1
  205. package/dist/chunks/sinks-CGdKmq_8.js +0 -1
  206. package/dist/chunks/status-Daaak6Bo.js +0 -1
  207. package/dist/chunks/switcher-BpgmH4AI.js +0 -1
  208. package/dist/chunks/useMainLoopModel-DwjSVzzO.js +0 -1
  209. package/dist/chunks/useMergedTools-Bw8FchX8.js +0 -1
  210. package/dist/chunks/worktree-B8apCnVe.js +0 -1
@@ -1,2 +1,2 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{$a as t,Aa as n,Ba as r,Bx as i,Cx as a,Fa as o,Fx as s,Ga as c,Gx as l,Ia as u,Iv as d,Ix as f,Ja as p,Jp as m,Lx as h,Ma as g,Mo as _,Na as v,No as y,Pa as b,Px as x,Ra as S,Rv as C,Ua as w,Va as T,Wa as E,Wx as ee,Yp as te,co as D,eo as O,jo as k,lo as ne,no as A,oo as j,to as M,uo as re,yx as ie,zx as N}from"./loadAgentsDir-DlPbtIsS.js";import{It as ae,J as P}from"./state-B4jiUise.js";import{I as oe,R as F,V as se,f as ce,u as I}from"./debug-Bglx1aTu.js";import{b as L,h as R,s as z}from"./settings-B2jvL8Dp.js";import{o as B,s as V}from"./log-D2TIwHBV.js";import{l as H,o as U}from"./stringUtils-C718f5ey.js";import{n as W,t as G}from"./pluginStartupCheck-DTMa6TgL.js";import{dirname as le,join as K}from"path";function q(e){if(!Q.includes(e))throw Error(`Invalid scope "${e}". Must be one of: ${Q.join(`, `)}`)}function ue(e){return Q.includes(e)}function J(e){return e===`project`||e===`local`?P():void 0}function de(e){return z(`projectSettings`)?.enabledPlugins?.[e]===!0}function fe(e){let t=e.includes(`@`);for(let n of[`local`,`project`,`user`]){let r=z(i(n))?.enabledPlugins;if(r){for(let i of Object.keys(r))if(t?i===e:i.startsWith(`${e}@`))return{pluginId:i,scope:n}}}return null}function pe(e,t){let{name:n,marketplace:r}=N(e);return t.find(t=>t.name===e||t.name===n?!0:r&&t.source?t.name===n&&t.source.includes(`@${r}`):!1)}function me(e){let{name:t}=N(e),n=O();if(n.plugins[e]?.length)return{pluginId:e,pluginName:t};let r=Object.keys(n.plugins).find(e=>{let{name:r}=N(e);return r===t&&(n.plugins[e]?.length??0)>0});return r?{pluginId:r,pluginName:t}:null}function Y(e){let t=O().plugins[e];if(!t||t.length===0)return{scope:`user`};let n=P(),r=t.find(e=>e.scope===`local`&&e.projectPath===n);if(r)return{scope:r.scope,projectPath:r.projectPath};let i=t.find(e=>e.scope===`project`&&e.projectPath===n);if(i)return{scope:i.scope,projectPath:i.projectPath};let a=t.find(e=>e.scope===`user`);return a?{scope:a.scope}:{scope:t[0].scope,projectPath:t[0].projectPath}}async function he(e,t=`user`){q(t);let{name:n,marketplace:i}=N(e),a,o,s;if(i){let t=await D(e);t&&(a=t.entry,o=i,s=t.marketplaceInstallLocation)}else{let e=await re();for(let[t,r]of Object.entries(e))try{let e=(await j(t)).plugins.find(e=>e.name===n);if(e){a=e,o=t,s=r.installLocation;break}}catch(e){V(se(e))}}if(!a||!o)return{success:!1,message:`Plugin "${n}" not found in ${i?`marketplace "${i}"`:`any configured marketplace`}`};let c=a,l=`${c.name}@${o}`,u=await w({pluginId:l,entry:c,scope:t,marketplaceInstallLocation:s});if(!u.ok){let e=u;switch(e.reason){case`local-source-no-location`:return{success:!1,message:`Cannot install local plugin "${e.pluginName}" without marketplace install location`};case`settings-write-failed`:return{success:!1,message:`Failed to update settings: ${e.message}`};case`resolution-failed`:return{success:!1,message:r(e.resolution)};case`blocked-by-policy`:return{success:!1,message:`Plugin "${e.pluginName}" is blocked by your organization's policy and cannot be installed`};case`dependency-blocked-by-policy`:return{success:!1,message:`Plugin "${e.pluginName}" depends on "${e.blockedDependency}", which is blocked by your organization's policy`}}}return{success:!0,message:`Successfully installed plugin: ${l} (scope: ${t})${u.depNote}`,pluginId:l,pluginName:c.name,scope:t}}async function ge(e,t=`user`,n=!0){q(t);let{enabled:r,disabled:a}=await u(),o=[...r,...a],c=pe(e,o),l=i(t),f=z(l),p,m;if(c)p=Object.keys(f?.enabledPlugins??{}).find(t=>t===e||t===c.name||t.startsWith(`${c.name}@`))??(e.includes(`@`)?e:c.name),m=c.name;else{let t=me(e);if(!t)return{success:!1,message:`Plugin "${e}" not found in installed plugins`};p=t.pluginId,m=t.pluginName}let h=J(t),g=O().plugins[p],_=g?.find(e=>e.scope===t&&e.projectPath===h);if(!_){let{scope:n}=Y(p);return n!==t&&g&&g.length>0?n===`project`?{success:!1,message:`Plugin "${e}" is enabled at project scope (.workmate/settings.json, shared with your team). To disable just for you: claude plugin disable ${e} --scope local`}:{success:!1,message:`Plugin "${e}" is installed in ${n} scope, not ${t}. Use --scope ${n} to uninstall.`}:{success:!1,message:`Plugin "${e}" is not installed in ${t} scope. Use --scope to specify the correct scope.`}}let v=_.installPath,b={...f?.enabledPlugins};b[p]=void 0,L(l,{enabledPlugins:b}),k(),M(p,t,h);let S=O().plugins[p],C=!S||S.length===0;C&&v&&await y(v),C&&(d(p),n&&await ie(p));let w=x(p,o),T=s(w);return{success:!0,message:`Successfully uninstalled plugin: ${m} (scope: ${t})${T}`,pluginId:p,pluginName:m,scope:t,reverseDependents:w.length>0?w:void 0}}async function X(e,t,n){let r=t?`enable`:`disable`;if(l(e)){let{error:n}=L(`userSettings`,{enabledPlugins:{...z(`userSettings`)?.enabledPlugins,[e]:t}});if(n)return{success:!1,message:`Failed to ${r} built-in plugin: ${n.message}`};k();let{name:i}=N(e);return{success:!0,message:`Successfully ${r}d built-in plugin: ${i}`,pluginId:e,pluginName:i,scope:`user`}}n&&q(n);let a,o,c=fe(e);if(n)if(o=n,c)a=c.pluginId;else if(e.includes(`@`))a=e;else return{success:!1,message:`Plugin "${e}" not found in settings. Use plugin@marketplace format.`};else if(c)a=c.pluginId,o=c.scope;else if(e.includes(`@`))a=e,o=`user`;else return{success:!1,message:`Plugin "${e}" not found in any editable settings scope. Use plugin@marketplace format.`};if(t&&te(a))return{success:!1,message:`Plugin "${a}" is blocked by your organization's policy and cannot be enabled`};let d=i(o),f=z(d)?.enabledPlugins?.[a],p={user:0,project:1,local:2},m=n&&c&&p[n]>p[c.scope];if(n&&f===void 0&&c&&c.scope!==n&&!m)return{success:!1,message:`Plugin "${e}" is installed at ${c.scope} scope, not ${n}. Use --scope ${c.scope} or omit --scope to auto-detect.`};if(t===(n&&!m?f===!0:G().has(a)))return{success:!1,message:`Plugin "${e}" is already ${t?`enabled`:`disabled`}${n?` at ${n} scope`:``}`};let h;if(!t){let{enabled:e,disabled:t}=await u(),n=x(a,[...e,...t]);n.length>0&&(h=n)}let{error:g}=L(d,{enabledPlugins:{...z(d)?.enabledPlugins,[a]:t}});if(g)return{success:!1,message:`Failed to ${r} plugin: ${g.message}`};k();let{name:_}=N(a),v=s(h);return{success:!0,message:`Successfully ${r}d plugin: ${_} (scope: ${o})${v}`,pluginId:a,pluginName:_,scope:o,reverseDependents:h}}async function _e(e,t){return X(e,!0,t)}async function ve(e,t){return X(e,!1,t)}async function Z(){let e=G();if(e.size===0)return{success:!0,message:`No enabled plugins to disable`};let t=[],n=[];for(let[r]of e){let e=await X(r,!1);e.success?t.push(r):n.push(`${r}: ${e.message}`)}return n.length>0?{success:!1,message:`Disabled ${t.length} ${H(t.length,`plugin`)}, ${n.length} failed:\n${n.join(`
1
+ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{$a as t,Aa as n,Ba as r,Bx as i,Cx as a,Fa as o,Fx as s,Ga as c,Gx as l,Ia as u,Iv as d,Ix as f,Ja as p,Jp as m,Lx as h,Ma as g,Mo as _,Na as v,No as y,Pa as b,Px as x,Ra as S,Rv as C,Ua as w,Va as T,Wa as E,Wx as ee,Yp as te,co as D,eo as O,jo as k,lo as ne,no as A,oo as j,to as M,uo as re,yx as ie,zx as N}from"./loadAgentsDir-B0Anodo0.js";import{It as ae,J as P}from"./state-B4jiUise.js";import{I as oe,R as F,V as se,f as ce,u as I}from"./debug-Bglx1aTu.js";import{b as L,h as R,s as z}from"./settings-B2jvL8Dp.js";import{o as B,s as V}from"./log-D2TIwHBV.js";import{l as H,o as U}from"./stringUtils-C718f5ey.js";import{n as W,t as G}from"./pluginStartupCheck-SRXOyqr7.js";import{dirname as le,join as K}from"path";function q(e){if(!Q.includes(e))throw Error(`Invalid scope "${e}". Must be one of: ${Q.join(`, `)}`)}function ue(e){return Q.includes(e)}function J(e){return e===`project`||e===`local`?P():void 0}function de(e){return z(`projectSettings`)?.enabledPlugins?.[e]===!0}function fe(e){let t=e.includes(`@`);for(let n of[`local`,`project`,`user`]){let r=z(i(n))?.enabledPlugins;if(r){for(let i of Object.keys(r))if(t?i===e:i.startsWith(`${e}@`))return{pluginId:i,scope:n}}}return null}function pe(e,t){let{name:n,marketplace:r}=N(e);return t.find(t=>t.name===e||t.name===n?!0:r&&t.source?t.name===n&&t.source.includes(`@${r}`):!1)}function me(e){let{name:t}=N(e),n=O();if(n.plugins[e]?.length)return{pluginId:e,pluginName:t};let r=Object.keys(n.plugins).find(e=>{let{name:r}=N(e);return r===t&&(n.plugins[e]?.length??0)>0});return r?{pluginId:r,pluginName:t}:null}function Y(e){let t=O().plugins[e];if(!t||t.length===0)return{scope:`user`};let n=P(),r=t.find(e=>e.scope===`local`&&e.projectPath===n);if(r)return{scope:r.scope,projectPath:r.projectPath};let i=t.find(e=>e.scope===`project`&&e.projectPath===n);if(i)return{scope:i.scope,projectPath:i.projectPath};let a=t.find(e=>e.scope===`user`);return a?{scope:a.scope}:{scope:t[0].scope,projectPath:t[0].projectPath}}async function he(e,t=`user`){q(t);let{name:n,marketplace:i}=N(e),a,o,s;if(i){let t=await D(e);t&&(a=t.entry,o=i,s=t.marketplaceInstallLocation)}else{let e=await re();for(let[t,r]of Object.entries(e))try{let e=(await j(t)).plugins.find(e=>e.name===n);if(e){a=e,o=t,s=r.installLocation;break}}catch(e){V(se(e))}}if(!a||!o)return{success:!1,message:`Plugin "${n}" not found in ${i?`marketplace "${i}"`:`any configured marketplace`}`};let c=a,l=`${c.name}@${o}`,u=await w({pluginId:l,entry:c,scope:t,marketplaceInstallLocation:s});if(!u.ok){let e=u;switch(e.reason){case`local-source-no-location`:return{success:!1,message:`Cannot install local plugin "${e.pluginName}" without marketplace install location`};case`settings-write-failed`:return{success:!1,message:`Failed to update settings: ${e.message}`};case`resolution-failed`:return{success:!1,message:r(e.resolution)};case`blocked-by-policy`:return{success:!1,message:`Plugin "${e.pluginName}" is blocked by your organization's policy and cannot be installed`};case`dependency-blocked-by-policy`:return{success:!1,message:`Plugin "${e.pluginName}" depends on "${e.blockedDependency}", which is blocked by your organization's policy`}}}return{success:!0,message:`Successfully installed plugin: ${l} (scope: ${t})${u.depNote}`,pluginId:l,pluginName:c.name,scope:t}}async function ge(e,t=`user`,n=!0){q(t);let{enabled:r,disabled:a}=await u(),o=[...r,...a],c=pe(e,o),l=i(t),f=z(l),p,m;if(c)p=Object.keys(f?.enabledPlugins??{}).find(t=>t===e||t===c.name||t.startsWith(`${c.name}@`))??(e.includes(`@`)?e:c.name),m=c.name;else{let t=me(e);if(!t)return{success:!1,message:`Plugin "${e}" not found in installed plugins`};p=t.pluginId,m=t.pluginName}let h=J(t),g=O().plugins[p],_=g?.find(e=>e.scope===t&&e.projectPath===h);if(!_){let{scope:n}=Y(p);return n!==t&&g&&g.length>0?n===`project`?{success:!1,message:`Plugin "${e}" is enabled at project scope (.workmate/settings.json, shared with your team). To disable just for you: claude plugin disable ${e} --scope local`}:{success:!1,message:`Plugin "${e}" is installed in ${n} scope, not ${t}. Use --scope ${n} to uninstall.`}:{success:!1,message:`Plugin "${e}" is not installed in ${t} scope. Use --scope to specify the correct scope.`}}let v=_.installPath,b={...f?.enabledPlugins};b[p]=void 0,L(l,{enabledPlugins:b}),k(),M(p,t,h);let S=O().plugins[p],C=!S||S.length===0;C&&v&&await y(v),C&&(d(p),n&&await ie(p));let w=x(p,o),T=s(w);return{success:!0,message:`Successfully uninstalled plugin: ${m} (scope: ${t})${T}`,pluginId:p,pluginName:m,scope:t,reverseDependents:w.length>0?w:void 0}}async function X(e,t,n){let r=t?`enable`:`disable`;if(l(e)){let{error:n}=L(`userSettings`,{enabledPlugins:{...z(`userSettings`)?.enabledPlugins,[e]:t}});if(n)return{success:!1,message:`Failed to ${r} built-in plugin: ${n.message}`};k();let{name:i}=N(e);return{success:!0,message:`Successfully ${r}d built-in plugin: ${i}`,pluginId:e,pluginName:i,scope:`user`}}n&&q(n);let a,o,c=fe(e);if(n)if(o=n,c)a=c.pluginId;else if(e.includes(`@`))a=e;else return{success:!1,message:`Plugin "${e}" not found in settings. Use plugin@marketplace format.`};else if(c)a=c.pluginId,o=c.scope;else if(e.includes(`@`))a=e,o=`user`;else return{success:!1,message:`Plugin "${e}" not found in any editable settings scope. Use plugin@marketplace format.`};if(t&&te(a))return{success:!1,message:`Plugin "${a}" is blocked by your organization's policy and cannot be enabled`};let d=i(o),f=z(d)?.enabledPlugins?.[a],p={user:0,project:1,local:2},m=n&&c&&p[n]>p[c.scope];if(n&&f===void 0&&c&&c.scope!==n&&!m)return{success:!1,message:`Plugin "${e}" is installed at ${c.scope} scope, not ${n}. Use --scope ${c.scope} or omit --scope to auto-detect.`};if(t===(n&&!m?f===!0:G().has(a)))return{success:!1,message:`Plugin "${e}" is already ${t?`enabled`:`disabled`}${n?` at ${n} scope`:``}`};let h;if(!t){let{enabled:e,disabled:t}=await u(),n=x(a,[...e,...t]);n.length>0&&(h=n)}let{error:g}=L(d,{enabledPlugins:{...z(d)?.enabledPlugins,[a]:t}});if(g)return{success:!1,message:`Failed to ${r} plugin: ${g.message}`};k();let{name:_}=N(a),v=s(h);return{success:!0,message:`Successfully ${r}d plugin: ${_} (scope: ${o})${v}`,pluginId:a,pluginName:_,scope:o,reverseDependents:h}}async function _e(e,t){return X(e,!0,t)}async function ve(e,t){return X(e,!1,t)}async function Z(){let e=G();if(e.size===0)return{success:!0,message:`No enabled plugins to disable`};let t=[],n=[];for(let[r]of e){let e=await X(r,!1);e.success?t.push(r):n.push(`${r}: ${e.message}`)}return n.length>0?{success:!1,message:`Disabled ${t.length} ${H(t.length,`plugin`)}, ${n.length} failed:\n${n.join(`
2
2
  `)}`}:{success:!0,message:`Disabled ${t.length} ${H(t.length,`plugin`)}`}}async function ye(e,n){let{name:r,marketplace:i}=N(e),a=i?`${r}@${i}`:e,o=await D(e);if(!o)return{success:!1,message:`Plugin "${r}" not found`,pluginId:a,scope:n};let{entry:s,marketplaceInstallLocation:c}=o,l=t().plugins[a];if(!l||l.length===0)return{success:!1,message:`Plugin "${r}" is not installed`,pluginId:a,scope:n};let u=J(n),d=l.find(e=>e.scope===n&&e.projectPath===u);return d?be({pluginId:a,pluginName:r,entry:s,marketplaceInstallLocation:c,installation:d,scope:n,projectPath:u}):{success:!1,message:`Plugin "${r}" is not installed at scope ${u?`${n} (${u})`:n}`,pluginId:a,scope:n}}async function be({pluginId:e,pluginName:r,entry:i,marketplaceInstallLocation:a,installation:o,scope:s,projectPath:c}){let l=I(),u=o.version,d,f,p=!1,m;if(typeof i.source!=`string`){let t=await n(i.source,{manifest:{name:i.name}});d=t.path,p=!0,m=t.gitCommitSha,f=await E(e,i.source,t.manifest,t.path,i.version,t.gitCommitSha)}else{let t;try{t=await l.stat(a)}catch(t){if(F(t))return{success:!1,message:`Marketplace directory not found at ${a}`,pluginId:e,scope:s};throw t}d=K(t.isDirectory()?a:le(a),i.source);try{await l.stat(d)}catch(t){if(F(t))return{success:!1,message:`Plugin source not found at ${d}`,pluginId:e,scope:s};throw t}let n,r=K(d,`.claude-plugin`,`plugin.json`);try{n=await S(r,i.name,i.source)}catch{}f=await E(e,i.source,n,d,i.version)}try{let n=v(e,f),a=b(e,f);if(o.version===f||o.installPath===n||o.installPath===a)return{success:!0,message:`${r} is already at the latest version (${f}).`,pluginId:e,newVersion:f,oldVersion:u,alreadyUpToDate:!0,scope:s};n=await g(d,e,f,i);let l=o.installPath;if(A(e,s,c,n,f,m),l&&l!==n){let e=t();Object.values(e.plugins).some(e=>e.some(e=>e.installPath===l))||await y(l)}let p=c?`${s} (${c})`:s;return{success:!0,message:`Plugin "${r}" updated from ${u||`unknown`} to ${f} for scope ${p}. Restart to apply changes.`,pluginId:e,newVersion:f,oldVersion:u,scope:s}}finally{p&&d!==v(e,f)&&await l.rm(d,{recursive:!0,force:!0})}}var Q,$,xe=e((()=>{ae(),ee(),oe(),ce(),B(),_(),f(),p(),ne(),a(),h(),T(),o(),C(),m(),W(),c(),R(),U(),Q=[`user`,`project`,`local`],$=[`user`,`project`,`local`,`managed`]}));export{_e as a,he as c,ge as d,ye as f,ve as i,ue as l,$ as n,Y as o,Z as r,xe as s,Q as t,de as u};
@@ -0,0 +1 @@
1
+ import{n as e,t}from"./pluginStartupCheck-SRXOyqr7.js";e();export{t as getPluginEditableScopes};
@@ -1 +1 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{Hx as t,Ja as n,Lx as r,Va as i,Vx as a,lo as o}from"./loadAgentsDir-DlPbtIsS.js";import{n as s}from"./cwd-Pa83R95t.js";import{c,i as l}from"./debug-Bglx1aTu.js";import{_t as u,h as d,s as f}from"./settings-B2jvL8Dp.js";import{o as p}from"./log-D2TIwHBV.js";import"path";function m(){let e=new Map,t=a();for(let[n,r]of Object.entries(t))n.includes(`@`)&&(r===!0?e.set(n,`flag`):r===!1&&e.delete(n));for(let{scope:n,source:r}of[{scope:`managed`,source:`policySettings`},{scope:`user`,source:`userSettings`},{scope:`project`,source:`projectSettings`},{scope:`local`,source:`localSettings`},{scope:`flag`,source:`flagSettings`}]){let i=f(r);if(i?.enabledPlugins)for(let[a,o]of Object.entries(i.enabledPlugins))a.includes(`@`)&&(a in t&&t[a]!==o&&c(`Plugin ${a} from --add-dir (${t[a]}) overridden by ${r} (${o})`),o===!0?e.set(a,n):o===!1&&e.delete(a))}return c(`Found ${e.size} enabled plugins with scopes: ${Array.from(e.entries()).map(([e,t])=>`${e}(${t})`).join(`, `)}`),e}var h=e((()=>{s(),l(),p(),d(),t(),n(),o(),r(),i(),u()}));export{h as n,m as t};
1
+ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{Hx as t,Ja as n,Lx as r,Va as i,Vx as a,lo as o}from"./loadAgentsDir-B0Anodo0.js";import{n as s}from"./cwd-Pa83R95t.js";import{c,i as l}from"./debug-Bglx1aTu.js";import{_t as u,h as d,s as f}from"./settings-B2jvL8Dp.js";import{o as p}from"./log-D2TIwHBV.js";import"path";function m(){let e=new Map,t=a();for(let[n,r]of Object.entries(t))n.includes(`@`)&&(r===!0?e.set(n,`flag`):r===!1&&e.delete(n));for(let{scope:n,source:r}of[{scope:`managed`,source:`policySettings`},{scope:`user`,source:`userSettings`},{scope:`project`,source:`projectSettings`},{scope:`local`,source:`localSettings`},{scope:`flag`,source:`flagSettings`}]){let i=f(r);if(i?.enabledPlugins)for(let[a,o]of Object.entries(i.enabledPlugins))a.includes(`@`)&&(a in t&&t[a]!==o&&c(`Plugin ${a} from --add-dir (${t[a]}) overridden by ${r} (${o})`),o===!0?e.set(a,n):o===!1&&e.delete(a))}return c(`Found ${e.size} enabled plugins with scopes: ${Array.from(e.entries()).map(([e,t])=>`${e}(${t})`).join(`, `)}`),e}var h=e((()=>{s(),l(),p(),d(),t(),n(),o(),r(),i(),u()}));export{h as n,m as t};
@@ -1,4 +1,4 @@
1
- import{n as e,t}from"./figures-5ThXQEtq.js";import{Bx as n,Do as r,Fa as i,Fv as a,Ia as o,Ja as s,Kx as c,Lx as l,Mo as u,Pv as d,Qa as f,_o as p,eo as m,fo as h,ho as g,jo as _,ko as v,lo as ee,po as te,qx as y,ro as b,uo as x,xo as S,zx as C}from"./loadAgentsDir-DlPbtIsS.js";import{Hn as w,It as T}from"./state-B4jiUise.js";import{C as E,I as ne,M as D,x as re}from"./debug-Bglx1aTu.js";import{o as O,s as k}from"./log-D2TIwHBV.js";import{l as A,o as j}from"./stringUtils-C718f5ey.js";import{n as M,r as N}from"./analytics-DJobLaWP.js";import{n as P,t as F}from"./exit-s9XGerrH.js";import{n as I,s as L,t as R}from"./pluginOperations-hXYLrzM2.js";import{a as z,i as B,n as V,o as H,r as U,t as ie}from"./pluginCliCommands-DXZfCZsv.js";import{a as W,c as G,i as K,n as q,r as J,s as Y,t as ae}from"./validatePlugin-D6tFo87L.js";import{basename as oe,dirname as X}from"path";e(),T(),M(),L(),y(),ne(),O(),u(),G(),s(),r(),ee(),d(),K(),l(),i(),ae(),re(),j();function Z(e,n){k(e),F(`${t.cross} Failed to ${n}: ${D(e)}`)}function Q(e){e.errors.length>0&&(console.log(`${t.cross} Found ${e.errors.length} ${A(e.errors.length,`error`)}:\n`),e.errors.forEach(e=>{console.log(` ${t.pointer} ${e.path}: ${e.message}`)}),console.log(``)),e.warnings.length>0&&(console.log(`${t.warning} Found ${e.warnings.length} ${A(e.warnings.length,`warning`)}:\n`),e.warnings.forEach(e=>{console.log(` ${t.pointer} ${e.path}: ${e.message}`)}),console.log(``))}async function $(e,n){n.cowork&&w(!0);try{let n=await q(e);console.log(`Validating ${n.fileType} manifest: ${n.filePath}\n`),Q(n);let r=[];if(n.fileType===`plugin`){let e=X(n.filePath);if(oe(e)===`.claude-plugin`){r=await J(X(e));for(let e of r)console.log(`Validating ${e.fileType}: ${e.filePath}\n`),Q(e)}}let i=n.success&&r.every(e=>e.success),a=n.warnings.length>0||r.some(e=>e.warnings.length>0);i?P(a?`${t.tick} Validation passed with warnings`:`${t.tick} Validation passed`):(console.log(`${t.cross} Validation failed`),process.exit(1))}catch(e){k(e),console.error(`${t.cross} Unexpected error during validation: ${D(e)}`),process.exit(2)}}async function se(e){e.cowork&&w(!0),N(`tengu_plugin_list_command`,{});let n=m(),{getPluginEditableScopes:r}=await import(`./pluginStartupCheck-HS1ZceZa.js`),i=r(),s=Object.keys(n.plugins),{enabled:l,disabled:u,errors:d}=await o(),p=[...l,...u],h=p.filter(e=>e.source.endsWith(`@inline`)),g=d.filter(e=>e.source.endsWith(`@inline`)||e.source.startsWith(`inline[`));if(e.json){let t=new Map(p.map(e=>[e.source,e])),r=[];for(let e of s.sort()){let o=n.plugins[e];if(!o||o.length===0)continue;let s=C(e).name,l=d.filter(t=>t.source===e||`plugin`in t&&t.plugin===s).map(c);for(let n of o){let o=t.get(e),s;if(o){let e=o.mcpServers||await a(o);e&&Object.keys(e).length>0&&(s=e)}r.push({id:e,version:n.version||`unknown`,scope:n.scope,enabled:i.has(e),installPath:n.installPath,installedAt:n.installedAt,lastUpdated:n.lastUpdated,projectPath:n.projectPath,mcpServers:s,errors:l.length>0?l:void 0})}}for(let e of h){let t=e.mcpServers||await a(e),n=g.filter(t=>t.source===e.source||`plugin`in t&&t.plugin===e.name).map(c);r.push({id:e.source,version:e.manifest.version??`unknown`,scope:`session`,enabled:e.enabled!==!1,installPath:e.path,mcpServers:t&&Object.keys(t).length>0?t:void 0,errors:n.length>0?n:void 0})}for(let e of g.filter(e=>e.source.startsWith(`inline[`)))r.push({id:e.source,version:`unknown`,scope:`session`,enabled:!1,installPath:`path`in e?e.path:``,errors:[c(e)]});if(e.available){let e=[];try{let[t,n]=await Promise.all([x(),Y()]),{marketplaces:r}=await v(t);for(let{name:t,data:i}of r)if(i)for(let r of i.plugins){let i=S(r.name,t);f(i)||e.push({pluginId:i,name:r.name,description:r.description,marketplaceName:t,version:r.version,source:r.source,installCount:n?.get(i)})}}catch{}P(E({installed:r,available:e},null,2))}else P(E(r,null,2))}s.length===0&&h.length===0&&g.length===0&&P("No plugins installed. Use `claude plugin install` to install a plugin."),s.length>0&&console.log(`Installed plugins:
1
+ import{n as e,t}from"./figures-5ThXQEtq.js";import{Bx as n,Do as r,Fa as i,Fv as a,Ia as o,Ja as s,Kx as c,Lx as l,Mo as u,Pv as d,Qa as f,_o as p,eo as m,fo as h,ho as g,jo as _,ko as v,lo as ee,po as te,qx as y,ro as b,uo as x,xo as S,zx as C}from"./loadAgentsDir-B0Anodo0.js";import{Hn as w,It as T}from"./state-B4jiUise.js";import{C as E,I as ne,M as D,x as re}from"./debug-Bglx1aTu.js";import{o as O,s as k}from"./log-D2TIwHBV.js";import{l as A,o as j}from"./stringUtils-C718f5ey.js";import{n as M,r as N}from"./analytics-DJobLaWP.js";import{n as P,t as F}from"./exit-s9XGerrH.js";import{n as I,s as L,t as R}from"./pluginOperations-CcUSHAIa.js";import{a as z,i as B,n as V,o as H,r as U,t as ie}from"./pluginCliCommands-CJv5uhOG.js";import{a as W,c as G,i as K,n as q,r as J,s as Y,t as ae}from"./validatePlugin-BMSoeb_b.js";import{basename as oe,dirname as X}from"path";e(),T(),M(),L(),y(),ne(),O(),u(),G(),s(),r(),ee(),d(),K(),l(),i(),ae(),re(),j();function Z(e,n){k(e),F(`${t.cross} Failed to ${n}: ${D(e)}`)}function Q(e){e.errors.length>0&&(console.log(`${t.cross} Found ${e.errors.length} ${A(e.errors.length,`error`)}:\n`),e.errors.forEach(e=>{console.log(` ${t.pointer} ${e.path}: ${e.message}`)}),console.log(``)),e.warnings.length>0&&(console.log(`${t.warning} Found ${e.warnings.length} ${A(e.warnings.length,`warning`)}:\n`),e.warnings.forEach(e=>{console.log(` ${t.pointer} ${e.path}: ${e.message}`)}),console.log(``))}async function $(e,n){n.cowork&&w(!0);try{let n=await q(e);console.log(`Validating ${n.fileType} manifest: ${n.filePath}\n`),Q(n);let r=[];if(n.fileType===`plugin`){let e=X(n.filePath);if(oe(e)===`.claude-plugin`){r=await J(X(e));for(let e of r)console.log(`Validating ${e.fileType}: ${e.filePath}\n`),Q(e)}}let i=n.success&&r.every(e=>e.success),a=n.warnings.length>0||r.some(e=>e.warnings.length>0);i?P(a?`${t.tick} Validation passed with warnings`:`${t.tick} Validation passed`):(console.log(`${t.cross} Validation failed`),process.exit(1))}catch(e){k(e),console.error(`${t.cross} Unexpected error during validation: ${D(e)}`),process.exit(2)}}async function se(e){e.cowork&&w(!0),N(`tengu_plugin_list_command`,{});let n=m(),{getPluginEditableScopes:r}=await import(`./pluginStartupCheck-CRBUO9gP.js`),i=r(),s=Object.keys(n.plugins),{enabled:l,disabled:u,errors:d}=await o(),p=[...l,...u],h=p.filter(e=>e.source.endsWith(`@inline`)),g=d.filter(e=>e.source.endsWith(`@inline`)||e.source.startsWith(`inline[`));if(e.json){let t=new Map(p.map(e=>[e.source,e])),r=[];for(let e of s.sort()){let o=n.plugins[e];if(!o||o.length===0)continue;let s=C(e).name,l=d.filter(t=>t.source===e||`plugin`in t&&t.plugin===s).map(c);for(let n of o){let o=t.get(e),s;if(o){let e=o.mcpServers||await a(o);e&&Object.keys(e).length>0&&(s=e)}r.push({id:e,version:n.version||`unknown`,scope:n.scope,enabled:i.has(e),installPath:n.installPath,installedAt:n.installedAt,lastUpdated:n.lastUpdated,projectPath:n.projectPath,mcpServers:s,errors:l.length>0?l:void 0})}}for(let e of h){let t=e.mcpServers||await a(e),n=g.filter(t=>t.source===e.source||`plugin`in t&&t.plugin===e.name).map(c);r.push({id:e.source,version:e.manifest.version??`unknown`,scope:`session`,enabled:e.enabled!==!1,installPath:e.path,mcpServers:t&&Object.keys(t).length>0?t:void 0,errors:n.length>0?n:void 0})}for(let e of g.filter(e=>e.source.startsWith(`inline[`)))r.push({id:e.source,version:`unknown`,scope:`session`,enabled:!1,installPath:`path`in e?e.path:``,errors:[c(e)]});if(e.available){let e=[];try{let[t,n]=await Promise.all([x(),Y()]),{marketplaces:r}=await v(t);for(let{name:t,data:i}of r)if(i)for(let r of i.plugins){let i=S(r.name,t);f(i)||e.push({pluginId:i,name:r.name,description:r.description,marketplaceName:t,version:r.version,source:r.source,installCount:n?.get(i)})}}catch{}P(E({installed:r,available:e},null,2))}else P(E(r,null,2))}s.length===0&&h.length===0&&g.length===0&&P("No plugins installed. Use `claude plugin install` to install a plugin."),s.length>0&&console.log(`Installed plugins:
2
2
  `);for(let e of s.sort()){let r=n.plugins[e];if(!r||r.length===0)continue;let a=C(e).name,o=d.filter(t=>t.source===e||`plugin`in t&&t.plugin===a);for(let n of r){let r=i.has(e),a=o.length>0?`${t.cross} failed to load`:r?`${t.tick} enabled`:`${t.cross} disabled`,s=n.version||`unknown`,l=n.scope;console.log(` ${t.pointer} ${e}`),console.log(` Version: ${s}`),console.log(` Scope: ${l}`),console.log(` Status: ${a}`);for(let e of o)console.log(` Error: ${c(e)}`);console.log(``)}}if(h.length>0||g.length>0){console.log(`Session-only plugins (--plugin-dir):
3
3
  `);for(let e of h){let n=g.filter(t=>t.source===e.source||`plugin`in t&&t.plugin===e.name),r=n.length>0?`${t.cross} loaded with errors`:`${t.tick} loaded`;console.log(` ${t.pointer} ${e.source}`),console.log(` Version: ${e.manifest.version??`unknown`}`),console.log(` Path: ${e.path}`),console.log(` Status: ${r}`);for(let e of n)console.log(` Error: ${c(e)}`);console.log(``)}for(let e of g.filter(e=>e.source.startsWith(`inline[`)))console.log(` ${t.pointer} ${e.source}: ${t.cross} ${c(e)}\n`)}P()}async function ce(e,r){r.cowork&&w(!0);try{let i=await W(e);i||F(`${t.cross} Invalid marketplace source format. Try: owner/repo, https://..., or ./path`),`error`in i&&F(`${t.cross} ${i.error}`);let a=r.scope??`user`;a!==`user`&&a!==`project`&&a!==`local`&&F(`${t.cross} Invalid scope '${a}'. Use: user, project, or local`);let o=n(a),s=i;r.sparse&&r.sparse.length>0&&(s.source===`github`||s.source===`git`?s={...s,sparsePaths:r.sparse}:F(`${t.cross} --sparse is only supported for github and git marketplace sources (got: ${s.source})`)),console.log(`Adding marketplace...`);let{name:c,alreadyMaterialized:l,resolvedSource:u}=await b(s,e=>{console.log(e)});p(c,{source:u},o),_();let d=s.source;s.source===`github`&&(d=s.repo),N(`tengu_marketplace_added`,{source_type:d}),P(l?`${t.tick} Marketplace '${c}' already on disk — declared in ${a} settings`:`${t.tick} Successfully added marketplace: ${c} (declared in ${a} settings)`)}catch(e){Z(e,`add marketplace`)}}async function le(e){e.cowork&&w(!0);try{let n=await x(),r=Object.keys(n);e.json&&P(E(r.sort().map(e=>{let t=n[e],r=t?.source;return{name:e,source:r?.source,...r?.source===`github`&&{repo:r.repo},...r?.source===`git`&&{url:r.url},...r?.source===`url`&&{url:r.url},...r?.source===`directory`&&{path:r.path},...r?.source===`file`&&{path:r.path},installLocation:t?.installLocation}}),null,2)),r.length===0&&P(`No marketplaces configured`),console.log(`Configured marketplaces:
4
4
  `),r.forEach(e=>{let r=n[e];if(console.log(` ${t.pointer} ${e}`),r?.source){let e=r.source;e.source===`github`?console.log(` Source: GitHub (${e.repo})`):e.source===`git`?console.log(` Source: Git (${e.url})`):e.source===`url`?console.log(` Source: URL (${e.url})`):e.source===`directory`?console.log(` Source: Directory (${e.path})`):e.source===`file`&&console.log(` Source: File (${e.path})`)}console.log(``)}),P()}catch(e){Z(e,`list marketplaces`)}}async function ue(e,n){n.cowork&&w(!0);try{await g(e),_(),N(`tengu_marketplace_removed`,{marketplace_name:e}),P(`${t.tick} Successfully removed marketplace: ${e}`)}catch(e){Z(e,`remove marketplace`)}}async function de(e,n){n.cowork&&w(!0);try{if(e)console.log(`Updating marketplace: ${e}...`),await te(e,e=>{console.log(e)}),_(),N(`tengu_marketplace_updated`,{marketplace_name:e}),P(`${t.tick} Successfully updated marketplace: ${e}`);else{let e=await x(),n=Object.keys(e);n.length===0&&P(`No marketplaces configured`),console.log(`Updating ${n.length} marketplace(s)...`),await h(),_(),N(`tengu_marketplace_updated_all`,{count:n.length}),P(`${t.tick} Successfully updated ${n.length} marketplace(s)`)}}catch(e){Z(e,`update marketplace(s)`)}}async function fe(e,t){t.cowork&&w(!0);let n=t.scope||`user`;t.cowork&&n!==`user`&&F(`--cowork can only be used with user scope`),R.includes(n)||F(`Invalid scope: ${n}. Must be one of: ${R.join(`, `)}.`);let{name:r,marketplace:i}=C(e);N(`tengu_plugin_install_command`,{_PROTO_plugin_name:r,...i&&{_PROTO_marketplace_name:i},scope:n}),await B(e,n)}async function pe(e,t){t.cowork&&w(!0);let n=t.scope||`user`;t.cowork&&n!==`user`&&F(`--cowork can only be used with user scope`),R.includes(n)||F(`Invalid scope: ${n}. Must be one of: ${R.join(`, `)}.`);let{name:r,marketplace:i}=C(e);N(`tengu_plugin_uninstall_command`,{_PROTO_plugin_name:r,...i&&{_PROTO_marketplace_name:i},scope:n}),await z(e,n,t.keepData)}async function me(e,t){t.cowork&&w(!0);let n;t.scope&&(R.includes(t.scope)||F(`Invalid scope "${t.scope}". Valid scopes: ${R.join(`, `)}`),n=t.scope),t.cowork&&n!==void 0&&n!==`user`&&F(`--cowork can only be used with user scope`),t.cowork&&n===void 0&&(n=`user`);let{name:r,marketplace:i}=C(e);N(`tengu_plugin_enable_command`,{_PROTO_plugin_name:r,...i&&{_PROTO_marketplace_name:i},scope:n??`auto`}),await U(e,n)}async function he(e,t){if(t.all&&e&&F(`Cannot use --all with a specific plugin`),!t.all&&!e&&F(`Please specify a plugin name or use --all to disable all plugins`),t.cowork&&w(!0),t.all){t.scope&&F(`Cannot use --scope with --all`),N(`tengu_plugin_disable_command`,{}),await ie();return}let n;t.scope&&(R.includes(t.scope)||F(`Invalid scope "${t.scope}". Valid scopes: ${R.join(`, `)}`),n=t.scope),t.cowork&&n!==void 0&&n!==`user`&&F(`--cowork can only be used with user scope`),t.cowork&&n===void 0&&(n=`user`);let{name:r,marketplace:i}=C(e);N(`tengu_plugin_disable_command`,{_PROTO_plugin_name:r,...i&&{_PROTO_marketplace_name:i},scope:n??`auto`}),await V(e,n)}async function ge(e,t){t.cowork&&w(!0);let{name:n,marketplace:r}=C(e);N(`tengu_plugin_update_command`,{_PROTO_plugin_name:n,...r&&{_PROTO_marketplace_name:r}});let i=`user`;t.scope&&(I.includes(t.scope)||F(`Invalid scope "${t.scope}". Valid scopes: ${I.join(`, `)}`),i=t.scope),t.cowork&&i!==`user`&&F(`--cowork can only be used with user scope`),await H(e,i)}export{ce as marketplaceAddHandler,le as marketplaceListHandler,ue as marketplaceRemoveHandler,de as marketplaceUpdateHandler,he as pluginDisableHandler,me as pluginEnableHandler,fe as pluginInstallHandler,se as pluginListHandler,pe as pluginUninstallHandler,ge as pluginUpdateHandler,$ as pluginValidateHandler};
@@ -1,4 +1,4 @@
1
- import{c as e,l as t,o as n,s as r}from"./envUtils-DfkgIdYf.js";import{n as i,t as a}from"./defineProperty-C-QyHrDq.js";import{_t as o,vt as s}from"./esm-eTAUP-La.js";import{$_ as c,$d as l,$m as u,$p as d,$r as f,$v as p,A as m,Ag as h,Al as g,As as ee,B as _,Bl as te,Bo as ne,Bp as re,Bt as v,By as y,C as ie,CC as b,Cc as x,Cg as S,Cn as C,Cv as ae,Cy as oe,D_ as se,Dm as ce,Dv as w,E_ as le,Ec as ue,Ei as de,Fa as fe,Fl as pe,Fo as me,GC as he,Ho as ge,Hs as _e,Id as ve,Ig as ye,Il as be,Io as T,K_ as xe,Kn as Se,Ku as Ce,La as we,Ld as Te,Lo as Ee,Ls as De,Mv as Oe,Mw as ke,Ng as Ae,Ni as E,Ns as je,OC as Me,Oa as Ne,Og as Pe,Oi as Fe,PS as Ie,Pi as Le,Pl as Re,Po as ze,Qd as Be,Qm as Ve,Qp as He,Ro as Ue,Rr as We,Rs as Ge,Sc as Ke,Sg as qe,Sn as Je,Ss as Ye,Sv as Xe,T_ as Ze,Tm as Qe,Ty as $e,Uo as et,Us as tt,V as nt,Vo as D,Vp as O,WC as rt,W_ as it,Wu as at,XC as ot,X_ as st,Xd as k,Xn as ct,Xr as lt,YC as ut,Yi as dt,Zd as ft,Zp as pt,Zr as mt,Zv as ht,_c as gt,_g as _t,_i as vt,_r as yt,af as bt,ao as xt,b as St,bc as Ct,bg as wt,bm as Tt,bn as Et,bs as Dt,cs as Ot,do as kt,ef as At,eh as jt,ei as Mt,ey as Nt,f as Pt,gC as Ft,gc as It,gg as Lt,gi as A,gu as Rt,gv as zt,hi as Bt,hu as Vt,if as Ht,im as Ut,io as Wt,ja as Gt,jl as Kt,jm as qt,js as Jt,kC as Yt,ka as Xt,kg as Zt,km as Qt,ks as $t,lf as en,lo as tn,lp as nn,ls as rn,mc as an,mn as on,mo as sn,nf as cn,nv as ln,ny as un,o as dn,of as fn,os as pn,pc as mn,pv as hn,qC as gn,q_ as _n,rf as vn,rm as yn,rv as bn,s as xn,sC as Sn,sS as Cn,ss as wn,tf as Tn,th as En,tv as Dn,ty as On,up as kn,v as An,vg as jn,vi as Mn,vn as Nn,w as Pn,wC as Fn,wg as In,wi as Ln,wm as Rn,wv as zn,xc as Bn,xm as Vn,xn as Hn,y as Un,yC as Wn,yc as Gn,yn as Kn,zl as qn,zo as Jn,zt as Yn}from"./loadAgentsDir-DlPbtIsS.js";import{$ as j,A as M,B as Xn,F as N,G as P,L as Zn,N as Qn,P as F,Q as I,S as L,V as R,W as z,Y as B,Z as V,f as $n,j as er,l as tr,o as nr,s as H,x as rr}from"./types-Dx7P7JLQ.js";import{G as ir,It as ar,Lt as or,Pn as sr,Wn as cr,Wt as lr,bn as ur,cn as dr,in as fr,j as pr,k as mr,st as U,xn as hr}from"./state-B4jiUise.js";import{n as gr,t as _r}from"./cwd-Pa83R95t.js";import{$ as vr,C as W,E as yr,I as br,M as G,S as xr,V as Sr,c as K,et as Cr,f as wr,i as q,u as Tr,x as Er}from"./debug-Bglx1aTu.js";import{Hn as Dr,W as Or,Wn as kr,Xr as Ar,Yr as jr,Zr as Mr,_t as Nr,d as Pr,er as Fr,h as Ir,nr as Lr,rt as Rr,tt as zr,u as Br,ut as Vr}from"./settings-B2jvL8Dp.js";import{O as Hr,j as Ur}from"./config-C-Y2qtB2.js";import{i as Wr,n as Gr,o as Kr}from"./process-gEbdy6uY.js";import{H as qr,c as Jr,i as Yr,o as Xr,q as Zr,s as J}from"./log-D2TIwHBV.js";import{n as Qr,r as $r}from"./analytics-DJobLaWP.js";import{G as ei,H as ti,Jt as ni,K as ri,L as ii,U as ai,Yt as oi,Zt as si,_ as ci,d as li,et as ui,h as di,n as fi,nt as pi,o as mi,qt as hi}from"./model-BwBG0V1u.js";import{_t as gi,at as _i,bn as vi,it as yi,tn as bi,vn as xi,vt as Si,yt as Ci}from"./prompt-mM79EGnT.js";import{i as wi,n as Ti,r as Ei,t as Di}from"./reject-Bld5E-bn.js";import{h as Oi,m as ki}from"./firstPartyEventLogger-M6UMli2c.js";import{t as Ai}from"./pluginBlocklist-q01ackCf.js";import{n as ji,t as Mi}from"./toolPool-CX5wDBi1.js";import{n as Ni}from"./conversationRecovery-2ft8sCPE.js";import{a as Pi,i as Fi,n as Ii,r as Li}from"./QueryEngine-DYxBjJ4i.js";import{n as Ri,r as zi}from"./sessionTitle-k4wpUS5l.js";import{n as Bi,r as Vi}from"./sideQuestion-DLJxyrlp.js";import{a as Hi,n as Ui}from"./grove-O6qp7ITR.js";import{n as Wi,r as Gi}from"./context-noninteractive-Dd4xIoP1.js";import{n as Ki,r as qi}from"./modelOptions-DRaG3bo0.js";import{a as Ji,o as Yi,t as Xi}from"./skillChangeDetector-xviGstqm.js";import{n as Zi}from"./reconciler-CeXqh95g.js";import{n as Qi,t as $i}from"./refresh-Ce2yk28a.js";import{dirname as ea,join as ta}from"path";import{randomUUID as Y}from"crypto";import{readFile as na,stat as ra}from"fs/promises";import{cwd as X}from"process";rr(),nr();var ia=H(()=>P({inputTokens:z(),outputTokens:z(),cacheReadInputTokens:z(),cacheCreationInputTokens:z(),webSearchRequests:z(),costUSD:z(),contextWindow:z(),maxOutputTokens:z()})),aa=H(()=>R(`json_schema`));H(()=>P({type:aa()}));var oa=H(()=>P({type:R(`json_schema`),schema:B(V(),j())}));H(()=>oa());var sa=H(()=>M([`user`,`project`,`org`,`temporary`,`oauth`]));H(()=>M([`local`,`user`,`project`]).describe(`Config scope for settings.`)),H(()=>R(`context-1m-2025-08-07`));var ca=H(()=>P({type:R(`adaptive`)}).describe(`Work Mate decides when and how much to think (Opus 4.6+).`)),la=H(()=>P({type:R(`enabled`),budgetTokens:z().optional()}).describe(`Fixed thinking token budget (older models)`)),ua=H(()=>P({type:R(`disabled`)}).describe(`No extended thinking`));H(()=>I([ca(),la(),ua()]).describe(`Controls Work Mate's thinking/reasoning behavior. When set, takes precedence over the deprecated maxThinkingTokens.`));var da=H(()=>P({type:R(`stdio`).optional(),command:V(),args:F(V()).optional(),env:B(V(),V()).optional()})),fa=H(()=>P({type:R(`sse`),url:V(),headers:B(V(),V()).optional()})),pa=H(()=>P({type:R(`http`),url:V(),headers:B(V(),V()).optional()})),ma=H(()=>P({type:R(`sdk`),name:V()})),ha=H(()=>I([da(),fa(),pa(),ma()])),ga=H(()=>P({type:R(`claudeai-proxy`),url:V(),id:V()})),_a=H(()=>I([ha(),ga()])),va=H(()=>P({name:V().describe(`Server name as configured`),status:M([`connected`,`failed`,`needs-auth`,`pending`,`disabled`]).describe(`Current connection status`),serverInfo:P({name:V(),version:V()}).optional().describe(`Server information (available when connected)`),error:V().optional().describe(`Error message (available when status is 'failed')`),config:_a().optional().describe(`Server configuration (includes URL for HTTP/SSE servers)`),scope:V().optional().describe(`Configuration scope (e.g., project, user, local, claudeai, managed)`),tools:F(P({name:V(),description:V().optional(),annotations:P({readOnly:N().optional(),destructive:N().optional(),openWorld:N().optional()}).optional()})).optional().describe(`Tools provided by this server (available when connected)`),capabilities:P({experimental:B(V(),j()).optional()}).optional().describe(`@internal Server capabilities (available when connected). experimental['claude/channel'] is only present if the server's plugin is on the approved channels allowlist — use its presence to decide whether to show an Enable-channel prompt.`)}).describe(`Status information for an MCP server connection.`));H(()=>P({added:F(V()).describe(`Names of servers that were added`),removed:F(V()).describe(`Names of servers that were removed`),errors:B(V(),V()).describe(`Map of server names to error messages for servers that failed to connect`)}).describe(`Result of a setMcpServers operation.`));var ya=H(()=>M([`userSettings`,`projectSettings`,`localSettings`,`session`,`cliArg`])),ba=H(()=>M([`allow`,`deny`,`ask`])),xa=H(()=>P({toolName:V(),ruleContent:V().optional()})),Sa=H(()=>Zn(`type`,[P({type:R(`addRules`),rules:F(xa()),behavior:ba(),destination:ya()}),P({type:R(`replaceRules`),rules:F(xa()),behavior:ba(),destination:ya()}),P({type:R(`removeRules`),rules:F(xa()),behavior:ba(),destination:ya()}),P({type:R(`setMode`),mode:Xn(()=>wa()),destination:ya()}),P({type:R(`addDirectories`),directories:F(V()),destination:ya()}),P({type:R(`removeDirectories`),directories:F(V()),destination:ya()})])),Ca=H(()=>M([`user_temporary`,`user_permanent`,`user_reject`]).describe(`Classification of this permission decision for telemetry. SDK hosts that prompt users (desktop apps, IDEs) should set this to reflect what actually happened: user_temporary for allow-once, user_permanent for always-allow (both the click and later cache hits), user_reject for deny. If unset, the CLI infers conservatively (temporary for allow, reject for deny). The vocabulary matches tool_decision OTel events (monitoring-usage docs).`));H(()=>I([P({behavior:R(`allow`),updatedInput:B(V(),j()).optional(),updatedPermissions:F(Sa()).optional(),toolUseID:V().optional(),decisionClassification:Ca().optional()}),P({behavior:R(`deny`),message:V(),interrupt:N().optional(),toolUseID:V().optional(),decisionClassification:Ca().optional()})]));var wa=H(()=>M([`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).`)),Ta=`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(`.`),Ea=H(()=>M(Ta)),Z=H(()=>P({session_id:V(),transcript_path:V(),cwd:V(),permission_mode:V().optional(),agent_id:V().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:V().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).`)})),Da=H(()=>Z().and(P({hook_event_name:R(`PreToolUse`),tool_name:V(),tool_input:j(),tool_use_id:V()}))),Oa=H(()=>Z().and(P({hook_event_name:R(`PermissionRequest`),tool_name:V(),tool_input:j(),permission_suggestions:F(Sa()).optional()}))),ka=H(()=>Z().and(P({hook_event_name:R(`PostToolUse`),tool_name:V(),tool_input:j(),tool_response:j(),tool_use_id:V()}))),Aa=H(()=>Z().and(P({hook_event_name:R(`PostToolUseFailure`),tool_name:V(),tool_input:j(),tool_use_id:V(),error:V(),is_interrupt:N().optional()}))),ja=H(()=>Z().and(P({hook_event_name:R(`PermissionDenied`),tool_name:V(),tool_input:j(),tool_use_id:V(),reason:V()}))),Ma=H(()=>Z().and(P({hook_event_name:R(`Notification`),message:V(),title:V().optional(),notification_type:V()}))),Na=H(()=>Z().and(P({hook_event_name:R(`UserPromptSubmit`),prompt:V()}))),Pa=H(()=>Z().and(P({hook_event_name:R(`SessionStart`),source:M([`startup`,`resume`,`clear`,`compact`]),agent_type:V().optional(),model:V().optional()}))),Fa=H(()=>Z().and(P({hook_event_name:R(`Setup`),trigger:M([`init`,`maintenance`])}))),Ia=H(()=>Z().and(P({hook_event_name:R(`Stop`),stop_hook_active:N(),last_assistant_message:V().optional().describe(`Text content of the last assistant message before stopping. Avoids the need to read and parse the transcript file.`)}))),La=H(()=>Z().and(P({hook_event_name:R(`StopFailure`),error:Fo(),error_details:V().optional(),last_assistant_message:V().optional()}))),Ra=H(()=>Z().and(P({hook_event_name:R(`SubagentStart`),agent_id:V(),agent_type:V()}))),za=H(()=>Z().and(P({hook_event_name:R(`SubagentStop`),stop_hook_active:N(),agent_id:V(),agent_transcript_path:V(),agent_type:V(),last_assistant_message:V().optional().describe(`Text content of the last assistant message before stopping. Avoids the need to read and parse the transcript file.`)}))),Ba=H(()=>Z().and(P({hook_event_name:R(`PreCompact`),trigger:M([`manual`,`auto`]),custom_instructions:V().nullable()}))),Va=H(()=>Z().and(P({hook_event_name:R(`PostCompact`),trigger:M([`manual`,`auto`]),compact_summary:V().describe(`The conversation summary produced by compaction`)}))),Ha=H(()=>Z().and(P({hook_event_name:R(`TeammateIdle`),teammate_name:V(),team_name:V()}))),Ua=H(()=>Z().and(P({hook_event_name:R(`TaskCreated`),task_id:V(),task_subject:V(),task_description:V().optional(),teammate_name:V().optional(),team_name:V().optional()}))),Wa=H(()=>Z().and(P({hook_event_name:R(`TaskCompleted`),task_id:V(),task_subject:V(),task_description:V().optional(),teammate_name:V().optional(),team_name:V().optional()}))),Ga=H(()=>Z().and(P({hook_event_name:R(`Elicitation`),mcp_server_name:V(),message:V(),mode:M([`form`,`url`]).optional(),url:V().optional(),elicitation_id:V().optional(),requested_schema:B(V(),j()).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.`)),Ka=H(()=>Z().and(P({hook_event_name:R(`ElicitationResult`),mcp_server_name:V(),elicitation_id:V().optional(),mode:M([`form`,`url`]).optional(),action:M([`accept`,`decline`,`cancel`]),content:B(V(),j()).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.`)),qa=[`user_settings`,`project_settings`,`local_settings`,`policy_settings`,`skills`],Ja=H(()=>Z().and(P({hook_event_name:R(`ConfigChange`),source:M(qa),file_path:V().optional()}))),Ya=[`session_start`,`nested_traversal`,`path_glob_match`,`include`,`compact`],Xa=[`User`,`Project`,`Local`,`Managed`],Za=H(()=>Z().and(P({hook_event_name:R(`InstructionsLoaded`),file_path:V(),memory_type:M(Xa),load_reason:M(Ya),globs:F(V()).optional(),trigger_file_path:V().optional(),parent_file_path:V().optional()}))),Qa=H(()=>Z().and(P({hook_event_name:R(`WorktreeCreate`),name:V()}))),$a=H(()=>Z().and(P({hook_event_name:R(`WorktreeRemove`),worktree_path:V()}))),eo=H(()=>Z().and(P({hook_event_name:R(`CwdChanged`),old_cwd:V(),new_cwd:V()}))),to=H(()=>Z().and(P({hook_event_name:R(`FileChanged`),file_path:V(),event:M([`change`,`add`,`unlink`])}))),no=[`clear`,`resume`,`prompt_input_exit`,`other`,`bypass_permissions_disabled`],ro=H(()=>M(no)),io=H(()=>Z().and(P({hook_event_name:R(`SessionEnd`),reason:ro()}))),ao=H(()=>I([Da(),ka(),Aa(),ja(),Ma(),Na(),Pa(),io(),Ia(),La(),Ra(),za(),Ba(),Va(),Oa(),Fa(),Ha(),Ua(),Wa(),Ga(),Ka(),Ja(),Za(),Qa(),$a(),eo(),to()])),oo=H(()=>P({async:R(!0),asyncTimeout:z().optional()})),so=H(()=>P({hookEventName:R(`PreToolUse`),permissionDecision:ba().optional(),permissionDecisionReason:V().optional(),updatedInput:B(V(),j()).optional(),additionalContext:V().optional()})),co=H(()=>P({hookEventName:R(`UserPromptSubmit`),additionalContext:V().optional()})),lo=H(()=>P({hookEventName:R(`SessionStart`),additionalContext:V().optional(),initialUserMessage:V().optional(),watchPaths:F(V()).optional()})),uo=H(()=>P({hookEventName:R(`Setup`),additionalContext:V().optional()})),fo=H(()=>P({hookEventName:R(`SubagentStart`),additionalContext:V().optional()})),po=H(()=>P({hookEventName:R(`PostToolUse`),additionalContext:V().optional(),updatedMCPToolOutput:j().optional()})),mo=H(()=>P({hookEventName:R(`PostToolUseFailure`),additionalContext:V().optional()})),ho=H(()=>P({hookEventName:R(`PermissionDenied`),retry:N().optional()})),go=H(()=>P({hookEventName:R(`Notification`),additionalContext:V().optional()})),_o=H(()=>P({hookEventName:R(`PermissionRequest`),decision:I([P({behavior:R(`allow`),updatedInput:B(V(),j()).optional(),updatedPermissions:F(Sa()).optional()}),P({behavior:R(`deny`),message:V().optional(),interrupt:N().optional()})])})),vo=H(()=>P({hookEventName:R(`CwdChanged`),watchPaths:F(V()).optional()})),yo=H(()=>P({hookEventName:R(`FileChanged`),watchPaths:F(V()).optional()})),bo=H(()=>P({continue:N().optional(),suppressOutput:N().optional(),stopReason:V().optional(),decision:M([`approve`,`block`]).optional(),systemMessage:V().optional(),reason:V().optional(),hookSpecificOutput:I([so(),co(),lo(),uo(),fo(),po(),mo(),ho(),go(),_o(),xo(),So(),vo(),yo(),Co()]).optional()})),xo=H(()=>P({hookEventName:R(`Elicitation`),action:M([`accept`,`decline`,`cancel`]).optional(),content:B(V(),j()).optional()}).describe(`Hook-specific output for the Elicitation event. Return this to programmatically accept or decline an MCP elicitation request.`)),So=H(()=>P({hookEventName:R(`ElicitationResult`),action:M([`accept`,`decline`,`cancel`]).optional(),content:B(V(),j()).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.`)),Co=H(()=>P({hookEventName:R(`WorktreeCreate`),worktreePath:V()}).describe(`Hook-specific output for the WorktreeCreate event. Provides the absolute path to the created worktree directory. Command hooks print the path on stdout instead.`));H(()=>I([oo(),bo()]));var wo=H(()=>P({key:V().describe(`Unique key for this option, returned in the response`),label:V().describe(`Display text for this option`),description:V().optional().describe(`Optional description shown below the label`)}));H(()=>P({prompt:V().describe(`Request ID. Presence of this key marks the line as a prompt request.`),message:V().describe(`The prompt message to display to the user`),options:F(wo()).describe(`Available options for the user to choose from`)})),H(()=>P({prompt_response:V().describe(`The request ID from the corresponding prompt request`),selected:V().describe(`The key of the selected option`)}));var To=H(()=>P({name:V().describe(`Skill name (without the leading slash)`),description:V().describe(`Description of what the skill does`),argumentHint:V().describe(`Hint for skill arguments (e.g., "<file>")`)}).describe(`Information about an available skill (invoked via /command syntax).`)),Eo=H(()=>P({name:V().describe(`Agent type identifier (e.g., "Explore")`),description:V().describe(`Description of when to use this agent`),model:V().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.`)),Do=H(()=>P({value:V().describe(`Model identifier to use in API calls`),displayName:V().describe(`Human-readable display name`),description:V().describe(`Description of the model's capabilities`),supportsAdaptiveThinking:N().optional().describe(`Whether this model supports adaptive thinking (Work Mate decides when and how much to think)`),supportsFastMode:N().optional().describe(`Whether this model supports fast mode`),supportsAutoMode:N().optional().describe(`Whether this model supports auto mode`)}).describe(`Information about an available model.`)),Oo=H(()=>P({email:V().optional(),organization:V().optional(),subscriptionType:V().optional(),tokenSource:V().optional(),apiKeySource:V().optional(),apiProvider:M([`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.`)),ko=H(()=>I([V(),B(V(),ha())])),Ao=H(()=>P({description:V().describe(`Natural language description of when to use this agent`),tools:F(V()).optional().describe(`Array of allowed tool names. If omitted, inherits all tools from parent`),disallowedTools:F(V()).optional().describe(`Array of tool names to explicitly disallow for this agent`),prompt:V().describe(`The agent's system prompt`),model:V().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:F(ko()).optional(),criticalSystemReminder_EXPERIMENTAL:V().optional().describe(`Experimental: Critical reminder added to system prompt`),skills:F(V()).optional().describe(`Array of skill names to preload into the agent context`),initialPrompt:V().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:z().int().positive().optional().describe(`Maximum number of agentic turns (API round-trips) before stopping`),background:N().optional().describe(`Run this agent as a background task (non-blocking, fire-and-forget) when invoked`),memory:M([`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:wa().optional().describe(`Permission mode controlling how tool executions are handled`)}).describe(`Definition for a custom subagent that can be invoked via the Agent tool.`));H(()=>M([`user`,`project`,`local`]).describe(`Source for loading filesystem-based settings. 'user' - Global user settings (~/.workmate/settings.json). 'project' - Project settings (.workmate/settings.json). 'local' - Local settings (.workmate/settings.local.json).`)),H(()=>P({type:R(`local`).describe(`Plugin type. Currently only 'local' is supported`),path:V().describe(`Absolute or relative path to the plugin directory`)}).describe(`Configuration for loading a plugin.`)),H(()=>P({canRewind:N(),error:V().optional(),filesChanged:F(V()).optional(),insertions:z().optional(),deletions:z().optional()}).describe(`Result of a rewindFiles operation.`));var jo=H(()=>j()),Mo=H(()=>j()),No=H(()=>j()),Q=H(()=>V()),Po=H(()=>j()),Fo=H(()=>M([`authentication_failed`,`billing_error`,`rate_limit`,`invalid_request`,`server_error`,`unknown`,`max_output_tokens`])),Io=H(()=>I([R(`compacting`),er()])),Lo=H(()=>P({type:R(`user`),message:jo(),parent_tool_use_id:V().nullable(),isSynthetic:N().optional(),tool_use_result:j().optional(),priority:M([`now`,`next`,`later`]).optional(),timestamp:V().optional().describe(`ISO timestamp when the message was created on the originating process. Older emitters omit it; consumers should fall back to receive time.`)})),Ro=H(()=>Lo().extend({uuid:Q().optional(),session_id:V().optional()})),zo=H(()=>Lo().extend({uuid:Q(),session_id:V(),isReplay:R(!0)})),Bo=H(()=>P({status:M([`allowed`,`allowed_warning`,`rejected`]),resetsAt:z().optional(),rateLimitType:M([`five_hour`,`seven_day`,`seven_day_opus`,`seven_day_sonnet`,`overage`]).optional(),utilization:z().optional(),overageStatus:M([`allowed`,`allowed_warning`,`rejected`]).optional(),overageResetsAt:z().optional(),overageDisabledReason:M([`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:N().optional(),surpassedThreshold:z().optional()}).describe(`Rate limit information for claude.ai subscription users.`)),Vo=H(()=>P({type:R(`assistant`),message:Mo(),parent_tool_use_id:V().nullable(),error:Fo().optional(),uuid:Q(),session_id:V()})),Ho=H(()=>P({type:R(`rate_limit_event`),rate_limit_info:Bo(),uuid:Q(),session_id:V()}).describe(`Rate limit event emitted when rate limit info changes.`)),Uo=H(()=>P({type:R(`streamlined_text`),text:V().describe(`Text content preserved from the assistant message`),session_id:V(),uuid:Q()}).describe(`@internal Streamlined text message - replaces SDKAssistantMessage in streamlined output. Text content preserved, thinking and tool_use blocks removed.`)),Wo=H(()=>P({type:R(`streamlined_tool_use_summary`),tool_summary:V().describe(`Summary of tool calls (e.g., "Read 2 files, wrote 1 file")`),session_id:V(),uuid:Q()}).describe(`@internal Streamlined tool use summary - replaces tool_use blocks in streamlined output with a cumulative summary string.`)),Go=H(()=>P({tool_name:V(),tool_use_id:V(),tool_input:B(V(),j())})),Ko=H(()=>P({type:R(`result`),subtype:R(`success`),duration_ms:z(),duration_api_ms:z(),is_error:N(),num_turns:z(),result:V(),stop_reason:V().nullable(),total_cost_usd:z(),usage:Po(),modelUsage:B(V(),ia()),permission_denials:F(Go()),structured_output:j().optional(),fast_mode_state:gs().optional(),uuid:Q(),session_id:V()})),qo=H(()=>P({type:R(`result`),subtype:M([`error_during_execution`,`error_max_turns`,`error_max_budget_usd`,`error_max_structured_output_retries`]),duration_ms:z(),duration_api_ms:z(),is_error:N(),num_turns:z(),stop_reason:V().nullable(),total_cost_usd:z(),usage:Po(),modelUsage:B(V(),ia()),permission_denials:F(Go()),errors:F(V()),fast_mode_state:gs().optional(),uuid:Q(),session_id:V()})),Jo=H(()=>I([Ko(),qo()])),Yo=H(()=>P({type:R(`system`),subtype:R(`init`),agents:F(V()).optional(),apiKeySource:sa(),betas:F(V()).optional(),claude_code_version:V(),cwd:V(),tools:F(V()),mcp_servers:F(P({name:V(),status:V()})),model:V(),permissionMode:wa(),slash_commands:F(V()),output_style:V(),skills:F(V()),plugins:F(P({name:V(),path:V(),source:V().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:gs().optional(),uuid:Q(),session_id:V()})),Xo=H(()=>P({type:R(`stream_event`),event:No(),parent_tool_use_id:V().nullable(),uuid:Q(),session_id:V()})),Zo=H(()=>P({type:R(`system`),subtype:R(`compact_boundary`),compact_metadata:P({trigger:M([`manual`,`auto`]),pre_tokens:z(),preserved_segment:P({head_uuid:Q(),anchor_uuid:Q(),tail_uuid:Q()}).optional().describe(`Relink info for messagesToKeep. Loaders splice the preserved segment at anchor_uuid (summary for suffix-preserving, boundary for prefix-preserving partial compact) so resume includes preserved content. Unset when compaction summarizes everything (no messagesToKeep).`)}),uuid:Q(),session_id:V()})),Qo=H(()=>P({type:R(`system`),subtype:R(`status`),status:Io(),permissionMode:wa().optional(),uuid:Q(),session_id:V()})),$o=H(()=>P({type:R(`system`),subtype:R(`post_turn_summary`),summarizes_uuid:V(),status_category:M([`blocked`,`waiting`,`completed`,`review_ready`,`failed`]),status_detail:V(),is_noteworthy:N(),title:V(),description:V(),recent_action:V(),needs_action:V(),artifact_urls:F(V()),uuid:Q(),session_id:V()}).describe(`@internal Background post-turn summary emitted after each assistant turn. summarizes_uuid points to the assistant message this summarizes.`)),es=H(()=>P({type:R(`system`),subtype:R(`api_retry`),attempt:z(),max_retries:z(),retry_delay_ms:z(),error_status:z().nullable(),error:Fo(),uuid:Q(),session_id:V()}).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.`)),ts=H(()=>P({type:R(`system`),subtype:R(`local_command_output`),content:V(),uuid:Q(),session_id:V()}).describe(`Output from a local slash command (e.g. /voice, /cost). Displayed as assistant-style text in the transcript.`)),ns=H(()=>P({type:R(`system`),subtype:R(`hook_started`),hook_id:V(),hook_name:V(),hook_event:V(),uuid:Q(),session_id:V()})),rs=H(()=>P({type:R(`system`),subtype:R(`hook_progress`),hook_id:V(),hook_name:V(),hook_event:V(),stdout:V(),stderr:V(),output:V(),uuid:Q(),session_id:V()})),is=H(()=>P({type:R(`system`),subtype:R(`hook_response`),hook_id:V(),hook_name:V(),hook_event:V(),output:V(),stdout:V(),stderr:V(),exit_code:z().optional(),outcome:M([`success`,`error`,`cancelled`]),uuid:Q(),session_id:V()})),as=H(()=>P({type:R(`tool_progress`),tool_use_id:V(),tool_name:V(),parent_tool_use_id:V().nullable(),elapsed_time_seconds:z(),task_id:V().optional(),uuid:Q(),session_id:V()})),os=H(()=>P({type:R(`auth_status`),isAuthenticating:N(),output:F(V()),error:V().optional(),uuid:Q(),session_id:V()})),ss=H(()=>P({type:R(`system`),subtype:R(`files_persisted`),files:F(P({filename:V(),file_id:V()})),failed:F(P({filename:V(),error:V()})),processed_at:V(),uuid:Q(),session_id:V()})),cs=H(()=>P({type:R(`system`),subtype:R(`task_notification`),task_id:V(),tool_use_id:V().optional(),status:M([`completed`,`failed`,`stopped`]),output_file:V(),summary:V(),usage:P({total_tokens:z(),tool_uses:z(),duration_ms:z()}).optional(),uuid:Q(),session_id:V()})),ls=H(()=>P({type:R(`system`),subtype:R(`task_started`),task_id:V(),tool_use_id:V().optional(),description:V(),task_type:V().optional(),workflow_name:V().optional().describe(`meta.name from the workflow script (e.g. 'spec'). Only set when task_type is 'local_workflow'.`),prompt:V().optional(),uuid:Q(),session_id:V()})),us=H(()=>P({type:R(`system`),subtype:R(`session_state_changed`),state:M([`idle`,`running`,`requires_action`]),uuid:Q(),session_id:V()}).describe(`Mirrors notifySessionStateChanged. 'idle' fires after heldBackResult flushes and the bg-agent do-while exits — authoritative turn-over signal.`)),ds=H(()=>P({type:R(`system`),subtype:R(`task_progress`),task_id:V(),tool_use_id:V().optional(),description:V(),usage:P({total_tokens:z(),tool_uses:z(),duration_ms:z()}),last_tool_name:V().optional(),summary:V().optional(),uuid:Q(),session_id:V()})),fs=H(()=>P({type:R(`tool_use_summary`),summary:V(),preceding_tool_use_ids:F(V()),uuid:Q(),session_id:V()})),ps=H(()=>P({type:R(`system`),subtype:R(`elicitation_complete`),mcp_server_name:V(),elicitation_id:V(),uuid:Q(),session_id:V()}).describe(`Emitted when an MCP server confirms that a URL-mode elicitation is complete.`)),ms=H(()=>P({type:R(`prompt_suggestion`),suggestion:V(),uuid:Q(),session_id:V()}).describe(`Predicted next user prompt, emitted after each turn when promptSuggestions is enabled.`));H(()=>P({sessionId:V().describe(`Unique session identifier (UUID).`),summary:V().describe(`Display title for the session: custom title, auto-generated summary, or first prompt.`),lastModified:z().describe(`Last modified time in milliseconds since epoch.`),fileSize:z().optional().describe(`File size in bytes. Only populated for local JSONL storage.`),customTitle:V().optional().describe(`User-set session title via /rename.`),firstPrompt:V().optional().describe(`First meaningful user prompt in the session.`),gitBranch:V().optional().describe(`Git branch at the end of the session.`),cwd:V().optional().describe(`Working directory for the session.`),tag:V().optional().describe(`User-set session tag.`),createdAt:z().optional().describe(`Creation time in milliseconds since epoch, extracted from the first entry's timestamp.`)}).describe(`Session metadata returned by listSessions and getSessionInfo.`));var hs=H(()=>I([Vo(),Ro(),zo(),Jo(),Yo(),Xo(),Zo(),Qo(),es(),ts(),ns(),rs(),is(),as(),os(),cs(),ls(),ds(),us(),ss(),fs(),Ho(),ps(),ms()])),gs=H(()=>M([`off`,`cooldown`,`on`]).describe(`Fast mode state: off, in cooldown after rate limit, or actively enabled.`));rr(),nr();var _s=H(()=>j()),vs=H(()=>P({matcher:V().optional(),hookCallbackIds:F(V()),timeout:z().optional()}).describe(`Configuration for matching and routing hook callbacks.`)),ys=H(()=>P({subtype:R(`initialize`),hooks:B(Ea(),F(vs())).optional(),sdkMcpServers:F(V()).optional(),jsonSchema:B(V(),j()).optional(),systemPrompt:V().optional(),appendSystemPrompt:V().optional(),agents:B(V(),Ao()).optional(),promptSuggestions:N().optional(),agentProgressSummaries:N().optional()}).describe(`Initializes the SDK session with hooks, MCP servers, and agent configuration.`));H(()=>P({commands:F(To()),agents:F(Eo()),output_style:V(),available_output_styles:F(V()),models:F(Do()),account:Oo(),pid:z().optional().describe(`@internal CLI process PID for tmux socket isolation`),fast_mode_state:gs().optional()}).describe(`Response from session initialization with available commands, models, and account info.`));var bs=H(()=>P({subtype:R(`interrupt`)}).describe(`Interrupts the currently running conversation turn.`)),xs=H(()=>P({subtype:R(`can_use_tool`),tool_name:V(),input:B(V(),j()),permission_suggestions:F(Sa()).optional(),blocked_path:V().optional(),decision_reason:V().optional(),title:V().optional(),display_name:V().optional(),tool_use_id:V(),agent_id:V().optional(),description:V().optional()}).describe(`Requests permission to use a tool with the given input.`)),Ss=H(()=>P({subtype:R(`set_permission_mode`),mode:wa()}).describe(`Sets the permission mode for tool execution handling.`)),Cs=H(()=>P({subtype:R(`set_model`),model:V().optional()}).describe(`Sets the model to use for subsequent conversation turns.`)),ws=H(()=>P({subtype:R(`set_max_thinking_tokens`),max_thinking_tokens:z().nullable()}).describe(`Sets the maximum number of thinking tokens for extended thinking.`)),Ts=H(()=>P({subtype:R(`mcp_status`)}).describe(`Requests the current status of all MCP server connections.`));H(()=>P({mcpServers:F(va())}).describe(`Response containing the current status of all MCP server connections.`));var Es=H(()=>P({subtype:R(`get_context_usage`)}).describe(`Requests a breakdown of current context window usage by category.`)),Ds=H(()=>P({name:V(),tokens:z(),color:V(),isDeferred:N().optional()})),Os=H(()=>P({color:V(),isFilled:N(),categoryName:V(),tokens:z(),percentage:z(),squareFullness:z()}));H(()=>P({categories:F(Ds()),totalTokens:z(),maxTokens:z(),rawMaxTokens:z(),percentage:z(),gridRows:F(F(Os())),model:V(),memoryFiles:F(P({path:V(),type:V(),tokens:z()})),mcpTools:F(P({name:V(),serverName:V(),tokens:z(),isLoaded:N().optional()})),deferredBuiltinTools:F(P({name:V(),tokens:z(),isLoaded:N()})).optional(),systemTools:F(P({name:V(),tokens:z()})).optional(),systemPromptSections:F(P({name:V(),tokens:z()})).optional(),agents:F(P({agentType:V(),source:V(),tokens:z()})),slashCommands:P({totalCommands:z(),includedCommands:z(),tokens:z()}).optional(),skills:P({totalSkills:z(),includedSkills:z(),tokens:z(),skillFrontmatter:F(P({name:V(),source:V(),tokens:z()}))}).optional(),autoCompactThreshold:z().optional(),isAutoCompactEnabled:N(),messageBreakdown:P({toolCallTokens:z(),toolResultTokens:z(),attachmentTokens:z(),assistantMessageTokens:z(),userMessageTokens:z(),toolCallsByType:F(P({name:V(),callTokens:z(),resultTokens:z()})),attachmentsByType:F(P({name:V(),tokens:z()}))}).optional(),apiUsage:P({input_tokens:z(),output_tokens:z(),cache_creation_input_tokens:z(),cache_read_input_tokens:z()}).nullable()}).describe(`Breakdown of current context window usage by category (system prompt, tools, messages, etc.).`));var ks=H(()=>P({subtype:R(`rewind_files`),user_message_id:V(),dry_run:N().optional()}).describe(`Rewinds file changes made since a specific user message.`));H(()=>P({canRewind:N(),error:V().optional(),filesChanged:F(V()).optional(),insertions:z().optional(),deletions:z().optional()}).describe(`Result of a rewindFiles operation.`));var As=H(()=>P({subtype:R(`cancel_async_message`),message_uuid:V()}).describe(`Drops a pending async user message from the command queue by uuid. No-op if already dequeued for execution.`));H(()=>P({cancelled:N()}).describe(`Result of a cancel_async_message operation. cancelled=false means the message was not in the queue (already dequeued or never enqueued).`));var js=H(()=>P({subtype:R(`seed_read_state`),path:V(),mtime:z()}).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.`)),Ms=H(()=>P({subtype:R(`hook_callback`),callback_id:V(),input:ao(),tool_use_id:V().optional()}).describe(`Delivers a hook callback with its input data.`)),Ns=H(()=>P({subtype:R(`mcp_message`),server_name:V(),message:_s()}).describe(`Sends a JSON-RPC message to a specific MCP server.`)),Ps=H(()=>P({subtype:R(`mcp_set_servers`),servers:B(V(),ha())}).describe(`Replaces the set of dynamically managed MCP servers.`));H(()=>P({added:F(V()),removed:F(V()),errors:B(V(),V())}).describe(`Result of replacing the set of dynamically managed MCP servers.`));var Fs=H(()=>P({subtype:R(`reload_plugins`)}).describe(`Reloads plugins from disk and returns the refreshed session components.`));H(()=>P({commands:F(To()),agents:F(Eo()),plugins:F(P({name:V(),path:V(),source:V().optional()})),mcpServers:F(va()),error_count:z()}).describe(`Refreshed commands, agents, plugins, and MCP server status after reload.`));var Is=H(()=>P({subtype:R(`mcp_reconnect`),serverName:V()}).describe(`Reconnects a disconnected or failed MCP server.`)),Ls=H(()=>P({subtype:R(`mcp_toggle`),serverName:V(),enabled:N()}).describe(`Enables or disables an MCP server.`)),Rs=H(()=>P({subtype:R(`stop_task`),task_id:V()}).describe(`Stops a running task.`)),zs=H(()=>P({subtype:R(`apply_flag_settings`),settings:B(V(),j())}).describe(`Merges the provided settings into the flag settings layer, updating the active configuration.`)),Bs=H(()=>P({subtype:R(`get_settings`)}).describe(`Returns the effective merged settings and the raw per-source settings.`));H(()=>P({effective:B(V(),j()),sources:F(P({source:M([`userSettings`,`projectSettings`,`localSettings`,`flagSettings`,`policySettings`]),settings:B(V(),j())})).describe(`Ordered low-to-high priority — later entries override earlier ones.`),applied:P({model:V()}).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 Vs=H(()=>P({subtype:R(`elicitation`),mcp_server_name:V(),message:V(),mode:M([`form`,`url`]).optional(),url:V().optional(),elicitation_id:V().optional(),requested_schema:B(V(),j()).optional()}).describe(`Requests the SDK consumer to handle an MCP elicitation (user input request).`)),Hs=H(()=>P({action:M([`accept`,`decline`,`cancel`]),content:B(V(),j()).optional()}).describe(`Response from the SDK consumer for an elicitation request.`)),Us=H(()=>I([bs(),xs(),ys(),Ss(),Cs(),ws(),Ts(),Es(),Ms(),Ns(),ks(),As(),js(),Ps(),Fs(),Is(),Ls(),Rs(),zs(),Bs(),Vs()])),Ws=H(()=>P({type:R(`control_request`),request_id:V(),request:Us()})),Gs=H(()=>P({subtype:R(`success`),request_id:V(),response:B(V(),j()).optional()})),Ks=H(()=>P({subtype:R(`error`),request_id:V(),error:V(),pending_permission_requests:F(Xn(()=>Ws())).optional()})),qs=H(()=>P({type:R(`control_response`),response:I([Gs(),Ks()])})),Js=H(()=>P({type:R(`control_cancel_request`),request_id:V()}).describe(`Cancels a currently open control request.`)),Ys=H(()=>P({type:R(`keep_alive`)}).describe(`Keep-alive message to maintain WebSocket connection.`)),Xs=H(()=>P({type:R(`update_environment_variables`),variables:B(V(),V())}).describe(`Updates environment variables at runtime.`));H(()=>I([hs(),Uo(),Wo(),$o(),qs(),Ws(),Js(),Ys()])),H(()=>I([Ro(),Ws(),qs(),Ys(),Xs()])),n(),i(),ar(),vr(),br(),Er(),wr(),Gr(),jr(),Hn(),rr(),q(),nr(),Qt(),Je(),H(()=>L.object({tool_name:L.string().describe(`The name of the tool requesting permission`),input:L.record(L.string(),L.unknown()).describe(`The input for the tool`),tool_use_id:L.string().optional().describe(`The unique tool use request ID`)}));var Zs=H(()=>L.enum([`user_temporary`,`user_permanent`,`user_reject`]).optional().catch(void 0)),Qs=H(()=>L.object({behavior:L.literal(`allow`),updatedInput:L.record(L.string(),L.unknown()),updatedPermissions:L.array(C()).optional().catch(e=>{K(`Malformed updatedPermissions from SDK host ignored: ${e.error.issues[0]?.message??`unknown`}`,{level:`warn`})}),toolUseID:L.string().optional(),decisionClassification:Zs()})),$s=H(()=>L.object({behavior:L.literal(`deny`),message:L.string(),interrupt:L.boolean().optional(),toolUseID:L.string().optional(),decisionClassification:Zs()})),ec=H(()=>L.union([Qs(),$s()]));function tc(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:ce(e.toolPermissionContext,t)})),qt(t));let a=Object.keys(e.updatedInput).length>0?e.updatedInput:n;return{...e,updatedInput:a,decisionReason:i}}else e.behavior===`deny`&&e.interrupt&&(K(`SDK permission prompt deny+interrupt: tool=${t.name} message=${e.message}`),r.abortController.abort());return{...e,decisionReason:i}}gr(),Zr(),Xr(),Lr(),tr(),Nr(),Rr(),Ir(),xi(),bi(),gn(),b(),Wn(),un(),h(),wt(),Vn(),At(),ve(),Kt(),Bn(),an(),Ot(),wn(),dt(),E(),vt(),yt(),Kn(),on(),nt();var nc=/\u2028|\u2029/g;function rc(e){return e.replace(nc,e=>e===`\u2028`?`\\u2028`:`\\u2029`)}function ic(e){return rc(W(e))}q(),Er(),rr(),Qt();var ac=`SandboxNetworkAccess`;function oc(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 sc(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 cc=1e3,lc=class{constructor(e,t){a(this,`input`,void 0),a(this,`replayUserMessages`,void 0),a(this,`structuredInput`,void 0),a(this,`pendingRequests`,new Map),a(this,`restoredWorkerState`,Promise.resolve(null)),a(this,`inputClosed`,!1),a(this,`unexpectedResponseCallback`,void 0),a(this,`resolvedToolUseIds`,new Set),a(this,`prependedLines`,[]),a(this,`onControlRequestSent`,void 0),a(this,`onControlRequestResolved`,void 0),a(this,`outbound`,new Ct),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>cc)){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(`${W({type:`user`,content:e,uuid:``,session_id:``,message:{role:`user`,content:e},parent_tool_use_id:null})}\n`)}async*read(){let e=``,t=async function*(){for(;;){this.prependedLines.length>0&&(e=this.prependedLines.join(``)+e,this.prependedLines=[]);let t=e.indexOf(`
1
+ import{c as e,l as t,o as n,s as r}from"./envUtils-DfkgIdYf.js";import{n as i,t as a}from"./defineProperty-C-QyHrDq.js";import{_t as o,vt as s}from"./esm-BXTZz3av.js";import{$_ as c,$d as l,$m as u,$p as d,$r as f,$v as p,A as m,Ag as h,Al as g,As as ee,B as _,Bl as te,Bo as ne,Bp as re,Bt as v,By as y,C as ie,CC as b,Cc as x,Cg as S,Cn as C,Cv as ae,Cy as oe,D_ as se,Dm as ce,Dv as w,E_ as le,Ec as ue,Ei as de,Fa as fe,Fl as pe,Fo as me,GC as he,Ho as ge,Hs as _e,Id as ve,Ig as ye,Il as be,Io as T,K_ as xe,Kn as Se,Ku as Ce,La as we,Ld as Te,Lo as Ee,Ls as De,Mv as Oe,Mw as ke,Ng as Ae,Ni as E,Ns as je,OC as Me,Oa as Ne,Og as Pe,Oi as Fe,PS as Ie,Pi as Le,Pl as Re,Po as ze,Qd as Be,Qm as Ve,Qp as He,Ro as Ue,Rr as We,Rs as Ge,Sc as Ke,Sg as qe,Sn as Je,Ss as Ye,Sv as Xe,T_ as Ze,Tm as Qe,Ty as $e,Uo as et,Us as tt,V as nt,Vo as D,Vp as O,WC as rt,W_ as it,Wu as at,XC as ot,X_ as st,Xd as k,Xn as ct,Xr as lt,YC as ut,Yi as dt,Zd as ft,Zp as pt,Zr as mt,Zv as ht,_c as gt,_g as _t,_i as vt,_r as yt,af as bt,ao as xt,b as St,bc as Ct,bg as wt,bm as Tt,bn as Et,bs as Dt,cs as Ot,do as kt,ef as At,eh as jt,ei as Mt,ey as Nt,f as Pt,gC as Ft,gc as It,gg as Lt,gi as A,gu as Rt,gv as zt,hi as Bt,hu as Vt,if as Ht,im as Ut,io as Wt,ja as Gt,jl as Kt,jm as qt,js as Jt,kC as Yt,ka as Xt,kg as Zt,km as Qt,ks as $t,lf as en,lo as tn,lp as nn,ls as rn,mc as an,mn as on,mo as sn,nf as cn,nv as ln,ny as un,o as dn,of as fn,os as pn,pc as mn,pv as hn,qC as gn,q_ as _n,rf as vn,rm as yn,rv as bn,s as xn,sC as Sn,sS as Cn,ss as wn,tf as Tn,th as En,tv as Dn,ty as On,up as kn,v as An,vg as jn,vi as Mn,vn as Nn,w as Pn,wC as Fn,wg as In,wi as Ln,wm as Rn,wv as zn,xc as Bn,xm as Vn,xn as Hn,y as Un,yC as Wn,yc as Gn,yn as Kn,zl as qn,zo as Jn,zt as Yn}from"./loadAgentsDir-B0Anodo0.js";import{$ as j,A as M,B as Xn,F as N,G as P,L as Zn,N as Qn,P as F,Q as I,S as L,V as R,W as z,Y as B,Z as V,f as $n,j as er,l as tr,o as nr,s as H,x as rr}from"./types-Dx7P7JLQ.js";import{G as ir,It as ar,Lt as or,Pn as sr,Wn as cr,Wt as lr,bn as ur,cn as dr,in as fr,j as pr,k as mr,st as U,xn as hr}from"./state-B4jiUise.js";import{n as gr,t as _r}from"./cwd-Pa83R95t.js";import{$ as vr,C as W,E as yr,I as br,M as G,S as xr,V as Sr,c as K,et as Cr,f as wr,i as q,u as Tr,x as Er}from"./debug-Bglx1aTu.js";import{Hn as Dr,W as Or,Wn as kr,Xr as Ar,Yr as jr,Zr as Mr,_t as Nr,d as Pr,er as Fr,h as Ir,nr as Lr,rt as Rr,tt as zr,u as Br,ut as Vr}from"./settings-B2jvL8Dp.js";import{O as Hr,j as Ur}from"./config-C-Y2qtB2.js";import{i as Wr,n as Gr,o as Kr}from"./process-gEbdy6uY.js";import{H as qr,c as Jr,i as Yr,o as Xr,q as Zr,s as J}from"./log-D2TIwHBV.js";import{n as Qr,r as $r}from"./analytics-DJobLaWP.js";import{G as ei,H as ti,Jt as ni,K as ri,L as ii,U as ai,Yt as oi,Zt as si,_ as ci,d as li,et as ui,h as di,n as fi,nt as pi,o as mi,qt as hi}from"./model-BvQFFOf8.js";import{_t as gi,at as _i,bn as vi,it as yi,tn as bi,vn as xi,vt as Si,yt as Ci}from"./prompt-CJ1l3XXk.js";import{i as wi,n as Ti,r as Ei,t as Di}from"./reject-DtcCfuZV.js";import{h as Oi,m as ki}from"./firstPartyEventLogger-QmjjQmgt.js";import{t as Ai}from"./pluginBlocklist-9OrNEh--.js";import{n as ji,t as Mi}from"./toolPool-V-7Yv0GA.js";import{n as Ni}from"./conversationRecovery-DliPBo_z.js";import{a as Pi,i as Fi,n as Ii,r as Li}from"./QueryEngine-DdLWvJv6.js";import{n as Ri,r as zi}from"./sessionTitle-k4wpUS5l.js";import{n as Bi,r as Vi}from"./sideQuestion-D49GsfH7.js";import{a as Hi,n as Ui}from"./grove-O6qp7ITR.js";import{n as Wi,r as Gi}from"./context-noninteractive-C7wrRZnM.js";import{n as Ki,r as qi}from"./modelOptions-BBvF3wHK.js";import{a as Ji,o as Yi,t as Xi}from"./skillChangeDetector-DkOJoNhT.js";import{n as Zi}from"./reconciler-ykkSPR-i.js";import{n as Qi,t as $i}from"./refresh-Dn_I1R4v.js";import{dirname as ea,join as ta}from"path";import{randomUUID as Y}from"crypto";import{readFile as na,stat as ra}from"fs/promises";import{cwd as X}from"process";rr(),nr();var ia=H(()=>P({inputTokens:z(),outputTokens:z(),cacheReadInputTokens:z(),cacheCreationInputTokens:z(),webSearchRequests:z(),costUSD:z(),contextWindow:z(),maxOutputTokens:z()})),aa=H(()=>R(`json_schema`));H(()=>P({type:aa()}));var oa=H(()=>P({type:R(`json_schema`),schema:B(V(),j())}));H(()=>oa());var sa=H(()=>M([`user`,`project`,`org`,`temporary`,`oauth`]));H(()=>M([`local`,`user`,`project`]).describe(`Config scope for settings.`)),H(()=>R(`context-1m-2025-08-07`));var ca=H(()=>P({type:R(`adaptive`)}).describe(`Work Mate decides when and how much to think (Opus 4.6+).`)),la=H(()=>P({type:R(`enabled`),budgetTokens:z().optional()}).describe(`Fixed thinking token budget (older models)`)),ua=H(()=>P({type:R(`disabled`)}).describe(`No extended thinking`));H(()=>I([ca(),la(),ua()]).describe(`Controls Work Mate's thinking/reasoning behavior. When set, takes precedence over the deprecated maxThinkingTokens.`));var da=H(()=>P({type:R(`stdio`).optional(),command:V(),args:F(V()).optional(),env:B(V(),V()).optional()})),fa=H(()=>P({type:R(`sse`),url:V(),headers:B(V(),V()).optional()})),pa=H(()=>P({type:R(`http`),url:V(),headers:B(V(),V()).optional()})),ma=H(()=>P({type:R(`sdk`),name:V()})),ha=H(()=>I([da(),fa(),pa(),ma()])),ga=H(()=>P({type:R(`claudeai-proxy`),url:V(),id:V()})),_a=H(()=>I([ha(),ga()])),va=H(()=>P({name:V().describe(`Server name as configured`),status:M([`connected`,`failed`,`needs-auth`,`pending`,`disabled`]).describe(`Current connection status`),serverInfo:P({name:V(),version:V()}).optional().describe(`Server information (available when connected)`),error:V().optional().describe(`Error message (available when status is 'failed')`),config:_a().optional().describe(`Server configuration (includes URL for HTTP/SSE servers)`),scope:V().optional().describe(`Configuration scope (e.g., project, user, local, claudeai, managed)`),tools:F(P({name:V(),description:V().optional(),annotations:P({readOnly:N().optional(),destructive:N().optional(),openWorld:N().optional()}).optional()})).optional().describe(`Tools provided by this server (available when connected)`),capabilities:P({experimental:B(V(),j()).optional()}).optional().describe(`@internal Server capabilities (available when connected). experimental['claude/channel'] is only present if the server's plugin is on the approved channels allowlist — use its presence to decide whether to show an Enable-channel prompt.`)}).describe(`Status information for an MCP server connection.`));H(()=>P({added:F(V()).describe(`Names of servers that were added`),removed:F(V()).describe(`Names of servers that were removed`),errors:B(V(),V()).describe(`Map of server names to error messages for servers that failed to connect`)}).describe(`Result of a setMcpServers operation.`));var ya=H(()=>M([`userSettings`,`projectSettings`,`localSettings`,`session`,`cliArg`])),ba=H(()=>M([`allow`,`deny`,`ask`])),xa=H(()=>P({toolName:V(),ruleContent:V().optional()})),Sa=H(()=>Zn(`type`,[P({type:R(`addRules`),rules:F(xa()),behavior:ba(),destination:ya()}),P({type:R(`replaceRules`),rules:F(xa()),behavior:ba(),destination:ya()}),P({type:R(`removeRules`),rules:F(xa()),behavior:ba(),destination:ya()}),P({type:R(`setMode`),mode:Xn(()=>wa()),destination:ya()}),P({type:R(`addDirectories`),directories:F(V()),destination:ya()}),P({type:R(`removeDirectories`),directories:F(V()),destination:ya()})])),Ca=H(()=>M([`user_temporary`,`user_permanent`,`user_reject`]).describe(`Classification of this permission decision for telemetry. SDK hosts that prompt users (desktop apps, IDEs) should set this to reflect what actually happened: user_temporary for allow-once, user_permanent for always-allow (both the click and later cache hits), user_reject for deny. If unset, the CLI infers conservatively (temporary for allow, reject for deny). The vocabulary matches tool_decision OTel events (monitoring-usage docs).`));H(()=>I([P({behavior:R(`allow`),updatedInput:B(V(),j()).optional(),updatedPermissions:F(Sa()).optional(),toolUseID:V().optional(),decisionClassification:Ca().optional()}),P({behavior:R(`deny`),message:V(),interrupt:N().optional(),toolUseID:V().optional(),decisionClassification:Ca().optional()})]));var wa=H(()=>M([`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).`)),Ta=`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(`.`),Ea=H(()=>M(Ta)),Z=H(()=>P({session_id:V(),transcript_path:V(),cwd:V(),permission_mode:V().optional(),agent_id:V().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:V().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).`)})),Da=H(()=>Z().and(P({hook_event_name:R(`PreToolUse`),tool_name:V(),tool_input:j(),tool_use_id:V()}))),Oa=H(()=>Z().and(P({hook_event_name:R(`PermissionRequest`),tool_name:V(),tool_input:j(),permission_suggestions:F(Sa()).optional()}))),ka=H(()=>Z().and(P({hook_event_name:R(`PostToolUse`),tool_name:V(),tool_input:j(),tool_response:j(),tool_use_id:V()}))),Aa=H(()=>Z().and(P({hook_event_name:R(`PostToolUseFailure`),tool_name:V(),tool_input:j(),tool_use_id:V(),error:V(),is_interrupt:N().optional()}))),ja=H(()=>Z().and(P({hook_event_name:R(`PermissionDenied`),tool_name:V(),tool_input:j(),tool_use_id:V(),reason:V()}))),Ma=H(()=>Z().and(P({hook_event_name:R(`Notification`),message:V(),title:V().optional(),notification_type:V()}))),Na=H(()=>Z().and(P({hook_event_name:R(`UserPromptSubmit`),prompt:V()}))),Pa=H(()=>Z().and(P({hook_event_name:R(`SessionStart`),source:M([`startup`,`resume`,`clear`,`compact`]),agent_type:V().optional(),model:V().optional()}))),Fa=H(()=>Z().and(P({hook_event_name:R(`Setup`),trigger:M([`init`,`maintenance`])}))),Ia=H(()=>Z().and(P({hook_event_name:R(`Stop`),stop_hook_active:N(),last_assistant_message:V().optional().describe(`Text content of the last assistant message before stopping. Avoids the need to read and parse the transcript file.`)}))),La=H(()=>Z().and(P({hook_event_name:R(`StopFailure`),error:Fo(),error_details:V().optional(),last_assistant_message:V().optional()}))),Ra=H(()=>Z().and(P({hook_event_name:R(`SubagentStart`),agent_id:V(),agent_type:V()}))),za=H(()=>Z().and(P({hook_event_name:R(`SubagentStop`),stop_hook_active:N(),agent_id:V(),agent_transcript_path:V(),agent_type:V(),last_assistant_message:V().optional().describe(`Text content of the last assistant message before stopping. Avoids the need to read and parse the transcript file.`)}))),Ba=H(()=>Z().and(P({hook_event_name:R(`PreCompact`),trigger:M([`manual`,`auto`]),custom_instructions:V().nullable()}))),Va=H(()=>Z().and(P({hook_event_name:R(`PostCompact`),trigger:M([`manual`,`auto`]),compact_summary:V().describe(`The conversation summary produced by compaction`)}))),Ha=H(()=>Z().and(P({hook_event_name:R(`TeammateIdle`),teammate_name:V(),team_name:V()}))),Ua=H(()=>Z().and(P({hook_event_name:R(`TaskCreated`),task_id:V(),task_subject:V(),task_description:V().optional(),teammate_name:V().optional(),team_name:V().optional()}))),Wa=H(()=>Z().and(P({hook_event_name:R(`TaskCompleted`),task_id:V(),task_subject:V(),task_description:V().optional(),teammate_name:V().optional(),team_name:V().optional()}))),Ga=H(()=>Z().and(P({hook_event_name:R(`Elicitation`),mcp_server_name:V(),message:V(),mode:M([`form`,`url`]).optional(),url:V().optional(),elicitation_id:V().optional(),requested_schema:B(V(),j()).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.`)),Ka=H(()=>Z().and(P({hook_event_name:R(`ElicitationResult`),mcp_server_name:V(),elicitation_id:V().optional(),mode:M([`form`,`url`]).optional(),action:M([`accept`,`decline`,`cancel`]),content:B(V(),j()).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.`)),qa=[`user_settings`,`project_settings`,`local_settings`,`policy_settings`,`skills`],Ja=H(()=>Z().and(P({hook_event_name:R(`ConfigChange`),source:M(qa),file_path:V().optional()}))),Ya=[`session_start`,`nested_traversal`,`path_glob_match`,`include`,`compact`],Xa=[`User`,`Project`,`Local`,`Managed`],Za=H(()=>Z().and(P({hook_event_name:R(`InstructionsLoaded`),file_path:V(),memory_type:M(Xa),load_reason:M(Ya),globs:F(V()).optional(),trigger_file_path:V().optional(),parent_file_path:V().optional()}))),Qa=H(()=>Z().and(P({hook_event_name:R(`WorktreeCreate`),name:V()}))),$a=H(()=>Z().and(P({hook_event_name:R(`WorktreeRemove`),worktree_path:V()}))),eo=H(()=>Z().and(P({hook_event_name:R(`CwdChanged`),old_cwd:V(),new_cwd:V()}))),to=H(()=>Z().and(P({hook_event_name:R(`FileChanged`),file_path:V(),event:M([`change`,`add`,`unlink`])}))),no=[`clear`,`resume`,`prompt_input_exit`,`other`,`bypass_permissions_disabled`],ro=H(()=>M(no)),io=H(()=>Z().and(P({hook_event_name:R(`SessionEnd`),reason:ro()}))),ao=H(()=>I([Da(),ka(),Aa(),ja(),Ma(),Na(),Pa(),io(),Ia(),La(),Ra(),za(),Ba(),Va(),Oa(),Fa(),Ha(),Ua(),Wa(),Ga(),Ka(),Ja(),Za(),Qa(),$a(),eo(),to()])),oo=H(()=>P({async:R(!0),asyncTimeout:z().optional()})),so=H(()=>P({hookEventName:R(`PreToolUse`),permissionDecision:ba().optional(),permissionDecisionReason:V().optional(),updatedInput:B(V(),j()).optional(),additionalContext:V().optional()})),co=H(()=>P({hookEventName:R(`UserPromptSubmit`),additionalContext:V().optional()})),lo=H(()=>P({hookEventName:R(`SessionStart`),additionalContext:V().optional(),initialUserMessage:V().optional(),watchPaths:F(V()).optional()})),uo=H(()=>P({hookEventName:R(`Setup`),additionalContext:V().optional()})),fo=H(()=>P({hookEventName:R(`SubagentStart`),additionalContext:V().optional()})),po=H(()=>P({hookEventName:R(`PostToolUse`),additionalContext:V().optional(),updatedMCPToolOutput:j().optional()})),mo=H(()=>P({hookEventName:R(`PostToolUseFailure`),additionalContext:V().optional()})),ho=H(()=>P({hookEventName:R(`PermissionDenied`),retry:N().optional()})),go=H(()=>P({hookEventName:R(`Notification`),additionalContext:V().optional()})),_o=H(()=>P({hookEventName:R(`PermissionRequest`),decision:I([P({behavior:R(`allow`),updatedInput:B(V(),j()).optional(),updatedPermissions:F(Sa()).optional()}),P({behavior:R(`deny`),message:V().optional(),interrupt:N().optional()})])})),vo=H(()=>P({hookEventName:R(`CwdChanged`),watchPaths:F(V()).optional()})),yo=H(()=>P({hookEventName:R(`FileChanged`),watchPaths:F(V()).optional()})),bo=H(()=>P({continue:N().optional(),suppressOutput:N().optional(),stopReason:V().optional(),decision:M([`approve`,`block`]).optional(),systemMessage:V().optional(),reason:V().optional(),hookSpecificOutput:I([so(),co(),lo(),uo(),fo(),po(),mo(),ho(),go(),_o(),xo(),So(),vo(),yo(),Co()]).optional()})),xo=H(()=>P({hookEventName:R(`Elicitation`),action:M([`accept`,`decline`,`cancel`]).optional(),content:B(V(),j()).optional()}).describe(`Hook-specific output for the Elicitation event. Return this to programmatically accept or decline an MCP elicitation request.`)),So=H(()=>P({hookEventName:R(`ElicitationResult`),action:M([`accept`,`decline`,`cancel`]).optional(),content:B(V(),j()).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.`)),Co=H(()=>P({hookEventName:R(`WorktreeCreate`),worktreePath:V()}).describe(`Hook-specific output for the WorktreeCreate event. Provides the absolute path to the created worktree directory. Command hooks print the path on stdout instead.`));H(()=>I([oo(),bo()]));var wo=H(()=>P({key:V().describe(`Unique key for this option, returned in the response`),label:V().describe(`Display text for this option`),description:V().optional().describe(`Optional description shown below the label`)}));H(()=>P({prompt:V().describe(`Request ID. Presence of this key marks the line as a prompt request.`),message:V().describe(`The prompt message to display to the user`),options:F(wo()).describe(`Available options for the user to choose from`)})),H(()=>P({prompt_response:V().describe(`The request ID from the corresponding prompt request`),selected:V().describe(`The key of the selected option`)}));var To=H(()=>P({name:V().describe(`Skill name (without the leading slash)`),description:V().describe(`Description of what the skill does`),argumentHint:V().describe(`Hint for skill arguments (e.g., "<file>")`)}).describe(`Information about an available skill (invoked via /command syntax).`)),Eo=H(()=>P({name:V().describe(`Agent type identifier (e.g., "Explore")`),description:V().describe(`Description of when to use this agent`),model:V().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.`)),Do=H(()=>P({value:V().describe(`Model identifier to use in API calls`),displayName:V().describe(`Human-readable display name`),description:V().describe(`Description of the model's capabilities`),supportsAdaptiveThinking:N().optional().describe(`Whether this model supports adaptive thinking (Work Mate decides when and how much to think)`),supportsFastMode:N().optional().describe(`Whether this model supports fast mode`),supportsAutoMode:N().optional().describe(`Whether this model supports auto mode`)}).describe(`Information about an available model.`)),Oo=H(()=>P({email:V().optional(),organization:V().optional(),subscriptionType:V().optional(),tokenSource:V().optional(),apiKeySource:V().optional(),apiProvider:M([`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.`)),ko=H(()=>I([V(),B(V(),ha())])),Ao=H(()=>P({description:V().describe(`Natural language description of when to use this agent`),tools:F(V()).optional().describe(`Array of allowed tool names. If omitted, inherits all tools from parent`),disallowedTools:F(V()).optional().describe(`Array of tool names to explicitly disallow for this agent`),prompt:V().describe(`The agent's system prompt`),model:V().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:F(ko()).optional(),criticalSystemReminder_EXPERIMENTAL:V().optional().describe(`Experimental: Critical reminder added to system prompt`),skills:F(V()).optional().describe(`Array of skill names to preload into the agent context`),initialPrompt:V().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:z().int().positive().optional().describe(`Maximum number of agentic turns (API round-trips) before stopping`),background:N().optional().describe(`Run this agent as a background task (non-blocking, fire-and-forget) when invoked`),memory:M([`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:wa().optional().describe(`Permission mode controlling how tool executions are handled`)}).describe(`Definition for a custom subagent that can be invoked via the Agent tool.`));H(()=>M([`user`,`project`,`local`]).describe(`Source for loading filesystem-based settings. 'user' - Global user settings (~/.workmate/settings.json). 'project' - Project settings (.workmate/settings.json). 'local' - Local settings (.workmate/settings.local.json).`)),H(()=>P({type:R(`local`).describe(`Plugin type. Currently only 'local' is supported`),path:V().describe(`Absolute or relative path to the plugin directory`)}).describe(`Configuration for loading a plugin.`)),H(()=>P({canRewind:N(),error:V().optional(),filesChanged:F(V()).optional(),insertions:z().optional(),deletions:z().optional()}).describe(`Result of a rewindFiles operation.`));var jo=H(()=>j()),Mo=H(()=>j()),No=H(()=>j()),Q=H(()=>V()),Po=H(()=>j()),Fo=H(()=>M([`authentication_failed`,`billing_error`,`rate_limit`,`invalid_request`,`server_error`,`unknown`,`max_output_tokens`])),Io=H(()=>I([R(`compacting`),er()])),Lo=H(()=>P({type:R(`user`),message:jo(),parent_tool_use_id:V().nullable(),isSynthetic:N().optional(),tool_use_result:j().optional(),priority:M([`now`,`next`,`later`]).optional(),timestamp:V().optional().describe(`ISO timestamp when the message was created on the originating process. Older emitters omit it; consumers should fall back to receive time.`)})),Ro=H(()=>Lo().extend({uuid:Q().optional(),session_id:V().optional()})),zo=H(()=>Lo().extend({uuid:Q(),session_id:V(),isReplay:R(!0)})),Bo=H(()=>P({status:M([`allowed`,`allowed_warning`,`rejected`]),resetsAt:z().optional(),rateLimitType:M([`five_hour`,`seven_day`,`seven_day_opus`,`seven_day_sonnet`,`overage`]).optional(),utilization:z().optional(),overageStatus:M([`allowed`,`allowed_warning`,`rejected`]).optional(),overageResetsAt:z().optional(),overageDisabledReason:M([`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:N().optional(),surpassedThreshold:z().optional()}).describe(`Rate limit information for claude.ai subscription users.`)),Vo=H(()=>P({type:R(`assistant`),message:Mo(),parent_tool_use_id:V().nullable(),error:Fo().optional(),uuid:Q(),session_id:V()})),Ho=H(()=>P({type:R(`rate_limit_event`),rate_limit_info:Bo(),uuid:Q(),session_id:V()}).describe(`Rate limit event emitted when rate limit info changes.`)),Uo=H(()=>P({type:R(`streamlined_text`),text:V().describe(`Text content preserved from the assistant message`),session_id:V(),uuid:Q()}).describe(`@internal Streamlined text message - replaces SDKAssistantMessage in streamlined output. Text content preserved, thinking and tool_use blocks removed.`)),Wo=H(()=>P({type:R(`streamlined_tool_use_summary`),tool_summary:V().describe(`Summary of tool calls (e.g., "Read 2 files, wrote 1 file")`),session_id:V(),uuid:Q()}).describe(`@internal Streamlined tool use summary - replaces tool_use blocks in streamlined output with a cumulative summary string.`)),Go=H(()=>P({tool_name:V(),tool_use_id:V(),tool_input:B(V(),j())})),Ko=H(()=>P({type:R(`result`),subtype:R(`success`),duration_ms:z(),duration_api_ms:z(),is_error:N(),num_turns:z(),result:V(),stop_reason:V().nullable(),total_cost_usd:z(),usage:Po(),modelUsage:B(V(),ia()),permission_denials:F(Go()),structured_output:j().optional(),fast_mode_state:gs().optional(),uuid:Q(),session_id:V()})),qo=H(()=>P({type:R(`result`),subtype:M([`error_during_execution`,`error_max_turns`,`error_max_budget_usd`,`error_max_structured_output_retries`]),duration_ms:z(),duration_api_ms:z(),is_error:N(),num_turns:z(),stop_reason:V().nullable(),total_cost_usd:z(),usage:Po(),modelUsage:B(V(),ia()),permission_denials:F(Go()),errors:F(V()),fast_mode_state:gs().optional(),uuid:Q(),session_id:V()})),Jo=H(()=>I([Ko(),qo()])),Yo=H(()=>P({type:R(`system`),subtype:R(`init`),agents:F(V()).optional(),apiKeySource:sa(),betas:F(V()).optional(),claude_code_version:V(),cwd:V(),tools:F(V()),mcp_servers:F(P({name:V(),status:V()})),model:V(),permissionMode:wa(),slash_commands:F(V()),output_style:V(),skills:F(V()),plugins:F(P({name:V(),path:V(),source:V().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:gs().optional(),uuid:Q(),session_id:V()})),Xo=H(()=>P({type:R(`stream_event`),event:No(),parent_tool_use_id:V().nullable(),uuid:Q(),session_id:V()})),Zo=H(()=>P({type:R(`system`),subtype:R(`compact_boundary`),compact_metadata:P({trigger:M([`manual`,`auto`]),pre_tokens:z(),preserved_segment:P({head_uuid:Q(),anchor_uuid:Q(),tail_uuid:Q()}).optional().describe(`Relink info for messagesToKeep. Loaders splice the preserved segment at anchor_uuid (summary for suffix-preserving, boundary for prefix-preserving partial compact) so resume includes preserved content. Unset when compaction summarizes everything (no messagesToKeep).`)}),uuid:Q(),session_id:V()})),Qo=H(()=>P({type:R(`system`),subtype:R(`status`),status:Io(),permissionMode:wa().optional(),uuid:Q(),session_id:V()})),$o=H(()=>P({type:R(`system`),subtype:R(`post_turn_summary`),summarizes_uuid:V(),status_category:M([`blocked`,`waiting`,`completed`,`review_ready`,`failed`]),status_detail:V(),is_noteworthy:N(),title:V(),description:V(),recent_action:V(),needs_action:V(),artifact_urls:F(V()),uuid:Q(),session_id:V()}).describe(`@internal Background post-turn summary emitted after each assistant turn. summarizes_uuid points to the assistant message this summarizes.`)),es=H(()=>P({type:R(`system`),subtype:R(`api_retry`),attempt:z(),max_retries:z(),retry_delay_ms:z(),error_status:z().nullable(),error:Fo(),uuid:Q(),session_id:V()}).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.`)),ts=H(()=>P({type:R(`system`),subtype:R(`local_command_output`),content:V(),uuid:Q(),session_id:V()}).describe(`Output from a local slash command (e.g. /voice, /cost). Displayed as assistant-style text in the transcript.`)),ns=H(()=>P({type:R(`system`),subtype:R(`hook_started`),hook_id:V(),hook_name:V(),hook_event:V(),uuid:Q(),session_id:V()})),rs=H(()=>P({type:R(`system`),subtype:R(`hook_progress`),hook_id:V(),hook_name:V(),hook_event:V(),stdout:V(),stderr:V(),output:V(),uuid:Q(),session_id:V()})),is=H(()=>P({type:R(`system`),subtype:R(`hook_response`),hook_id:V(),hook_name:V(),hook_event:V(),output:V(),stdout:V(),stderr:V(),exit_code:z().optional(),outcome:M([`success`,`error`,`cancelled`]),uuid:Q(),session_id:V()})),as=H(()=>P({type:R(`tool_progress`),tool_use_id:V(),tool_name:V(),parent_tool_use_id:V().nullable(),elapsed_time_seconds:z(),task_id:V().optional(),uuid:Q(),session_id:V()})),os=H(()=>P({type:R(`auth_status`),isAuthenticating:N(),output:F(V()),error:V().optional(),uuid:Q(),session_id:V()})),ss=H(()=>P({type:R(`system`),subtype:R(`files_persisted`),files:F(P({filename:V(),file_id:V()})),failed:F(P({filename:V(),error:V()})),processed_at:V(),uuid:Q(),session_id:V()})),cs=H(()=>P({type:R(`system`),subtype:R(`task_notification`),task_id:V(),tool_use_id:V().optional(),status:M([`completed`,`failed`,`stopped`]),output_file:V(),summary:V(),usage:P({total_tokens:z(),tool_uses:z(),duration_ms:z()}).optional(),uuid:Q(),session_id:V()})),ls=H(()=>P({type:R(`system`),subtype:R(`task_started`),task_id:V(),tool_use_id:V().optional(),description:V(),task_type:V().optional(),workflow_name:V().optional().describe(`meta.name from the workflow script (e.g. 'spec'). Only set when task_type is 'local_workflow'.`),prompt:V().optional(),uuid:Q(),session_id:V()})),us=H(()=>P({type:R(`system`),subtype:R(`session_state_changed`),state:M([`idle`,`running`,`requires_action`]),uuid:Q(),session_id:V()}).describe(`Mirrors notifySessionStateChanged. 'idle' fires after heldBackResult flushes and the bg-agent do-while exits — authoritative turn-over signal.`)),ds=H(()=>P({type:R(`system`),subtype:R(`task_progress`),task_id:V(),tool_use_id:V().optional(),description:V(),usage:P({total_tokens:z(),tool_uses:z(),duration_ms:z()}),last_tool_name:V().optional(),summary:V().optional(),uuid:Q(),session_id:V()})),fs=H(()=>P({type:R(`tool_use_summary`),summary:V(),preceding_tool_use_ids:F(V()),uuid:Q(),session_id:V()})),ps=H(()=>P({type:R(`system`),subtype:R(`elicitation_complete`),mcp_server_name:V(),elicitation_id:V(),uuid:Q(),session_id:V()}).describe(`Emitted when an MCP server confirms that a URL-mode elicitation is complete.`)),ms=H(()=>P({type:R(`prompt_suggestion`),suggestion:V(),uuid:Q(),session_id:V()}).describe(`Predicted next user prompt, emitted after each turn when promptSuggestions is enabled.`));H(()=>P({sessionId:V().describe(`Unique session identifier (UUID).`),summary:V().describe(`Display title for the session: custom title, auto-generated summary, or first prompt.`),lastModified:z().describe(`Last modified time in milliseconds since epoch.`),fileSize:z().optional().describe(`File size in bytes. Only populated for local JSONL storage.`),customTitle:V().optional().describe(`User-set session title via /rename.`),firstPrompt:V().optional().describe(`First meaningful user prompt in the session.`),gitBranch:V().optional().describe(`Git branch at the end of the session.`),cwd:V().optional().describe(`Working directory for the session.`),tag:V().optional().describe(`User-set session tag.`),createdAt:z().optional().describe(`Creation time in milliseconds since epoch, extracted from the first entry's timestamp.`)}).describe(`Session metadata returned by listSessions and getSessionInfo.`));var hs=H(()=>I([Vo(),Ro(),zo(),Jo(),Yo(),Xo(),Zo(),Qo(),es(),ts(),ns(),rs(),is(),as(),os(),cs(),ls(),ds(),us(),ss(),fs(),Ho(),ps(),ms()])),gs=H(()=>M([`off`,`cooldown`,`on`]).describe(`Fast mode state: off, in cooldown after rate limit, or actively enabled.`));rr(),nr();var _s=H(()=>j()),vs=H(()=>P({matcher:V().optional(),hookCallbackIds:F(V()),timeout:z().optional()}).describe(`Configuration for matching and routing hook callbacks.`)),ys=H(()=>P({subtype:R(`initialize`),hooks:B(Ea(),F(vs())).optional(),sdkMcpServers:F(V()).optional(),jsonSchema:B(V(),j()).optional(),systemPrompt:V().optional(),appendSystemPrompt:V().optional(),agents:B(V(),Ao()).optional(),promptSuggestions:N().optional(),agentProgressSummaries:N().optional()}).describe(`Initializes the SDK session with hooks, MCP servers, and agent configuration.`));H(()=>P({commands:F(To()),agents:F(Eo()),output_style:V(),available_output_styles:F(V()),models:F(Do()),account:Oo(),pid:z().optional().describe(`@internal CLI process PID for tmux socket isolation`),fast_mode_state:gs().optional()}).describe(`Response from session initialization with available commands, models, and account info.`));var bs=H(()=>P({subtype:R(`interrupt`)}).describe(`Interrupts the currently running conversation turn.`)),xs=H(()=>P({subtype:R(`can_use_tool`),tool_name:V(),input:B(V(),j()),permission_suggestions:F(Sa()).optional(),blocked_path:V().optional(),decision_reason:V().optional(),title:V().optional(),display_name:V().optional(),tool_use_id:V(),agent_id:V().optional(),description:V().optional()}).describe(`Requests permission to use a tool with the given input.`)),Ss=H(()=>P({subtype:R(`set_permission_mode`),mode:wa()}).describe(`Sets the permission mode for tool execution handling.`)),Cs=H(()=>P({subtype:R(`set_model`),model:V().optional()}).describe(`Sets the model to use for subsequent conversation turns.`)),ws=H(()=>P({subtype:R(`set_max_thinking_tokens`),max_thinking_tokens:z().nullable()}).describe(`Sets the maximum number of thinking tokens for extended thinking.`)),Ts=H(()=>P({subtype:R(`mcp_status`)}).describe(`Requests the current status of all MCP server connections.`));H(()=>P({mcpServers:F(va())}).describe(`Response containing the current status of all MCP server connections.`));var Es=H(()=>P({subtype:R(`get_context_usage`)}).describe(`Requests a breakdown of current context window usage by category.`)),Ds=H(()=>P({name:V(),tokens:z(),color:V(),isDeferred:N().optional()})),Os=H(()=>P({color:V(),isFilled:N(),categoryName:V(),tokens:z(),percentage:z(),squareFullness:z()}));H(()=>P({categories:F(Ds()),totalTokens:z(),maxTokens:z(),rawMaxTokens:z(),percentage:z(),gridRows:F(F(Os())),model:V(),memoryFiles:F(P({path:V(),type:V(),tokens:z()})),mcpTools:F(P({name:V(),serverName:V(),tokens:z(),isLoaded:N().optional()})),deferredBuiltinTools:F(P({name:V(),tokens:z(),isLoaded:N()})).optional(),systemTools:F(P({name:V(),tokens:z()})).optional(),systemPromptSections:F(P({name:V(),tokens:z()})).optional(),agents:F(P({agentType:V(),source:V(),tokens:z()})),slashCommands:P({totalCommands:z(),includedCommands:z(),tokens:z()}).optional(),skills:P({totalSkills:z(),includedSkills:z(),tokens:z(),skillFrontmatter:F(P({name:V(),source:V(),tokens:z()}))}).optional(),autoCompactThreshold:z().optional(),isAutoCompactEnabled:N(),messageBreakdown:P({toolCallTokens:z(),toolResultTokens:z(),attachmentTokens:z(),assistantMessageTokens:z(),userMessageTokens:z(),toolCallsByType:F(P({name:V(),callTokens:z(),resultTokens:z()})),attachmentsByType:F(P({name:V(),tokens:z()}))}).optional(),apiUsage:P({input_tokens:z(),output_tokens:z(),cache_creation_input_tokens:z(),cache_read_input_tokens:z()}).nullable()}).describe(`Breakdown of current context window usage by category (system prompt, tools, messages, etc.).`));var ks=H(()=>P({subtype:R(`rewind_files`),user_message_id:V(),dry_run:N().optional()}).describe(`Rewinds file changes made since a specific user message.`));H(()=>P({canRewind:N(),error:V().optional(),filesChanged:F(V()).optional(),insertions:z().optional(),deletions:z().optional()}).describe(`Result of a rewindFiles operation.`));var As=H(()=>P({subtype:R(`cancel_async_message`),message_uuid:V()}).describe(`Drops a pending async user message from the command queue by uuid. No-op if already dequeued for execution.`));H(()=>P({cancelled:N()}).describe(`Result of a cancel_async_message operation. cancelled=false means the message was not in the queue (already dequeued or never enqueued).`));var js=H(()=>P({subtype:R(`seed_read_state`),path:V(),mtime:z()}).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.`)),Ms=H(()=>P({subtype:R(`hook_callback`),callback_id:V(),input:ao(),tool_use_id:V().optional()}).describe(`Delivers a hook callback with its input data.`)),Ns=H(()=>P({subtype:R(`mcp_message`),server_name:V(),message:_s()}).describe(`Sends a JSON-RPC message to a specific MCP server.`)),Ps=H(()=>P({subtype:R(`mcp_set_servers`),servers:B(V(),ha())}).describe(`Replaces the set of dynamically managed MCP servers.`));H(()=>P({added:F(V()),removed:F(V()),errors:B(V(),V())}).describe(`Result of replacing the set of dynamically managed MCP servers.`));var Fs=H(()=>P({subtype:R(`reload_plugins`)}).describe(`Reloads plugins from disk and returns the refreshed session components.`));H(()=>P({commands:F(To()),agents:F(Eo()),plugins:F(P({name:V(),path:V(),source:V().optional()})),mcpServers:F(va()),error_count:z()}).describe(`Refreshed commands, agents, plugins, and MCP server status after reload.`));var Is=H(()=>P({subtype:R(`mcp_reconnect`),serverName:V()}).describe(`Reconnects a disconnected or failed MCP server.`)),Ls=H(()=>P({subtype:R(`mcp_toggle`),serverName:V(),enabled:N()}).describe(`Enables or disables an MCP server.`)),Rs=H(()=>P({subtype:R(`stop_task`),task_id:V()}).describe(`Stops a running task.`)),zs=H(()=>P({subtype:R(`apply_flag_settings`),settings:B(V(),j())}).describe(`Merges the provided settings into the flag settings layer, updating the active configuration.`)),Bs=H(()=>P({subtype:R(`get_settings`)}).describe(`Returns the effective merged settings and the raw per-source settings.`));H(()=>P({effective:B(V(),j()),sources:F(P({source:M([`userSettings`,`projectSettings`,`localSettings`,`flagSettings`,`policySettings`]),settings:B(V(),j())})).describe(`Ordered low-to-high priority — later entries override earlier ones.`),applied:P({model:V()}).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 Vs=H(()=>P({subtype:R(`elicitation`),mcp_server_name:V(),message:V(),mode:M([`form`,`url`]).optional(),url:V().optional(),elicitation_id:V().optional(),requested_schema:B(V(),j()).optional()}).describe(`Requests the SDK consumer to handle an MCP elicitation (user input request).`)),Hs=H(()=>P({action:M([`accept`,`decline`,`cancel`]),content:B(V(),j()).optional()}).describe(`Response from the SDK consumer for an elicitation request.`)),Us=H(()=>I([bs(),xs(),ys(),Ss(),Cs(),ws(),Ts(),Es(),Ms(),Ns(),ks(),As(),js(),Ps(),Fs(),Is(),Ls(),Rs(),zs(),Bs(),Vs()])),Ws=H(()=>P({type:R(`control_request`),request_id:V(),request:Us()})),Gs=H(()=>P({subtype:R(`success`),request_id:V(),response:B(V(),j()).optional()})),Ks=H(()=>P({subtype:R(`error`),request_id:V(),error:V(),pending_permission_requests:F(Xn(()=>Ws())).optional()})),qs=H(()=>P({type:R(`control_response`),response:I([Gs(),Ks()])})),Js=H(()=>P({type:R(`control_cancel_request`),request_id:V()}).describe(`Cancels a currently open control request.`)),Ys=H(()=>P({type:R(`keep_alive`)}).describe(`Keep-alive message to maintain WebSocket connection.`)),Xs=H(()=>P({type:R(`update_environment_variables`),variables:B(V(),V())}).describe(`Updates environment variables at runtime.`));H(()=>I([hs(),Uo(),Wo(),$o(),qs(),Ws(),Js(),Ys()])),H(()=>I([Ro(),Ws(),qs(),Ys(),Xs()])),n(),i(),ar(),vr(),br(),Er(),wr(),Gr(),jr(),Hn(),rr(),q(),nr(),Qt(),Je(),H(()=>L.object({tool_name:L.string().describe(`The name of the tool requesting permission`),input:L.record(L.string(),L.unknown()).describe(`The input for the tool`),tool_use_id:L.string().optional().describe(`The unique tool use request ID`)}));var Zs=H(()=>L.enum([`user_temporary`,`user_permanent`,`user_reject`]).optional().catch(void 0)),Qs=H(()=>L.object({behavior:L.literal(`allow`),updatedInput:L.record(L.string(),L.unknown()),updatedPermissions:L.array(C()).optional().catch(e=>{K(`Malformed updatedPermissions from SDK host ignored: ${e.error.issues[0]?.message??`unknown`}`,{level:`warn`})}),toolUseID:L.string().optional(),decisionClassification:Zs()})),$s=H(()=>L.object({behavior:L.literal(`deny`),message:L.string(),interrupt:L.boolean().optional(),toolUseID:L.string().optional(),decisionClassification:Zs()})),ec=H(()=>L.union([Qs(),$s()]));function tc(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:ce(e.toolPermissionContext,t)})),qt(t));let a=Object.keys(e.updatedInput).length>0?e.updatedInput:n;return{...e,updatedInput:a,decisionReason:i}}else e.behavior===`deny`&&e.interrupt&&(K(`SDK permission prompt deny+interrupt: tool=${t.name} message=${e.message}`),r.abortController.abort());return{...e,decisionReason:i}}gr(),Zr(),Xr(),Lr(),tr(),Nr(),Rr(),Ir(),xi(),bi(),gn(),b(),Wn(),un(),h(),wt(),Vn(),At(),ve(),Kt(),Bn(),an(),Ot(),wn(),dt(),E(),vt(),yt(),Kn(),on(),nt();var nc=/\u2028|\u2029/g;function rc(e){return e.replace(nc,e=>e===`\u2028`?`\\u2028`:`\\u2029`)}function ic(e){return rc(W(e))}q(),Er(),rr(),Qt();var ac=`SandboxNetworkAccess`;function oc(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 sc(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 cc=1e3,lc=class{constructor(e,t){a(this,`input`,void 0),a(this,`replayUserMessages`,void 0),a(this,`structuredInput`,void 0),a(this,`pendingRequests`,new Map),a(this,`restoredWorkerState`,Promise.resolve(null)),a(this,`inputClosed`,!1),a(this,`unexpectedResponseCallback`,void 0),a(this,`resolvedToolUseIds`,new Set),a(this,`prependedLines`,[]),a(this,`onControlRequestSent`,void 0),a(this,`onControlRequestResolved`,void 0),a(this,`outbound`,new Ct),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>cc)){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(`${W({type:`user`,content:e,uuid:``,session_id:``,message:{role:`user`,content:e},parent_tool_use_id:null})}\n`)}async*read(){let e=``,t=async function*(){for(;;){this.prependedLines.length>0&&(e=this.prependedLines.join(``)+e,this.prependedLines=[]);let t=e.indexOf(`
2
2
  `);if(t===-1)break;let n=e.slice(0,t);e=e.slice(t+1);let r=await this.processLine(n);r&&(Ar(`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=xr(e);if(t.type===`keep_alive`)return;if(t.type===`update_environment_variables`){let e=t.variables??{},n=Object.keys(e);for(let[t,n]of Object.entries(e))process.env[t]=n;K(`[structuredIO] applied update_environment_variables: ${n.join(`, `)}`);return}if(t.type===`control_response`){let e=`uuid`in t&&typeof t.uuid==`string`?t.uuid:void 0;e&&Tn(e,`completed`);let n=t.response,r=this.pendingRequests.get(n.request_id);if(!r){let e=(n.subtype===`success`?n.response:void 0)?.toolUseID;if(typeof e==`string`&&this.resolvedToolUseIds.has(e)){K(`Ignoring duplicate control_response for already-resolved toolUseID=${e} request_id=${n.request_id}`);return}this.unexpectedResponseCallback&&await this.unexpectedResponseCallback(t);return}if(this.trackResolvedToolUseId(r.request),this.pendingRequests.delete(n.request_id),r.request.request.subtype===`can_use_tool`&&this.onControlRequestResolved&&this.onControlRequestResolved(n.request_id),n.subtype===`error`){r.reject(Error(n.error??`Unknown error`));return}let i=n.response;if(r.schema)try{r.resolve(r.schema.parse(i))}catch(e){r.reject(e)}else r.resolve({});return this.replayUserMessages?t:void 0}if(t.type!==`user`&&t.type!==`control_request`&&t.type!==`assistant`&&t.type!==`system`){K(`Ignoring unknown message type: ${t.type}`,{level:`warn`});return}return t.type===`control_request`?(t.request||uc(`Error: Missing request on control_request`),t):(t.type===`assistant`||t.type===`system`||t.message?.role!==`user`&&uc(`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){Kr(`${ic(e)}\n`)}async sendRequest(e,t,n,r=Y()){let i={type:`control_request`,request_id:r,request:e};if(this.inputClosed)throw Error(`Stream closed`);if(n?.aborted)throw Error(`Request aborted`);this.outbound.enqueue(i),e.subtype===`can_use_tool`&&this.onControlRequestSent&&this.onControlRequestSent(i);let a=()=>{this.outbound.enqueue({type:`control_cancel_request`,request_id:r});let e=this.pendingRequests.get(r);e&&(this.trackResolvedToolUseId(e.request),e.reject(new yr))};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 _(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=dc(t.name,a,n,r,s.suggestions).then(e=>({source:`hook`,decision:e})),o=Y();e?.(sc(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:oc(s.decisionReason),tool_use_id:a,agent_id:r.agentId},ec(),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):tc((await l).result,t,n,r):tc(u.result,t,n,r)}catch(e){return tc({behavior:`deny`,message:`Tool permission request failed: ${e}`,toolUseID:a},t,n,r)}finally{this.getPendingPermissionRequests().length===0&&pe(`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},Et(),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},Hs(),r)}catch{return{action:`cancel`}}}createSandboxAskCallback(){return async e=>{try{return(await this.sendRequest({subtype:`can_use_tool`,tool_name:ac,input:{host:e.host},tool_use_id:Y(),description:`Allow network connection to ${e.host}?`},ec())).behavior===`allow`}catch{return!1}}}async sendMcpMessage(e,t){return(await this.sendRequest({subtype:`mcp_message`,server_name:e,message:t},P({mcp_response:Qn()}))).mcp_response}};function uc(e){console.error(e),process.exit(1)}async function dc(e,t,n,r,i){let a=r.getAppState().toolPermissionContext.mode,o=v(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){qt(i);let e=ce(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`}}}}gi(),Or(),Ci(),[...Si],q();var fc=`[stdout-guard]`,pc=!1,$=``,mc=null;function hc(e){if(e.length===0)return!0;try{return JSON.parse(e),!0}catch{return!1}}function gc(){pc||(pc=!0,mc=process.stdout.write.bind(process.stdout),process.stdout.write=((e,t,n)=>{let r=typeof e==`string`?e:Buffer.from(e).toString(`utf-8`);$+=r;let i,a=!0;for(;(i=$.indexOf(`
3
3
  `))!==-1;){let e=$.slice(0,i);$=$.slice(i+1),hc(e)?a=mc(`${e}\n`):(process.stderr.write(`${fc} ${e}\n`),K(`streamJsonStdoutGuard diverted non-JSON stdout line: ${e.slice(0,200)}`))}let o=typeof t==`function`?t:n;return o&&queueMicrotask(()=>o()),a}),Cr(async()=>{$.length>0&&(mc&&hc($)?mc(`${$}\n`):process.stderr.write(`${fc} ${$}\n`),$=``),mc&&(process.stdout.write=mc,mc=null),pc=!1}))}Hr(),Me(),Ie(),w(),zt(),le(),_i(),ue(),Ye(),D(),tn(),fe(),dn(),Mi(),q(),br(),gr(),br(),Xr(),ke(),q();function _c(e){let t=process.env.CLAUDE_CODE_EXIT_AFTER_STOP_DELAY,n=t?parseInt(t,10):null,r=n&&!isNaN(n)&&n>0,i=null,a=0;return{start(){i&&(clearTimeout(i),i=null),r&&(a=Date.now(),i=setTimeout(()=>{let t=Date.now()-a;e()&&t>=n&&(K(`Exiting after ${n}ms of idle time`),A())},n))},stop(){i&&(clearTimeout(i),i=null)}}}si(),pi(),ti(),li(),Ei(),Di(),o(),Ve(),O(),tt(),De(),$t(),Xt(),St(),zi(),Bi();function vc(e){if(e.toLowerCase().endsWith(`.jsonl`))return{sessionId:Y(),ingressUrl:null,isUrl:!1,jsonlFile:e,isJsonlFile:!0};if(Te(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}hi(),y(),ht(),c(),Rn(),Ut(),kn(),en(),bt(),Be(),at(),It(),Gi(),qi(),q(),Er();async function yc(){try{let e=await na(Ue(),`utf-8`),t=Vr().safeParse(xr(e));return t.success?t.data:(K(`Invalid known_marketplaces.json in zip cache: ${t.error.message}`,{level:`error`}),{})}catch{return{}}}async function bc(e){await ze(Ue(),W(e,null,2))}async function xc(e,t){let n=Ee();if(!n)return;let r=await Sc(t);r!==null&&await ze(ta(n,T(e)),r)}async function Sc(e){let t=[ta(e,`.claude-plugin`,`marketplace.json`),ta(e,`marketplace.json`),e];for(let e of t)try{return await na(e,`utf-8`)}catch{}return null}async function Cc(){let e=await kt();for(let[t,n]of Object.entries(e))if(n.installLocation)try{await xc(t,n.installLocation)}catch(e){K(`Failed to save marketplace JSON for ${t}: ${e}`)}await bc({...await yc(),...e})}Qr(),vr(),q(),jr(),Xr(),tn(),D();async function wc(){let e=et();K(`installPluginsForHeadless: starting${e?` (zip cache mode)`:``}`);let t=await sn();t&&(Wt(),Gt(`headlessPluginInstall: seed marketplaces registered`)),e&&(await Tr().mkdir(Jn()),await Tr().mkdir(ne()));let n=Object.keys(xt()).length,r={marketplaces_installed:0,delisted_count:0},i=t;try{if(n===0)K(`installPluginsForHeadless: no marketplaces declared`);else{let t=await Mr(`headless_marketplace_reconcile`,()=>Zi({skip:e?(e,t)=>!ge(t):void 0,onProgress:e=>{e.type===`installed`?K(`installPluginsForHeadless: installed marketplace ${e.name}`):e.type===`failed`&&K(`installPluginsForHeadless: failed to install marketplace ${e.name}: ${e.error}`)}}),e=>({installed_count:e.installed.length,updated_count:e.updated.length,failed_count:e.failed.length,skipped_count:e.skipped.length}));t.skipped.length>0&&K(`installPluginsForHeadless: skipped ${t.skipped.length} marketplace(s) unsupported by zip cache: ${t.skipped.join(`, `)}`);let n=t.installed.length+t.updated.length;n>0&&(Wt(),Gt(`headlessPluginInstall: marketplaces reconciled`),i=!0),r.marketplaces_installed=n}e&&await Cc();let t=await Ai();return r.delisted_count=t.length,t.length>0&&(i=!0),i&&Gt(`headlessPluginInstall: plugins changed`),e&&Cr(me),i}catch(e){return J(e),!1}finally{$r(`tengu_headless_plugin_install`,r)}}Dr(),Qr(),q(),jr(),At(),Kt(),Xr(),Gr(),ve(),vt(),vr(),gr(),nt(),on(),dt(),Er(),$i(),fe(),_t(),Vt(),qn(),br(),ki();var Tc=1e4,Ec=new Set,Dc=[];function Oc(e){if(Ec.has(e))return!1;if(Ec.add(e),Dc.push(e),Dc.length>Tc){let e=Dc.splice(0,Dc.length-Tc);for(let t of e)Ec.delete(t)}return!0}function kc(e){return typeof e==`string`?[{type:`text`,text:e}]:e}function Ac(e){return e.length===1?e[0]:e.every(e=>typeof e==`string`)?e.join(`
4
4
  `):e.flatMap(kc)}function jc(e,t){return t!==void 0&&t.mode===`prompt`&&t.workload===e.workload&&t.isMeta===e.isMeta}async function Mc(e,n,r,i,a,o,s,c){if(Fn.subscribe(e=>{re(e,r),ei()&&r(e=>{let t=e.settings,n=t.fastMode===!0&&!t.fastModePerSessionOptIn;return{...e,fastMode:n}})}),!ut()&&t(process.env.CLAUDE_CODE_PROACTIVE)&&rt(`command`),typeof Bun<`u`&&setInterval(()=>{process.memoryUsage.rss()>350*1024*1024?Bun.gc(!0):Bun.gc(!1)},1e3).unref(),ft(),k(`runHeadless_entry`),await Hi()&&await Ui(),k(`after_grove_check`),c.resumeSessionAt&&!c.resume){process.stderr.write(`Error: --resume-session-at requires --resume
@@ -8,6 +8,6 @@ import{c as e,l as t,o as n,s as r}from"./envUtils-DfkgIdYf.js";import{n as i,t
8
8
  `),A(1);return}if(c.outputFormat===`stream-json`&&!c.verbose){process.stderr.write(`Error: When using --print, --output-format=stream-json requires --verbose
9
9
  `),A(1);return}let ne=x(p.mcp.tools,p.toolPermissionContext),v=[...a,...ne],y=Fc(c.sdkUrl?`stdio`:c.permissionPromptToolName,u,()=>n().mcp.tools,e=>{r(e=>({...e,attribution:{...e.attribution,permissionPromptCount:e.attribution.permissionPromptCount+1}})),pe(`requires_action`,e)});c.permissionPromptToolName&&(v=v.filter(e=>!vi(e,c.permissionPromptToolName))),Wr(),k(`after_loadInitialMessages`),await ui(),k(`after_modelStrings`);let ie=c.outputFormat===`json`&&c.verbose,b=[],S;k(`before_runHeadlessStreaming`);for await(let e of Nc(u,p.mcp.clients,[...i,...p.mcp.commands],v,m,y,o,n,r,s,c,h))c.outputFormat===`stream-json`&&c.verbose&&await u.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`&&(ie&&b.push(e),S=e);switch(c.outputFormat){case`json`:if(S?.type!==`result`)throw Error(`No messages returned`);if(c.verbose){Kr(`${W(b)}\n`);break}Kr(`${W(S)}\n`);break;case`stream-json`:break;default:if(S?.type!==`result`)throw Error(`No messages returned`);switch(S.subtype){case`success`:Kr(S.result.endsWith(`
10
10
  `)?S.result:`${S.result}\n`);break;case`error_during_execution`:Kr(`Execution error`);break;case`error_max_turns`:Kr(`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`:Kr(`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`:Kr(`Error: Failed to provide valid structured output after maximum retries.
11
- Tip: Simplify your schema or check if the output format matches the expected structure.`)}}if(l(),Ur())try{let{drainPendingExtraction:e}=await import(`./extractMemories-xP63mv6R.js`);await e()}catch{}A(S?.type===`result`&&S?.is_error?1:0)}function Nc(n,i,a,o,c,u,d,f,m,h,_,ne){let re=!1,v,y=!1,ie=null,b,x=n.outbound;process.on(`SIGINT`,()=>{Ar(`info`,`shutdown_signal`,{signal:`SIGINT`}),b&&!b.signal.aborted&&b.abort(),Bt(0)}),Cr(async()=>{let e={};for(let t of Lt(f()))Rt(t)&&(e[t.type]=(e[t.type]??0)+1);Ar(`info`,`run_state_at_shutdown`,{run_active:re,run_phase:v,worker_status:g(),internal_events_pending:n.internalEventsPending,bg_tasks:e})}),be(e=>{(e==="default"||e===`acceptEdits`||e===`bypassPermissions`||e===`plan`||e===`auto`||e===`dontAsk`)&&x.enqueue({type:`system`,subtype:`status`,status:null,permissionMode:e,uuid:Y(),session_id:U()})});let C={abortController:null,inflightPromise:null,lastEmitted:null,pendingSuggestion:null,pendingLastEmittedEntry:null},ce=e=>{let t=Fi(e);t&&x.enqueue({type:`rate_limit_event`,rate_limit_info:t,uuid:Y(),session_id:U()})};Ge.add(ce);let w=c,le=Dt(c,X(),100),ue=Ze(100),fe=process.env.CLAUDE_CODE_RESUME_INTERRUPTED_TURN;ne&&ne.kind!==`none`&&fe&&(K(`[print.ts] Auto-resuming interrupted turn (kind: ${ne.kind})`),Bc(w,ne.message),In({mode:`prompt`,value:ne.message.message.content,uuid:Y()}));let me=Ki().map(e=>{let t=e.value===null?`default`:e.value,n=t==="default"?fi():ci(t),r=Ce(n),i=ri(e.value),a=s(n);return{name:t,value:t,displayName:e.label,description:e.description,...r&&{supportsAdaptiveThinking:!0},...i&&{supportsFastMode:!0},...a&&{supportsAutoMode:!0}}}),ge=_.userSpecifiedModel;function ve(e,t){let n=Cn(e,di(t));w.push(...n);for(let e of n)typeof e.message.content==`string`&&e.message.content.includes(`<local-command-stdout>`)&&x.enqueue({type:`user`,content:e.message.content,message:e.message,session_id:U(),parent_tool_use_id:null,uuid:e.uuid,timestamp:e.timestamp,isReplay:!0})}let T=[],Te=[],Ee=new Set;function De(e){for(let t of e){if(t.type!==`connected`||Ee.has(t.name)||t.config.type===`sdk`)continue;let e=t.name;try{t.client.setRequestHandler(oe,async(t,r)=>{Jr(e,`Elicitation request received in print mode: ${W(t)}`);let i=t.params.mode===`url`?`url`:`form`;$r(`tengu_mcp_elicitation_shown`,{mode:i});let a=await p(e,t.params,r.signal);if(a)return Jr(e,`Elicitation resolved by hook: ${W(a)}`),$r(`tengu_mcp_elicitation_response`,{mode:i,action:a.action}),a;let o=`url`in t.params?t.params.url:void 0,s=`requestedSchema`in t.params?t.params.requestedSchema:void 0,c=`elicitationId`in t.params?t.params.elicitationId:void 0,l=await n.handleElicitation(e,t.params.message,s,r.signal,i,o,c),u=await Nt(e,l,r.signal,i,c);return $r(`tengu_mcp_elicitation_response`,{mode:i,action:u.action}),u}),t.client.setNotificationHandler($e,t=>{let{elicitationId:n}=t.params;Jr(e,`Elicitation completion notification: ${n}`),Yn({message:`MCP server "${e}" confirmed elicitation ${n} complete`,notificationType:`elicitation_complete`}),x.enqueue({type:`system`,subtype:`elicitation_complete`,mcp_server_name:e,elicitation_id:n,uuid:Y(),session_id:U()})}),Ee.add(e)}catch{}}}async function ke(){let e=new Set(Object.keys(d)),t=new Set(T.map(e=>e.name)),r=Array.from(e).some(e=>!t.has(e)),i=Array.from(t).some(t=>!e.has(t)),a=T.some(e=>e.type===`pending`),o=T.some(e=>e.type===`failed`);if(r||i||a||o){for(let t of T)e.has(t.name)||t.type===`connected`&&await t.cleanup();let r=await ln(d,(e,t)=>n.sendMcpMessage(e,t));T=r.clients,Te=r.tools;let i=kr([...t,...e]);m(e=>({...e,mcp:{...e.mcp,tools:[...e.mcp.tools.filter(e=>!i.some(t=>e.name.startsWith(zr(t)))),...Te]}})),Qe(T)}}ke();let E={clients:[],tools:[],configs:{}},Me=e=>{let t=Ke(e.toolPermissionContext,e.mcp.tools),n=Yt(ji([...o,...Te,...E.tools],t,e.toolPermissionContext.mode),`name`);_.permissionPromptToolName&&(n=n.filter(e=>!vi(e,_.permissionPromptToolName)));let r=pr();if(r&&!_.jsonSchema){let e=yi(r);`tool`in e&&(n=[...n,e.tool])}return n},Ne=Promise.resolve({response:{added:[],removed:[],errors:{}},sdkServersChanged:!1});function Ie(e){let t=async()=>{let t=new Set(T.map(e=>e.name)),n=await Gc(e,{configs:d,clients:T,tools:Te},E,m);for(let e of Object.keys(d))delete d[e];if(Object.assign(d,n.newSdkState.configs),T=n.newSdkState.clients,Te=n.newSdkState.tools,E=n.newDynamicState,n.sdkServersChanged){let e=new Set(T.map(e=>e.name)),n=kr([...t,...e]);m(e=>({...e,mcp:{...e.mcp,tools:[...e.mcp.tools.filter(e=>!n.some(t=>e.name.startsWith(zr(t)))),...Te]}}))}return{response:n.response,sdkServersChanged:n.sdkServersChanged}};return Ne=Ne.then(t,t),Ne}function ze(){let e=f(),t=e.mcp.clients,n=Yt([...e.mcp.tools,...E.tools],`name`),r=new Set([...t.map(e=>e.name),...T.map(e=>e.name)]);return[...t,...T,...E.clients.filter(e=>!r.has(e.name))].map(e=>{let t;if(e.config.type===`sse`||e.config.type===`http`)t={type:e.config.type,url:e.config.url,headers:e.config.headers};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`?hn(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 Be(){try{await wc()&&await Xe()}catch(e){J(e)}}let Ve=null;r()||(t(process.env.CLAUDE_CODE_SYNC_PLUGIN_INSTALL)?Ve=Be():Be());let He=_c(()=>!re),Ue=a,Je=h;async function Ye(){let{agentDefinitions:e}=await Qi(m);Ue=await Fe(X());let t=Je.filter(e=>e.source===`flagSettings`);Je=[...e.allAgents,...t]}async function Xe(){let{servers:e}=await ae(),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(d))n.type===`sdk`&&!(e in t)&&(t[e]=n);let{response:n,sdkServersChanged:r}=await Ie(t);r&&ke(),K(`Headless MCP refresh: added=${n.added.length}, removed=${n.removed.length}`)}let et=Xi.subscribe(()=>{Ln(),Fe(X()).then(e=>{Ue=e})}),tt=()=>{setTimeout(()=>{!ut()||ot()||y||(async()=>{let e=await fn({basePrompt:`<${qr}>${new Date().toLocaleTimeString()}</${qr}>`,currentDir:X(),shouldCreate:()=>!y});if(y){await cn({commands:e});return}for(let t of e)In({...t,uuid:Y()});nt()})().catch(e=>{J(e),K(`[Proactive] failed to create headless tick: ${e}`,{level:`error`})})},0)};ye(()=>{b&&Pe(`now`).length>0&&b.abort(`interrupt`)});let nt=async()=>{if(re)return;if(re=!0,v=void 0,pe(`running`),He.stop(),k(`run_entry`),await ke(),k(`after_updateSdkMcp`),Ve){let e=parseInt(process.env.CLAUDE_CODE_SYNC_PLUGIN_INSTALL_TIMEOUT_MS||``,10);if(e>0){let t=Oi(e).then(()=>`timeout`);await Promise.race([Ve,t])===`timeout`&&(J(Error(`CLAUDE_CODE_SYNC_PLUGIN_INSTALL: plugin installation timed out after ${e}ms`)),$r(`tengu_sync_plugin_install_timeout`,{timeout_ms:e}))}else await Ve;Ve=null,await Ye();let{setupPluginHookHotReload:t}=await import(`./loadPluginHooks-C_msxVIc.js`);t()}let t=e=>e.agentId===void 0;try{let r,i=!1,a=async()=>{for(;r=qe(t);){if(r.mode!==`prompt`&&r.mode!==`orphaned-permission`&&r.mode!==`task-notification`)throw Error(`only prompt commands are supported in streaming mode`);let i=[r];if(r.mode===`prompt`)for(;jc(r,Ae(t));)i.push(qe(t));let a=await vn(i);if(i=a.attachmentCommands,i.length===0)continue;r=i[0],r.mode===`prompt`&&i.length>1&&(r={...r,value:Ac(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&&x.enqueue({type:`user`,content:e.value,message:{role:`user`,content:e.value},session_id:U(),parent_tool_use_id:null,uuid:e.uuid,isReplay:!0});let s=f(),c=[...s.mcp.clients,...T,...E.clients];De(c);let d=Me(s);for(let e of o)Tn(e,`started`);if(r.mode===`task-notification`){let e=typeof r.value==`string`?r.value:``,t=e.match(/<task-id>([^<]+)<\/task-id>/),n=e.match(/<tool-use-id>([^<]+)<\/tool-use-id>/),i=e.match(/<output-file>([^<]+)<\/output-file>/),a=e.match(/<status>([^<]+)<\/status>/),o=e.match(/<summary>([^<]+)<\/summary>/),s=e=>e===`completed`||e===`failed`||e===`stopped`||e===`killed`,c=a?.[1],l=s(c)?c===`killed`?`stopped`:c:`completed`,u=e.match(/<usage>([\s\S]*?)<\/usage>/)?.[1]??``,d=u.match(/<total_tokens>(\d+)<\/total_tokens>/),f=u.match(/<tool_uses>(\d+)<\/tool_uses>/),p=u.match(/<duration_ms>(\d+)<\/duration_ms>/);a&&x.enqueue({type:`system`,subtype:`task_notification`,task_id:t?.[1]??``,tool_use_id:n?.[1],status:l,output_file:i?.[1]??``,summary:o?.[1]??``,usage:d&&f?{total_tokens:parseInt(d[1],10),tool_uses:parseInt(f[1],10),duration_ms:p?parseInt(p[1],10):0}:void 0,session_id:U(),uuid:Y()})}let p=r.value,h=a.claimedCommands;if(C.abortController?.abort(),C.abortController=null,C.pendingSuggestion=null,C.pendingLastEmittedEntry=null,C.lastEmitted&&r.mode===`prompt`){let e=typeof p==`string`?p:p.find(e=>e.type===`text`)?.text;typeof e==`string`&&ee(C.lastEmitted.text,e,C.lastEmitted.emittedAt,C.lastEmitted.promptId,C.lastEmitted.generationRequestId),C.lastEmitted=null}b=On(),k(`before_ask`),Gn();let g=r,te=!1;try{if(await ni(g.workload??_.workload,async()=>{for await(let e of Ii({commands:Yt([...Ue,...s.mcp.commands],`name`),prompt:p,promptUuid:g.uuid,isMeta:g.isMeta,cwd:X(),tools:d,verbose:_.verbose,mcpClients:c,thinkingConfig:_.thinkingConfig,maxTurns:_.maxTurns,maxBudgetUsd:_.maxBudgetUsd,taskBudget:_.taskBudget,canUseTool:u,userSpecifiedModel:ge,fallbackModel:_.fallbackModel,jsonSchema:pr()??_.jsonSchema,mutableMessages:w,getReadFileCache:()=>ue.size===0?le:se(le,ue),setReadFileCache:e=>{le=e;for(let[e,t]of ue.entries()){let n=le.get(e);(!n||t.timestamp>n.timestamp)&&le.set(e,t)}ue.clear()},customSystemPrompt:_.systemPrompt,appendSystemPrompt:_.appendSystemPrompt,getAppState:f,setAppState:m,abortController:b,replayUserMessages:_.replayUserMessages,includePartialMessages:_.includePartialMessages,handleElicitation:(e,t,r)=>n.handleElicitation(e,t.message,void 0,r,t.mode,t.url,`elicitationId`in t?t.elicitationId:void 0),agents:Je,orphanedPermission:g.orphanedPermission,setSDKStatus:e=>{x.enqueue({type:`system`,subtype:`status`,status:e,session_id:U(),uuid:Y()})}}))if(e.type===`result`){te=!!e.is_error;for(let e of jn())x.enqueue(e);Lt(f()).some(e=>(e.type===`local_agent`||e.type===`local_workflow`)&&Rt(e))?ie=e:(ie=null,x.enqueue(e))}else{for(let e of jn())x.enqueue(e);x.enqueue(e)}}),te)await Ht({commands:h,outcome:{type:`failed`,message:`ask() returned an error result`},currentDir:X(),priority:`later`,workload:g.workload??_.workload});else{let e=await Ht({commands:h,outcome:{type:`completed`},currentDir:X(),priority:`later`,workload:g.workload??_.workload});for(let t of e)In({...t,uuid:Y()})}}catch(e){throw await Ht({commands:h,outcome:{type:`failed`,error:e},currentDir:X(),priority:`later`,workload:g.workload??_.workload}),e}for(let e of o)Tn(e,`completed`);if(_.promptSuggestions&&!e(process.env.CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION)){C.abortController?.abort();let e=new AbortController;C.abortController=e;let t=_e();if(!t)Jt(`sdk_no_params`,void 0,void 0,`sdk`);else{let n={promise:null};n.promise=(async()=>{try{let n=await je(e,w,f,t,`sdk`);if(!n||e.signal.aborted)return;let r={type:`prompt_suggestion`,suggestion:n.suggestion,uuid:Y(),session_id:U()},i={text:n.suggestion,emittedAt:Date.now(),promptId:n.promptId,generationRequestId:n.generationRequestId};ie?(C.pendingSuggestion=r,C.pendingLastEmittedEntry={text:i.text,promptId:i.promptId,generationRequestId:i.generationRequestId}):(C.lastEmitted=i,x.enqueue(r))}catch(e){if(e instanceof Error&&(e.name===`AbortError`||e.name===`APIUserAbortError`)){Jt(`aborted`,void 0,void 0,`sdk`);return}J(Sr(e))}finally{C.inflightPromise===n.promise&&(C.inflightPromise=null)}})(),C.inflightPromise=n.promise}}l(),gt(),ft()}};do{for(let e of jn())x.enqueue(e);v=`draining_commands`,await a(),i=!1;{let e=Lt(f()).some(e=>Rt(e)),n=Ae(t)!==void 0;(e||n)&&(i=!0,n||(v=`waiting_for_agents`,await Oi(100)))}}while(i);ie&&(x.enqueue(ie),ie=null,C.pendingSuggestion&&(x.enqueue(C.pendingSuggestion),C.pendingLastEmittedEntry&&(C.lastEmitted={...C.pendingLastEmittedEntry,emittedAt:Date.now()},C.pendingLastEmittedEntry=null),C.pendingSuggestion=null))}catch(e){try{await n.write({type:`result`,subtype:`error_during_execution`,duration_ms:0,duration_api_ms:0,is_error:!0,num_turns:0,stop_reason:null,session_id:U(),total_cost_usd:0,usage:Sn,modelUsage:{},permission_denials:[],uuid:Y(),errors:[G(e),...Yr().map(e=>e.error)]})}catch{}C.abortController?.abort(),A(1);return}finally{if(v=`finally_flush`,await n.flushInternalEvents(),v=`finally_post_flush`,!Mn()){pe(`idle`);for(let e of jn())x.enqueue(e)}re=!1,He.start()}if(ut()&&!ot()&&Ae(t)===void 0&&!y){tt();return}if(Ae(t)!==void 0){nt();return}y&&(C.inflightPromise&&await Promise.race([C.inflightPromise,Oi(5e3)]),C.abortController?.abort(),C.abortController=null,await pn(),et(),Ge.delete(ce),x.done())},D=(e,t)=>{x.enqueue({type:`control_response`,response:{subtype:`success`,request_id:e.request_id,response:t}})},O=(e,t)=>{x.enqueue({type:`control_response`,response:{subtype:`error`,request_id:e.request_id,error:t}})},it=new Set;return n.setUnexpectedResponseCallback(async e=>{await Uc({message:e,setAppState:m,handledToolUseIds:it,onEnqueued:()=>{nt()}})}),(async()=>{let e=!1;Ar(`info`,`cli_message_loop_started`);for await(let t of n.structuredInput){let r=`uuid`in t?t.uuid:void 0;if(r&&t.type!==`user`&&t.type!==`control_response`&&Tn(r,`completed`),t.type===`control_request`){let r=t,o=r.request;if(r.request.subtype===`interrupt`)m(e=>({...e,attribution:{...e.attribution,escapeCount:e.attribution.escapeCount+1}})),b&&b.abort(),C.abortController?.abort(),C.abortController=null,C.lastEmitted=null,C.pendingSuggestion=null,D(r);else if(o.subtype===`end_session`){K(`[print.ts] end_session received, reason=${o.reason??`unspecified`}`),b&&b.abort(),C.abortController?.abort(),C.abortController=null,C.lastEmitted=null,C.pendingSuggestion=null,D(r);break}else if(r.request.subtype===`initialize`){if(r.request.sdkMcpServers&&r.request.sdkMcpServers.length>0)for(let e of r.request.sdkMcpServers)d[e]={type:`sdk`,name:e};await Ic(r.request,r.request_id,e,x,a,me,n,_,h,f),r.request.promptSuggestions&&m(e=>e.promptSuggestionEnabled?e:{...e,promptSuggestionEnabled:!0}),r.request.agentProgressSummaries&&sr(!0),e=!0,Zt()&&nt()}else if(r.request.subtype===`set_permission_mode`){let e=r.request;m(t=>({...t,toolPermissionContext:Rc(e,r.request_id,t.toolPermissionContext,x)}))}else if(r.request.subtype===`set_model`){let e=r.request.model??`default`,t=e==="default"?fi():e;ge=t,ur(t),Re({model:t}),ve(e,t),D(r)}else if(r.request.subtype===`set_max_thinking_tokens`)r.request.max_thinking_tokens===null?_.thinkingConfig=void 0:r.request.max_thinking_tokens===0?_.thinkingConfig={type:`disabled`}:_.thinkingConfig={type:`enabled`,budgetTokens:r.request.max_thinking_tokens},D(r);else if(r.request.subtype===`mcp_status`)D(r,{mcpServers:ze()});else if(r.request.subtype===`get_context_usage`)try{let e=f(),t=await Wi({messages:w,getAppState:f,options:{mainLoopModel:mi(),tools:Me(e),agentDefinitions:e.agentDefinitions,customSystemPrompt:_.systemPrompt,appendSystemPrompt:_.appendSystemPrompt}});D(r,{...t})}catch(e){O(r,G(e))}else if(r.request.subtype===`mcp_message`){let e=r.request,t=T.find(t=>t.name===e.server_name);t&&t.type===`connected`&&t.client?.transport?.onmessage&&t.client.transport.onmessage(e.message),D(r)}else if(r.request.subtype===`rewind_files`){let e=f(),t=await Lc(r.request.user_message_id,e,m,r.request.dry_run??!1);t.canRewind||r.request.dry_run?D(r,t):O(r,t.error??`Unexpected error`)}else if(r.request.subtype===`cancel_async_message`){let e=r.request.message_uuid,t=S(t=>t.uuid===e);D(r,{cancelled:t.length>0})}else if(r.request.subtype===`seed_read_state`){try{let e=Fr(r.request.path),t=Math.floor((await ra(e)).mtimeMs);if(t<=r.request.mtime){let n=await na(e,`utf-8`),r=(n.charCodeAt(0)===65279?n.slice(1):n).replaceAll(`\r
11
+ Tip: Simplify your schema or check if the output format matches the expected structure.`)}}if(l(),Ur())try{let{drainPendingExtraction:e}=await import(`./extractMemories-D4Dl1itt.js`);await e()}catch{}A(S?.type===`result`&&S?.is_error?1:0)}function Nc(n,i,a,o,c,u,d,f,m,h,_,ne){let re=!1,v,y=!1,ie=null,b,x=n.outbound;process.on(`SIGINT`,()=>{Ar(`info`,`shutdown_signal`,{signal:`SIGINT`}),b&&!b.signal.aborted&&b.abort(),Bt(0)}),Cr(async()=>{let e={};for(let t of Lt(f()))Rt(t)&&(e[t.type]=(e[t.type]??0)+1);Ar(`info`,`run_state_at_shutdown`,{run_active:re,run_phase:v,worker_status:g(),internal_events_pending:n.internalEventsPending,bg_tasks:e})}),be(e=>{(e==="default"||e===`acceptEdits`||e===`bypassPermissions`||e===`plan`||e===`auto`||e===`dontAsk`)&&x.enqueue({type:`system`,subtype:`status`,status:null,permissionMode:e,uuid:Y(),session_id:U()})});let C={abortController:null,inflightPromise:null,lastEmitted:null,pendingSuggestion:null,pendingLastEmittedEntry:null},ce=e=>{let t=Fi(e);t&&x.enqueue({type:`rate_limit_event`,rate_limit_info:t,uuid:Y(),session_id:U()})};Ge.add(ce);let w=c,le=Dt(c,X(),100),ue=Ze(100),fe=process.env.CLAUDE_CODE_RESUME_INTERRUPTED_TURN;ne&&ne.kind!==`none`&&fe&&(K(`[print.ts] Auto-resuming interrupted turn (kind: ${ne.kind})`),Bc(w,ne.message),In({mode:`prompt`,value:ne.message.message.content,uuid:Y()}));let me=Ki().map(e=>{let t=e.value===null?`default`:e.value,n=t==="default"?fi():ci(t),r=Ce(n),i=ri(e.value),a=s(n);return{name:t,value:t,displayName:e.label,description:e.description,...r&&{supportsAdaptiveThinking:!0},...i&&{supportsFastMode:!0},...a&&{supportsAutoMode:!0}}}),ge=_.userSpecifiedModel;function ve(e,t){let n=Cn(e,di(t));w.push(...n);for(let e of n)typeof e.message.content==`string`&&e.message.content.includes(`<local-command-stdout>`)&&x.enqueue({type:`user`,content:e.message.content,message:e.message,session_id:U(),parent_tool_use_id:null,uuid:e.uuid,timestamp:e.timestamp,isReplay:!0})}let T=[],Te=[],Ee=new Set;function De(e){for(let t of e){if(t.type!==`connected`||Ee.has(t.name)||t.config.type===`sdk`)continue;let e=t.name;try{t.client.setRequestHandler(oe,async(t,r)=>{Jr(e,`Elicitation request received in print mode: ${W(t)}`);let i=t.params.mode===`url`?`url`:`form`;$r(`tengu_mcp_elicitation_shown`,{mode:i});let a=await p(e,t.params,r.signal);if(a)return Jr(e,`Elicitation resolved by hook: ${W(a)}`),$r(`tengu_mcp_elicitation_response`,{mode:i,action:a.action}),a;let o=`url`in t.params?t.params.url:void 0,s=`requestedSchema`in t.params?t.params.requestedSchema:void 0,c=`elicitationId`in t.params?t.params.elicitationId:void 0,l=await n.handleElicitation(e,t.params.message,s,r.signal,i,o,c),u=await Nt(e,l,r.signal,i,c);return $r(`tengu_mcp_elicitation_response`,{mode:i,action:u.action}),u}),t.client.setNotificationHandler($e,t=>{let{elicitationId:n}=t.params;Jr(e,`Elicitation completion notification: ${n}`),Yn({message:`MCP server "${e}" confirmed elicitation ${n} complete`,notificationType:`elicitation_complete`}),x.enqueue({type:`system`,subtype:`elicitation_complete`,mcp_server_name:e,elicitation_id:n,uuid:Y(),session_id:U()})}),Ee.add(e)}catch{}}}async function ke(){let e=new Set(Object.keys(d)),t=new Set(T.map(e=>e.name)),r=Array.from(e).some(e=>!t.has(e)),i=Array.from(t).some(t=>!e.has(t)),a=T.some(e=>e.type===`pending`),o=T.some(e=>e.type===`failed`);if(r||i||a||o){for(let t of T)e.has(t.name)||t.type===`connected`&&await t.cleanup();let r=await ln(d,(e,t)=>n.sendMcpMessage(e,t));T=r.clients,Te=r.tools;let i=kr([...t,...e]);m(e=>({...e,mcp:{...e.mcp,tools:[...e.mcp.tools.filter(e=>!i.some(t=>e.name.startsWith(zr(t)))),...Te]}})),Qe(T)}}ke();let E={clients:[],tools:[],configs:{}},Me=e=>{let t=Ke(e.toolPermissionContext,e.mcp.tools),n=Yt(ji([...o,...Te,...E.tools],t,e.toolPermissionContext.mode),`name`);_.permissionPromptToolName&&(n=n.filter(e=>!vi(e,_.permissionPromptToolName)));let r=pr();if(r&&!_.jsonSchema){let e=yi(r);`tool`in e&&(n=[...n,e.tool])}return n},Ne=Promise.resolve({response:{added:[],removed:[],errors:{}},sdkServersChanged:!1});function Ie(e){let t=async()=>{let t=new Set(T.map(e=>e.name)),n=await Gc(e,{configs:d,clients:T,tools:Te},E,m);for(let e of Object.keys(d))delete d[e];if(Object.assign(d,n.newSdkState.configs),T=n.newSdkState.clients,Te=n.newSdkState.tools,E=n.newDynamicState,n.sdkServersChanged){let e=new Set(T.map(e=>e.name)),n=kr([...t,...e]);m(e=>({...e,mcp:{...e.mcp,tools:[...e.mcp.tools.filter(e=>!n.some(t=>e.name.startsWith(zr(t)))),...Te]}}))}return{response:n.response,sdkServersChanged:n.sdkServersChanged}};return Ne=Ne.then(t,t),Ne}function ze(){let e=f(),t=e.mcp.clients,n=Yt([...e.mcp.tools,...E.tools],`name`),r=new Set([...t.map(e=>e.name),...T.map(e=>e.name)]);return[...t,...T,...E.clients.filter(e=>!r.has(e.name))].map(e=>{let t;if(e.config.type===`sse`||e.config.type===`http`)t={type:e.config.type,url:e.config.url,headers:e.config.headers};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`?hn(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 Be(){try{await wc()&&await Xe()}catch(e){J(e)}}let Ve=null;r()||(t(process.env.CLAUDE_CODE_SYNC_PLUGIN_INSTALL)?Ve=Be():Be());let He=_c(()=>!re),Ue=a,Je=h;async function Ye(){let{agentDefinitions:e}=await Qi(m);Ue=await Fe(X());let t=Je.filter(e=>e.source===`flagSettings`);Je=[...e.allAgents,...t]}async function Xe(){let{servers:e}=await ae(),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(d))n.type===`sdk`&&!(e in t)&&(t[e]=n);let{response:n,sdkServersChanged:r}=await Ie(t);r&&ke(),K(`Headless MCP refresh: added=${n.added.length}, removed=${n.removed.length}`)}let et=Xi.subscribe(()=>{Ln(),Fe(X()).then(e=>{Ue=e})}),tt=()=>{setTimeout(()=>{!ut()||ot()||y||(async()=>{let e=await fn({basePrompt:`<${qr}>${new Date().toLocaleTimeString()}</${qr}>`,currentDir:X(),shouldCreate:()=>!y});if(y){await cn({commands:e});return}for(let t of e)In({...t,uuid:Y()});nt()})().catch(e=>{J(e),K(`[Proactive] failed to create headless tick: ${e}`,{level:`error`})})},0)};ye(()=>{b&&Pe(`now`).length>0&&b.abort(`interrupt`)});let nt=async()=>{if(re)return;if(re=!0,v=void 0,pe(`running`),He.stop(),k(`run_entry`),await ke(),k(`after_updateSdkMcp`),Ve){let e=parseInt(process.env.CLAUDE_CODE_SYNC_PLUGIN_INSTALL_TIMEOUT_MS||``,10);if(e>0){let t=Oi(e).then(()=>`timeout`);await Promise.race([Ve,t])===`timeout`&&(J(Error(`CLAUDE_CODE_SYNC_PLUGIN_INSTALL: plugin installation timed out after ${e}ms`)),$r(`tengu_sync_plugin_install_timeout`,{timeout_ms:e}))}else await Ve;Ve=null,await Ye();let{setupPluginHookHotReload:t}=await import(`./loadPluginHooks-BSwCtQ6T.js`);t()}let t=e=>e.agentId===void 0;try{let r,i=!1,a=async()=>{for(;r=qe(t);){if(r.mode!==`prompt`&&r.mode!==`orphaned-permission`&&r.mode!==`task-notification`)throw Error(`only prompt commands are supported in streaming mode`);let i=[r];if(r.mode===`prompt`)for(;jc(r,Ae(t));)i.push(qe(t));let a=await vn(i);if(i=a.attachmentCommands,i.length===0)continue;r=i[0],r.mode===`prompt`&&i.length>1&&(r={...r,value:Ac(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&&x.enqueue({type:`user`,content:e.value,message:{role:`user`,content:e.value},session_id:U(),parent_tool_use_id:null,uuid:e.uuid,isReplay:!0});let s=f(),c=[...s.mcp.clients,...T,...E.clients];De(c);let d=Me(s);for(let e of o)Tn(e,`started`);if(r.mode===`task-notification`){let e=typeof r.value==`string`?r.value:``,t=e.match(/<task-id>([^<]+)<\/task-id>/),n=e.match(/<tool-use-id>([^<]+)<\/tool-use-id>/),i=e.match(/<output-file>([^<]+)<\/output-file>/),a=e.match(/<status>([^<]+)<\/status>/),o=e.match(/<summary>([^<]+)<\/summary>/),s=e=>e===`completed`||e===`failed`||e===`stopped`||e===`killed`,c=a?.[1],l=s(c)?c===`killed`?`stopped`:c:`completed`,u=e.match(/<usage>([\s\S]*?)<\/usage>/)?.[1]??``,d=u.match(/<total_tokens>(\d+)<\/total_tokens>/),f=u.match(/<tool_uses>(\d+)<\/tool_uses>/),p=u.match(/<duration_ms>(\d+)<\/duration_ms>/);a&&x.enqueue({type:`system`,subtype:`task_notification`,task_id:t?.[1]??``,tool_use_id:n?.[1],status:l,output_file:i?.[1]??``,summary:o?.[1]??``,usage:d&&f?{total_tokens:parseInt(d[1],10),tool_uses:parseInt(f[1],10),duration_ms:p?parseInt(p[1],10):0}:void 0,session_id:U(),uuid:Y()})}let p=r.value,h=a.claimedCommands;if(C.abortController?.abort(),C.abortController=null,C.pendingSuggestion=null,C.pendingLastEmittedEntry=null,C.lastEmitted&&r.mode===`prompt`){let e=typeof p==`string`?p:p.find(e=>e.type===`text`)?.text;typeof e==`string`&&ee(C.lastEmitted.text,e,C.lastEmitted.emittedAt,C.lastEmitted.promptId,C.lastEmitted.generationRequestId),C.lastEmitted=null}b=On(),k(`before_ask`),Gn();let g=r,te=!1;try{if(await ni(g.workload??_.workload,async()=>{for await(let e of Ii({commands:Yt([...Ue,...s.mcp.commands],`name`),prompt:p,promptUuid:g.uuid,isMeta:g.isMeta,cwd:X(),tools:d,verbose:_.verbose,mcpClients:c,thinkingConfig:_.thinkingConfig,maxTurns:_.maxTurns,maxBudgetUsd:_.maxBudgetUsd,taskBudget:_.taskBudget,canUseTool:u,userSpecifiedModel:ge,fallbackModel:_.fallbackModel,jsonSchema:pr()??_.jsonSchema,mutableMessages:w,getReadFileCache:()=>ue.size===0?le:se(le,ue),setReadFileCache:e=>{le=e;for(let[e,t]of ue.entries()){let n=le.get(e);(!n||t.timestamp>n.timestamp)&&le.set(e,t)}ue.clear()},customSystemPrompt:_.systemPrompt,appendSystemPrompt:_.appendSystemPrompt,getAppState:f,setAppState:m,abortController:b,replayUserMessages:_.replayUserMessages,includePartialMessages:_.includePartialMessages,handleElicitation:(e,t,r)=>n.handleElicitation(e,t.message,void 0,r,t.mode,t.url,`elicitationId`in t?t.elicitationId:void 0),agents:Je,orphanedPermission:g.orphanedPermission,setSDKStatus:e=>{x.enqueue({type:`system`,subtype:`status`,status:e,session_id:U(),uuid:Y()})}}))if(e.type===`result`){te=!!e.is_error;for(let e of jn())x.enqueue(e);Lt(f()).some(e=>(e.type===`local_agent`||e.type===`local_workflow`)&&Rt(e))?ie=e:(ie=null,x.enqueue(e))}else{for(let e of jn())x.enqueue(e);x.enqueue(e)}}),te)await Ht({commands:h,outcome:{type:`failed`,message:`ask() returned an error result`},currentDir:X(),priority:`later`,workload:g.workload??_.workload});else{let e=await Ht({commands:h,outcome:{type:`completed`},currentDir:X(),priority:`later`,workload:g.workload??_.workload});for(let t of e)In({...t,uuid:Y()})}}catch(e){throw await Ht({commands:h,outcome:{type:`failed`,error:e},currentDir:X(),priority:`later`,workload:g.workload??_.workload}),e}for(let e of o)Tn(e,`completed`);if(_.promptSuggestions&&!e(process.env.CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION)){C.abortController?.abort();let e=new AbortController;C.abortController=e;let t=_e();if(!t)Jt(`sdk_no_params`,void 0,void 0,`sdk`);else{let n={promise:null};n.promise=(async()=>{try{let n=await je(e,w,f,t,`sdk`);if(!n||e.signal.aborted)return;let r={type:`prompt_suggestion`,suggestion:n.suggestion,uuid:Y(),session_id:U()},i={text:n.suggestion,emittedAt:Date.now(),promptId:n.promptId,generationRequestId:n.generationRequestId};ie?(C.pendingSuggestion=r,C.pendingLastEmittedEntry={text:i.text,promptId:i.promptId,generationRequestId:i.generationRequestId}):(C.lastEmitted=i,x.enqueue(r))}catch(e){if(e instanceof Error&&(e.name===`AbortError`||e.name===`APIUserAbortError`)){Jt(`aborted`,void 0,void 0,`sdk`);return}J(Sr(e))}finally{C.inflightPromise===n.promise&&(C.inflightPromise=null)}})(),C.inflightPromise=n.promise}}l(),gt(),ft()}};do{for(let e of jn())x.enqueue(e);v=`draining_commands`,await a(),i=!1;{let e=Lt(f()).some(e=>Rt(e)),n=Ae(t)!==void 0;(e||n)&&(i=!0,n||(v=`waiting_for_agents`,await Oi(100)))}}while(i);ie&&(x.enqueue(ie),ie=null,C.pendingSuggestion&&(x.enqueue(C.pendingSuggestion),C.pendingLastEmittedEntry&&(C.lastEmitted={...C.pendingLastEmittedEntry,emittedAt:Date.now()},C.pendingLastEmittedEntry=null),C.pendingSuggestion=null))}catch(e){try{await n.write({type:`result`,subtype:`error_during_execution`,duration_ms:0,duration_api_ms:0,is_error:!0,num_turns:0,stop_reason:null,session_id:U(),total_cost_usd:0,usage:Sn,modelUsage:{},permission_denials:[],uuid:Y(),errors:[G(e),...Yr().map(e=>e.error)]})}catch{}C.abortController?.abort(),A(1);return}finally{if(v=`finally_flush`,await n.flushInternalEvents(),v=`finally_post_flush`,!Mn()){pe(`idle`);for(let e of jn())x.enqueue(e)}re=!1,He.start()}if(ut()&&!ot()&&Ae(t)===void 0&&!y){tt();return}if(Ae(t)!==void 0){nt();return}y&&(C.inflightPromise&&await Promise.race([C.inflightPromise,Oi(5e3)]),C.abortController?.abort(),C.abortController=null,await pn(),et(),Ge.delete(ce),x.done())},D=(e,t)=>{x.enqueue({type:`control_response`,response:{subtype:`success`,request_id:e.request_id,response:t}})},O=(e,t)=>{x.enqueue({type:`control_response`,response:{subtype:`error`,request_id:e.request_id,error:t}})},it=new Set;return n.setUnexpectedResponseCallback(async e=>{await Uc({message:e,setAppState:m,handledToolUseIds:it,onEnqueued:()=>{nt()}})}),(async()=>{let e=!1;Ar(`info`,`cli_message_loop_started`);for await(let t of n.structuredInput){let r=`uuid`in t?t.uuid:void 0;if(r&&t.type!==`user`&&t.type!==`control_response`&&Tn(r,`completed`),t.type===`control_request`){let r=t,o=r.request;if(r.request.subtype===`interrupt`)m(e=>({...e,attribution:{...e.attribution,escapeCount:e.attribution.escapeCount+1}})),b&&b.abort(),C.abortController?.abort(),C.abortController=null,C.lastEmitted=null,C.pendingSuggestion=null,D(r);else if(o.subtype===`end_session`){K(`[print.ts] end_session received, reason=${o.reason??`unspecified`}`),b&&b.abort(),C.abortController?.abort(),C.abortController=null,C.lastEmitted=null,C.pendingSuggestion=null,D(r);break}else if(r.request.subtype===`initialize`){if(r.request.sdkMcpServers&&r.request.sdkMcpServers.length>0)for(let e of r.request.sdkMcpServers)d[e]={type:`sdk`,name:e};await Ic(r.request,r.request_id,e,x,a,me,n,_,h,f),r.request.promptSuggestions&&m(e=>e.promptSuggestionEnabled?e:{...e,promptSuggestionEnabled:!0}),r.request.agentProgressSummaries&&sr(!0),e=!0,Zt()&&nt()}else if(r.request.subtype===`set_permission_mode`){let e=r.request;m(t=>({...t,toolPermissionContext:Rc(e,r.request_id,t.toolPermissionContext,x)}))}else if(r.request.subtype===`set_model`){let e=r.request.model??`default`,t=e==="default"?fi():e;ge=t,ur(t),Re({model:t}),ve(e,t),D(r)}else if(r.request.subtype===`set_max_thinking_tokens`)r.request.max_thinking_tokens===null?_.thinkingConfig=void 0:r.request.max_thinking_tokens===0?_.thinkingConfig={type:`disabled`}:_.thinkingConfig={type:`enabled`,budgetTokens:r.request.max_thinking_tokens},D(r);else if(r.request.subtype===`mcp_status`)D(r,{mcpServers:ze()});else if(r.request.subtype===`get_context_usage`)try{let e=f(),t=await Wi({messages:w,getAppState:f,options:{mainLoopModel:mi(),tools:Me(e),agentDefinitions:e.agentDefinitions,customSystemPrompt:_.systemPrompt,appendSystemPrompt:_.appendSystemPrompt}});D(r,{...t})}catch(e){O(r,G(e))}else if(r.request.subtype===`mcp_message`){let e=r.request,t=T.find(t=>t.name===e.server_name);t&&t.type===`connected`&&t.client?.transport?.onmessage&&t.client.transport.onmessage(e.message),D(r)}else if(r.request.subtype===`rewind_files`){let e=f(),t=await Lc(r.request.user_message_id,e,m,r.request.dry_run??!1);t.canRewind||r.request.dry_run?D(r,t):O(r,t.error??`Unexpected error`)}else if(r.request.subtype===`cancel_async_message`){let e=r.request.message_uuid,t=S(t=>t.uuid===e);D(r,{cancelled:t.length>0})}else if(r.request.subtype===`seed_read_state`){try{let e=Fr(r.request.path),t=Math.floor((await ra(e)).mtimeMs);if(t<=r.request.mtime){let n=await na(e,`utf-8`),r=(n.charCodeAt(0)===65279?n.slice(1):n).replaceAll(`\r
12
12
  `,`
13
13
  `);ue.set(e,{content:r,timestamp:t,offset:void 0,limit:void 0})}}catch{}D(r)}else if(r.request.subtype===`mcp_set_servers`){let{response:e,sdkServersChanged:t}=await Ie(r.request.servers);D(r,e),t&&ke()}else if(r.request.subtype===`reload_plugins`)try{let e=await Qi(m),t=Je.filter(e=>e.source===`flagSettings`);Je=[...e.agentDefinitions.allAgents,...t];let n=[],[i,a,o]=await Promise.allSettled([Fe(X()),Xe(),we()]);i.status===`fulfilled`?Ue=i.value:J(i.reason),a.status===`rejected`&&J(a.reason),o.status===`fulfilled`?n=o.value.enabled.map(e=>({name:e.name,path:e.path,source:e.source})):J(o.reason),D(r,{commands:Ue.filter(e=>e.userInvocable!==!1).map(e=>({name:Le(e),description:de(e),argumentHint:e.argumentHint||``})),agents:Je.map(e=>({name:e.agentType,description:e.whenToUse,model:e.model===`inherit`?void 0:e.model})),plugins:n,mcpServers:ze(),error_count:e.error_count})}catch(e){O(r,G(e))}else if(r.request.subtype===`mcp_reconnect`){let e=f(),{serverName:t}=r.request;Ee.delete(t);let n=zn(t)??i.find(e=>e.name===t)?.config??T.find(e=>e.name===t)?.config??E.clients.find(e=>e.name===t)?.config??e.mcp.clients.find(e=>e.name===t)?.config??null;if(!n)O(r,`Server not found: ${t}`);else{let e=await Dn(t,n),i=zr(t);if(m(n=>({...n,mcp:{...n.mcp,clients:n.mcp.clients.map(n=>n.name===t?e.client:n),tools:[...Ti(n.mcp.tools,e=>e.name?.startsWith(i)),...e.tools],commands:[...Ti(n.mcp.commands,e=>bn(e,t)),...e.commands],resources:e.resources&&e.resources.length>0?{...n.mcp.resources,[t]:e.resources}:wi(n.mcp.resources,t)}})),E={...E,clients:[...E.clients.filter(e=>e.name!==t),e.client],tools:[...E.tools.filter(e=>!e.name?.startsWith(i)),...e.tools]},e.client.type===`connected`)De([e.client]),D(r);else{let t=e.client.type===`failed`?e.client.error??`Connection failed`:`Server status: ${e.client.type}`;O(r,t)}}}else if(r.request.subtype===`mcp_toggle`){let e=f(),{serverName:t,enabled:n}=r.request;Ee.delete(t);let a=zn(t)??i.find(e=>e.name===t)?.config??T.find(e=>e.name===t)?.config??E.clients.find(e=>e.name===t)?.config??e.mcp.clients.find(e=>e.name===t)?.config??null;if(!a)O(r,`Server not found: ${t}`);else if(n){Oe(t,!0);let e=await Dn(t,a),n=zr(t);if(m(r=>({...r,mcp:{...r.mcp,clients:r.mcp.clients.map(n=>n.name===t?e.client:n),tools:[...Ti(r.mcp.tools,e=>e.name?.startsWith(n)),...e.tools],commands:[...Ti(r.mcp.commands,e=>bn(e,t)),...e.commands],resources:e.resources&&e.resources.length>0?{...r.mcp.resources,[t]:e.resources}:wi(r.mcp.resources,t)}})),e.client.type===`connected`)De([e.client]),D(r);else{let t=e.client.type===`failed`?e.client.error??`Connection failed`:`Server status: ${e.client.type}`;O(r,t)}}else{Oe(t,!1);let n=[...i,...T,...E.clients,...e.mcp.clients].find(e=>e.name===t);n&&n.type===`connected`&&await xe(t,a);let o=zr(t);m(e=>({...e,mcp:{...e.mcp,clients:e.mcp.clients.map(e=>e.name===t?{name:t,type:`disabled`,config:a}:e),tools:Ti(e.mcp.tools,e=>e.name?.startsWith(o)),commands:Ti(e.mcp.commands,e=>bn(e,t)),resources:wi(e.mcp.resources,t)}})),D(r)}}else if(r.request.subtype===`apply_flag_settings`){let e=mi(),t=mr()??{},n=r.request.settings,i={...t,...n};for(let e of Object.keys(i))i[e]===null&&delete i[e];fr(i),Fn.notifyChange(`flagSettings`),`model`in n&&(n.model==null?ur(void 0):ur(String(n.model)));let a=mi();if(a!==e){ge=a;let e=n.model?String(n.model):`default`;Re({model:a}),ve(e,a)}D(r)}else if(r.request.subtype===`get_settings`){let e=mi();D(r,{...Br(),applied:{model:e}})}else if(r.request.subtype===`stop_task`){let{task_id:e}=r.request;try{await te(e,{getAppState:f,setAppState:m}),D(r,{})}catch(e){O(r,G(e))}}else if(o.subtype===`generate_session_title`){let e=o.description,t=o.persist,n=(b&&!b.signal.aborted?b:On()).signal;(async()=>{try{let i=await Ri(e,n);if(i&&t)try{Mt(U(),i)}catch(e){J(e)}D(r,{title:i})}catch(e){O(r,G(e))}})()}else if(o.subtype===`side_question`){let e=o.question;(async()=>{try{let t=_e(),n=t?{...t,toolUseContext:{...t.toolUseContext,abortController:On()}}:await Pi({tools:Me(f()),commands:Ue,mcpClients:[...f().mcp.clients,...T,...E.clients],messages:w,readFileState:le,getAppState:f,setAppState:m,customSystemPrompt:_.systemPrompt,appendSystemPrompt:_.appendSystemPrompt,thinkingConfig:_.thinkingConfig,agents:Je}),i=await Vi({question:e,cacheSafeParams:n});D(r,{response:i.response})}catch(e){O(r,G(e))}})()}else r.request.subtype===`set_proactive`?(r.request.enabled?ut()||(rt(`command`),tt()):he(),D(r)):O(r,`Unsupported control request subtype: ${r.request.subtype}`);continue}else if(t.type===`control_response`){_.replayUserMessages&&x.enqueue(t);continue}else if(t.type===`keep_alive`)continue;else if(t.type===`update_environment_variables`)continue;else if(t.type===`assistant`||t.type===`system`){let e=Li([t]);w.push(...e),t.type===`assistant`&&_.replayUserMessages&&x.enqueue(t);continue}if(t.type!==`user`)continue;let o=t;if(e=!0,o.uuid){let e=U(),t=await Se(e,o.uuid);if(t||Ec.has(o.uuid)){K(`Skipping duplicate user message: ${o.uuid}`),_.replayUserMessages&&(K(`Sending acknowledgment for duplicate user message: ${o.uuid}`),x.enqueue({type:`user`,content:o.message?.content??``,message:o.message,session_id:e,parent_tool_use_id:null,uuid:o.uuid,timestamp:o.timestamp,isReplay:!0})),t&&Tn(o.uuid,`completed`);continue}Oc(o.uuid)}In({mode:`prompt`,value:o.message.content,uuid:o.uuid,priority:o.priority}),m(e=>({...e,attribution:nn(e.attribution,e=>{We(e).catch(e=>{K(`Attribution: Failed to save snapshot: ${e}`)})})})),nt()}y=!0,re||(C.inflightPromise&&await Promise.race([C.inflightPromise,Oi(5e3)]),C.abortController?.abort(),C.abortController=null,await pn(),et(),Ge.delete(ce),x.done())})(),x}function Pc(e){let t=async(n,r,i,a,o,s)=>{let c=s??await _(n,r,i,a,o);if(c.behavior===`allow`||c.behavior===`deny`)return c;let{signal:l,cleanup:u}=Nn(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 tc(ec().parse($n(h.content[0].text)),e,r,i)};return t}function Fc(e,t,n,r){if(e===`stdio`)return t.createCanUseTool(r);if(!e)return async(e,t,n,r,i,a)=>a??await _(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=>vi(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`),A(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`),A(1),Error(t)}i=Pc(r)}return i(t,r,a,o,s,c)}}async function Ic(e,t,n,r,i,a,o,s,c,l){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&&(s.systemPrompt=e.systemPrompt),e.appendSystemPrompt!==void 0&&(s.appendSystemPrompt=e.appendSystemPrompt),e.promptSuggestions!==void 0&&(s.promptSuggestions=e.promptSuggestions),e.agents){let t=Pt(e.agents,`flagSettings`);c.push(...t)}if(s.agent){let e=ir()===s.agent,t=c.find(e=>e.agentType===s.agent);if(t&&!e){if(hr(t.agentType),!s.systemPrompt&&!xn(t)){let e=t.getSystemPrompt();e&&(s.systemPrompt=e)}!s.userSpecifiedModel&&t.model&&t.model!==`inherit`&&ur(ci(t.model)),t.initialPrompt&&o.prependUserMessage(t.initialPrompt)}else t?.initialPrompt&&o.prependUserMessage(t.initialPrompt)}let u=Pr()?.outputStyle||`default`,d=await Ne(_r());if(e.hooks){let t={};for(let[n,r]of Object.entries(e.hooks))t[n]=r.map(e=>{let t=e.hookCallbackIds.map(t=>o.createHookCallback(t,e.timeout));return{matcher:e.matcher,hooks:t}});lr(t)}e.jsonSchema&&dr(e.jsonSchema);let f={commands:i.filter(e=>e.userInvocable!==!1).map(e=>({name:Le(e),description:de(e),argumentHint:e.argumentHint||``})),agents:c.map(e=>({name:e.agentType,description:e.whenToUse,model:e.model===`inherit`?void 0:e.model})),output_style:u,available_output_styles:Object.keys(d),models:a,account:{apiProvider:oi()},pid:process.pid};if(ei()&&ai()){let e=l();f.fast_mode_state=ii(s.userSpecifiedModel??null,e.fastMode)}r.enqueue({type:`control_response`,response:{subtype:`success`,request_id:t,response:f}})}async function Lc(e,t,n,r){if(!He())return{canRewind:!1,error:`File rewinding is not enabled.`,filesChanged:[]};if(!pt(t.fileHistory,e))return{canRewind:!1,error:`No file checkpoint found for this message.`,filesChanged:[]};if(r){let n=await d(t.fileHistory,e);return{canRewind:!0,filesChanged:n?.filesChanged??[],insertions:n?.insertions,deletions:n?.deletions}}try{await yn(e=>n(t=>({...t,fileHistory:e(t.fileHistory)})),e)}catch(e){return{canRewind:!1,error:`Failed to rewind: ${G(e)}`,filesChanged:[]}}return{canRewind:!0,filesChanged:[]}}function Rc(e,t,n,r){if(e.mode===`bypassPermissions`){if(Pn())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`&&!ie()){let e=Un();return r.enqueue({type:`control_response`,response:{subtype:`error`,request_id:t,error:e?`Cannot set permission mode to auto: ${An(e)}`:`Cannot set permission mode to auto`}}),n}return r.enqueue({type:`control_response`,response:{subtype:`success`,request_id:t,response:{mode:e.mode}}}),{...m(n.mode,e.mode,n),mode:e.mode}}function zc(e,t){if(t===`stream-json`){let t={type:`result`,subtype:`error_during_execution`,duration_ms:0,duration_api_ms:0,is_error:!0,num_turns:0,stop_reason:null,session_id:U(),total_cost_usd:0,usage:Sn,modelUsage:{},permission_denials:[],uuid:Y(),errors:[e]};process.stdout.write(`${W(t)}\n`)}else process.stderr.write(`${e}\n`)}function Bc(e,t){let n=e.findIndex(e=>e.uuid===t.uuid);n!==-1&&e.splice(n,2)}async function Vc(e,t){let n=!or();if(t.continue)try{$r(`tengu_continue_print`,{});let r=await Ni(void 0,void 0);if(r)return t.forkSession||r.sessionId&&(cr(Tt(r.sessionId),r.fullPath?ea(r.fullPath):null),n&&await lt()),Yi(r,e),mt(t.forkSession?{...r,worktreeSession:void 0}:r),{messages:r.messages,turnInterruptionState:r.turnInterruptionState,agentSetting:r.agentSetting}}catch(e){return J(e),A(1),{messages:[]}}if(t.resume)try{$r(`tengu_resume_print`,{});let r=vc(typeof t.resume==`string`?t.resume:``);if(!r){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`),zc(e,t.outputFormat),A(1),{messages:[]}}let i=await Ni(r.sessionId,r.jsonlFile||void 0);if(!i||i.messages.length===0)return zc(`No conversation found with session ID: ${r.sessionId}`,t.outputFormat),A(1),{messages:[]};if(t.resumeSessionAt){let e=i.messages.findIndex(e=>e.uuid===t.resumeSessionAt);if(e<0)return zc(`No message found with message.uuid of: ${t.resumeSessionAt}`,t.outputFormat),A(1),{messages:[]};i.messages=e>=0?i.messages.slice(0,e+1):[]}return!t.forkSession&&i.sessionId&&(cr(Tt(i.sessionId),i.fullPath?ea(i.fullPath):null),n&&await lt()),Yi(i,e),mt(t.forkSession?{...i,worktreeSession:void 0}:i),{messages:i.messages,turnInterruptionState:i.turnInterruptionState,agentSetting:i.agentSetting}}catch(e){return J(e),zc(e instanceof Error?`Failed to resume session: ${e.message}`:`Failed to resume session with --print mode`,t.outputFormat),A(1),{messages:[]}}return{messages:await(t.sessionStartHooksPromise??u(`startup`))}}function Hc(e,t){let n;return n=typeof e==`string`?e.trim()===``?mn([]):mn([W({type:`user`,content:e,uuid:``,session_id:``,message:{role:`user`,content:e},parent_tool_use_id:null})]):e,new lc(n,t.replayUserMessages)}async function Uc({message:e,setAppState:t,onEnqueued:n,handledToolUseIds:r}){let i=e.response;if(i?.subtype===`success`&&i.response?.toolUseID&&typeof i.response.toolUseID==`string`){let e=i.response,t=e.toolUseID;if(!t)return!1;if(K(`handleOrphanedPermissionResponse: received orphaned control_response for toolUseID=${t} request_id=${i.request_id}`),r.has(t))return K(`handleOrphanedPermissionResponse: skipping duplicate orphaned permission for toolUseID=${t} (already handled)`),!1;let a=await ct(t);return a?(r.add(t),K(`handleOrphanedPermissionResponse: enqueuing orphaned permission for toolUseID=${t} messageID=${a.message.id}`),In({mode:`orphaned-permission`,value:[],orphanedPermission:{permissionResult:e,assistantMessage:a}}),n?.(),!0):(K(`handleOrphanedPermissionResponse: no unresolved tool_use found for toolUseID=${t} (already resolved in transcript)`),!1)}return!1}function Wc(e){return{...e,scope:`dynamic`}}async function Gc(e,t,n,r){let{allowed:i,blocked:a}=Xe(e),o={};for(let e of a)o[e]=`Blocked by enterprise policy (allowedMcpServers/deniedMcpServers)`;let s={},c={};for(let[e,t]of Object.entries(i))t.type===`sdk`?s[e]=t:c[e]=t;let l=new Set(Object.keys(t.configs)),u=new Set(Object.keys(s)),d=[],f=[],p={...t.configs},m=[...t.clients],h=[...t.tools];for(let e of l)if(!u.has(e)){let t=m.find(t=>t.name===e);t&&t.type===`connected`&&await t.cleanup(),m=m.filter(t=>t.name!==e);let n=`mcp__${e}__`;h=h.filter(e=>!e.name.startsWith(n)),delete p[e],f.push(e)}for(let[e,t]of Object.entries(s))if(!l.has(e)){p[e]=t;let n={type:`pending`,name:e,config:{...t,scope:`dynamic`}};m=[...m,n],d.push(e)}let g=await Kc(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 Kc(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||!it(r,Wc(i))}),c=[],l=[],u={},d=[...t.clients],f=[...t.tools];for(let e of[...a,...s]){let n=d.find(t=>t.name===e),r=t.configs[e];if(n&&r){if(n.type===`connected`)try{await n.cleanup()}catch(e){J(e)}await xe(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=Wc(n);if(n.type===`sdk`){l.push(t);continue}try{let e=await _n(t,r);if(d.push(e),e.type===`connected`){let t=await st(e);f.push(...t)}else e.type===`failed`&&(u[t]=e.error||`Connection failed`);l.push(t)}catch(e){let n=Sr(e);u[t]=n.message,J(n)}}let p={};for(let t of i){let n=e[t];n&&(p[t]=Wc(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{Mc as runHeadless};
@@ -1 +1 @@
1
- import{a as e}from"./rolldown-runtime-DaDcL9Zw.js";import{Af as t,Cm as n,Db as r,Eb as i,Oc as a,Of as o,Sm as s,Xu as c,Yi as l,Zu as u,fS as d,gS as f,jf as p,kc as m,kf as h,lS as g,pS as _}from"./loadAgentsDir-DlPbtIsS.js";import{I as v,t as y}from"./src-DL3w8VPk.js";import{t as b}from"./jsx-runtime-Bb4Xn-E0.js";import{A as x,I as S,M as C}from"./debug-Bglx1aTu.js";import{h as w,t as T}from"./settings-B2jvL8Dp.js";import{n as E,r as D}from"./analytics-DJobLaWP.js";import{bt as O,yt as k}from"./prompt-mM79EGnT.js";import{randomUUID as A}from"crypto";y(),h(),u(),p();var j=b();function M({input:e,progress:n,verbose:r}){return(0,j.jsxs)(v,{flexDirection:`column`,marginTop:1,children:[(0,j.jsx)(c,{addMargin:!1,param:{text:`<bash-input>${e}</bash-input>`,type:`text`}}),n?(0,j.jsx)(t,{fullOutput:n.fullOutput,output:n.output,elapsedTimeSeconds:n.elapsedTimeSeconds,totalLines:n.totalLines,verbose:r}):o.renderToolUseProgressMessage?.([],{verbose:r,tools:[],terminalSize:void 0})]})}S(),E(),i(),l(),w();function N(){return T().defaultShell??`bash`}h(),k(),n();async function P(t,n,i,c,l){let u=O()&&N()===`powershell`;D(`tengu_input_bash`,{powershell:u});let p=_({content:f({inputString:`<bash-input>${t}</bash-input>`,precedingInputBlocks:n})}),h;l({jsx:(0,j.jsx)(M,{input:t,progress:null,verbose:c.options.verbose}),shouldHidePromptInput:!1});try{let n={...c,setToolJSX:e=>{h=e?.jsx}},d=e=>{l({jsx:(0,j.jsxs)(j.Fragment,{children:[(0,j.jsx)(M,{input:t,progress:e.data,verbose:c.options.verbose}),h]}),shouldHidePromptInput:!1,showSpinner:!1})},f=null;u&&(f=(m(),e(a)).PowerShellTool);let v=f??o,y=(f?await f.call({command:t,dangerouslyDisableSandbox:!0},n,void 0,void 0,d):await o.call({command:t,dangerouslyDisableSandbox:!0},n,void 0,void 0,d)).data;if(!y)throw Error(`No result received from shell command`);let b=y.stderr,x=await r(v,{...y,stderr:``},A()),S=typeof x.content==`string`?x.content:s(y.stdout);return{messages:[g(),p,...i,_({content:`<bash-stdout>${S}</bash-stdout><bash-stderr>${s(b)}</bash-stderr>`})],shouldQuery:!1}}catch(e){return e instanceof x?e.interrupted?{messages:[g(),p,d({toolUse:!1}),...i],shouldQuery:!1}:{messages:[g(),p,...i,_({content:`<bash-stdout>${s(e.stdout)}</bash-stdout><bash-stderr>${s(e.stderr)}</bash-stderr>`})],shouldQuery:!1}:{messages:[g(),p,...i,_({content:`<bash-stderr>Command failed: ${s(C(e))}</bash-stderr>`})],shouldQuery:!1}}finally{l(null)}}export{P as processBashCommand};
1
+ import{a as e}from"./rolldown-runtime-DaDcL9Zw.js";import{Af as t,Cm as n,Db as r,Eb as i,Oc as a,Of as o,Sm as s,Xu as c,Yi as l,Zu as u,fS as d,gS as f,jf as p,kc as m,kf as h,lS as g,pS as _}from"./loadAgentsDir-B0Anodo0.js";import{I as v,t as y}from"./src-DL3w8VPk.js";import{t as b}from"./jsx-runtime-Bb4Xn-E0.js";import{A as x,I as S,M as C}from"./debug-Bglx1aTu.js";import{h as w,t as T}from"./settings-B2jvL8Dp.js";import{n as E,r as D}from"./analytics-DJobLaWP.js";import{bt as O,yt as k}from"./prompt-CJ1l3XXk.js";import{randomUUID as A}from"crypto";y(),h(),u(),p();var j=b();function M({input:e,progress:n,verbose:r}){return(0,j.jsxs)(v,{flexDirection:`column`,marginTop:1,children:[(0,j.jsx)(c,{addMargin:!1,param:{text:`<bash-input>${e}</bash-input>`,type:`text`}}),n?(0,j.jsx)(t,{fullOutput:n.fullOutput,output:n.output,elapsedTimeSeconds:n.elapsedTimeSeconds,totalLines:n.totalLines,verbose:r}):o.renderToolUseProgressMessage?.([],{verbose:r,tools:[],terminalSize:void 0})]})}S(),E(),i(),l(),w();function N(){return T().defaultShell??`bash`}h(),k(),n();async function P(t,n,i,c,l){let u=O()&&N()===`powershell`;D(`tengu_input_bash`,{powershell:u});let p=_({content:f({inputString:`<bash-input>${t}</bash-input>`,precedingInputBlocks:n})}),h;l({jsx:(0,j.jsx)(M,{input:t,progress:null,verbose:c.options.verbose}),shouldHidePromptInput:!1});try{let n={...c,setToolJSX:e=>{h=e?.jsx}},d=e=>{l({jsx:(0,j.jsxs)(j.Fragment,{children:[(0,j.jsx)(M,{input:t,progress:e.data,verbose:c.options.verbose}),h]}),shouldHidePromptInput:!1,showSpinner:!1})},f=null;u&&(f=(m(),e(a)).PowerShellTool);let v=f??o,y=(f?await f.call({command:t,dangerouslyDisableSandbox:!0},n,void 0,void 0,d):await o.call({command:t,dangerouslyDisableSandbox:!0},n,void 0,void 0,d)).data;if(!y)throw Error(`No result received from shell command`);let b=y.stderr,x=await r(v,{...y,stderr:``},A()),S=typeof x.content==`string`?x.content:s(y.stdout);return{messages:[g(),p,...i,_({content:`<bash-stdout>${S}</bash-stdout><bash-stderr>${s(b)}</bash-stderr>`})],shouldQuery:!1}}catch(e){return e instanceof x?e.interrupted?{messages:[g(),p,d({toolUse:!1}),...i],shouldQuery:!1}:{messages:[g(),p,...i,_({content:`<bash-stdout>${s(e.stdout)}</bash-stdout><bash-stderr>${s(e.stderr)}</bash-stderr>`})],shouldQuery:!1}:{messages:[g(),p,...i,_({content:`<bash-stderr>Command failed: ${s(C(e))}</bash-stderr>`})],shouldQuery:!1}}finally{l(null)}}export{P as processBashCommand};
@@ -1,4 +1,4 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{ct as t,ot as n}from"./esm-eTAUP-La.js";import{$l as r,Ag as i,B as a,Di as o,E as s,Fd as c,Id as l,Jb as u,Jm as d,Kb as f,Km as p,Lh as m,Lx as h,Mi as g,Ni as _,Op as v,Pi as y,Qo as b,Rx as x,Si as S,Tg as C,Ti as w,Us as T,V as E,Vs as D,Ws as O,Yi as ee,Zo as te,_S as ne,_d as k,b as A,cf as re,cg as ie,cu as ae,dg as oe,es as se,eu as ce,fS as le,gS as j,gd as M,hc as ue,hd as de,iu as fe,kp as pe,lS as N,lf as me,mS as he,mc as ge,ny as P,oS as F,pS as I,qb as L,sf as _e,su as ve,tS as ye,tu as R,ty as be,uS as xe,ua as Se,vS as Ce,vd as we,wa as Te,wg as Ee,yd as De,zh as Oe,zx as z}from"./loadAgentsDir-DlPbtIsS.js";import{It as ke,Mn as Ae,st as je,t as Me}from"./state-B4jiUise.js";import{E as Ne,I as Pe,c as B,f as Fe,i as V,k as H,u as Ie}from"./debug-Bglx1aTu.js";import{Dt as Le,Et as Re}from"./settings-B2jvL8Dp.js";import{D as U,O as W,o as ze,q as Be,s as G}from"./log-D2TIwHBV.js";import{n as Ve,r as K}from"./analytics-DJobLaWP.js";import{Kt as He,qt as Ue}from"./model-BwBG0V1u.js";import{h as We,m as Ge}from"./firstPartyEventLogger-M6UMli2c.js";import{E as Ke,T as qe,w as Je}from"./sessionTracing-BoDDYLxW.js";import{randomUUID as q}from"crypto";function Ye(e,t,n,r,i){let a=0;for(let o of Le){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}'`),De(e,t,o,s)}:void 0;k(e,t,o,n.matcher||``,s,c,i),a++}}a>0&&B(`Registered ${a} hooks from skill '${r}'`)}var Xe=e((()=>{Re(),V(),we()}));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=`${r} (MCP)`,i=!0,a=2);let o=n.slice(a).join(` `);return{commandName:r,args:o,isMcp:i}}var Qe=e((()=>{}));function $e(){return!1}function J(){if(!$e())throw Error(`ToolUseContext.options.allowBackgroundForkedSlashCommands is test-only and cannot be enabled outside NODE_ENV=test.`)}async function et(e,t,n,r,i,a,o){let s=c(),l=e.pluginInfo?z(e.pluginInfo.repository).marketplace:void 0;K(`tengu_slash_command_forked`,{command_name:e.name,invocation_trigger:`user-slash`,...e.pluginInfo&&{_PROTO_plugin_name:e.pluginInfo.pluginManifest.name,...l&&{_PROTO_marketplace_name:l},...R(e.pluginInfo)}});let{skillContent:u,modifiedGetAppState:d,baseAgent:f,promptMessages:p}=await O(e,t,n);B(`Executing forked slash command /${e.name} with agent ${f.agentType}`);let m=n.options.allowBackgroundForkedSlashCommands===!0;if(m&&J(),m){let t=be(),r=y(e),i=He(),c=e=>C({value:e,mode:`prompt`,priority:`later`,isMeta:!0,skipSlashCommands:!0,workload:i}),l=async()=>{if(!o?.runId)return;let e=await _e({runId:o.runId,rootDir:o.rootDir,priority:`later`,workload:i});for(let t of e)Ee(t)},u=async e=>{o?.runId&&await re({runId:o.runId,rootDir:o.rootDir,error:e instanceof Error?e.message:String(e)})};return(async()=>{let i=Date.now()+$;for(;Date.now()<i&&n.getAppState().mcp.clients.some(e=>e.type===`pending`);)await We(Q);let o=n.options.refreshTools?.()??n.options.tools,u=[];for await(let r of M({agentDefinition:f,promptMessages:p,toolUseContext:{...n,getAppState:d,abortController:t},canUseTool:a,isAsync:!0,querySource:`agent:custom`,model:e.model,availableTools:o,override:{agentId:s}}))u.push(r);let m=D(u,`Command completed`);B(`Background forked command /${r} completed (agent ${s})`),c(`<scheduled-task-result command="/${r}">\n${m}\n</scheduled-task-result>`);try{await l()}catch(e){G(e)}})().catch(async e=>{G(e),c(`<scheduled-task-result command="/${r}" status="failed">\n${e instanceof Error?e.message:String(e)}\n</scheduled-task-result>`),await u(e)}),{messages:[],shouldQuery:!1,command:e,deferAutonomyCompletion:!!o?.runId}}let h=[],g=[],_=`forked-command-${e.name}`,v=0,b=e=>(v++,{type:`progress`,data:{message:e,type:`agent_progress`,prompt:u,agentId:s},parentToolUseID:_,toolUseID:`${_}-${v}`,timestamp:new Date().toISOString(),uuid:q()}),x=()=>{i({jsx:ae(g,{tools:n.options.tools,verbose:!1}),shouldHidePromptInput:!1,shouldContinueAnimation:!0,showSpinner:!0})};x();try{for await(let t of M({agentDefinition:f,promptMessages:p,toolUseContext:{...n,getAppState:d},canUseTool:a,isAsync:!1,querySource:`agent:custom`,model:e.model,availableTools:n.options.tools})){h.push(t);let e=Se([t]);if(t.type===`assistant`){let r=ie(t);r>0&&n.setResponseLength(e=>e+r);let i=e[0];i&&i.type===`assistant`&&(g.push(b(t)),x())}if(t.type===`user`){let t=e[0];t&&t.type===`user`&&(g.push(b(t)),x())}}}finally{i(null)}let S=D(h,`Command completed`);return B(`Forked slash command /${e.name} completed with agent ${s}`),{messages:[I({content:j({inputString:`/${y(e)} ${t}`.trim(),precedingInputBlocks:r})}),I({content:`<local-command-stdout>\n${S}\n</local-command-stdout>`})],shouldQuery:!1,command:e,resultText:S}}function tt(e){return!/[^a-zA-Z0-9:\-_]/.test(e)}async function nt(e,t,n,r,i,a,o,s,c,l){let u=Ze(e);if(!u){K(`tengu_input_slash_missing`,{});let e="Commands are in the form `/command [args]`";return{messages:[N(),...r,I({content:j({inputString:e,precedingInputBlocks:t})})],shouldQuery:!1,resultText:e}}let{commandName:d,args:f,isMcp:p}=u,m=p?`mcp`:S().has(d)?d:`custom`;if(!g(d,i.options.commands)){let n=!1;try{await Ie().stat(`/${d}`),n=!0}catch{}if(tt(d)&&!n){K(`tengu_input_slash_invalid`,{input:d});let e=`Unknown skill: ${d}`;return{messages:[N(),...r,I({content:j({inputString:e,precedingInputBlocks:t})}),...f?[xe(`Args from unknown skill: ${f}`,`warning`)]:[]],shouldQuery:!1,resultText:e}}let i=q();return Ae(i),K(`tengu_input_prompt`,{}),qe(`user_prompt`,{prompt_length:String(e.length),prompt:Ke(e),"prompt.id":i}),{messages:[I({content:j({inputString:e,precedingInputBlocks:t}),uuid:o}),...r],shouldQuery:!0}}let{messages:h,shouldQuery:_,allowedTools:v,model:y,command:b,resultText:C,nextInput:w,submitNextInput:T,deferAutonomyCompletion:E}=await rt(d,f,a,i,t,n,s,c,o,l);if(h.length===0){let e={input:m};if(b.type===`prompt`&&b.pluginInfo){let{pluginManifest:t,repository:n}=b.pluginInfo,{marketplace:r}=z(n),i=x(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,R(b.pluginInfo))}return K(`tengu_input_command`,{...e,invocation_trigger:`user-slash`}),{messages:[],shouldQuery:!1,model:y,nextInput:w,submitNextInput:T,deferAutonomyCompletion:E}}if(h.length===2&&h[1].type===`user`&&typeof h[1].message.content==`string`&&h[1].message.content.startsWith(`Unknown command:`))return e.startsWith(`/var`)||e.startsWith(`/tmp`)||e.startsWith(`/private`)||K(`tengu_input_slash_invalid`,{input:d}),{messages:[N(),...h],shouldQuery:_,allowedTools:v,model:y};let D={input:m};if(b.type===`prompt`&&b.pluginInfo){let{pluginManifest:e,repository:t}=b.pluginInfo,{marketplace:n}=z(t),r=x(n);D._PROTO_plugin_name=e.name,n&&(D._PROTO_marketplace_name=n),D.plugin_repository=r?t:`third-party`,D.plugin_name=r?e.name:`third-party`,r&&e.version&&(D.plugin_version=e.version),Object.assign(D,R(b.pluginInfo))}K(`tengu_input_command`,{...D,invocation_trigger:`user-slash`});let O=h.length>0&&h[0]&&ye(h[0]);return{messages:_||h.every(Te)||O?h:[N(),...h],shouldQuery:_,allowedTools:v,model:y,resultText:C,nextInput:w,submitNextInput:T,deferAutonomyCompletion:E}}async function rt(e,t,n,r,i,s,c,l,u,d){let f=o(e,r.options.commands);if(f.type===`prompt`&&f.userInvocable!==!1&&ce(e),f.userInvocable===!1)return{messages:[I({content:j({inputString:`/${e}`,precedingInputBlocks:i})}),I({content:`This skill can only be invoked by Work Mate, not directly by users. Ask Work Mate to use the "${e}" skill for you.`})],shouldQuery:!1,command:f};try{switch(f.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:f,nextInput:r?.nextInput,submitNextInput:r?.submitNextInput});return}let o=(r?.metaMessages??[]).map(e=>I({content:e,isMeta:!0})),s=pe()&&typeof n==`string`&&n.endsWith(` dismissed`),c=r?.displayArgs??t;e({messages:r?.display===`system`?s?o:[F(Y(f,c)),F(`<local-command-stdout>${n}</local-command-stdout>`),...o]:[I({content:j({inputString:Y(f,c),precedingInputBlocks:i})}),I(n?{content:`<local-command-stdout>${n}</local-command-stdout>`}:{content:`<local-command-stdout>${ne}</local-command-stdout>`}),...o],shouldQuery:r?.shouldQuery??!1,command:f,nextInput:r?.nextInput,submitNextInput:r?.submitNextInput})};f.load().then(e=>e.call(o,{...r,canUseTool:l},t)).then(t=>{if(t!=null){if(r.options.isNonInteractiveSession){e({messages:[],shouldQuery:!1,command:f});return}a||n({jsx:t,shouldHidePromptInput:!0,showSpinner:!1,isLocalJSXCommand:!0,isImmediate:f.immediate===!0})}}).catch(t=>{G(t),!a&&(a=!0,n({jsx:null,shouldHidePromptInput:!1,clearLocalJSX:!0}),e({messages:[],shouldQuery:!1,command:f}))})});case`local`:{let e=I({content:j({inputString:Y(f,f.isSensitive&&t.trim()?`***`:t),precedingInputBlocks:i})});try{let n=N(),i=await(await f.load()).call(t,r);if(i.type===`skip`)return{messages:[],shouldQuery:!1,command:f};if(i.type===`compact`){let t=[n,e,...i.displayText?[I({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 Oe(),{messages:p(r),shouldQuery:!1,command:f}}return{messages:[e,F(`<local-command-stdout>${i.value}</local-command-stdout>`)],shouldQuery:!1,command:f,resultText:i.value}}catch(t){return G(t),{messages:[e,F(`<local-command-stderr>${String(t)}</local-command-stderr>`)],shouldQuery:!1,command:f}}}case`prompt`:try{return f.context===`fork`?await et(f,t,r,i,n,l??a,d):await Z(f,t,r,i,s,u)}catch(e){return e instanceof Ne?{messages:[I({content:j({inputString:Y(f,t),precedingInputBlocks:i})}),le({toolUse:!1})],shouldQuery:!1,command:f}:{messages:[I({content:j({inputString:Y(f,t),precedingInputBlocks:i})}),I({content:`<local-command-stderr>${String(e)}</local-command-stderr>`})],shouldQuery:!1,command:f}}}}catch(e){if(e instanceof H)return{messages:[I({content:j({inputString:e.message,precedingInputBlocks:i})})],shouldQuery:!1,command:f};throw e}}function Y(e,t){return he(y(e),t)}function X(e,t=`loading`){return[`<${U}>${e}</${U}>`,`<${W}>${e}</${W}>`,`<skill-format>true</skill-format>`].join(`
1
+ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{ct as t,ot as n}from"./esm-BXTZz3av.js";import{$l as r,Ag as i,B as a,Di as o,E as s,Fd as c,Id as l,Jb as u,Jm as d,Kb as f,Km as p,Lh as m,Lx as h,Mi as g,Ni as _,Op as v,Pi as y,Qo as b,Rx as x,Si as S,Tg as C,Ti as w,Us as T,V as E,Vs as D,Ws as O,Yi as ee,Zo as te,_S as ne,_d as k,b as A,cf as re,cg as ie,cu as ae,dg as oe,es as se,eu as ce,fS as le,gS as j,gd as M,hc as ue,hd as de,iu as fe,kp as pe,lS as N,lf as me,mS as he,mc as ge,ny as P,oS as F,pS as I,qb as L,sf as _e,su as ve,tS as ye,tu as R,ty as be,uS as xe,ua as Se,vS as Ce,vd as we,wa as Te,wg as Ee,yd as De,zh as Oe,zx as z}from"./loadAgentsDir-B0Anodo0.js";import{It as ke,Mn as Ae,st as je,t as Me}from"./state-B4jiUise.js";import{E as Ne,I as Pe,c as B,f as Fe,i as V,k as H,u as Ie}from"./debug-Bglx1aTu.js";import{Dt as Le,Et as Re}from"./settings-B2jvL8Dp.js";import{D as U,O as W,o as ze,q as Be,s as G}from"./log-D2TIwHBV.js";import{n as Ve,r as K}from"./analytics-DJobLaWP.js";import{Kt as He,qt as Ue}from"./model-BvQFFOf8.js";import{h as We,m as Ge}from"./firstPartyEventLogger-QmjjQmgt.js";import{E as Ke,T as qe,w as Je}from"./sessionTracing-CtbeAD0s.js";import{randomUUID as q}from"crypto";function Ye(e,t,n,r,i){let a=0;for(let o of Le){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}'`),De(e,t,o,s)}:void 0;k(e,t,o,n.matcher||``,s,c,i),a++}}a>0&&B(`Registered ${a} hooks from skill '${r}'`)}var Xe=e((()=>{Re(),V(),we()}));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=`${r} (MCP)`,i=!0,a=2);let o=n.slice(a).join(` `);return{commandName:r,args:o,isMcp:i}}var Qe=e((()=>{}));function $e(){return!1}function J(){if(!$e())throw Error(`ToolUseContext.options.allowBackgroundForkedSlashCommands is test-only and cannot be enabled outside NODE_ENV=test.`)}async function et(e,t,n,r,i,a,o){let s=c(),l=e.pluginInfo?z(e.pluginInfo.repository).marketplace:void 0;K(`tengu_slash_command_forked`,{command_name:e.name,invocation_trigger:`user-slash`,...e.pluginInfo&&{_PROTO_plugin_name:e.pluginInfo.pluginManifest.name,...l&&{_PROTO_marketplace_name:l},...R(e.pluginInfo)}});let{skillContent:u,modifiedGetAppState:d,baseAgent:f,promptMessages:p}=await O(e,t,n);B(`Executing forked slash command /${e.name} with agent ${f.agentType}`);let m=n.options.allowBackgroundForkedSlashCommands===!0;if(m&&J(),m){let t=be(),r=y(e),i=He(),c=e=>C({value:e,mode:`prompt`,priority:`later`,isMeta:!0,skipSlashCommands:!0,workload:i}),l=async()=>{if(!o?.runId)return;let e=await _e({runId:o.runId,rootDir:o.rootDir,priority:`later`,workload:i});for(let t of e)Ee(t)},u=async e=>{o?.runId&&await re({runId:o.runId,rootDir:o.rootDir,error:e instanceof Error?e.message:String(e)})};return(async()=>{let i=Date.now()+$;for(;Date.now()<i&&n.getAppState().mcp.clients.some(e=>e.type===`pending`);)await We(Q);let o=n.options.refreshTools?.()??n.options.tools,u=[];for await(let r of M({agentDefinition:f,promptMessages:p,toolUseContext:{...n,getAppState:d,abortController:t},canUseTool:a,isAsync:!0,querySource:`agent:custom`,model:e.model,availableTools:o,override:{agentId:s}}))u.push(r);let m=D(u,`Command completed`);B(`Background forked command /${r} completed (agent ${s})`),c(`<scheduled-task-result command="/${r}">\n${m}\n</scheduled-task-result>`);try{await l()}catch(e){G(e)}})().catch(async e=>{G(e),c(`<scheduled-task-result command="/${r}" status="failed">\n${e instanceof Error?e.message:String(e)}\n</scheduled-task-result>`),await u(e)}),{messages:[],shouldQuery:!1,command:e,deferAutonomyCompletion:!!o?.runId}}let h=[],g=[],_=`forked-command-${e.name}`,v=0,b=e=>(v++,{type:`progress`,data:{message:e,type:`agent_progress`,prompt:u,agentId:s},parentToolUseID:_,toolUseID:`${_}-${v}`,timestamp:new Date().toISOString(),uuid:q()}),x=()=>{i({jsx:ae(g,{tools:n.options.tools,verbose:!1}),shouldHidePromptInput:!1,shouldContinueAnimation:!0,showSpinner:!0})};x();try{for await(let t of M({agentDefinition:f,promptMessages:p,toolUseContext:{...n,getAppState:d},canUseTool:a,isAsync:!1,querySource:`agent:custom`,model:e.model,availableTools:n.options.tools})){h.push(t);let e=Se([t]);if(t.type===`assistant`){let r=ie(t);r>0&&n.setResponseLength(e=>e+r);let i=e[0];i&&i.type===`assistant`&&(g.push(b(t)),x())}if(t.type===`user`){let t=e[0];t&&t.type===`user`&&(g.push(b(t)),x())}}}finally{i(null)}let S=D(h,`Command completed`);return B(`Forked slash command /${e.name} completed with agent ${s}`),{messages:[I({content:j({inputString:`/${y(e)} ${t}`.trim(),precedingInputBlocks:r})}),I({content:`<local-command-stdout>\n${S}\n</local-command-stdout>`})],shouldQuery:!1,command:e,resultText:S}}function tt(e){return!/[^a-zA-Z0-9:\-_]/.test(e)}async function nt(e,t,n,r,i,a,o,s,c,l){let u=Ze(e);if(!u){K(`tengu_input_slash_missing`,{});let e="Commands are in the form `/command [args]`";return{messages:[N(),...r,I({content:j({inputString:e,precedingInputBlocks:t})})],shouldQuery:!1,resultText:e}}let{commandName:d,args:f,isMcp:p}=u,m=p?`mcp`:S().has(d)?d:`custom`;if(!g(d,i.options.commands)){let n=!1;try{await Ie().stat(`/${d}`),n=!0}catch{}if(tt(d)&&!n){K(`tengu_input_slash_invalid`,{input:d});let e=`Unknown skill: ${d}`;return{messages:[N(),...r,I({content:j({inputString:e,precedingInputBlocks:t})}),...f?[xe(`Args from unknown skill: ${f}`,`warning`)]:[]],shouldQuery:!1,resultText:e}}let i=q();return Ae(i),K(`tengu_input_prompt`,{}),qe(`user_prompt`,{prompt_length:String(e.length),prompt:Ke(e),"prompt.id":i}),{messages:[I({content:j({inputString:e,precedingInputBlocks:t}),uuid:o}),...r],shouldQuery:!0}}let{messages:h,shouldQuery:_,allowedTools:v,model:y,command:b,resultText:C,nextInput:w,submitNextInput:T,deferAutonomyCompletion:E}=await rt(d,f,a,i,t,n,s,c,o,l);if(h.length===0){let e={input:m};if(b.type===`prompt`&&b.pluginInfo){let{pluginManifest:t,repository:n}=b.pluginInfo,{marketplace:r}=z(n),i=x(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,R(b.pluginInfo))}return K(`tengu_input_command`,{...e,invocation_trigger:`user-slash`}),{messages:[],shouldQuery:!1,model:y,nextInput:w,submitNextInput:T,deferAutonomyCompletion:E}}if(h.length===2&&h[1].type===`user`&&typeof h[1].message.content==`string`&&h[1].message.content.startsWith(`Unknown command:`))return e.startsWith(`/var`)||e.startsWith(`/tmp`)||e.startsWith(`/private`)||K(`tengu_input_slash_invalid`,{input:d}),{messages:[N(),...h],shouldQuery:_,allowedTools:v,model:y};let D={input:m};if(b.type===`prompt`&&b.pluginInfo){let{pluginManifest:e,repository:t}=b.pluginInfo,{marketplace:n}=z(t),r=x(n);D._PROTO_plugin_name=e.name,n&&(D._PROTO_marketplace_name=n),D.plugin_repository=r?t:`third-party`,D.plugin_name=r?e.name:`third-party`,r&&e.version&&(D.plugin_version=e.version),Object.assign(D,R(b.pluginInfo))}K(`tengu_input_command`,{...D,invocation_trigger:`user-slash`});let O=h.length>0&&h[0]&&ye(h[0]);return{messages:_||h.every(Te)||O?h:[N(),...h],shouldQuery:_,allowedTools:v,model:y,resultText:C,nextInput:w,submitNextInput:T,deferAutonomyCompletion:E}}async function rt(e,t,n,r,i,s,c,l,u,d){let f=o(e,r.options.commands);if(f.type===`prompt`&&f.userInvocable!==!1&&ce(e),f.userInvocable===!1)return{messages:[I({content:j({inputString:`/${e}`,precedingInputBlocks:i})}),I({content:`This skill can only be invoked by Work Mate, not directly by users. Ask Work Mate to use the "${e}" skill for you.`})],shouldQuery:!1,command:f};try{switch(f.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:f,nextInput:r?.nextInput,submitNextInput:r?.submitNextInput});return}let o=(r?.metaMessages??[]).map(e=>I({content:e,isMeta:!0})),s=pe()&&typeof n==`string`&&n.endsWith(` dismissed`),c=r?.displayArgs??t;e({messages:r?.display===`system`?s?o:[F(Y(f,c)),F(`<local-command-stdout>${n}</local-command-stdout>`),...o]:[I({content:j({inputString:Y(f,c),precedingInputBlocks:i})}),I(n?{content:`<local-command-stdout>${n}</local-command-stdout>`}:{content:`<local-command-stdout>${ne}</local-command-stdout>`}),...o],shouldQuery:r?.shouldQuery??!1,command:f,nextInput:r?.nextInput,submitNextInput:r?.submitNextInput})};f.load().then(e=>e.call(o,{...r,canUseTool:l},t)).then(t=>{if(t!=null){if(r.options.isNonInteractiveSession){e({messages:[],shouldQuery:!1,command:f});return}a||n({jsx:t,shouldHidePromptInput:!0,showSpinner:!1,isLocalJSXCommand:!0,isImmediate:f.immediate===!0})}}).catch(t=>{G(t),!a&&(a=!0,n({jsx:null,shouldHidePromptInput:!1,clearLocalJSX:!0}),e({messages:[],shouldQuery:!1,command:f}))})});case`local`:{let e=I({content:j({inputString:Y(f,f.isSensitive&&t.trim()?`***`:t),precedingInputBlocks:i})});try{let n=N(),i=await(await f.load()).call(t,r);if(i.type===`skip`)return{messages:[],shouldQuery:!1,command:f};if(i.type===`compact`){let t=[n,e,...i.displayText?[I({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 Oe(),{messages:p(r),shouldQuery:!1,command:f}}return{messages:[e,F(`<local-command-stdout>${i.value}</local-command-stdout>`)],shouldQuery:!1,command:f,resultText:i.value}}catch(t){return G(t),{messages:[e,F(`<local-command-stderr>${String(t)}</local-command-stderr>`)],shouldQuery:!1,command:f}}}case`prompt`:try{return f.context===`fork`?await et(f,t,r,i,n,l??a,d):await Z(f,t,r,i,s,u)}catch(e){return e instanceof Ne?{messages:[I({content:j({inputString:Y(f,t),precedingInputBlocks:i})}),le({toolUse:!1})],shouldQuery:!1,command:f}:{messages:[I({content:j({inputString:Y(f,t),precedingInputBlocks:i})}),I({content:`<local-command-stderr>${String(e)}</local-command-stderr>`})],shouldQuery:!1,command:f}}}}catch(e){if(e instanceof H)return{messages:[I({content:j({inputString:e.message,precedingInputBlocks:i})})],shouldQuery:!1,command:f};throw e}}function Y(e,t){return he(y(e),t)}function X(e,t=`loading`){return[`<${U}>${e}</${U}>`,`<${W}>${e}</${W}>`,`<skill-format>true</skill-format>`].join(`
2
2
  `)}function it(e,t){return[`<${U}>${e}</${U}>`,`<${W}>/${e}</${W}>`,t?`<command-args>${t}</command-args>`:null].filter(Boolean).join(`
3
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=w(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,r,i=[],a=[],o){let c=await e.getPromptForCommand(t,r),l=!L(`hooks`)||u(e.source);if(e.hooks&&l){let t=je();Ye(r.setAppState,t,e.hooks,e.name,e.type===`prompt`?e.skillRoot:void 0)}let d=e.source?`${e.source}:${e.name}`:e.name,f=c.filter(e=>e.type===`text`).map(e=>e.text).join(`
4
4
 
@@ -0,0 +1 @@
1
+ import{i as e,r as t}from"./prompt-CJ1l3XXk.js";t();export{e as isDeferredTool};
@@ -1,4 +1,4 @@
1
- import{a as e,n as t,o as n,r,t as i}from"./rolldown-runtime-DaDcL9Zw.js";import{l as a,o}from"./envUtils-DfkgIdYf.js";import{n as s,t as c}from"./defineProperty-C-QyHrDq.js";import{$ as l,G as u,W as d,Z as f,o as p,s as m,x as h}from"./types-Dx7P7JLQ.js";import{C as g,I as _,j as v,x as y}from"./debug-Bglx1aTu.js";import{G as b,K as x,U as S,W as C,Z as w,q as T}from"./settings-B2jvL8Dp.js";import{H as E,q as D}from"./log-D2TIwHBV.js";import{i as O,o as k}from"./platform-BacQ6ACS.js";import{d as A,o as j}from"./model-BwBG0V1u.js";import{join as M,parse as N,resolve as P,sep as ee}from"node:path";import{createHash as F}from"node:crypto";import{appendFile as I,mkdir as te,readFile as L,readdir as ne,rm as re,writeFile as ie}from"node:fs/promises";function ae(e,t){return{tool_use_id:e,type:`tool_result`,content:t}}function oe(e){return e.filter(e=>e.data?.type!==`hook_progress`)}function se(e,t){return e.name===t||(e.aliases?.includes(t)??!1)}function ce(e,t){return e.find(e=>se(e,t))}function le(e){return{...de,userFacingName:()=>e.name,...e}}var ue,de,fe=t((()=>{ue=()=>({mode:`default`,additionalWorkingDirectories:new Map,alwaysAllowRules:{},alwaysDenyRules:{},alwaysAskRules:{},isBypassPermissionsModeAvailable:!0}),de={isEnabled:()=>!0,isConcurrencySafe:e=>!1,isReadOnly:e=>!1,isDestructive:e=>!1,checkPermissions:(e,t)=>Promise.resolve({behavior:`allow`,updatedInput:e}),toAutoClassifierInput:e=>``,userFacingName:e=>``}})),pe,me,he,ge,_e=t((()=>{pe=`Edit`,me=`/.workmate/**`,he=`~/.workmate/**`,ge=`File has been unexpectedly modified. Read it again before attempting to write it.`}));function ve(e){let t=e.trim();if(!t)return null;if(t.endsWith(`-`)){let e=parseInt(t.slice(0,-1),10);return isNaN(e)||e<1?null:{firstPage:e,lastPage:1/0}}let n=t.indexOf(`-`);if(n===-1){let e=parseInt(t,10);return isNaN(e)||e<1?null:{firstPage:e,lastPage:e}}let r=parseInt(t.slice(0,n),10),i=parseInt(t.slice(n+1),10);return isNaN(r)||isNaN(i)||r<1||i<1||i<r?null:{firstPage:r,lastPage:i}}function ye(){return!j().toLowerCase().includes(`claude-3-haiku`)}function be(e){let t=e.startsWith(`.`)?e.slice(1):e;return xe.has(t.toLowerCase())}var xe,Se=t((()=>{A(),xe=new Set([`pdf`])})),R,Ce=t((()=>{R=`Bash`}));function we(e,t,n){return`Reads a file from the local filesystem. You can access any file directly by using this tool.
1
+ import{a as e,n as t,o as n,r,t as i}from"./rolldown-runtime-DaDcL9Zw.js";import{l as a,o}from"./envUtils-DfkgIdYf.js";import{n as s,t as c}from"./defineProperty-C-QyHrDq.js";import{$ as l,G as u,W as d,Z as f,o as p,s as m,x as h}from"./types-Dx7P7JLQ.js";import{C as g,I as _,j as v,x as y}from"./debug-Bglx1aTu.js";import{G as b,K as x,U as S,W as C,Z as w,q as T}from"./settings-B2jvL8Dp.js";import{H as E,q as D}from"./log-D2TIwHBV.js";import{i as O,o as k}from"./platform-BacQ6ACS.js";import{d as A,o as j}from"./model-BvQFFOf8.js";import{join as M,parse as N,resolve as P,sep as ee}from"node:path";import{createHash as F}from"node:crypto";import{appendFile as I,mkdir as te,readFile as L,readdir as ne,rm as re,writeFile as ie}from"node:fs/promises";function ae(e,t){return{tool_use_id:e,type:`tool_result`,content:t}}function oe(e){return e.filter(e=>e.data?.type!==`hook_progress`)}function se(e,t){return e.name===t||(e.aliases?.includes(t)??!1)}function ce(e,t){return e.find(e=>se(e,t))}function le(e){return{...de,userFacingName:()=>e.name,...e}}var ue,de,fe=t((()=>{ue=()=>({mode:`default`,additionalWorkingDirectories:new Map,alwaysAllowRules:{},alwaysDenyRules:{},alwaysAskRules:{},isBypassPermissionsModeAvailable:!0}),de={isEnabled:()=>!0,isConcurrencySafe:e=>!1,isReadOnly:e=>!1,isDestructive:e=>!1,checkPermissions:(e,t)=>Promise.resolve({behavior:`allow`,updatedInput:e}),toAutoClassifierInput:e=>``,userFacingName:e=>``}})),pe,me,he,ge,_e=t((()=>{pe=`Edit`,me=`/.workmate/**`,he=`~/.workmate/**`,ge=`File has been unexpectedly modified. Read it again before attempting to write it.`}));function ve(e){let t=e.trim();if(!t)return null;if(t.endsWith(`-`)){let e=parseInt(t.slice(0,-1),10);return isNaN(e)||e<1?null:{firstPage:e,lastPage:1/0}}let n=t.indexOf(`-`);if(n===-1){let e=parseInt(t,10);return isNaN(e)||e<1?null:{firstPage:e,lastPage:e}}let r=parseInt(t.slice(0,n),10),i=parseInt(t.slice(n+1),10);return isNaN(r)||isNaN(i)||r<1||i<1||i<r?null:{firstPage:r,lastPage:i}}function ye(){return!j().toLowerCase().includes(`claude-3-haiku`)}function be(e){let t=e.startsWith(`.`)?e.slice(1):e;return xe.has(t.toLowerCase())}var xe,Se=t((()=>{A(),xe=new Set([`pdf`])})),R,Ce=t((()=>{R=`Bash`}));function we(e,t,n){return`Reads a file from the local filesystem. You can access any file directly by using this tool.
2
2
  Assume this tool is able to read all files on the machine. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.
3
3
 
4
4
  Usage:
@@ -0,0 +1 @@
1
+ import{fx as e,vx as t}from"./loadAgentsDir-B0Anodo0.js";t();export{e as clearPromptCache};
@@ -1,4 +1,4 @@
1
- import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{n as t,t as n}from"./memoize-BK3gG5ob.js";import{P_ as r,z_ as i}from"./loadAgentsDir-DlPbtIsS.js";import{Rn as a,t as o}from"./src-DL3w8VPk.js";import{T as s,c,f as l,i as u,u as d,x as f}from"./debug-Bglx1aTu.js";import{_ as p,b as m,x as h,y as g}from"./stringUtils-C718f5ey.js";import{i as _,n as v,o as y,s as b}from"./history-CQiUERTL.js";import{n as x,t as S}from"./tempfile-CHO5wXsV.js";import{basename as C}from"path";import{spawn as w,spawnSync as T}from"child_process";function E(e){return!!g(e)}function D(e){let t=C(e.split(` `)[0]??``);return A.find(e=>t.includes(e))}function O(e,t,n){return n?M.has(e)?[`-g`,`${t}:${n}`]:e===`subl`?[`${t}:${n}`]:[t]:[t]}function k(e,t){let n=N();if(!n)return!1;let r=n.split(` `),i=r[0]??n,o=r.slice(1),s=D(n);if(s){let r=O(s,e,t),a={detached:!0,stdio:`ignore`},l;return l=process.platform===`win32`?w(`${n} ${r.map(e=>`"${e}"`).join(` `)}`,{...a,shell:!0}):w(i,[...o,...r],a),l.on(`error`,e=>c(`editor spawn failed: ${e}`,{level:`error`})),l.unref(),!0}let l=a.get(process.stdout);if(!l)return!1;let u=t&&j.test(C(i));l.enterAlternateScreen();try{let r={stdio:`inherit`},a;return a=process.platform===`win32`?T(`${n} ${u?`+${t} `:``}"${e}"`,{...r,shell:!0}):T(i,[...o,...u?[`+${t}`,e]:[e]],r),a.error?(c(`editor spawn failed: ${a.error}`,{level:`error`}),!1):!0}finally{l.exitAlternateScreen()}}var A,j,M,N,P=e((()=>{n(),o(),u(),p(),A=[`code`,`cursor`,`windsurf`,`codium`,`subl`,`atom`,`gedit`,`notepad++`,`notepad`],j=/\b(vi|vim|nvim|nano|emacs|pico|micro|helix|hx)\b/,M=new Set([`code`,`cursor`,`windsurf`,`codium`]),N=t(()=>process.env.VISUAL?.trim()?process.env.VISUAL.trim():process.env.EDITOR?.trim()?process.env.EDITOR.trim():process.platform===`win32`?`start /wait notepad`:[`code`,`vi`,`nano`].find(e=>E(e)))}));function F(e){return D(e)!==void 0}function I(e){let t=d(),n=a.get(process.stdout);if(!n)throw Error(`Ink instance not found - cannot pause rendering`);let r=N();if(!r)return{content:null};try{t.statSync(e)}catch{return{content:null}}let o=!F(r);o?n.enterAlternateScreen():(n.pause(),n.suspendStdin());try{return m(`${z[r]??r} "${e}"`,{stdio:`inherit`}),{content:t.readFileSync(e,{encoding:`utf-8`})}}catch(e){if(typeof e==`object`&&e&&`status`in e&&typeof e.status==`number`){let t=e.status;if(t!==0)return{content:null,error:`${i(r)} exited with code ${t}`}}return{content:null}}finally{o?n.exitAlternateScreen():(n.resumeStdin(),n.resume())}}function L(e,t,n){let r=e;for(let[e,t]of Object.entries(n))if(t.type===`text`){let n=parseInt(e,10),i=t.content,a=r.indexOf(i);if(a!==-1){let e=_(n,y(i));r=r.slice(0,a)+e+r.slice(a+i.length)}}return r}function R(e,t){let n=d(),r=S();try{s(r,t?v(e,t):e,{encoding:`utf-8`,flush:!0});let n=I(r);if(n.content===null)return n;let i=n.content;return i.endsWith(`
1
+ import{n as e}from"./rolldown-runtime-DaDcL9Zw.js";import{n as t,t as n}from"./memoize-BK3gG5ob.js";import{P_ as r,z_ as i}from"./loadAgentsDir-B0Anodo0.js";import{Rn as a,t as o}from"./src-DL3w8VPk.js";import{T as s,c,f as l,i as u,u as d,x as f}from"./debug-Bglx1aTu.js";import{_ as p,b as m,x as h,y as g}from"./stringUtils-C718f5ey.js";import{i as _,n as v,o as y,s as b}from"./history-BMycjPTT.js";import{n as x,t as S}from"./tempfile-CHO5wXsV.js";import{basename as C}from"path";import{spawn as w,spawnSync as T}from"child_process";function E(e){return!!g(e)}function D(e){let t=C(e.split(` `)[0]??``);return A.find(e=>t.includes(e))}function O(e,t,n){return n?M.has(e)?[`-g`,`${t}:${n}`]:e===`subl`?[`${t}:${n}`]:[t]:[t]}function k(e,t){let n=N();if(!n)return!1;let r=n.split(` `),i=r[0]??n,o=r.slice(1),s=D(n);if(s){let r=O(s,e,t),a={detached:!0,stdio:`ignore`},l;return l=process.platform===`win32`?w(`${n} ${r.map(e=>`"${e}"`).join(` `)}`,{...a,shell:!0}):w(i,[...o,...r],a),l.on(`error`,e=>c(`editor spawn failed: ${e}`,{level:`error`})),l.unref(),!0}let l=a.get(process.stdout);if(!l)return!1;let u=t&&j.test(C(i));l.enterAlternateScreen();try{let r={stdio:`inherit`},a;return a=process.platform===`win32`?T(`${n} ${u?`+${t} `:``}"${e}"`,{...r,shell:!0}):T(i,[...o,...u?[`+${t}`,e]:[e]],r),a.error?(c(`editor spawn failed: ${a.error}`,{level:`error`}),!1):!0}finally{l.exitAlternateScreen()}}var A,j,M,N,P=e((()=>{n(),o(),u(),p(),A=[`code`,`cursor`,`windsurf`,`codium`,`subl`,`atom`,`gedit`,`notepad++`,`notepad`],j=/\b(vi|vim|nvim|nano|emacs|pico|micro|helix|hx)\b/,M=new Set([`code`,`cursor`,`windsurf`,`codium`]),N=t(()=>process.env.VISUAL?.trim()?process.env.VISUAL.trim():process.env.EDITOR?.trim()?process.env.EDITOR.trim():process.platform===`win32`?`start /wait notepad`:[`code`,`vi`,`nano`].find(e=>E(e)))}));function F(e){return D(e)!==void 0}function I(e){let t=d(),n=a.get(process.stdout);if(!n)throw Error(`Ink instance not found - cannot pause rendering`);let r=N();if(!r)return{content:null};try{t.statSync(e)}catch{return{content:null}}let o=!F(r);o?n.enterAlternateScreen():(n.pause(),n.suspendStdin());try{return m(`${z[r]??r} "${e}"`,{stdio:`inherit`}),{content:t.readFileSync(e,{encoding:`utf-8`})}}catch(e){if(typeof e==`object`&&e&&`status`in e&&typeof e.status==`number`){let t=e.status;if(t!==0)return{content:null,error:`${i(r)} exited with code ${t}`}}return{content:null}}finally{o?n.exitAlternateScreen():(n.resumeStdin(),n.resume())}}function L(e,t,n){let r=e;for(let[e,t]of Object.entries(n))if(t.type===`text`){let n=parseInt(e,10),i=t.content,a=r.indexOf(i);if(a!==-1){let e=_(n,y(i));r=r.slice(0,a)+e+r.slice(a+i.length)}}return r}function R(e,t){let n=d(),r=S();try{s(r,t?v(e,t):e,{encoding:`utf-8`,flush:!0});let n=I(r);if(n.content===null)return n;let i=n.content;return i.endsWith(`
2
2
  `)&&!i.endsWith(`
3
3
 
4
4
  `)&&(i=i.slice(0,-1)),t&&(i=L(i,e,t)),{content:i}}finally{try{n.unlinkSync(r)}catch{}}}var z,B=e((()=>{b(),o(),P(),h(),l(),r(),f(),x(),z={code:`code -w`,subl:`subl --wait`}}));export{P as a,N as i,R as n,k as o,B as r,I as t};
@@ -1 +1 @@
1
- import{ao as e,lo as t,ro as n,uo as r}from"./loadAgentsDir-DlPbtIsS.js";import{It as i,J as a}from"./state-B4jiUise.js";import{I as o,M as s,c,i as l}from"./debug-Bglx1aTu.js";import{Dr as u,Lr as d,_t as f,kn as p,vt as m,wn as h}from"./settings-B2jvL8Dp.js";import{o as g,s as _}from"./log-D2TIwHBV.js";import{Mt as v,jt as y}from"./model-BwBG0V1u.js";import{isAbsolute as b,resolve as x}from"path";y(),i(),l(),o(),h(),d(),g(),t(),f();function S(e,t,n){let r=[],i=[],a=[];for(let[o,s]of Object.entries(e)){let e=t[o],c=w(s.source,n?.projectRoot);e?s.sourceIsFallback||v(c,e.source)?a.push(o):i.push({name:o,declaredSource:c,materializedSource:e.source}):r.push(o)}return{missing:r,sourceChanged:i,upToDate:a}}async function C(t){let i=e();if(Object.keys(i).length===0)return{installed:[],updated:[],failed:[],upToDate:[],skipped:[]};let o;try{o=await r()}catch(e){_(e),o={}}let l=S(i,o,{projectRoot:a()}),u=[...l.missing.map(e=>({name:e,source:w(i[e].source),action:`install`})),...l.sourceChanged.map(({name:e,declaredSource:t})=>({name:e,source:t,action:`update`}))],d=[],f=[];for(let e of u){if(t?.skip?.(e.name,e.source)){d.push(e.name);continue}if(e.action===`update`&&m(e.source)&&!await p(e.source.path)){c(`[reconcile] '${e.name}' declared path does not exist; keeping materialized entry`),d.push(e.name);continue}f.push(e)}if(f.length===0)return{installed:[],updated:[],failed:[],upToDate:l.upToDate,skipped:d};c(`[reconcile] ${f.length} marketplace(s): ${f.map(e=>`${e.name}(${e.action})`).join(`, `)}`);let h=[],g=[],v=[];for(let e=0;e<f.length;e++){let{name:r,source:i,action:a}=f[e];t?.onProgress?.({type:`installing`,name:r,action:a,index:e+1,total:f.length});try{let e=await n(i);a===`install`?h.push(r):g.push(r),t?.onProgress?.({type:`installed`,name:r,alreadyMaterialized:e.alreadyMaterialized})}catch(e){let n=s(e);v.push({name:r,error:n}),t?.onProgress?.({type:`failed`,name:r,error:n}),_(e)}}return{installed:h,updated:g,failed:v,upToDate:l.upToDate,skipped:d}}function w(e,t){if((e.source===`directory`||e.source===`file`)&&!b(e.path)){let n=t??a(),r=u(n);return{...e,path:x(r??n,e.path)}}return e}export{C as n,S as t};
1
+ import{ao as e,lo as t,ro as n,uo as r}from"./loadAgentsDir-B0Anodo0.js";import{It as i,J as a}from"./state-B4jiUise.js";import{I as o,M as s,c,i as l}from"./debug-Bglx1aTu.js";import{Dr as u,Lr as d,_t as f,kn as p,vt as m,wn as h}from"./settings-B2jvL8Dp.js";import{o as g,s as _}from"./log-D2TIwHBV.js";import{Mt as v,jt as y}from"./model-BvQFFOf8.js";import{isAbsolute as b,resolve as x}from"path";y(),i(),l(),o(),h(),d(),g(),t(),f();function S(e,t,n){let r=[],i=[],a=[];for(let[o,s]of Object.entries(e)){let e=t[o],c=w(s.source,n?.projectRoot);e?s.sourceIsFallback||v(c,e.source)?a.push(o):i.push({name:o,declaredSource:c,materializedSource:e.source}):r.push(o)}return{missing:r,sourceChanged:i,upToDate:a}}async function C(t){let i=e();if(Object.keys(i).length===0)return{installed:[],updated:[],failed:[],upToDate:[],skipped:[]};let o;try{o=await r()}catch(e){_(e),o={}}let l=S(i,o,{projectRoot:a()}),u=[...l.missing.map(e=>({name:e,source:w(i[e].source),action:`install`})),...l.sourceChanged.map(({name:e,declaredSource:t})=>({name:e,source:t,action:`update`}))],d=[],f=[];for(let e of u){if(t?.skip?.(e.name,e.source)){d.push(e.name);continue}if(e.action===`update`&&m(e.source)&&!await p(e.source.path)){c(`[reconcile] '${e.name}' declared path does not exist; keeping materialized entry`),d.push(e.name);continue}f.push(e)}if(f.length===0)return{installed:[],updated:[],failed:[],upToDate:l.upToDate,skipped:d};c(`[reconcile] ${f.length} marketplace(s): ${f.map(e=>`${e.name}(${e.action})`).join(`, `)}`);let h=[],g=[],v=[];for(let e=0;e<f.length;e++){let{name:r,source:i,action:a}=f[e];t?.onProgress?.({type:`installing`,name:r,action:a,index:e+1,total:f.length});try{let e=await n(i);a===`install`?h.push(r):g.push(r),t?.onProgress?.({type:`installed`,name:r,alreadyMaterialized:e.alreadyMaterialized})}catch(e){let n=s(e);v.push({name:r,error:n}),t?.onProgress?.({type:`failed`,name:r,error:n}),_(e)}}return{installed:h,updated:g,failed:v,upToDate:l.upToDate,skipped:d}}function w(e,t){if((e.source===`directory`||e.source===`file`)&&!b(e.path)){let n=t??a(),r=u(n);return{...e,path:x(r??n,e.path)}}return e}export{C as n,S as t};