@readmagic/workmate 0.0.32 → 0.0.33

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 (199) hide show
  1. package/dist/chunks/{AddWorkspaceDirectory-vexJPqPV.js → AddWorkspaceDirectory-BumCrGco.js} +1 -1
  2. package/dist/chunks/AgentsMdExternalIncludesDialog-DVV850lX.js +1 -0
  3. package/dist/chunks/{AgentsMdExternalIncludesDialog-DgfH_qbT.js → AgentsMdExternalIncludesDialog-N2vk_aGD.js} +1 -1
  4. package/dist/chunks/{App-Dc1bPgMO.js → App-DTZAQfkJ.js} +1 -1
  5. package/dist/chunks/{BackgroundTasksDialog-By1aAUjA.js → BackgroundTasksDialog-DyyB6cZS.js} +1 -1
  6. package/dist/chunks/{BypassPermissionsModeDialog-BfT29YcX.js → BypassPermissionsModeDialog-D_p_e2U7.js} +1 -1
  7. package/dist/chunks/{CustomSelect-C1eyA6Kb.js → CustomSelect-ORKQehkS.js} +1 -1
  8. package/dist/chunks/{DiffDialog-DlzYbkSE.js → DiffDialog-CbdanHHm.js} +1 -1
  9. package/dist/chunks/{Doctor-Bysh947B.js → Doctor-6ahUD7Yd.js} +1 -1
  10. package/dist/chunks/Doctor-CuZ-IrYy.js +1 -0
  11. package/dist/chunks/{ExitFlow-DdgKWYBy.js → ExitFlow-B8ayNa09.js} +1 -1
  12. package/dist/chunks/{InvalidConfigDialog-B5hyg2fw.js → InvalidConfigDialog-BKxcHo6Z.js} +1 -1
  13. package/dist/chunks/{InvalidSettingsDialog-NORkKmDs.js → InvalidSettingsDialog-DAii7mDz.js} +1 -1
  14. package/dist/chunks/{KeybindingProviderSetup-Dfo4pevM.js → KeybindingProviderSetup-CY_lcLOl.js} +1 -1
  15. package/dist/chunks/{MCPConnectionManager-DTNuL42C.js → MCPConnectionManager-_2ZbLspv.js} +1 -1
  16. package/dist/chunks/{MCPToolListView-CmyNoMRA.js → MCPToolListView-DJZDBRwY.js} +1 -1
  17. package/dist/chunks/{McpParsingWarnings-F5n38r1V.js → McpParsingWarnings-Db14NMyl.js} +1 -1
  18. package/dist/chunks/{MessageSelector-CB3shj7u.js → MessageSelector-Cx0bcXdi.js} +1 -1
  19. package/dist/chunks/{Messages-DHOApZZj.js → Messages-CjoAePf7.js} +1 -1
  20. package/dist/chunks/{Onboarding-LjlAtPO-.js → Onboarding-7tBb3T-M.js} +1 -1
  21. package/dist/chunks/{PromptInputFooterSuggestions-ChS18ulx.js → PromptInputFooterSuggestions-xmiwrtJ2.js} +1 -1
  22. package/dist/chunks/{PromptInputHelpMenu-BG4Xvwlp.js → PromptInputHelpMenu-D7DqC4Cn.js} +1 -1
  23. package/dist/chunks/{ProviderSetup-ebTTSOUN.js → ProviderSetup-DVnWBk55.js} +1 -1
  24. package/dist/chunks/{QueryEngine-D_X2cZgn.js → QueryEngine-DOO68yZV.js} +1 -1
  25. package/dist/chunks/{REPL-CJAN4D4C.js → REPL-BSCGRKyo.js} +4 -4
  26. package/dist/chunks/REPL-DKzgjZ6o.js +1 -0
  27. package/dist/chunks/{ResumeConversation-Vsc6MgfT.js → ResumeConversation-CRhqsgBC.js} +1 -1
  28. package/dist/chunks/SearchExtraToolsTool-C97KJ4aA.js +1 -0
  29. package/dist/chunks/{Settings-Bx9sAK4z.js → Settings-DreltueU.js} +2 -2
  30. package/dist/chunks/{Spinner-bYnSD54K.js → Spinner-B8YFDqiB.js} +1 -1
  31. package/dist/chunks/{TextInput-DJaXm3Y2.js → TextInput-D8z9K9ui.js} +1 -1
  32. package/dist/chunks/{ThemePicker-DTRkcYKg.js → ThemePicker-BG5IfkFL.js} +1 -1
  33. package/dist/chunks/{TrustDialog-CCLPfwKL.js → TrustDialog-QNLHLGmP.js} +1 -1
  34. package/dist/chunks/{_baseEach-CVpc553F.js → _baseEach-DNEnukum.js} +1 -1
  35. package/dist/chunks/{add-dir-CC99_pE2.js → add-dir-CnlSkl-b.js} +1 -1
  36. package/dist/chunks/{agentDisplay-CouNgts6.js → agentDisplay-CG9rKWtq.js} +1 -1
  37. package/dist/chunks/{agents-ByQvpZ-y.js → agents-BqXRXbE8.js} +1 -1
  38. package/dist/chunks/{agents-B0CpBZFY.js → agents-qG0rNfYf.js} +1 -1
  39. package/dist/chunks/{allErrors-BlYbbyyw.js → allErrors-CNnflwGr.js} +1 -1
  40. package/dist/chunks/{backgroundHousekeeping-C86ALKjw.js → backgroundHousekeeping-BspgLesq.js} +1 -1
  41. package/dist/chunks/backgroundHousekeeping-GawmgHeR.js +1 -0
  42. package/dist/chunks/{branch-BQ_M1T0j.js → branch-D_94wxwM.js} +1 -1
  43. package/dist/chunks/{btw-y1tuqCvG.js → btw-CAeVTHuf.js} +1 -1
  44. package/dist/chunks/{caches-CcK6hjFh.js → caches-BHoyfJoA.js} +1 -1
  45. package/dist/chunks/caches-RNaB2_AR.js +1 -0
  46. package/dist/chunks/{channel-D0MXuZ5p.js → channel-C4416TRT.js} +1 -1
  47. package/dist/chunks/{channel-BocoQ6RM.js → channel-Dyd-yaym.js} +2 -2
  48. package/dist/chunks/{clear-Dh0ZUTyq.js → clear-DhNKs3lV.js} +1 -1
  49. package/dist/chunks/commands-C-GF2YWs.js +1 -0
  50. package/dist/chunks/{compact-Drhb6hKF.js → compact-CAig9gJw.js} +1 -1
  51. package/dist/chunks/config-C-sRwFEr.js +1 -0
  52. package/dist/chunks/{context-BsbQnZOh.js → context-BIFpient.js} +1 -1
  53. package/dist/chunks/context-noninteractive-DotqNWvl.js +1 -0
  54. package/dist/chunks/{context-noninteractive-BmjENE43.js → context-noninteractive-EGPwVr60.js} +1 -1
  55. package/dist/chunks/conversation-DTI52FnH.js +1 -0
  56. package/dist/chunks/{conversation-CxvOL7c4.js → conversation-xTrvBX4W.js} +1 -1
  57. package/dist/chunks/{conversationRecovery-CM94gKCQ.js → conversationRecovery-CjexlHQZ.js} +1 -1
  58. package/dist/chunks/{crossProjectResume-Cq1oZ0F6.js → crossProjectResume-TYEdbdfj.js} +1 -1
  59. package/dist/chunks/{diff-DHn2Qup2.js → diff-BjodqyQk.js} +1 -1
  60. package/dist/chunks/doctor-BiaE1VxH.js +1 -0
  61. package/dist/chunks/{entry-tt6FI8GT.js → entry-avSUlTQm.js} +1 -1
  62. package/dist/chunks/{exit-Q-xc8GEs.js → exit-DFWdzIc6.js} +1 -1
  63. package/dist/chunks/{extraUsage-CnQUVxGf.js → extraUsage-q3OWeWjV.js} +1 -1
  64. package/dist/chunks/extractMemories-COnBUALO.js +1 -0
  65. package/dist/chunks/{fast-BeKnNZaH.js → fast-ByhYSait.js} +1 -1
  66. package/dist/chunks/fast-CrcV5wxl.js +1 -0
  67. package/dist/chunks/{fetchModelList-531U79it.js → fetchModelList-D0jIkvN-.js} +1 -1
  68. package/dist/chunks/fetchModelList-DBdOpRqU.js +1 -0
  69. package/dist/chunks/{fileSuggestions-sTa3fiI8.js → fileSuggestions-RURqGY2V.js} +1 -1
  70. package/dist/chunks/{gemini-BzN-GtAf.js → gemini-DsQxIwTq.js} +1 -1
  71. package/dist/chunks/{generateSessionName-DGzU61fU.js → generateSessionName-CTUD5OCr.js} +1 -1
  72. package/dist/chunks/{goal-DOF3kWop.js → goal-BGBTyotH.js} +1 -1
  73. package/dist/chunks/{grok-jsEI7sLT.js → grok-DIsSHEKU.js} +1 -1
  74. package/dist/chunks/{help-CYH2fCqh.js → help-nCNtESeM.js} +1 -1
  75. package/dist/chunks/{hooks-BBL70Pl1.js → hooks-BsmdK_In.js} +1 -1
  76. package/dist/chunks/hooks-DG0-4_wq.js +1 -0
  77. package/dist/chunks/{install-DIv3UQHd.js → install-DMIhfw9V.js} +1 -1
  78. package/dist/chunks/{instrumentation-CzXp-AVx.js → instrumentation-DwK8mG7W.js} +3 -3
  79. package/dist/chunks/{job-B38MURYt.js → job-C8wb0GoC.js} +1 -1
  80. package/dist/chunks/{launchLocalMemory-ClOCP1QH.js → launchLocalMemory-Cpd1IKqK.js} +1 -1
  81. package/dist/chunks/{launchOnboarding-Km72c-fV.js → launchOnboarding-CQ3PM2PE.js} +1 -1
  82. package/dist/chunks/{loadAgentsDir-izAo6rpy.js → loadAgentsDir--CZjFk5b.js} +21 -21
  83. package/dist/chunks/loadAgentsDir-CEOAjqDc.js +1 -0
  84. package/dist/chunks/{loadPluginHooks-BBa5nd8Z.js → loadPluginHooks-CO9vFOYw.js} +1 -1
  85. package/dist/chunks/localSearch-D671mYHo.js +1 -0
  86. package/dist/chunks/{localSearch-BqJfYIga.js → localSearch-gYa9DI1o.js} +1 -1
  87. package/dist/chunks/{logoUtils-Mvbi4iz4.js → logoUtils-CTPl32kP.js} +1 -1
  88. package/dist/chunks/{magicDocs-Beuyy0aV.js → magicDocs-BmVLZ09Z.js} +1 -1
  89. package/dist/chunks/{main-CkDjqZz5.js → main-lRz0vhVy.js} +5 -5
  90. package/dist/chunks/{mcp-BQubBUXS.js → mcp-Bcb9Ge46.js} +1 -1
  91. package/dist/chunks/{mcp-D8SeoRoL.js → mcp-DQJ_8Wh6.js} +1 -1
  92. package/dist/chunks/{mcp-YtIqT_CN.js → mcp-G6t4Lrpk.js} +1 -1
  93. package/dist/chunks/{memory-CFvypHzK.js → memory-DxSaWDW2.js} +1 -1
  94. package/dist/chunks/{mode-CLmT-L6g.js → mode-DD9Fvft0.js} +1 -1
  95. package/dist/chunks/{model-cu29eOoS.js → model-BBpicrKb.js} +1 -1
  96. package/dist/chunks/{model-BdWlSYyq.js → model-CttVg7um.js} +1 -1
  97. package/dist/chunks/{modelOptions-d5F1-LIh.js → modelOptions-CFwllkYA.js} +1 -1
  98. package/dist/chunks/{nativeInstaller-oMsFvcUC.js → nativeInstaller-rACz3E0Q.js} +1 -1
  99. package/dist/chunks/{notifications-ClFVMgnt.js → notifications-I7Gvua3o.js} +1 -1
  100. package/dist/chunks/{onChangeAppState-CvlswuIl.js → onChangeAppState-D5f-Fm83.js} +1 -1
  101. package/dist/chunks/{openai-BoYbxtOG.js → openai-BbDLbcxR.js} +1 -1
  102. package/dist/chunks/{overlayContext-DNYDip6r.js → overlayContext-DkcRGHuq.js} +1 -1
  103. package/dist/chunks/{partition-DRloaIYE.js → partition-Cme8qwzm.js} +1 -1
  104. package/dist/chunks/{permissions-RfHevyA2.js → permissions-BUIk_6ze.js} +1 -1
  105. package/dist/chunks/{pidLock-Bn9y7GMY.js → pidLock-C86UlfNU.js} +2 -2
  106. package/dist/chunks/{plan-CWfN8okc.js → plan-CiL_d9-B.js} +1 -1
  107. package/dist/chunks/{plugin-Bee-4gyo.js → plugin-DQxBd6KC.js} +1 -1
  108. package/dist/chunks/{pluginAutoupdate-xsdXYyA-.js → pluginAutoupdate-G9WJqgcL.js} +1 -1
  109. package/dist/chunks/{pluginBlocklist-BTdbSAHE.js → pluginBlocklist-CNBhu_2a.js} +1 -1
  110. package/dist/chunks/{pluginCliCommands-AlVmiNIz.js → pluginCliCommands-o37ZPkTm.js} +1 -1
  111. package/dist/chunks/{pluginFlagging-BGOionRt.js → pluginFlagging-BuhMpjgI.js} +1 -1
  112. package/dist/chunks/{pluginOperations-DYX4XPSc.js → pluginOperations-CjrgVUC_.js} +1 -1
  113. package/dist/chunks/{pluginStartupCheck-CGmmDw8e.js → pluginStartupCheck-BhXFOdBZ.js} +1 -1
  114. package/dist/chunks/pluginStartupCheck-vE98QcTK.js +1 -0
  115. package/dist/chunks/{plugins-_mf-Z_F5.js → plugins-C8dBDeBi.js} +1 -1
  116. package/dist/chunks/{print-9f_73BN2.js → print-DSp_tL9a.js} +2 -2
  117. package/dist/chunks/{processBashCommand-Do8AJN_g.js → processBashCommand-B9mPY43m.js} +1 -1
  118. package/dist/chunks/{processSlashCommand-BcMLjAEQ.js → processSlashCommand-BsL1c7gz.js} +1 -1
  119. package/dist/chunks/{prompt-B4rM4cgp.js → prompt-DDRveiQv.js} +1 -1
  120. package/dist/chunks/prompt-DF4VkaNR.js +1 -0
  121. package/dist/chunks/prompt-DnA1sxYJ.js +1 -0
  122. package/dist/chunks/{reconciler-BcpooxDV.js → reconciler-CtElVMda.js} +1 -1
  123. package/dist/chunks/{refresh-nrBMGYPi.js → refresh-B2wP7Eww.js} +1 -1
  124. package/dist/chunks/{reject-B3lkQjOv.js → reject-Dwn1HA4X.js} +1 -1
  125. package/dist/chunks/{reload-plugins-C6aSczZl.js → reload-plugins-IdDv2ypF.js} +1 -1
  126. package/dist/chunks/{rename-D3rmIsGf.js → rename-QhD0arLJ.js} +1 -1
  127. package/dist/chunks/{resume-Cj_JBDJU.js → resume-DU7l4Z27.js} +1 -1
  128. package/dist/chunks/{runtimeObserver-4vJtpquK.js → runtimeObserver-C8hrI5t8.js} +2 -2
  129. package/dist/chunks/{runtimeObserver-CgdVfPHy.js → runtimeObserver-CLa7QkQg.js} +1 -1
  130. package/dist/chunks/sandbox-adapter-DHCb-L3c.js +1 -0
  131. package/dist/chunks/{sandbox-toggle-Dt4lDgnB.js → sandbox-toggle-Bp6S0ymp.js} +1 -1
  132. package/dist/chunks/searchExtraTools-CuTtZ-Me.js +1 -0
  133. package/dist/chunks/{select-CPlgmbIJ.js → select-DyDrWYjM.js} +1 -1
  134. package/dist/chunks/sessionFileAccessHooks-CPkpkHpu.js +1 -0
  135. package/dist/chunks/sessionObserver-BHYhPhxa.js +1 -0
  136. package/dist/chunks/{sessionObserver-CFN7Ig3Q.js → sessionObserver-DYZ_LZS8.js} +1 -1
  137. package/dist/chunks/sessionStorage-DHZbnPR_.js +1 -0
  138. package/dist/chunks/{sessionTracing-nqfu1pVT.js → sessionTracing-BcryBpWL.js} +1 -1
  139. package/dist/chunks/{setup-Im12wZpx.js → setup-D6XTQLTX.js} +2 -2
  140. package/dist/chunks/{shadowedRuleDetection-CiG8S6iX.js → shadowedRuleDetection-cZuzST9g.js} +1 -1
  141. package/dist/chunks/{sideQuestion-BW9eo3IE.js → sideQuestion-BcZjHC9V.js} +1 -1
  142. package/dist/chunks/{sinks-C7vJLHLA.js → sinks-B-pWWNEz.js} +1 -1
  143. package/dist/chunks/sinks-Dj88SieQ.js +1 -0
  144. package/dist/chunks/{skillChangeDetector-CrsPxCzn.js → skillChangeDetector-MoZyEFF6.js} +1 -1
  145. package/dist/chunks/{skillGapStore-BV5H9Flk.js → skillGapStore-01n-MpeF.js} +2 -2
  146. package/dist/chunks/{skillLifecycle-EnEI14W2.js → skillLifecycle-DAb_kuAZ.js} +2 -2
  147. package/dist/chunks/{skillSearchPanel-CSm2Eq_U.js → skillSearchPanel-CsT69YTR.js} +2 -2
  148. package/dist/chunks/{skills-C69Im5ML.js → skills-CEup8xDF.js} +1 -1
  149. package/dist/chunks/status-Mc56SVQw.js +1 -0
  150. package/dist/chunks/{statusNoticeHelpers-BHExATuY.js → statusNoticeHelpers-BcmK0jH5.js} +1 -1
  151. package/dist/chunks/switcher-Bz7RJPx2.js +1 -0
  152. package/dist/chunks/{switcher-BdsveDwj.js → switcher-Dco5j_57.js} +1 -1
  153. package/dist/chunks/{tasks-CJDAZERm.js → tasks-sh5zjbfY.js} +1 -1
  154. package/dist/chunks/{templateJobs-fCnSjC9_.js → templateJobs-Cn0jm3Z9.js} +1 -1
  155. package/dist/chunks/{theme-B3baZuK8.js → theme-ILQQU3Mx.js} +1 -1
  156. package/dist/chunks/{tipRegistry-devcMyyn.js → tipRegistry-CEPK5jC0.js} +1 -1
  157. package/dist/chunks/{toolEventObserver-CNXN4TOt.js → toolEventObserver-DWcRzEHx.js} +1 -1
  158. package/dist/chunks/{toolPool-B4XkmUDX.js → toolPool-SaJ1Ro5s.js} +1 -1
  159. package/dist/chunks/{useExitOnCtrlCDWithKeybindings-BfgcAS50.js → useExitOnCtrlCDWithKeybindings-BsFfbQa0.js} +1 -1
  160. package/dist/chunks/useMainLoopModel-C-bQLl-G.js +1 -0
  161. package/dist/chunks/{useManagePlugins-CYUa0_Sn.js → useManagePlugins-CfWlznP3.js} +1 -1
  162. package/dist/chunks/{useMergedTools-By1K71LJ.js → useMergedTools-mr1TJN45.js} +1 -1
  163. package/dist/chunks/{useSearchInput-C4O9vs6X.js → useSearchInput-Box-MFjt.js} +1 -1
  164. package/dist/chunks/{useSettingsErrors-Cw8_cPbg.js → useSettingsErrors-Dix0683s.js} +1 -1
  165. package/dist/chunks/{util-CEVuoH2G.js → util-D-BHKShG.js} +1 -1
  166. package/dist/chunks/{validatePlugin-B7OHQSIx.js → validatePlugin-CBj9ro1j.js} +1 -1
  167. package/dist/chunks/worktree-CwTeHN9U.js +1 -0
  168. package/dist/cli.js +1 -1
  169. package/package.json +1 -1
  170. package/dist/chunks/AgentsMdExternalIncludesDialog-C1YY3Zjr.js +0 -1
  171. package/dist/chunks/Doctor-BTo-aW25.js +0 -1
  172. package/dist/chunks/REPL-BmB39a3K.js +0 -1
  173. package/dist/chunks/SearchExtraToolsTool-DxijDdxt.js +0 -1
  174. package/dist/chunks/backgroundHousekeeping-FTpq_e19.js +0 -1
  175. package/dist/chunks/caches-CO82GKDD.js +0 -1
  176. package/dist/chunks/commands-CqI8Xw3J.js +0 -1
  177. package/dist/chunks/config-DFScnxW_.js +0 -1
  178. package/dist/chunks/context-noninteractive-4Vn-NMDi.js +0 -1
  179. package/dist/chunks/conversation-CSnPSTPX.js +0 -1
  180. package/dist/chunks/doctor-DmJqkQqg.js +0 -1
  181. package/dist/chunks/extractMemories-DOfFiInm.js +0 -1
  182. package/dist/chunks/fast-ClJARykP.js +0 -1
  183. package/dist/chunks/fetchModelList-6pNEKem5.js +0 -1
  184. package/dist/chunks/hooks-ujSG0QYH.js +0 -1
  185. package/dist/chunks/loadAgentsDir-DbkvUkkw.js +0 -1
  186. package/dist/chunks/localSearch-BObbNIdd.js +0 -1
  187. package/dist/chunks/pluginStartupCheck-CQi735a4.js +0 -1
  188. package/dist/chunks/prompt-BnLHkqxH.js +0 -1
  189. package/dist/chunks/prompt-Bxk7M5A5.js +0 -1
  190. package/dist/chunks/sandbox-adapter-BNLLtZ41.js +0 -1
  191. package/dist/chunks/searchExtraTools-C1v6F01_.js +0 -1
  192. package/dist/chunks/sessionFileAccessHooks-BnOpxVs-.js +0 -1
  193. package/dist/chunks/sessionObserver-CnWQCO-S.js +0 -1
  194. package/dist/chunks/sessionStorage-Dr6JjGiG.js +0 -1
  195. package/dist/chunks/sinks-DMDnR8N8.js +0 -1
  196. package/dist/chunks/status-D2nNF67-.js +0 -1
  197. package/dist/chunks/switcher-DFyvU0Qc.js +0 -1
  198. package/dist/chunks/useMainLoopModel-CO_oa76K.js +0 -1
  199. package/dist/chunks/worktree-C9F9fuJ9.js +0 -1
@@ -1,4 +1,4 @@
1
- import{a as e,i as t,n,o as r,r as i,t as a}from"./rolldown-runtime-DaDcL9Zw.js";import{a as o,n as s,o as c,t as l}from"./isObject-C6qM3WEW.js";import{n as u,t as d}from"./memoize-BK3gG5ob.js";import{c as f,f as p,i as m,l as h,o as g,r as _,s as v,u as y}from"./envUtils-QyzA_cFM.js";import{n as b,t as x}from"./defineProperty-C-QyHrDq.js";import{a as S,c as C,i as w,n as T,o as E,r as D,s as O,t as k}from"./classPrivateFieldSet2-D4U5K-I3.js";import{n as A,t as ee}from"./classPrivateMethodInitSpec-BXQD0Vh4.js";import{i as te,n as ne,r as re,t as ie}from"./figures-5ThXQEtq.js";import{c as ae,f as j,i as oe,l as se,m as ce,r as M,t as N,u as le}from"./zod-CuNujUwx.js";import{n as ue,t as de}from"./axios-DaWTGg7G.js";import{$r as fe,Bt as pe,Ct as me,D as he,Fr as ge,Ft as _e,Gr as ve,H as ye,Hr as be,I as P,Kr as xe,Lr as Se,Lt as Ce,Mr as we,P as F,Pr as Te,Pt as Ee,Qr as De,Rn as Oe,T as ke,Tt as Ae,Vr as je,Wt as Me,Xn as Ne,Yt as Pe,Zt as Fe,ai as Ie,bn as Le,cr as Re,d as ze,di as Be,fi as Ve,fr as He,gr as Ue,gt as We,hr as Ge,j as Ke,l as qe,mi as Je,mr as eee,mt as tee,nt as nee,or as ree,ot as Ye,pi as iee,pr as aee,qr as Xe,sr as oee,t as Ze,vn as see,xr as cee,yr as lee,zr as uee}from"./src-BX54x08P.js";import{i as dee,r as Qe}from"./isSymbol-BO6cdPI7.js";import{t as $e}from"./jsx-runtime-Bb4Xn-E0.js";import{$i as et,$n as tt,$r as nt,$t as rt,Ai as it,An as fee,Ar as at,At as ot,B as st,Bi as pee,Bn as ct,Br as lt,Bt as mee,C as hee,Ci as gee,Ct as ut,Di as _ee,Dn as vee,Dr as yee,Ei as bee,En as dt,Er as xee,F as ft,Fi as pt,Fn as mt,Fr as ht,G as gt,Gi as I,Gn as _t,Gt as vt,H as yt,Hi as bt,Hr as xt,Ht as St,I as See,In as Ct,Ir as wt,J as Cee,Ji as Tt,Jr as Et,K as Dt,Ki as Ot,L as kt,Ln as wee,Lt as Tee,M as At,Mi as Eee,Mn as Dee,Mr as Oee,Mt as kee,N as jt,Ni as Aee,Nn as Mt,Nr as jee,Nt,O as Mee,Oi as Pt,On as Nee,Or as Pee,Ot as Fee,P as Ft,Pi as It,Pn as Lt,Pr as Iee,Pt as Rt,Qi as L,Qn as zt,Qt as Lee,R as Bt,Rr as Vt,S as Ree,Si as zee,Sr as Ht,St as Bee,T as Vee,Ti as Hee,Tn as Uee,Tr as Ut,Tt as Wt,U as Gt,Ui as Wee,Un as Kt,V as Gee,Vn as qt,Vr as Jt,W as Yt,Wi as Xt,Wn as Kee,Wr as Zt,Wt as Qt,X as $t,Xi as en,Xn as qee,Xr as tn,Xt as nn,Y as rn,Yn as an,Yr as on,Yt as sn,Z as Jee,Zn as cn,Zr as ln,Zt as Yee,_a as Xee,_i as Zee,_t as un,a as Qee,aa as dn,ai as fn,an as $ee,at as pn,ba as ete,bn as mn,br as hn,bt as tte,c as gn,ca as _n,ci as nte,cn as rte,cr as ite,ct as vn,d as yn,di as bn,dn as ate,dr as xn,dt as ote,ei as Sn,en as R,er as ste,f as cte,fi as Cn,fn as lte,fr as wn,ft as ute,g as dte,gi as fte,gr as Tn,gt as En,ha as pte,hi as mte,hn as Dn,hr as On,ht as kn,ia as An,ii as hte,in as gte,it as jn,j as _te,ji as vte,jn as yte,jr as bte,jt as xte,k as Ste,ki as Mn,kn as Nn,kt as Pn,l as Cte,la as Fn,li as wte,ln as Tte,lr as Ete,lt as In,m as Ln,mi as Dte,mn as Rn,mr as Ote,na as z,ni as kte,nn as zn,nt as Bn,o as Vn,oa as Hn,oi as Ate,on as jte,or as Mte,ot as Un,p as Nte,pa as Pte,pi as Fte,pr as Wn,pt as Gn,q as Ite,qi as Lte,qn as Kn,qr as qn,qt as Jn,ra as Yn,ri as Xn,rn as Zn,rt as Qn,s as $n,sa as B,si as er,sn as tr,sr as Rte,st as nr,t as rr,ta as V,tn as ir,tr as ar,tt as or,ua as zte,ui as Bte,ur as sr,ut as cr,vi as lr,vn as ur,vr as Vte,vt as dr,w as Hte,wi as Ute,wn as Wte,wr as fr,wt as pr,x as Gte,xr as mr,xt as hr,y as gr,ya as Kte,yi as _r,yn as vr,yr as qte,z as yr,zi as Jte,zn as Yte,zr as br}from"./settings-CA-5Px85.js";import{$ as Xte,$n as xr,$t as Sr,At as Cr,B as Zte,Br as wr,Bt as Qte,C as $te,Cn as Tr,Cr as ene,Ct as tne,D as nne,Dn as rne,Dr as Er,Dt as ine,En as Dr,Er as Or,Et as ane,F as kr,Ft as Ar,Gn as jr,Gr as one,Hn as sne,Ht as Mr,I as cne,It as Nr,J as Pr,Jr as lne,Jt as une,K as Fr,Kn as Ir,L as Lr,Lt as dne,M as Rr,Mt as fne,N as pne,Nt as mne,On as hne,Ot as gne,P as _ne,Pt as H,Q as vne,Qn as zr,Qt as yne,R as bne,Rn as xne,Rr as Sne,Rt as Cne,S as wne,Sr as Br,St as Tne,T as Vr,Tn as Ene,Tr as Dne,Tt as One,V as kne,Vr as Ane,W as jne,Wn as Mne,Wr as Nne,X as Hr,Xn as Pne,Xt as Fne,Y as Ur,Yr as Ine,Z as Lne,_ as Rne,_r as zne,_t as Bne,a as Vne,an as Hne,ar as Une,at as Wr,b as Wne,br as Gr,bt as Kr,c as Gne,ct as qr,d as Kne,di as qne,dt as Jr,et as Jne,f as Yne,fi as Xne,fn as Yr,ft as Zne,g as Qne,gr as $ne,gt as Xr,h as Zr,hi as ere,hn as tre,ht as nre,i as rre,in as Qr,ir as ire,kn as are,kt as ore,lt as sre,mi as cre,mn as lre,mt as ure,n as dre,ni as fre,nr as pre,nt as $r,o as mre,oi as hre,ot as ei,p as gre,pi as _re,pt as vre,q as ti,qn as yre,r as bre,ri as xre,rt as ni,s as Sre,si as Cre,tn as wre,tt as ri,u as ii,ui as Tre,ut as Ere,vt as Dre,w as Ore,wn as ai,wr as kre,x as Are,xr as oi,xt as si,yt as ci,zr as li,zt as jre}from"./state-CXY-q5gr.js";import{i as Mre,n as ui,r as Nre,t as U}from"./cwd-DrEEb4f5.js";import{$ as di,A as fi,C as W,E as pi,F as mi,G as Pre,H as hi,I as gi,J as _i,K as vi,L as Fre,M as G,N as yi,O as bi,P as Ire,R as xi,S as Si,T as Ci,V as wi,X as Lre,Y as Ti,Z as Rre,_ as Ei,c as K,d as Di,et as Oi,f as ki,g as Ai,i as q,j as ji,k as Mi,m as Ni,p as Pi,q as Fi,s as Ii,t as zre,tt as Bre,u as J,v as Vre,x as Li,y as Hre,z as Ri}from"./debug-NBJH_NxR.js";import{A as Ure,C as zi,D as Wre,E as Gre,O as Kre,S as qre,T as Bi,a as Vi,b as Hi,c as Ui,d as Wi,h as Gi,k as Jre,l as Yre,m as Ki,o as qi,s as Ji,t as Yi,u as Xi,w as Zi,x as Qi,y as $i}from"./config-CMtnYZR9.js";import{i as Xre,n as ea,r as ta,t as na}from"./execa-CBhG1doD.js";import{B as ra,D as ia,E as aa,F as oa,G as sa,H as ca,I as la,K as ua,L as da,M as fa,N as pa,O as ma,R as ha,S as ga,U as _a,V as va,W as ya,b as Zre,c as ba,d as Qre,g as $re,j as xa,l as Sa,m as eie,n as Ca,o as wa,p as tie,q as Ta,s as Y,x as nie,y as rie,z as Ea}from"./log-D98mO6yJ.js";import{i as Da,n as Oa,r as ka,t as Aa}from"./execFileNoThrow-7Ys9mO27.js";import{c as ja,i as Ma,n as Na,o as Pa,s as Fa,t as Ia}from"./bundledMode-Dqe4pz0a.js";import{n as La}from"./analytics-COpjZpvd.js";import{C as iie,_ as Ra,a as za,c as Ba,f as Va,h as Ha,i as aie,l as Ua,m as Wa,n as oie,o as sie,s as Ga,u as Ka,y as qa}from"./startupProfiler-C_xcIvEA.js";import{a as Ja,i as Ya,l as Xa,n as cie,o as Za,r as Qa,t as $a,u as eo}from"./stringUtils-CtJhTszO.js";import{A as lie,At as uie,B as die,C as fie,Ct as to,Dt as no,E as ro,Et as io,F as pie,Ft as ao,G as oo,H as mie,I as so,J as hie,K as co,L as gie,M as _ie,Mt as lo,N as vie,Nt as uo,O as fo,Ot as po,P as yie,Pt as mo,Q as bie,R as xie,S as Sie,St as ho,T as go,Tt as Cie,U as wie,V as Tie,X as Eie,Y as Die,Z as Oie,_ as _o,_t as vo,a as kie,at as yo,b as bo,bt as Aie,c as xo,d as jie,dt as So,et as Co,f as wo,ft as To,gt as Mie,h as Nie,ht as Eo,i as Do,it as Pie,j as Fie,k as Oo,kt as Iie,l as ko,m as Ao,mt as jo,n as Mo,nt as No,o as Po,ot as Fo,pt as Lie,q as Io,rt as Rie,s as Lo,t as Ro,tt as zie,u as zo,ut as Bo,v as Vo,vt as Ho,w as Bie,wt as Uo,xt as Vie,yt as Hie,z as Uie}from"./model-cu29eOoS.js";import{$ as Wo,$t as Wie,A as Gie,At as Go,B as Kie,Bt as Ko,Ct as qo,Dt as Jo,Et as Yo,Ft as Xo,G as qie,Gt as Zo,H as Jie,Ht as Qo,I as Yie,It as $o,J as Xie,Jt as Zie,K as Qie,Kt as es,Lt as $ie,Mt as eae,N as tae,Nt as nae,O as rae,Ot as ts,P as iae,Pt as aae,Q as oae,Qt as sae,R as cae,Rt as ns,S as lae,St as uae,T as dae,Tt as fae,U as pae,Ut as rs,Vt as is,W as mae,Wt as as,X as hae,Xt as gae,Y as _ae,Yt as os,Z as vae,Zt as yae,_ as bae,_n as xae,_t as ss,a as cs,an as Sae,at as ls,b as Cae,bn as us,bt as wae,c as ds,cn as Tae,ct as Eae,d as Dae,dt as Oae,en as kae,et as Aae,f as fs,ft as jae,g as ps,gn as ms,gt as hs,h as Mae,hn as gs,ht as _s,i as vs,in as ys,jt as bs,k as Nae,kt as Pae,l as Fae,ln as xs,lt as Ss,m as Iae,mn as Cs,mt as Lae,n as Rae,nn as zae,nt as ws,o as Bae,on as Ts,p as Vae,pn as Es,pt as Hae,q as Uae,qt as Ds,r as Os,rn as ks,rt as Wae,s as Gae,sn as Kae,st as qae,t as Jae,tn as As,tt as js,u as Yae,un as Xae,vn as Ms,vt as Zae,w as Qae,wt as Ns,xt as Ps,yn as Fs,yt as Is,z as $ae,zt as Ls}from"./prompt-B4rM4cgp.js";import{n as eoe,r as Rs}from"./lockfile-D_9vif6E.js";import{a as toe,c as zs,i as Bs,l as noe,m as roe,o as ioe,p as aoe,s as ooe}from"./proxy-MzIsnPd7.js";import{i as soe,r as coe}from"./projectOnboardingState-DqGLXSM_.js";import{S as loe,a as uoe,c as doe,n as Vs,s as foe,t as Hs,x as poe}from"./sleep-BGewNhNx.js";import{a as moe,i as hoe,n as goe,o as _oe,t as voe}from"./break-cache-B1nuWtD_.js";import{a as yoe,i as boe,l as Us,n as xoe,o as Ws,r as Soe,s as Coe,t as woe}from"./localSearch-BqJfYIga.js";import{a as Gs,c as Ks,n as Toe,s as qs}from"./ripgrep-CnK9qx1e.js";import{n as Eoe,r as Doe}from"./client-q_uGYC2E.js";import{r as Ooe,t as koe}from"./store-Z8rTjDHe.js";import{n as Aoe,t as joe}from"./client-D3QmHVeI.js";import{i as Moe,n as Noe,r as Js}from"./loader-DsEdsMHv.js";import{n as Poe,r as Foe,t as Ioe}from"./switcher-BdsveDwj.js";import{B as Ys,C as Xs,F as Zs,I as Loe,L as Qs,M as Roe,N as zoe,P as Boe,R as Voe,S as Hoe,T as $s,a as Uoe,c as ec,f as Woe,g as Goe,h as Koe,i as qoe,m as Joe,n as Yoe,o as Xoe,p as Zoe,s as tc,t as Qoe,u as $oe,v as ese,w as nc,x as tse,z as rc}from"./sessionTracing-nqfu1pVT.js";import{a as nse,o as rse,r as ic,s as ise,t as ase}from"./parser-D2kggQDp.js";import{i as ac,r as oc}from"./genericProcessUtils-XwqvFxyn.js";import{n as ose,r as sse,t as sc}from"./poorMode-BvypUTur.js";import{r as cse,t as lse}from"./sanitization-DV-94a9Z.js";import{n as use,t as dse}from"./worktreeModeEnabled-BFOYTTTr.js";import{n as fse,t as pse}from"./featureCheck-D6FjD-nt.js";import{r as mse,t as hse}from"./firstPartyEventLogger-RR5rvDtk.js";import*as gse from"os";import{homedir as cc,release as _se,tmpdir as lc,type as vse,userInfo as yse,version as bse}from"os";import*as uc from"path";import{basename as dc,delimiter as xse,dirname as fc,extname as pc,isAbsolute as mc,join as X,normalize as hc,parse as gc,posix as _c,relative as vc,resolve as yc,sep as bc,win32 as xc}from"path";import Sc from"node:process";import Cc,{basename as Sse,dirname as Cse,isAbsolute as wse,join as wc,relative as Tse,resolve as Tc}from"node:path";import*as Ec from"fs";import{accessSync as Ese,chmodSync as Dse,closeSync as Ose,constants as Dc,createReadStream as kse,existsSync as Ase,fstat as jse,fstatSync as Mse,mkdirSync as Nse,openSync as Pse,readFileSync as Oc,readSync as Fse,readdirSync as Ise,rm as Lse,rmSync as Rse,statSync as zse,unlinkSync as Bse,writeFileSync as Vse,writeSync as kc}from"fs";import{execSync as Hse,spawn as Use,spawnSync as Wse}from"node:child_process";import*as Ac from"node:fs";import{closeSync as Gse,existsSync as jc,mkdirSync as Kse,openSync as qse,readFileSync as Jse,readSync as Yse,readdirSync as Mc,renameSync as Xse,rmSync as Zse,statSync as Qse,unlinkSync as $se,writeFileSync as ece}from"node:fs";import{EOL as Nc,homedir as tce,tmpdir as Pc}from"node:os";import{createHash as nce,randomBytes as rce,randomUUID as ice}from"node:crypto";import{createHash as Fc,randomBytes as Ic,randomUUID as Lc}from"crypto";import{access as ace,appendFile as Rc,chmod as zc,copyFile as Bc,link as Vc,lstat as oce,mkdir as Hc,open as Uc,readFile as Wc,readdir as Gc,readlink as sce,realpath as Kc,rename as qc,rm as Jc,rmdir as cce,stat as Yc,symlink as Xc,truncate as lce,unlink as Zc,utimes as uce,writeFile as Qc}from"fs/promises";import"util";import{execFile as dce,execFileSync as fce,spawn as $c,spawnSync as el}from"child_process";import{fileURLToPath as pce,pathToFileURL as tl}from"url";import mce,{isIP as hce}from"net";import{setMaxListeners as gce}from"events";import{PassThrough as _ce}from"node:stream";import{mkdir as vce,readFile as nl,readdir as yce,rename as bce,rm as xce,writeFile as Sce}from"node:fs/promises";import{request as Cce}from"node:https";import{Agent as wce,createServer as Tce,request as rl}from"node:http";import{URL as il,fileURLToPath as Ece}from"node:url";import{BlockList as Dce,connect as al,isIP as ol}from"node:net";import{AsyncLocalStorage as Oce}from"async_hooks";import{connect as kce}from"node:tls";import{text as Ace}from"node:stream/consumers";import{join as sl}from"path/posix";import{lookup as jce}from"dns";function Mce(e){let t=e.slice(e.lastIndexOf(`.`)).toLowerCase();return Nce.has(t)}var Nce,Pce=n((()=>{Nce=new Set(`.png,.jpg,.jpeg,.gif,.bmp,.ico,.webp,.tiff,.tif,.mp4,.mov,.avi,.mkv,.webm,.wmv,.flv,.m4v,.mpeg,.mpg,.mp3,.wav,.ogg,.flac,.aac,.m4a,.wma,.aiff,.opus,.zip,.tar,.gz,.bz2,.7z,.rar,.xz,.z,.tgz,.iso,.exe,.dll,.so,.dylib,.bin,.o,.a,.obj,.lib,.app,.msi,.deb,.rpm,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.odt,.ods,.odp,.ttf,.otf,.woff,.woff2,.eot,.pyc,.pyo,.class,.jar,.war,.ear,.node,.wasm,.rlib,.sqlite,.sqlite3,.db,.mdb,.idx,.psd,.ai,.eps,.sketch,.fig,.xd,.blend,.3ds,.max,.swf,.fla,.lockb,.dat,.data`.split(`,`))}));function Fce(e,t){for(var n=-1,r=e==null?0:e.length;++n<r&&t(e[n],n,e)!==!1;);return e}var Ice=n((()=>{}));function Lce(e,t){return e&&Pt(t,Er(t),e)}var Rce=n((()=>{Mn(),Or()}));function zce(e,t){return e&&Pt(t,_ee(t),e)}var Bce=n((()=>{Mn(),bee()}));function Vce(e,t){return Pt(e,lne(e),t)}var Hce=n((()=>{Mn(),Ine()}));function Uce(e,t){return Pt(e,Jre(e),t)}var Wce=n((()=>{Mn(),Ure()}));function Gce(e){var t=e.length,n=new e.constructor(t);return t&&typeof e[0]==`string`&&Kce.call(e,`index`)&&(n.index=e.index,n.input=e.input),n}var Kce,qce=n((()=>{Kce=Object.prototype.hasOwnProperty}));function Jce(e,t){var n=t?lr(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.byteLength)}var Yce=n((()=>{_r()}));function Xce(e){var t=new e.constructor(e.source,Zce.exec(e));return t.lastIndex=e.lastIndex,t}var Zce,Qce=n((()=>{Zce=/\w*$/}));function $ce(e){return ll?Object(ll.call(e)):{}}var cl,ll,ele=n((()=>{c(),cl=o?o.prototype:void 0,ll=cl?cl.valueOf:void 0}));function tle(e,t,n){var r=e.constructor;switch(t){case ule:return lr(e);case nle:case rle:return new r(+e);case dle:return Jce(e,n);case fle:case ple:case mle:case hle:case gle:case _le:case vle:case yle:case ble:return fte(e,n);case ile:return new r;case ale:case cle:return new r(e);case ole:return Xce(e);case sle:return new r;case lle:return $ce(e)}}var nle,rle,ile,ale,ole,sle,cle,lle,ule,dle,fle,ple,mle,hle,gle,_le,vle,yle,ble,xle=n((()=>{_r(),Yce(),Qce(),ele(),Zee(),nle=`[object Boolean]`,rle=`[object Date]`,ile=`[object Map]`,ale=`[object Number]`,ole=`[object RegExp]`,sle=`[object Set]`,cle=`[object String]`,lle=`[object Symbol]`,ule=`[object ArrayBuffer]`,dle=`[object DataView]`,fle=`[object Float32Array]`,ple=`[object Float64Array]`,mle=`[object Int8Array]`,hle=`[object Int16Array]`,gle=`[object Int32Array]`,_le=`[object Uint8Array]`,vle=`[object Uint8ClampedArray]`,yle=`[object Uint16Array]`,ble=`[object Uint32Array]`}));function Sle(e){return dee(e)&&Gr(e)==Cle}var Cle,wle=n((()=>{oi(),Qe(),Cle=`[object Map]`})),ul,Tle,Ele=n((()=>{wle(),Ane(),Sne(),ul=li&&li.isMap,Tle=ul?wr(ul):Sle}));function Dle(e){return dee(e)&&Gr(e)==Ole}var Ole,kle=n((()=>{oi(),Qe(),Ole=`[object Set]`})),dl,Ale,jle=n((()=>{kle(),Ane(),Sne(),dl=li&&li.isSet,Ale=dl?wr(dl):Dle}));function fl(e,t,n,r,i,a){var o,c=t&Mle,l=t&Nle,u=t&Ple;if(n&&(o=i?n(e,r,i,a):n(e)),o!==void 0)return o;if(!s(e))return e;var d=xre(e);if(d){if(o=Gce(e),!c)return zee(e,o)}else{var f=Gr(e),p=f==ml||f==zle;if(one(e))return Ute(e,c);if(f==hl||f==pl||p&&!i){if(o=l||p?{}:Dte(e),!c)return l?Uce(e,zce(o,e)):Vce(e,Lce(o,e))}else{if(!kl[f])return i?e:{};o=tle(e,f,c)}}a||(a=new cre);var m=a.get(e);if(m)return m;a.set(e,o),Ale(e)?e.forEach(function(r){o.add(fl(r,t,n,r,e,a))}):Tle(e)&&e.forEach(function(r,i){o.set(i,fl(r,t,n,i,e,a))});var h=d?void 0:(u?l?Wre:kre:l?_ee:Er)(e);return Fce(h||e,function(r,i){h&&(i=r,r=e[i]),it(o,i,fl(r,t,n,i,e,a))}),o}var Mle,Nle,Ple,pl,Fle,Ile,Lle,Rle,ml,zle,Ble,Vle,hl,Hle,Ule,Wle,gl,_l,vl,yl,bl,xl,Sl,Cl,wl,Tl,El,Dl,Ol,kl,Al=n((()=>{ere(),Ice(),vte(),Rce(),Bce(),Hee(),gee(),Hce(),Wce(),Dne(),Kre(),oi(),qce(),xle(),mte(),fre(),Nne(),Ele(),l(),jle(),Or(),bee(),Mle=1,Nle=2,Ple=4,pl=`[object Arguments]`,Fle=`[object Array]`,Ile=`[object Boolean]`,Lle=`[object Date]`,Rle=`[object Error]`,ml=`[object Function]`,zle=`[object GeneratorFunction]`,Ble=`[object Map]`,Vle=`[object Number]`,hl=`[object Object]`,Hle=`[object RegExp]`,Ule=`[object Set]`,Wle=`[object String]`,gl=`[object Symbol]`,_l=`[object WeakMap]`,vl=`[object ArrayBuffer]`,yl=`[object DataView]`,bl=`[object Float32Array]`,xl=`[object Float64Array]`,Sl=`[object Int8Array]`,Cl=`[object Int16Array]`,wl=`[object Int32Array]`,Tl=`[object Uint8Array]`,El=`[object Uint8ClampedArray]`,Dl=`[object Uint16Array]`,Ol=`[object Uint32Array]`,kl={},kl[pl]=kl[Fle]=kl[vl]=kl[yl]=kl[Ile]=kl[Lle]=kl[bl]=kl[xl]=kl[Sl]=kl[Cl]=kl[wl]=kl[Ble]=kl[Vle]=kl[hl]=kl[Hle]=kl[Ule]=kl[Wle]=kl[gl]=kl[Tl]=kl[El]=kl[Dl]=kl[Ol]=!0,kl[Rle]=kl[ml]=kl[_l]=!1}));function Gle(e){return fl(e,jl|Ml)}var jl,Ml,Kle=n((()=>{Al(),jl=1,Ml=4}));function Nl(e){return e.sort((e,t)=>{let n=t.modified.getTime()-e.modified.getTime();return n===0?t.created.getTime()-e.created.getTime():n})}var qle=n((()=>{})),Pl=a((e=>{var t=Symbol.for(`yaml.alias`),n=Symbol.for(`yaml.document`),r=Symbol.for(`yaml.map`),i=Symbol.for(`yaml.pair`),a=Symbol.for(`yaml.scalar`),o=Symbol.for(`yaml.seq`),s=Symbol.for(`yaml.node.type`),c=e=>!!e&&typeof e==`object`&&e[s]===t,l=e=>!!e&&typeof e==`object`&&e[s]===n,u=e=>!!e&&typeof e==`object`&&e[s]===r,d=e=>!!e&&typeof e==`object`&&e[s]===i,f=e=>!!e&&typeof e==`object`&&e[s]===a,p=e=>!!e&&typeof e==`object`&&e[s]===o;function m(e){if(e&&typeof e==`object`)switch(e[s]){case r:case o:return!0}return!1}function h(e){if(e&&typeof e==`object`)switch(e[s]){case t:case r:case a:case o:return!0}return!1}e.ALIAS=t,e.DOC=n,e.MAP=r,e.NODE_TYPE=s,e.PAIR=i,e.SCALAR=a,e.SEQ=o,e.hasAnchor=e=>(f(e)||m(e))&&!!e.anchor,e.isAlias=c,e.isCollection=m,e.isDocument=l,e.isMap=u,e.isNode=h,e.isPair=d,e.isScalar=f,e.isSeq=p})),Fl=a((e=>{var t=Pl(),n=Symbol(`break visit`),r=Symbol(`skip children`),i=Symbol(`remove node`);function a(e,n){let r=l(n);t.isDocument(e)?o(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):o(null,e,r,Object.freeze([]))}a.BREAK=n,a.SKIP=r,a.REMOVE=i;function o(e,r,a,s){let c=u(e,r,a,s);if(t.isNode(c)||t.isPair(c))return d(e,s,c),o(e,c,a,s);if(typeof c!=`symbol`){if(t.isCollection(r)){s=Object.freeze(s.concat(r));for(let e=0;e<r.items.length;++e){let t=o(e,r.items[e],a,s);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){s=Object.freeze(s.concat(r));let e=o(`key`,r.key,a,s);if(e===n)return n;e===i&&(r.key=null);let t=o(`value`,r.value,a,s);if(t===n)return n;t===i&&(r.value=null)}}return c}async function s(e,n){let r=l(n);t.isDocument(e)?await c(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):await c(null,e,r,Object.freeze([]))}s.BREAK=n,s.SKIP=r,s.REMOVE=i;async function c(e,r,a,o){let s=await u(e,r,a,o);if(t.isNode(s)||t.isPair(s))return d(e,o,s),c(e,s,a,o);if(typeof s!=`symbol`){if(t.isCollection(r)){o=Object.freeze(o.concat(r));for(let e=0;e<r.items.length;++e){let t=await c(e,r.items[e],a,o);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){o=Object.freeze(o.concat(r));let e=await c(`key`,r.key,a,o);if(e===n)return n;e===i&&(r.key=null);let t=await c(`value`,r.value,a,o);if(t===n)return n;t===i&&(r.value=null)}}return s}function l(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function u(e,n,r,i){if(typeof r==`function`)return r(e,n,i);if(t.isMap(n))return r.Map?.(e,n,i);if(t.isSeq(n))return r.Seq?.(e,n,i);if(t.isPair(n))return r.Pair?.(e,n,i);if(t.isScalar(n))return r.Scalar?.(e,n,i);if(t.isAlias(n))return r.Alias?.(e,n,i)}function d(e,n,r){let i=n[n.length-1];if(t.isCollection(i))i.items[e]=r;else if(t.isPair(i))e===`key`?i.key=r:i.value=r;else if(t.isDocument(i))i.contents=r;else{let e=t.isAlias(i)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}e.visit=a,e.visitAsync=s})),Il=a((e=>{var t=Pl(),n=Fl(),r={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},i=e=>e.replace(/[!,[\]{}]/g,e=>r[e]),a=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,n){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let r=t.trim().split(/[ \t]+/),i=r.shift();switch(i){case`%TAG`:{if(r.length!==2&&(n(0,`%TAG directive should contain exactly two parts`),r.length<2))return!1;let[e,t]=r;return this.tags[e]=t,!0}case`%YAML`:{if(this.yaml.explicit=!0,r.length!==1)return n(0,`%YAML directive should contain exactly one part`),!1;let[e]=r;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let t=/^\d+\.\d+$/.test(e);return n(6,`Unsupported YAML version ${e}`,t),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let n=e.slice(2,-1);return n===`!`||n===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),n)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return n===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+i(e.substring(n.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],i=Object.entries(this.tags),a;if(e&&i.length>0&&t.isNode(e.contents)){let r={};n.visit(e.contents,(e,n)=>{t.isNode(n)&&n.tag&&(r[n.tag]=!0)}),a=Object.keys(r)}else a=[];for(let[t,n]of i)t===`!!`&&n===`tag:yaml.org,2002:`||(!e||a.some(e=>e.startsWith(n)))&&r.push(`%TAG ${t} ${n}`);return r.join(`
1
+ import{a as e,i as t,n,o as r,r as i,t as a}from"./rolldown-runtime-DaDcL9Zw.js";import{a as o,n as s,o as c,t as l}from"./isObject-C6qM3WEW.js";import{n as u,t as d}from"./memoize-BK3gG5ob.js";import{c as f,f as p,i as m,l as h,o as g,r as _,s as v,u as y}from"./envUtils-QyzA_cFM.js";import{n as b,t as x}from"./defineProperty-C-QyHrDq.js";import{a as S,c as C,i as w,n as T,o as E,r as D,s as O,t as k}from"./classPrivateFieldSet2-D4U5K-I3.js";import{n as A,t as ee}from"./classPrivateMethodInitSpec-BXQD0Vh4.js";import{i as te,n as ne,r as re,t as ie}from"./figures-5ThXQEtq.js";import{c as ae,f as j,i as oe,l as se,m as ce,r as M,t as N,u as le}from"./zod-CuNujUwx.js";import{n as ue,t as de}from"./axios-DaWTGg7G.js";import{$r as fe,Bt as pe,Ct as me,D as he,Fr as ge,Ft as _e,Gr as ve,H as ye,Hr as be,I as P,Kr as xe,Lr as Se,Lt as Ce,Mr as we,P as F,Pr as Te,Pt as Ee,Qr as De,Rn as Oe,T as ke,Tt as Ae,Vr as je,Wt as Me,Xn as Ne,Yt as Pe,Zt as Fe,ai as Ie,bn as Le,cr as Re,d as ze,di as Be,fi as Ve,fr as He,gr as Ue,gt as We,hr as Ge,j as Ke,l as qe,mi as Je,mr as eee,mt as tee,nt as nee,or as ree,ot as Ye,pi as iee,pr as aee,qr as Xe,sr as oee,t as Ze,vn as see,xr as cee,yr as lee,zr as uee}from"./src-BX54x08P.js";import{i as dee,r as Qe}from"./isSymbol-BO6cdPI7.js";import{t as $e}from"./jsx-runtime-Bb4Xn-E0.js";import{$i as et,$n as tt,$r as nt,$t as rt,Ai as it,An as fee,Ar as at,At as ot,B as st,Bi as pee,Bn as ct,Br as lt,Bt as mee,C as hee,Ci as gee,Ct as ut,Di as _ee,Dn as vee,Dr as yee,Ei as bee,En as dt,Er as xee,F as ft,Fi as pt,Fn as mt,Fr as ht,G as gt,Gi as I,Gn as _t,Gt as vt,H as yt,Hi as bt,Hr as xt,Ht as St,I as See,In as Ct,Ir as wt,J as Cee,Ji as Tt,Jr as Et,K as Dt,Ki as Ot,L as kt,Ln as wee,Lt as Tee,M as At,Mi as Eee,Mn as Dee,Mr as Oee,Mt as kee,N as jt,Ni as Aee,Nn as Mt,Nr as jee,Nt,O as Mee,Oi as Pt,On as Nee,Or as Pee,Ot as Fee,P as Ft,Pi as It,Pn as Lt,Pr as Iee,Pt as Rt,Qi as L,Qn as zt,Qt as Lee,R as Bt,Rr as Vt,S as Ree,Si as zee,Sr as Ht,St as Bee,T as Vee,Ti as Hee,Tn as Uee,Tr as Ut,Tt as Wt,U as Gt,Ui as Wee,Un as Kt,V as Gee,Vn as qt,Vr as Jt,W as Yt,Wi as Xt,Wn as Kee,Wr as Zt,Wt as Qt,X as $t,Xi as en,Xn as qee,Xr as tn,Xt as nn,Y as rn,Yn as an,Yr as on,Yt as sn,Z as Jee,Zn as cn,Zr as ln,Zt as Yee,_a as Xee,_i as Zee,_t as un,a as Qee,aa as dn,ai as fn,an as $ee,at as pn,ba as ete,bn as mn,br as hn,bt as tte,c as gn,ca as _n,ci as nte,cn as rte,cr as ite,ct as vn,d as yn,di as bn,dn as ate,dr as xn,dt as ote,ei as Sn,en as R,er as ste,f as cte,fi as Cn,fn as lte,fr as wn,ft as ute,g as dte,gi as fte,gr as Tn,gt as En,ha as pte,hi as mte,hn as Dn,hr as On,ht as kn,ia as An,ii as hte,in as gte,it as jn,j as _te,ji as vte,jn as yte,jr as bte,jt as xte,k as Ste,ki as Mn,kn as Nn,kt as Pn,l as Cte,la as Fn,li as wte,ln as Tte,lr as Ete,lt as In,m as Ln,mi as Dte,mn as Rn,mr as Ote,na as z,ni as kte,nn as zn,nt as Bn,o as Vn,oa as Hn,oi as Ate,on as jte,or as Mte,ot as Un,p as Nte,pa as Pte,pi as Fte,pr as Wn,pt as Gn,q as Ite,qi as Lte,qn as Kn,qr as qn,qt as Jn,ra as Yn,ri as Xn,rn as Zn,rt as Qn,s as $n,sa as B,si as er,sn as tr,sr as Rte,st as nr,t as rr,ta as V,tn as ir,tr as ar,tt as or,ua as zte,ui as Bte,ur as sr,ut as cr,vi as lr,vn as ur,vr as Vte,vt as dr,w as Hte,wi as Ute,wn as Wte,wr as fr,wt as pr,x as Gte,xr as mr,xt as hr,y as gr,ya as Kte,yi as _r,yn as vr,yr as qte,z as yr,zi as Jte,zn as Yte,zr as br}from"./settings-CA-5Px85.js";import{$ as Xte,$n as xr,$t as Sr,At as Cr,B as Zte,Br as wr,Bt as Qte,C as $te,Cn as Tr,Cr as ene,Ct as tne,D as nne,Dn as rne,Dr as Er,Dt as ine,En as Dr,Er as Or,Et as ane,F as kr,Ft as Ar,Gn as jr,Gr as one,Hn as sne,Ht as Mr,I as cne,It as Nr,J as Pr,Jr as lne,Jt as une,K as Fr,Kn as Ir,L as Lr,Lt as dne,M as Rr,Mt as fne,N as pne,Nt as mne,On as hne,Ot as gne,P as _ne,Pt as H,Q as vne,Qn as zr,Qt as yne,R as bne,Rn as xne,Rr as Sne,Rt as Cne,S as wne,Sr as Br,St as Tne,T as Vr,Tn as Ene,Tr as Dne,Tt as One,V as kne,Vr as Ane,W as jne,Wn as Mne,Wr as Nne,X as Hr,Xn as Pne,Xt as Fne,Y as Ur,Yr as Ine,Z as Lne,_ as Rne,_r as zne,_t as Bne,a as Vne,an as Hne,ar as Une,at as Wr,b as Wne,br as Gr,bt as Kr,c as Gne,ct as qr,d as Kne,di as qne,dt as Jr,et as Jne,f as Yne,fi as Xne,fn as Yr,ft as Zne,g as Qne,gr as $ne,gt as Xr,h as Zr,hi as ere,hn as tre,ht as nre,i as rre,in as Qr,ir as ire,kn as are,kt as ore,lt as sre,mi as cre,mn as lre,mt as ure,n as dre,ni as fre,nr as pre,nt as $r,o as mre,oi as hre,ot as ei,p as gre,pi as _re,pt as vre,q as ti,qn as yre,r as bre,ri as xre,rt as ni,s as Sre,si as Cre,tn as wre,tt as ri,u as ii,ui as Tre,ut as Ere,vt as Dre,w as Ore,wn as ai,wr as kre,x as Are,xr as oi,xt as si,yt as ci,zr as li,zt as jre}from"./state-CXY-q5gr.js";import{i as Mre,n as ui,r as Nre,t as U}from"./cwd-DrEEb4f5.js";import{$ as di,A as fi,C as W,E as pi,F as mi,G as Pre,H as hi,I as gi,J as _i,K as vi,L as Fre,M as G,N as yi,O as bi,P as Ire,R as xi,S as Si,T as Ci,V as wi,X as Lre,Y as Ti,Z as Rre,_ as Ei,c as K,d as Di,et as Oi,f as ki,g as Ai,i as q,j as ji,k as Mi,m as Ni,p as Pi,q as Fi,s as Ii,t as zre,tt as Bre,u as J,v as Vre,x as Li,y as Hre,z as Ri}from"./debug-NBJH_NxR.js";import{A as Ure,C as zi,D as Wre,E as Gre,O as Kre,S as qre,T as Bi,a as Vi,b as Hi,c as Ui,d as Wi,h as Gi,k as Jre,l as Yre,m as Ki,o as qi,s as Ji,t as Yi,u as Xi,w as Zi,x as Qi,y as $i}from"./config-CMtnYZR9.js";import{i as Xre,n as ea,r as ta,t as na}from"./execa-CBhG1doD.js";import{B as ra,D as ia,E as aa,F as oa,G as sa,H as ca,I as la,K as ua,L as da,M as fa,N as pa,O as ma,R as ha,S as ga,U as _a,V as va,W as ya,b as Zre,c as ba,d as Qre,g as $re,j as xa,l as Sa,m as eie,n as Ca,o as wa,p as tie,q as Ta,s as Y,x as nie,y as rie,z as Ea}from"./log-D98mO6yJ.js";import{i as Da,n as Oa,r as ka,t as Aa}from"./execFileNoThrow-7Ys9mO27.js";import{c as ja,i as Ma,n as Na,o as Pa,s as Fa,t as Ia}from"./bundledMode-Dqe4pz0a.js";import{n as La}from"./analytics-COpjZpvd.js";import{C as iie,_ as Ra,a as za,c as Ba,f as Va,h as Ha,i as aie,l as Ua,m as Wa,n as oie,o as sie,s as Ga,u as Ka,y as qa}from"./startupProfiler-C_xcIvEA.js";import{a as Ja,i as Ya,l as Xa,n as cie,o as Za,r as Qa,t as $a,u as eo}from"./stringUtils-CtJhTszO.js";import{A as lie,At as uie,B as die,C as fie,Ct as to,Dt as no,E as ro,Et as io,F as pie,Ft as ao,G as oo,H as mie,I as so,J as hie,K as co,L as gie,M as _ie,Mt as lo,N as vie,Nt as uo,O as fo,Ot as po,P as yie,Pt as mo,Q as bie,R as xie,S as Sie,St as ho,T as go,Tt as Cie,U as wie,V as Tie,X as Eie,Y as Die,Z as Oie,_ as _o,_t as vo,a as kie,at as yo,b as bo,bt as Aie,c as xo,d as jie,dt as So,et as Co,f as wo,ft as To,gt as Mie,h as Nie,ht as Eo,i as Do,it as Pie,j as Fie,k as Oo,kt as Iie,l as ko,m as Ao,mt as jo,n as Mo,nt as No,o as Po,ot as Fo,pt as Lie,q as Io,rt as Rie,s as Lo,t as Ro,tt as zie,u as zo,ut as Bo,v as Vo,vt as Ho,w as Bie,wt as Uo,xt as Vie,yt as Hie,z as Uie}from"./model-BBpicrKb.js";import{$ as Wo,$t as Wie,A as Gie,At as Go,B as Kie,Bt as Ko,Ct as qo,Dt as Jo,Et as Yo,Ft as Xo,G as qie,Gt as Zo,H as Jie,Ht as Qo,I as Yie,It as $o,J as Xie,Jt as Zie,K as Qie,Kt as es,Lt as $ie,Mt as eae,N as tae,Nt as nae,O as rae,Ot as ts,P as iae,Pt as aae,Q as oae,Qt as sae,R as cae,Rt as ns,S as lae,St as uae,T as dae,Tt as fae,U as pae,Ut as rs,Vt as is,W as mae,Wt as as,X as hae,Xt as gae,Y as _ae,Yt as os,Z as vae,Zt as yae,_ as bae,_n as xae,_t as ss,a as cs,an as Sae,at as ls,b as Cae,bn as us,bt as wae,c as ds,cn as Tae,ct as Eae,d as Dae,dt as Oae,en as kae,et as Aae,f as fs,ft as jae,g as ps,gn as ms,gt as hs,h as Mae,hn as gs,ht as _s,i as vs,in as ys,jt as bs,k as Nae,kt as Pae,l as Fae,ln as xs,lt as Ss,m as Iae,mn as Cs,mt as Lae,n as Rae,nn as zae,nt as ws,o as Bae,on as Ts,p as Vae,pn as Es,pt as Hae,q as Uae,qt as Ds,r as Os,rn as ks,rt as Wae,s as Gae,sn as Kae,st as qae,t as Jae,tn as As,tt as js,u as Yae,un as Xae,vn as Ms,vt as Zae,w as Qae,wt as Ns,xt as Ps,yn as Fs,yt as Is,z as $ae,zt as Ls}from"./prompt-DDRveiQv.js";import{n as eoe,r as Rs}from"./lockfile-D_9vif6E.js";import{a as toe,c as zs,i as Bs,l as noe,m as roe,o as ioe,p as aoe,s as ooe}from"./proxy-MzIsnPd7.js";import{i as soe,r as coe}from"./projectOnboardingState-DqGLXSM_.js";import{S as loe,a as uoe,c as doe,n as Vs,s as foe,t as Hs,x as poe}from"./sleep-BGewNhNx.js";import{a as moe,i as hoe,n as goe,o as _oe,t as voe}from"./break-cache-B1nuWtD_.js";import{a as yoe,i as boe,l as Us,n as xoe,o as Ws,r as Soe,s as Coe,t as woe}from"./localSearch-gYa9DI1o.js";import{a as Gs,c as Ks,n as Toe,s as qs}from"./ripgrep-CnK9qx1e.js";import{n as Eoe,r as Doe}from"./client-q_uGYC2E.js";import{r as Ooe,t as koe}from"./store-Z8rTjDHe.js";import{n as Aoe,t as joe}from"./client-D3QmHVeI.js";import{i as Moe,n as Noe,r as Js}from"./loader-DsEdsMHv.js";import{n as Poe,r as Foe,t as Ioe}from"./switcher-Dco5j_57.js";import{B as Ys,C as Xs,F as Zs,I as Loe,L as Qs,M as Roe,N as zoe,P as Boe,R as Voe,S as Hoe,T as $s,a as Uoe,c as ec,f as Woe,g as Goe,h as Koe,i as qoe,m as Joe,n as Yoe,o as Xoe,p as Zoe,s as tc,t as Qoe,u as $oe,v as ese,w as nc,x as tse,z as rc}from"./sessionTracing-BcryBpWL.js";import{a as nse,o as rse,r as ic,s as ise,t as ase}from"./parser-D2kggQDp.js";import{i as ac,r as oc}from"./genericProcessUtils-XwqvFxyn.js";import{n as ose,r as sse,t as sc}from"./poorMode-BvypUTur.js";import{r as cse,t as lse}from"./sanitization-DV-94a9Z.js";import{n as use,t as dse}from"./worktreeModeEnabled-BFOYTTTr.js";import{n as fse,t as pse}from"./featureCheck-D6FjD-nt.js";import{r as mse,t as hse}from"./firstPartyEventLogger-RR5rvDtk.js";import*as gse from"os";import{homedir as cc,release as _se,tmpdir as lc,type as vse,userInfo as yse,version as bse}from"os";import*as uc from"path";import{basename as dc,delimiter as xse,dirname as fc,extname as pc,isAbsolute as mc,join as X,normalize as hc,parse as gc,posix as _c,relative as vc,resolve as yc,sep as bc,win32 as xc}from"path";import Sc from"node:process";import Cc,{basename as Sse,dirname as Cse,isAbsolute as wse,join as wc,relative as Tse,resolve as Tc}from"node:path";import*as Ec from"fs";import{accessSync as Ese,chmodSync as Dse,closeSync as Ose,constants as Dc,createReadStream as kse,existsSync as Ase,fstat as jse,fstatSync as Mse,mkdirSync as Nse,openSync as Pse,readFileSync as Oc,readSync as Fse,readdirSync as Ise,rm as Lse,rmSync as Rse,statSync as zse,unlinkSync as Bse,writeFileSync as Vse,writeSync as kc}from"fs";import{execSync as Hse,spawn as Use,spawnSync as Wse}from"node:child_process";import*as Ac from"node:fs";import{closeSync as Gse,existsSync as jc,mkdirSync as Kse,openSync as qse,readFileSync as Jse,readSync as Yse,readdirSync as Mc,renameSync as Xse,rmSync as Zse,statSync as Qse,unlinkSync as $se,writeFileSync as ece}from"node:fs";import{EOL as Nc,homedir as tce,tmpdir as Pc}from"node:os";import{createHash as nce,randomBytes as rce,randomUUID as ice}from"node:crypto";import{createHash as Fc,randomBytes as Ic,randomUUID as Lc}from"crypto";import{access as ace,appendFile as Rc,chmod as zc,copyFile as Bc,link as Vc,lstat as oce,mkdir as Hc,open as Uc,readFile as Wc,readdir as Gc,readlink as sce,realpath as Kc,rename as qc,rm as Jc,rmdir as cce,stat as Yc,symlink as Xc,truncate as lce,unlink as Zc,utimes as uce,writeFile as Qc}from"fs/promises";import"util";import{execFile as dce,execFileSync as fce,spawn as $c,spawnSync as el}from"child_process";import{fileURLToPath as pce,pathToFileURL as tl}from"url";import mce,{isIP as hce}from"net";import{setMaxListeners as gce}from"events";import{PassThrough as _ce}from"node:stream";import{mkdir as vce,readFile as nl,readdir as yce,rename as bce,rm as xce,writeFile as Sce}from"node:fs/promises";import{request as Cce}from"node:https";import{Agent as wce,createServer as Tce,request as rl}from"node:http";import{URL as il,fileURLToPath as Ece}from"node:url";import{BlockList as Dce,connect as al,isIP as ol}from"node:net";import{AsyncLocalStorage as Oce}from"async_hooks";import{connect as kce}from"node:tls";import{text as Ace}from"node:stream/consumers";import{join as sl}from"path/posix";import{lookup as jce}from"dns";function Mce(e){let t=e.slice(e.lastIndexOf(`.`)).toLowerCase();return Nce.has(t)}var Nce,Pce=n((()=>{Nce=new Set(`.png,.jpg,.jpeg,.gif,.bmp,.ico,.webp,.tiff,.tif,.mp4,.mov,.avi,.mkv,.webm,.wmv,.flv,.m4v,.mpeg,.mpg,.mp3,.wav,.ogg,.flac,.aac,.m4a,.wma,.aiff,.opus,.zip,.tar,.gz,.bz2,.7z,.rar,.xz,.z,.tgz,.iso,.exe,.dll,.so,.dylib,.bin,.o,.a,.obj,.lib,.app,.msi,.deb,.rpm,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.odt,.ods,.odp,.ttf,.otf,.woff,.woff2,.eot,.pyc,.pyo,.class,.jar,.war,.ear,.node,.wasm,.rlib,.sqlite,.sqlite3,.db,.mdb,.idx,.psd,.ai,.eps,.sketch,.fig,.xd,.blend,.3ds,.max,.swf,.fla,.lockb,.dat,.data`.split(`,`))}));function Fce(e,t){for(var n=-1,r=e==null?0:e.length;++n<r&&t(e[n],n,e)!==!1;);return e}var Ice=n((()=>{}));function Lce(e,t){return e&&Pt(t,Er(t),e)}var Rce=n((()=>{Mn(),Or()}));function zce(e,t){return e&&Pt(t,_ee(t),e)}var Bce=n((()=>{Mn(),bee()}));function Vce(e,t){return Pt(e,lne(e),t)}var Hce=n((()=>{Mn(),Ine()}));function Uce(e,t){return Pt(e,Jre(e),t)}var Wce=n((()=>{Mn(),Ure()}));function Gce(e){var t=e.length,n=new e.constructor(t);return t&&typeof e[0]==`string`&&Kce.call(e,`index`)&&(n.index=e.index,n.input=e.input),n}var Kce,qce=n((()=>{Kce=Object.prototype.hasOwnProperty}));function Jce(e,t){var n=t?lr(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.byteLength)}var Yce=n((()=>{_r()}));function Xce(e){var t=new e.constructor(e.source,Zce.exec(e));return t.lastIndex=e.lastIndex,t}var Zce,Qce=n((()=>{Zce=/\w*$/}));function $ce(e){return ll?Object(ll.call(e)):{}}var cl,ll,ele=n((()=>{c(),cl=o?o.prototype:void 0,ll=cl?cl.valueOf:void 0}));function tle(e,t,n){var r=e.constructor;switch(t){case ule:return lr(e);case nle:case rle:return new r(+e);case dle:return Jce(e,n);case fle:case ple:case mle:case hle:case gle:case _le:case vle:case yle:case ble:return fte(e,n);case ile:return new r;case ale:case cle:return new r(e);case ole:return Xce(e);case sle:return new r;case lle:return $ce(e)}}var nle,rle,ile,ale,ole,sle,cle,lle,ule,dle,fle,ple,mle,hle,gle,_le,vle,yle,ble,xle=n((()=>{_r(),Yce(),Qce(),ele(),Zee(),nle=`[object Boolean]`,rle=`[object Date]`,ile=`[object Map]`,ale=`[object Number]`,ole=`[object RegExp]`,sle=`[object Set]`,cle=`[object String]`,lle=`[object Symbol]`,ule=`[object ArrayBuffer]`,dle=`[object DataView]`,fle=`[object Float32Array]`,ple=`[object Float64Array]`,mle=`[object Int8Array]`,hle=`[object Int16Array]`,gle=`[object Int32Array]`,_le=`[object Uint8Array]`,vle=`[object Uint8ClampedArray]`,yle=`[object Uint16Array]`,ble=`[object Uint32Array]`}));function Sle(e){return dee(e)&&Gr(e)==Cle}var Cle,wle=n((()=>{oi(),Qe(),Cle=`[object Map]`})),ul,Tle,Ele=n((()=>{wle(),Ane(),Sne(),ul=li&&li.isMap,Tle=ul?wr(ul):Sle}));function Dle(e){return dee(e)&&Gr(e)==Ole}var Ole,kle=n((()=>{oi(),Qe(),Ole=`[object Set]`})),dl,Ale,jle=n((()=>{kle(),Ane(),Sne(),dl=li&&li.isSet,Ale=dl?wr(dl):Dle}));function fl(e,t,n,r,i,a){var o,c=t&Mle,l=t&Nle,u=t&Ple;if(n&&(o=i?n(e,r,i,a):n(e)),o!==void 0)return o;if(!s(e))return e;var d=xre(e);if(d){if(o=Gce(e),!c)return zee(e,o)}else{var f=Gr(e),p=f==ml||f==zle;if(one(e))return Ute(e,c);if(f==hl||f==pl||p&&!i){if(o=l||p?{}:Dte(e),!c)return l?Uce(e,zce(o,e)):Vce(e,Lce(o,e))}else{if(!kl[f])return i?e:{};o=tle(e,f,c)}}a||(a=new cre);var m=a.get(e);if(m)return m;a.set(e,o),Ale(e)?e.forEach(function(r){o.add(fl(r,t,n,r,e,a))}):Tle(e)&&e.forEach(function(r,i){o.set(i,fl(r,t,n,i,e,a))});var h=d?void 0:(u?l?Wre:kre:l?_ee:Er)(e);return Fce(h||e,function(r,i){h&&(i=r,r=e[i]),it(o,i,fl(r,t,n,i,e,a))}),o}var Mle,Nle,Ple,pl,Fle,Ile,Lle,Rle,ml,zle,Ble,Vle,hl,Hle,Ule,Wle,gl,_l,vl,yl,bl,xl,Sl,Cl,wl,Tl,El,Dl,Ol,kl,Al=n((()=>{ere(),Ice(),vte(),Rce(),Bce(),Hee(),gee(),Hce(),Wce(),Dne(),Kre(),oi(),qce(),xle(),mte(),fre(),Nne(),Ele(),l(),jle(),Or(),bee(),Mle=1,Nle=2,Ple=4,pl=`[object Arguments]`,Fle=`[object Array]`,Ile=`[object Boolean]`,Lle=`[object Date]`,Rle=`[object Error]`,ml=`[object Function]`,zle=`[object GeneratorFunction]`,Ble=`[object Map]`,Vle=`[object Number]`,hl=`[object Object]`,Hle=`[object RegExp]`,Ule=`[object Set]`,Wle=`[object String]`,gl=`[object Symbol]`,_l=`[object WeakMap]`,vl=`[object ArrayBuffer]`,yl=`[object DataView]`,bl=`[object Float32Array]`,xl=`[object Float64Array]`,Sl=`[object Int8Array]`,Cl=`[object Int16Array]`,wl=`[object Int32Array]`,Tl=`[object Uint8Array]`,El=`[object Uint8ClampedArray]`,Dl=`[object Uint16Array]`,Ol=`[object Uint32Array]`,kl={},kl[pl]=kl[Fle]=kl[vl]=kl[yl]=kl[Ile]=kl[Lle]=kl[bl]=kl[xl]=kl[Sl]=kl[Cl]=kl[wl]=kl[Ble]=kl[Vle]=kl[hl]=kl[Hle]=kl[Ule]=kl[Wle]=kl[gl]=kl[Tl]=kl[El]=kl[Dl]=kl[Ol]=!0,kl[Rle]=kl[ml]=kl[_l]=!1}));function Gle(e){return fl(e,jl|Ml)}var jl,Ml,Kle=n((()=>{Al(),jl=1,Ml=4}));function Nl(e){return e.sort((e,t)=>{let n=t.modified.getTime()-e.modified.getTime();return n===0?t.created.getTime()-e.created.getTime():n})}var qle=n((()=>{})),Pl=a((e=>{var t=Symbol.for(`yaml.alias`),n=Symbol.for(`yaml.document`),r=Symbol.for(`yaml.map`),i=Symbol.for(`yaml.pair`),a=Symbol.for(`yaml.scalar`),o=Symbol.for(`yaml.seq`),s=Symbol.for(`yaml.node.type`),c=e=>!!e&&typeof e==`object`&&e[s]===t,l=e=>!!e&&typeof e==`object`&&e[s]===n,u=e=>!!e&&typeof e==`object`&&e[s]===r,d=e=>!!e&&typeof e==`object`&&e[s]===i,f=e=>!!e&&typeof e==`object`&&e[s]===a,p=e=>!!e&&typeof e==`object`&&e[s]===o;function m(e){if(e&&typeof e==`object`)switch(e[s]){case r:case o:return!0}return!1}function h(e){if(e&&typeof e==`object`)switch(e[s]){case t:case r:case a:case o:return!0}return!1}e.ALIAS=t,e.DOC=n,e.MAP=r,e.NODE_TYPE=s,e.PAIR=i,e.SCALAR=a,e.SEQ=o,e.hasAnchor=e=>(f(e)||m(e))&&!!e.anchor,e.isAlias=c,e.isCollection=m,e.isDocument=l,e.isMap=u,e.isNode=h,e.isPair=d,e.isScalar=f,e.isSeq=p})),Fl=a((e=>{var t=Pl(),n=Symbol(`break visit`),r=Symbol(`skip children`),i=Symbol(`remove node`);function a(e,n){let r=l(n);t.isDocument(e)?o(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):o(null,e,r,Object.freeze([]))}a.BREAK=n,a.SKIP=r,a.REMOVE=i;function o(e,r,a,s){let c=u(e,r,a,s);if(t.isNode(c)||t.isPair(c))return d(e,s,c),o(e,c,a,s);if(typeof c!=`symbol`){if(t.isCollection(r)){s=Object.freeze(s.concat(r));for(let e=0;e<r.items.length;++e){let t=o(e,r.items[e],a,s);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){s=Object.freeze(s.concat(r));let e=o(`key`,r.key,a,s);if(e===n)return n;e===i&&(r.key=null);let t=o(`value`,r.value,a,s);if(t===n)return n;t===i&&(r.value=null)}}return c}async function s(e,n){let r=l(n);t.isDocument(e)?await c(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):await c(null,e,r,Object.freeze([]))}s.BREAK=n,s.SKIP=r,s.REMOVE=i;async function c(e,r,a,o){let s=await u(e,r,a,o);if(t.isNode(s)||t.isPair(s))return d(e,o,s),c(e,s,a,o);if(typeof s!=`symbol`){if(t.isCollection(r)){o=Object.freeze(o.concat(r));for(let e=0;e<r.items.length;++e){let t=await c(e,r.items[e],a,o);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){o=Object.freeze(o.concat(r));let e=await c(`key`,r.key,a,o);if(e===n)return n;e===i&&(r.key=null);let t=await c(`value`,r.value,a,o);if(t===n)return n;t===i&&(r.value=null)}}return s}function l(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function u(e,n,r,i){if(typeof r==`function`)return r(e,n,i);if(t.isMap(n))return r.Map?.(e,n,i);if(t.isSeq(n))return r.Seq?.(e,n,i);if(t.isPair(n))return r.Pair?.(e,n,i);if(t.isScalar(n))return r.Scalar?.(e,n,i);if(t.isAlias(n))return r.Alias?.(e,n,i)}function d(e,n,r){let i=n[n.length-1];if(t.isCollection(i))i.items[e]=r;else if(t.isPair(i))e===`key`?i.key=r:i.value=r;else if(t.isDocument(i))i.contents=r;else{let e=t.isAlias(i)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}e.visit=a,e.visitAsync=s})),Il=a((e=>{var t=Pl(),n=Fl(),r={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},i=e=>e.replace(/[!,[\]{}]/g,e=>r[e]),a=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,n){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let r=t.trim().split(/[ \t]+/),i=r.shift();switch(i){case`%TAG`:{if(r.length!==2&&(n(0,`%TAG directive should contain exactly two parts`),r.length<2))return!1;let[e,t]=r;return this.tags[e]=t,!0}case`%YAML`:{if(this.yaml.explicit=!0,r.length!==1)return n(0,`%YAML directive should contain exactly one part`),!1;let[e]=r;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let t=/^\d+\.\d+$/.test(e);return n(6,`Unsupported YAML version ${e}`,t),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let n=e.slice(2,-1);return n===`!`||n===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),n)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return n===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+i(e.substring(n.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],i=Object.entries(this.tags),a;if(e&&i.length>0&&t.isNode(e.contents)){let r={};n.visit(e.contents,(e,n)=>{t.isNode(n)&&n.tag&&(r[n.tag]=!0)}),a=Object.keys(r)}else a=[];for(let[t,n]of i)t===`!!`&&n===`tag:yaml.org,2002:`||(!e||a.some(e=>e.startsWith(n)))&&r.push(`%TAG ${t} ${n}`);return r.join(`
2
2
  `)}};a.defaultYaml={explicit:!1,version:`1.2`},a.defaultTags={"!!":`tag:yaml.org,2002:`},e.Directives=a})),Ll=a((e=>{var t=Pl(),n=Fl();function r(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw Error(t)}return!0}function i(e){let t=new Set;return n.visit(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function a(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function o(e,n){let r=[],o=new Map,s=null;return{onAnchor:t=>{r.push(t),s??(s=i(e));let o=a(n,s);return s.add(o),o},setAnchors:()=>{for(let e of r){let n=o.get(e);if(typeof n==`object`&&n.anchor&&(t.isScalar(n.node)||t.isCollection(n.node)))n.node.anchor=n.anchor;else{let t=Error(`Failed to resolve repeated object (this should not happen)`);throw t.source=e,t}}},sourceObjects:o}}e.anchorIsValid=r,e.anchorNames=i,e.createNodeAnchors=o,e.findNewAnchor=a})),Rl=a((e=>{function t(e,n,r,i){if(i&&typeof i==`object`)if(Array.isArray(i))for(let n=0,r=i.length;n<r;++n){let r=i[n],a=t(e,i,String(n),r);a===void 0?delete i[n]:a!==r&&(i[n]=a)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let r=i.get(n),a=t(e,i,n,r);a===void 0?i.delete(n):a!==r&&i.set(n,a)}else if(i instanceof Set)for(let n of Array.from(i)){let r=t(e,i,n,n);r===void 0?i.delete(n):r!==n&&(i.delete(n),i.add(r))}else for(let[n,r]of Object.entries(i)){let a=t(e,i,n,r);a===void 0?delete i[n]:a!==r&&(i[n]=a)}return e.call(n,r,i)}e.applyReviver=t})),zl=a((e=>{var t=Pl();function n(e,r,i){if(Array.isArray(e))return e.map((e,t)=>n(e,String(t),i));if(e&&typeof e.toJSON==`function`){if(!i||!t.hasAnchor(e))return e.toJSON(r,i);let n={aliasCount:0,count:1,res:void 0};i.anchors.set(e,n),i.onCreate=e=>{n.res=e,delete i.onCreate};let a=e.toJSON(r,i);return i.onCreate&&i.onCreate(a),a}return typeof e==`bigint`&&!i?.keep?Number(e):e}e.toJS=n})),Bl=a((e=>{var t=Rl(),n=Pl(),r=zl();e.NodeBase=class{constructor(e){Object.defineProperty(this,n.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:i,maxAliasCount:a,onAnchor:o,reviver:s}={}){if(!n.isDocument(e))throw TypeError(`A document argument is required`);let c={anchors:new Map,doc:e,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof a==`number`?a:100},l=r.toJS(this,``,c);if(typeof o==`function`)for(let{count:e,res:t}of c.anchors.values())o(t,e);return typeof s==`function`?t.applyReviver(s,{"":l},``,l):l}}})),Vl=a((e=>{var t=Ll(),n=Fl(),r=Pl(),i=Bl(),a=zl(),o=class extends i.NodeBase{constructor(e){super(r.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){if(t?.maxAliasCount===0)throw ReferenceError(`Alias resolution is disabled`);let i;t?.aliasResolveCache?i=t.aliasResolveCache:(i=[],n.visit(e,{Node:(e,t)=>{(r.isAlias(t)||r.hasAnchor(t))&&i.push(t)}}),t&&(t.aliasResolveCache=i));let a;for(let e of i){if(e===this)break;e.anchor===this.source&&(a=e)}return a}toJSON(e,t){if(!t)return{source:this.source};let{anchors:n,doc:r,maxAliasCount:i}=t,o=this.resolve(r,t);if(!o){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(e)}let c=n.get(o);if(c||(a.toJS(o,null,t),c=n.get(o)),c?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(i>=0&&(c.count+=1,c.aliasCount===0&&(c.aliasCount=s(r,o,n)),c.count*c.aliasCount>i))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`);return c.res}toString(e,n,r){let i=`*${this.source}`;if(e){if(t.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(e)}if(e.implicitKey)return`${i} `}return i}};function s(e,t,n){if(r.isAlias(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}else if(r.isCollection(t)){let r=0;for(let i of t.items){let t=s(e,i,n);t>r&&(r=t)}return r}else if(r.isPair(t)){let r=s(e,t.key,n),i=s(e,t.value,n);return Math.max(r,i)}return 1}e.Alias=o})),Hl=a((e=>{var t=Pl(),n=Bl(),r=zl(),i=e=>!e||typeof e!=`function`&&typeof e!=`object`,a=class extends n.NodeBase{constructor(e){super(t.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:r.toJS(this.value,e,t)}toString(){return String(this.value)}};a.BLOCK_FOLDED=`BLOCK_FOLDED`,a.BLOCK_LITERAL=`BLOCK_LITERAL`,a.PLAIN=`PLAIN`,a.QUOTE_DOUBLE=`QUOTE_DOUBLE`,a.QUOTE_SINGLE=`QUOTE_SINGLE`,e.Scalar=a,e.isScalarValue=i})),Ul=a((e=>{var t=Vl(),n=Pl(),r=Hl(),i=`tag:yaml.org,2002:`;function a(e,t,n){if(t){let e=n.filter(e=>e.tag===t),r=e.find(e=>!e.format)??e[0];if(!r)throw Error(`Tag ${t} not found`);return r}return n.find(t=>t.identify?.(e)&&!t.format)}function o(e,o,s){if(n.isDocument(e)&&(e=e.contents),n.isNode(e))return e;if(n.isPair(e)){let t=s.schema[n.MAP].createNode?.(s.schema,null,s);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<`u`&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:c,onAnchor:l,onTagObj:u,schema:d,sourceObjects:f}=s,p;if(c&&e&&typeof e==`object`){if(p=f.get(e),p)return p.anchor??(p.anchor=l(e)),new t.Alias(p.anchor);p={anchor:null,node:null},f.set(e,p)}o?.startsWith(`!!`)&&(o=i+o.slice(2));let m=a(e,o,d.tags);if(!m){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new r.Scalar(e);return p&&(p.node=t),t}m=e instanceof Map?d[n.MAP]:Symbol.iterator in Object(e)?d[n.SEQ]:d[n.MAP]}u&&(u(m),delete s.onTagObj);let h=m?.createNode?m.createNode(s.schema,e,s):typeof m?.nodeClass?.from==`function`?m.nodeClass.from(s.schema,e,s):new r.Scalar(e);return o?h.tag=o:m.default||(h.tag=m.tag),p&&(p.node=h),h}e.createNode=o})),Wl=a((e=>{var t=Ul(),n=Pl(),r=Bl();function i(e,n,r){let i=r;for(let e=n.length-1;e>=0;--e){let t=n[e];if(typeof t==`number`&&Number.isInteger(t)&&t>=0){let e=[];e[t]=i,i=e}else i=new Map([[t,i]])}return t.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:new Map})}var a=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done;e.Collection=class extends r.NodeBase{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(t=>n.isNode(t)||n.isPair(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(a(e))this.add(t);else{let[r,...a]=e,o=this.get(r,!0);if(n.isCollection(o))o.addIn(a,t);else if(o===void 0&&this.schema)this.set(r,i(this.schema,a,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${a}`)}}deleteIn(e){let[t,...r]=e;if(r.length===0)return this.delete(t);let i=this.get(t,!0);if(n.isCollection(i))return i.deleteIn(r);throw Error(`Expected YAML collection at ${t}. Remaining path: ${r}`)}getIn(e,t){let[r,...i]=e,a=this.get(r,!0);return i.length===0?!t&&n.isScalar(a)?a.value:a:n.isCollection(a)?a.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!n.isPair(t))return!1;let r=t.value;return r==null||e&&n.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[t,...r]=e;if(r.length===0)return this.has(t);let i=this.get(t,!0);return n.isCollection(i)?i.hasIn(r):!1}setIn(e,t){let[r,...a]=e;if(a.length===0)this.set(r,t);else{let e=this.get(r,!0);if(n.isCollection(e))e.setIn(a,t);else if(e===void 0&&this.schema)this.set(r,i(this.schema,a,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${a}`)}}},e.collectionFromPath=i,e.isEmptyPath=a})),Gl=a((e=>{var t=e=>e.replace(/^(?!$)(?: $)?/gm,`#`);function n(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}e.indentComment=n,e.lineComment=(e,t,r)=>e.endsWith(`
3
3
  `)?n(r,t):r.includes(`
4
4
  `)?`
@@ -114,12 +114,12 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
114
114
  `)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
115
115
  `,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=l(c(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=l(c(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}}})),hue=a((e=>{var t=wu(),n=hu(),r=gu(),i=Jl(),a=Pl(),o=Du(),s=Ou();function c(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new o.LineCounter||null,prettyErrors:t}}function l(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=Array.from(l.compose(o.parse(e)));if(a&&i)for(let t of u)t.errors.forEach(r.prettifyError(e,i)),t.warnings.forEach(r.prettifyError(e,i));return u.length>0?u:Object.assign([],{empty:!0},l.streamInfo())}function u(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=null;for(let t of l.compose(o.parse(e),!0,e.length))if(!u)u=t;else if(u.options.logLevel!==`silent`){u.errors.push(new r.YAMLParseError(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return a&&i&&(u.errors.forEach(r.prettifyError(e,i)),u.warnings.forEach(r.prettifyError(e,i))),u}function d(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let a=u(e,n);if(!a)return null;if(a.warnings.forEach(e=>i.warn(a.options.logLevel,e)),a.errors.length>0){if(a.options.logLevel!==`silent`)throw a.errors[0];a.errors=[]}return a.toJS(Object.assign({reviver:r},n))}function f(e,t,r){let i=null;if(typeof t==`function`||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r==`string`&&(r=r.length),typeof r==`number`){let e=Math.round(r);r=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=r??t??{};if(!e)return}return a.isDocument(e)&&!i?e.toString(r):new n.Document(e,i,r).toString(r)}e.parse=d,e.parseAllDocuments=l,e.parseDocument=u,e.stringify=f})),ku=a((e=>{var t=wu(),n=hu(),r=mu(),i=gu(),a=Vl(),o=Pl(),s=Zl(),c=Hl(),l=$l(),u=tu(),d=Tu(),f=Eu(),p=Du(),m=Ou(),h=hue(),g=Fl();e.Composer=t.Composer,e.Document=n.Document,e.Schema=r.Schema,e.YAMLError=i.YAMLError,e.YAMLParseError=i.YAMLParseError,e.YAMLWarning=i.YAMLWarning,e.Alias=a.Alias,e.isAlias=o.isAlias,e.isCollection=o.isCollection,e.isDocument=o.isDocument,e.isMap=o.isMap,e.isNode=o.isNode,e.isPair=o.isPair,e.isScalar=o.isScalar,e.isSeq=o.isSeq,e.Pair=s.Pair,e.Scalar=c.Scalar,e.YAMLMap=l.YAMLMap,e.YAMLSeq=u.YAMLSeq,e.CST=d,e.Lexer=f.Lexer,e.LineCounter=p.LineCounter,e.Parser=m.Parser,e.parse=h.parse,e.parseAllDocuments=h.parseAllDocuments,e.parseDocument=h.parseDocument,e.stringify=h.stringify,e.visit=g.visit,e.visitAsync=g.visitAsync}));function Au(e){return typeof Bun<`u`?Bun.YAML.parse(e):ku().parse(e)}var ju=n((()=>{}));function gue(e){let t=e.split(`
116
116
  `),n=[];for(let e of t){let t=e.match(/^([a-zA-Z_-]+):\s+(.+)$/);if(t){let[,r,i]=t;if(!r||!i){n.push(e);continue}if(i.startsWith(`"`)&&i.endsWith(`"`)||i.startsWith(`'`)&&i.endsWith(`'`)){n.push(e);continue}if(zu.test(i)){let e=i.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`);n.push(`${r}: "${e}"`);continue}}n.push(e)}return n.join(`
117
- `)}function Mu(e,t){let n=e.match(Bu);if(!n)return{frontmatter:{},content:e};let r=n[1]||``,i=e.slice(n[0].length),a={};try{let e=Au(r);e&&typeof e==`object`&&!Array.isArray(e)&&(a=e)}catch{try{let e=Au(gue(r));e&&typeof e==`object`&&!Array.isArray(e)&&(a=e)}catch(e){K(`Failed to parse YAML frontmatter${t?` in ${t}`:``}: ${e instanceof Error?e.message:e}`,{level:`warn`})}}return{frontmatter:a,content:i}}function Nu(e){if(Array.isArray(e))return e.flatMap(Nu);if(typeof e!=`string`)return[];let t=[],n=``,r=0;for(let i=0;i<e.length;i++){let a=e[i];if(a===`{`)r++,n+=a;else if(a===`}`)r--,n+=a;else if(a===`,`&&r===0){let e=n.trim();e&&t.push(e),n=``}else n+=a}let i=n.trim();return i&&t.push(i),t.filter(e=>e.length>0).flatMap(e=>Pu(e))}function Pu(e){let t=e.match(/^([^{]*)\{([^}]+)\}(.*)$/);if(!t)return[e];let n=t[1]||``,r=t[2]||``,i=t[3]||``,a=r.split(`,`).map(e=>e.trim()),o=[];for(let e of a){let t=Pu(n+e+i);o.push(...t)}return o}function Fu(e){if(e==null)return;let t=typeof e==`number`?e:parseInt(String(e),10);if(Number.isInteger(t)&&t>0)return t}function Iu(e,t,n){return e==null?null:typeof e==`string`?e.trim()||null:typeof e==`number`||typeof e==`boolean`?String(e):(K(`Description invalid for ${n?`${n}:${t}`:t??`unknown`} - omitting`,{level:`warn`}),null)}function Lu(e){return e===!0||e===`true`}function Ru(e,t){if(e==null)return;let n=String(e).trim().toLowerCase();if(n!==``){if(Vu.includes(n))return n;K(`Frontmatter 'shell: ${e}' in ${t} is not recognized. Valid values: ${Vu.join(`, `)}. Falling back to bash.`,{level:`warn`})}}var zu,Bu,Vu,Hu=n((()=>{q(),ju(),zu=/[{}[\]*&#!|>%@`]|: /,Bu=/^---\s*\n([\s\S]*?)---\s*\n?/,Vu=[`bash`,`powershell`]}));function Uu(e){return lo()===`vertex`?Gu:e?.isNonInteractive?e.hasAppendSystemPrompt?Ku:qu:Gu}function _ue(){return!f(process.env.WORKMATE_ATTRIBUTION_HEADER)}function Wu(){if(!_ue())return``;let e=process.env.WORKMATE_ENTRYPOINT??`unknown`,t=Iie(),n=`x-anthropic-billing-header: cc_version=0.0.32; cc_entrypoint=${e};${t?` cc_workload=${t};`:``}`;return K(`attribution header ${n}`),n}var Gu,Ku,qu,Ju,Yu,Xu=n((()=>{q(),g(),mo(),uie(),Gu=`You are Work Mate, a CLI for Work Mate.`,Ku=`You are Work Mate, a CLI for Work Mate, running within the Work Mate Agent SDK.`,qu=`You are a Work Mate agent, built on the Work Mate Agent SDK.`,Ju=[Gu,Ku,qu],Yu=new Set(Ju)})),Zu,vue=n((()=>{Zu=e=>!1})),yue=a(((e,n)=>{var r=t(`child_process`),i=r.spawn,a=r.exec;n.exports=function(e,t,n){if(typeof t==`function`&&n===void 0&&(n=t,t=void 0),e=parseInt(e),Number.isNaN(e)){if(n)return n(Error(`pid must be a number`));throw Error(`pid must be a number`)}var r={},s={};switch(r[e]=[],s[e]=1,process.platform){case`win32`:a(`taskkill /pid `+e+` /T /F`,n);break;case`darwin`:c(e,r,s,function(e){return i(`pgrep`,[`-P`,e])},function(){o(r,t,n)});break;default:c(e,r,s,function(e){return i(`ps`,[`-o`,`pid`,`--no-headers`,`--ppid`,e])},function(){o(r,t,n)});break}};function o(e,t,n){var r={};try{Object.keys(e).forEach(function(n){e[n].forEach(function(e){r[e]||(s(e,t),r[e]=1)}),r[n]||(s(n,t),r[n]=1)})}catch(e){if(n)return n(e);throw e}if(n)return n()}function s(e,t){try{process.kill(parseInt(e,10),t)}catch(e){if(e.code!==`ESRCH`)throw e}}function c(e,t,n,r,i){var a=r(e),o=``;a.stdout.on(`data`,function(e){var e=e.toString(`ascii`);o+=e}),a.on(`close`,function(a){if(delete n[e],a!=0){Object.keys(n).length==0&&i();return}o.match(/\d+/g).forEach(function(a){a=parseInt(a,10),t[e].push(a),t[a]=[],n[a]=1,c(a,t,n,r,i)})})}}));function bue(e){if(typeof e==`string`)return Qu.find(t=>t===e)}var Qu,$u,ed,td,nd,rd,id,ad=n((()=>{Qu=[`user`,`feedback`,`project`,`reference`],$u=[`## Types of memory`,``,`<types>`,`<type>`,` <name>user</name>`,` <description>The user's role, goals, preferences, responsibilities, and knowledge. Use these to tailor your behavior to the user.</description>`,`</type>`,`<type>`,` <name>feedback</name>`,` <description>Guidance from the user about how to approach work — what to avoid and what to keep doing. Record from failure AND success. Include *why* so you can judge edge cases later. Structure content as: rule/fact, then **Why:** and **How to apply:** lines.</description>`,`</type>`,`<type>`,` <name>project</name>`,` <description>Information about ongoing work, goals, initiatives, bugs, or incidents not derivable from code or git history. Convert relative dates to absolute dates when saving (e.g., "Thursday" → "2026-03-05").</description>`,`</type>`,`<type>`,` <name>reference</name>`,` <description>Pointers to external systems where information can be found (e.g., Linear projects, Slack channels, Grafana dashboards).</description>`,`</type>`,`</types>`,``],ed=[`## What NOT to save in memory`,``,`- Code patterns, conventions, architecture, file paths, or project structure — these can be derived by reading the current project state.`,"- Git history, recent changes, or who-changed-what — `git log` / `git blame` are authoritative.",`- Debugging solutions or fix recipes — the fix is in the code; the commit message has the context.`,`- Anything already documented in AGENTS.md files.`,`- Ephemeral task details: in-progress work, temporary state, current conversation context.`,``,`These exclusions apply even when the user explicitly asks you to save. If they ask you to save a PR list or activity summary, ask what was *surprising* or *non-obvious* about it — that is the part worth keeping.`],td=`- Memory records can become stale over time. Use memory as context for what was true at a given point in time. Before answering the user or building assumptions based solely on information in memory records, verify that the memory is still correct and up-to-date by reading the current state of the files or resources. If a recalled memory conflicts with current information, trust what you observe now — and update or remove the stale memory rather than acting on it.`,nd=[`## When to access memories`,`- When memories seem relevant, or the user references prior-conversation work.`,`- You MUST access memory when the user explicitly asks you to check, recall, or remember.`,`- If the user says to *ignore* or *not use* memory: proceed as if MEMORY.md were empty. Do not apply remembered facts, cite, compare against, or mention memory content.`,td],rd=[`## Before recommending from memory`,``,`A memory that names a specific function, file, or flag is a claim that it existed *when the memory was written*. It may have been renamed, removed, or never merged. Before recommending it:`,``,`- If the memory names a file path: check the file exists.`,`- If the memory names a function or flag: grep for it.`,`- If the user is about to act on your recommendation (not just asking about history), verify first.`,``,`"The memory says X exists" is not the same as "X exists now."`,``,"A memory that summarizes repo state (activity logs, architecture snapshots) is frozen in time. If the user asks about *recent* or *current* state, prefer `git log` or reading the code over recalling the snapshot."],id=["```markdown",`---`,`name: {{memory name}}`,`description: {{one-line description — used to decide relevance in future conversations, so be specific}}`,`type: {{${Qu.join(`, `)}}}`,`---`,``,`{{memory content — for feedback/project types, structure as: rule/fact, then **Why:** and **How to apply:** lines}}`,"```"]}));function od(e){let t=e.trim(),n=t.split(`
117
+ `)}function Mu(e,t){let n=e.match(Bu);if(!n)return{frontmatter:{},content:e};let r=n[1]||``,i=e.slice(n[0].length),a={};try{let e=Au(r);e&&typeof e==`object`&&!Array.isArray(e)&&(a=e)}catch{try{let e=Au(gue(r));e&&typeof e==`object`&&!Array.isArray(e)&&(a=e)}catch(e){K(`Failed to parse YAML frontmatter${t?` in ${t}`:``}: ${e instanceof Error?e.message:e}`,{level:`warn`})}}return{frontmatter:a,content:i}}function Nu(e){if(Array.isArray(e))return e.flatMap(Nu);if(typeof e!=`string`)return[];let t=[],n=``,r=0;for(let i=0;i<e.length;i++){let a=e[i];if(a===`{`)r++,n+=a;else if(a===`}`)r--,n+=a;else if(a===`,`&&r===0){let e=n.trim();e&&t.push(e),n=``}else n+=a}let i=n.trim();return i&&t.push(i),t.filter(e=>e.length>0).flatMap(e=>Pu(e))}function Pu(e){let t=e.match(/^([^{]*)\{([^}]+)\}(.*)$/);if(!t)return[e];let n=t[1]||``,r=t[2]||``,i=t[3]||``,a=r.split(`,`).map(e=>e.trim()),o=[];for(let e of a){let t=Pu(n+e+i);o.push(...t)}return o}function Fu(e){if(e==null)return;let t=typeof e==`number`?e:parseInt(String(e),10);if(Number.isInteger(t)&&t>0)return t}function Iu(e,t,n){return e==null?null:typeof e==`string`?e.trim()||null:typeof e==`number`||typeof e==`boolean`?String(e):(K(`Description invalid for ${n?`${n}:${t}`:t??`unknown`} - omitting`,{level:`warn`}),null)}function Lu(e){return e===!0||e===`true`}function Ru(e,t){if(e==null)return;let n=String(e).trim().toLowerCase();if(n!==``){if(Vu.includes(n))return n;K(`Frontmatter 'shell: ${e}' in ${t} is not recognized. Valid values: ${Vu.join(`, `)}. Falling back to bash.`,{level:`warn`})}}var zu,Bu,Vu,Hu=n((()=>{q(),ju(),zu=/[{}[\]*&#!|>%@`]|: /,Bu=/^---\s*\n([\s\S]*?)---\s*\n?/,Vu=[`bash`,`powershell`]}));function Uu(e){return lo()===`vertex`?Gu:e?.isNonInteractive?e.hasAppendSystemPrompt?Ku:qu:Gu}function _ue(){return!f(process.env.WORKMATE_ATTRIBUTION_HEADER)}function Wu(){if(!_ue())return``;let e=process.env.WORKMATE_ENTRYPOINT??`unknown`,t=Iie(),n=`x-anthropic-billing-header: cc_version=0.0.33; cc_entrypoint=${e};${t?` cc_workload=${t};`:``}`;return K(`attribution header ${n}`),n}var Gu,Ku,qu,Ju,Yu,Xu=n((()=>{q(),g(),mo(),uie(),Gu=`You are Work Mate, a CLI for Work Mate.`,Ku=`You are Work Mate, a CLI for Work Mate, running within the Work Mate Agent SDK.`,qu=`You are a Work Mate agent, built on the Work Mate Agent SDK.`,Ju=[Gu,Ku,qu],Yu=new Set(Ju)})),Zu,vue=n((()=>{Zu=e=>!1})),yue=a(((e,n)=>{var r=t(`child_process`),i=r.spawn,a=r.exec;n.exports=function(e,t,n){if(typeof t==`function`&&n===void 0&&(n=t,t=void 0),e=parseInt(e),Number.isNaN(e)){if(n)return n(Error(`pid must be a number`));throw Error(`pid must be a number`)}var r={},s={};switch(r[e]=[],s[e]=1,process.platform){case`win32`:a(`taskkill /pid `+e+` /T /F`,n);break;case`darwin`:c(e,r,s,function(e){return i(`pgrep`,[`-P`,e])},function(){o(r,t,n)});break;default:c(e,r,s,function(e){return i(`ps`,[`-o`,`pid`,`--no-headers`,`--ppid`,e])},function(){o(r,t,n)});break}};function o(e,t,n){var r={};try{Object.keys(e).forEach(function(n){e[n].forEach(function(e){r[e]||(s(e,t),r[e]=1)}),r[n]||(s(n,t),r[n]=1)})}catch(e){if(n)return n(e);throw e}if(n)return n()}function s(e,t){try{process.kill(parseInt(e,10),t)}catch(e){if(e.code!==`ESRCH`)throw e}}function c(e,t,n,r,i){var a=r(e),o=``;a.stdout.on(`data`,function(e){var e=e.toString(`ascii`);o+=e}),a.on(`close`,function(a){if(delete n[e],a!=0){Object.keys(n).length==0&&i();return}o.match(/\d+/g).forEach(function(a){a=parseInt(a,10),t[e].push(a),t[a]=[],n[a]=1,c(a,t,n,r,i)})})}}));function bue(e){if(typeof e==`string`)return Qu.find(t=>t===e)}var Qu,$u,ed,td,nd,rd,id,ad=n((()=>{Qu=[`user`,`feedback`,`project`,`reference`],$u=[`## Types of memory`,``,`<types>`,`<type>`,` <name>user</name>`,` <description>The user's role, goals, preferences, responsibilities, and knowledge. Use these to tailor your behavior to the user.</description>`,`</type>`,`<type>`,` <name>feedback</name>`,` <description>Guidance from the user about how to approach work — what to avoid and what to keep doing. Record from failure AND success. Include *why* so you can judge edge cases later. Structure content as: rule/fact, then **Why:** and **How to apply:** lines.</description>`,`</type>`,`<type>`,` <name>project</name>`,` <description>Information about ongoing work, goals, initiatives, bugs, or incidents not derivable from code or git history. Convert relative dates to absolute dates when saving (e.g., "Thursday" → "2026-03-05").</description>`,`</type>`,`<type>`,` <name>reference</name>`,` <description>Pointers to external systems where information can be found (e.g., Linear projects, Slack channels, Grafana dashboards).</description>`,`</type>`,`</types>`,``],ed=[`## What NOT to save in memory`,``,`- Code patterns, conventions, architecture, file paths, or project structure — these can be derived by reading the current project state.`,"- Git history, recent changes, or who-changed-what — `git log` / `git blame` are authoritative.",`- Debugging solutions or fix recipes — the fix is in the code; the commit message has the context.`,`- Anything already documented in AGENTS.md files.`,`- Ephemeral task details: in-progress work, temporary state, current conversation context.`,``,`These exclusions apply even when the user explicitly asks you to save. If they ask you to save a PR list or activity summary, ask what was *surprising* or *non-obvious* about it — that is the part worth keeping.`],td=`- Memory records can become stale over time. Use memory as context for what was true at a given point in time. Before answering the user or building assumptions based solely on information in memory records, verify that the memory is still correct and up-to-date by reading the current state of the files or resources. If a recalled memory conflicts with current information, trust what you observe now — and update or remove the stale memory rather than acting on it.`,nd=[`## When to access memories`,`- When memories seem relevant, or the user references prior-conversation work.`,`- You MUST access memory when the user explicitly asks you to check, recall, or remember.`,`- If the user says to *ignore* or *not use* memory: proceed as if MEMORY.md were empty. Do not apply remembered facts, cite, compare against, or mention memory content.`,td],rd=[`## Before recommending from memory`,``,`A memory that names a specific function, file, or flag is a claim that it existed *when the memory was written*. It may have been renamed, removed, or never merged. Before recommending it:`,``,`- If the memory names a file path: check the file exists.`,`- If the memory names a function or flag: grep for it.`,`- If the user is about to act on your recommendation (not just asking about history), verify first.`,``,`"The memory says X exists" is not the same as "X exists now."`,``,"A memory that summarizes repo state (activity logs, architecture snapshots) is frozen in time. If the user asks about *recent* or *current* state, prefer `git log` or reading the code over recalling the snapshot."],id=["```markdown",`---`,`name: {{memory name}}`,`description: {{one-line description — used to decide relevance in future conversations, so be specific}}`,`type: {{${Qu.join(`, `)}}}`,`---`,``,`{{memory content — for feedback/project types, structure as: rule/fact, then **Why:** and **How to apply:** lines}}`,"```"]}));function od(e){let t=e.trim(),n=t.split(`
118
118
  `),r=n.length,i=t.length,a=r>200,o=i>fd;if(!a&&!o)return{content:t,lineCount:r,byteCount:i,wasLineTruncated:a,wasByteTruncated:o};let s=a?n.slice(0,200).join(`
119
119
  `):t;if(s.length>25e3){let e=s.lastIndexOf(`
120
120
  `,fd);s=s.slice(0,e>0?e:fd)}let c=o&&!a?`${Ka(i)} (limit: ${Ka(fd)}) — index entries are too long`:a&&!o?`${r} lines (limit: 200)`:`${r} lines and ${Ka(i)}`;return{content:s+`\n\n> WARNING: ${dd} is ${c}. Only part of it was loaded. Keep index entries to one line under ~200 chars; move detail into topic files.`,lineCount:r,byteCount:i,wasLineTruncated:a,wasByteTruncated:o}}async function sd(e){let t=J();try{await t.mkdir(e)}catch(t){K(`ensureMemoryDirExists failed for ${e}: ${(t instanceof Error&&`code`in t&&typeof t.code==`string`?t.code:void 0)??String(t)}`,{level:`debug`})}}function cd(e,t){J().readdir(e).then(e=>{let n=0,r=0;for(let t of e)t.isFile()?n++:t.isDirectory()&&r++;({...t})},()=>{})}function ld(e,t,n,r=!1){let i=r?[`## How to save memories`,``,"Write each memory to its own file (e.g., `user_role.md`, `feedback_testing.md`) using this frontmatter format:",``,...id,``,`- Keep the name, description, and type fields in memory files up-to-date with the content`,`- Organize memory semantically by topic, not chronologically`,`- Update or remove memories that turn out to be wrong or outdated`,`- Do not write duplicate memories. First check if there is an existing memory you can update before writing a new one.`]:[`## How to save memories`,``,`Saving a memory is a two-step process:`,``,"**Step 1** — write the memory to its own file (e.g., `user_role.md`, `feedback_testing.md`) using this frontmatter format:",``,...id,``,`**Step 2** — add a pointer to that file in \`${dd}\`. \`${dd}\` is an index, not a memory — each entry should be one line, under ~150 characters: \`- [Title](file.md) — one-line hook\`. It has no frontmatter. Never write memory content directly into \`${dd}\`.`,``,`- \`${dd}\` is always loaded into your conversation context — lines after 200 will be truncated, so keep the index concise`,`- Keep the name, description, and type fields in memory files up-to-date with the content`,`- Organize memory semantically by topic, not chronologically`,`- Update or remove memories that turn out to be wrong or outdated`,`- Do not write duplicate memories. First check if there is an existing memory you can update before writing a new one.`];return[`# ${e}`,``,`You have a persistent, file-based memory system at \`${t}\`. ${md}`,``,`You should build up this memory system over time so that future conversations can have a complete picture of who the user is, how they'd like to collaborate with you, what behaviors to avoid or repeat, and the context behind the work the user gives you.`,``,`If the user explicitly asks you to remember something, save it immediately as whichever type fits best. If they ask you to forget something, find and remove the relevant entry.`,``,...$u,...ed,``,...i,``,...nd,``,...rd,``,`## Memory and other forms of persistence`,`Memory is one of several persistence mechanisms available to you as you assist the user in a given conversation. The distinction is often that memory can be recalled in future conversations and should not be used for persisting information that is only useful within the scope of the current conversation.`,`- When to use or update a plan instead of memory: If you are about to start a non-trivial implementation task and would like to reach alignment with the user on your approach you should use a Plan rather than saving this information to memory. Similarly, if you already have a plan within the conversation and you have changed your approach persist that change by updating the plan rather than saving a memory.`,`- When to use or update tasks instead of memory: When you need to break your work in current conversation into discrete steps or keep track of your progress use tasks instead of saving to memory. Tasks are great for persisting information about the work that needs to be done in the current conversation, but memory should be reserved for information that will be useful in future conversations.`,``,...n??[],``]}function xue(e){let{displayName:t,memoryDir:n,extraGuidelines:r}=e,i=J(),a=n+dd,o=``;try{o=i.readFileSync(a,{encoding:`utf-8`})}catch{}let s=ld(t,n,r);if(o.trim()){let e=od(o),r=t===pd?`auto`:`agent`;cd(n,{content_length:e.byteCount,line_count:e.lineCount,was_truncated:e.wasLineTruncated,was_byte_truncated:e.wasByteTruncated,memory_type:r}),s.push(`## ${dd}`,``,e.content)}else s.push(`## ${dd}`,``,`Your ${dd} is currently empty. When you save new memories, they will appear here.`);return s.join(`
121
121
  `)}async function ud(){let e=Bi(),t=process.env.WORKMATE_COWORK_MEMORY_EXTRA_GUIDELINES,n=t&&t.trim().length>0?[t]:void 0;if(e){let e=Hi();return await sd(e),cd(e,{memory_type:`auto`}),ld(`auto memory`,e,n,!1).join(`
122
- `)}return h(process.env.WORKMATE_DISABLE_AUTO_MEMORY),!h(process.env.WORKMATE_DISABLE_AUTO_MEMORY)&&rr().autoMemoryEnabled,null}var dd,fd,pd,md,hd=n((()=>{ki(),zi(),La(),q(),g(),Ra(),Ln(),ad(),dd=`MEMORY.md`,fd=25e3,pd=`auto memory`,md=`This directory already exists — write to it directly with the Write tool (do not run mkdir or check for its existence).`}));function Sue(e){return e.replace(/:/g,`-`)}function gd(e){return process.env.WORKMATE_REMOTE_MEMORY_DIR?X(process.env.WORKMATE_REMOTE_MEMORY_DIR,`projects`,at(br(Hr())??Hr()),`agent-memory-local`,e)+bc:X(U(),`.workmate`,`agent-memory-local`,e)+bc}function _d(e,t){let n=Sue(e);switch(t){case`project`:return X(U(),`.workmate`,`agent-memory`,n)+bc;case`local`:return gd(n);case`user`:return X(Qi(),`agent-memory`,n)+bc}}function vd(e){let t=hc(e),n=Qi();if(t.startsWith(X(n,`agent-memory`)+bc)||t.startsWith(X(U(),`.workmate`,`agent-memory`)+bc))return!0;if(process.env.WORKMATE_REMOTE_MEMORY_DIR){if(t.includes(`${bc}agent-memory-local${bc}`)&&t.startsWith(X(process.env.WORKMATE_REMOTE_MEMORY_DIR,`projects`)+bc))return!0}else if(t.startsWith(X(U(),`.workmate`,`agent-memory-local`)+bc))return!0;return!1}function Cue(e){switch(e){case`user`:return`User (${X(Qi(),`agent-memory`)}/)`;case`project`:return`Project (.workmate/agent-memory/)`;case`local`:return`Local (${gd(`...`)})`;default:return`None`}}function yd(e,t){let n;switch(t){case`user`:n=`- Since this memory is user-scope, keep learnings general since they apply across all projects`;break;case`project`:n=`- Since this memory is project-scope and shared with your team via version control, tailor your memories to this project`;break;case`local`:n=`- Since this memory is local-scope (not checked into version control), tailor your memories to this project and machine`;break}let r=_d(e,t);sd(r);let i=process.env.WORKMATE_COWORK_MEMORY_EXTRA_GUIDELINES;return xue({displayName:`Persistent Agent Memory`,memoryDir:r,extraGuidelines:i&&i.trim().length>0?[n,i]:[n]})}var bd=n((()=>{H(),hd(),zi(),ui(),Et(),Wn()}));function xd(){let e=process.env.WORKMATE_ENVIRONMENT_KIND;return e===`byoc`||e===`anthropic_cloud`?e:null}var Sd=n((()=>{q()}));function wue(e){return Ic(4).readUInt32BE(0)%e}function Cd(e){return e[wue(e.length)]}function Tue(){return`${Cd(wd)}-${Cd(Ed)}-${Cd(Td)}`}var wd,Td,Ed,Eue=n((()=>{wd=`abundant.ancient.bright.calm.cheerful.clever.cozy.curious.dapper.dazzling.deep.delightful.eager.elegant.enchanted.fancy.fluffy.gentle.gleaming.golden.graceful.happy.hidden.humble.jolly.joyful.keen.kind.lively.lovely.lucky.luminous.magical.majestic.mellow.merry.mighty.misty.noble.peaceful.playful.polished.precious.proud.quiet.quirky.radiant.rosy.serene.shiny.silly.sleepy.smooth.snazzy.snug.snuggly.soft.sparkling.spicy.splendid.sprightly.starry.steady.sunny.swift.tender.tidy.toasty.tranquil.twinkly.valiant.vast.velvet.vivid.warm.whimsical.wild.wise.witty.wondrous.zany.zesty.zippy.breezy.bubbly.buzzing.cheeky.cosmic.cozy.crispy.crystalline.cuddly.drifting.dreamy.effervescent.ethereal.fizzy.flickering.floating.floofy.fluttering.foamy.frolicking.fuzzy.giggly.glimmering.glistening.glittery.glowing.goofy.groovy.harmonic.hazy.humming.iridescent.jaunty.jazzy.jiggly.melodic.moonlit.mossy.nifty.peppy.prancy.purrfect.purring.quizzical.rippling.rustling.shimmering.shimmying.snappy.snoopy.squishy.swirling.ticklish.tingly.twinkling.velvety.wiggly.wobbly.woolly.zazzy.abstract.adaptive.agile.async.atomic.binary.cached.compiled.composed.compressed.concurrent.cryptic.curried.declarative.delegated.distributed.dynamic.eager.elegant.encapsulated.enumerated.eventual.expressive.federated.functional.generic.greedy.hashed.idempotent.immutable.imperative.indexed.inherited.iterative.lazy.lexical.linear.linked.logical.memoized.modular.mutable.nested.optimized.parallel.parsed.partitioned.piped.polymorphic.pure.reactive.recursive.refactored.reflective.replicated.resilient.robust.scalable.sequential.serialized.sharded.sorted.staged.stateful.stateless.streamed.structured.synchronous.synthetic.temporal.transient.typed.unified.validated.vectorized.virtual`.split(`.`),Td=`aurora.avalanche.blossom.breeze.brook.bubble.canyon.cascade.cloud.clover.comet.coral.cosmos.creek.crescent.crystal.dawn.dewdrop.dusk.eclipse.ember.feather.fern.firefly.flame.flurry.fog.forest.frost.galaxy.garden.glacier.glade.grove.harbor.horizon.island.lagoon.lake.leaf.lightning.meadow.meteor.mist.moon.moonbeam.mountain.nebula.nova.ocean.orbit.pebble.petal.pine.planet.pond.puddle.quasar.rain.rainbow.reef.ripple.river.shore.sky.snowflake.spark.spring.star.stardust.starlight.storm.stream.summit.sun.sunbeam.sunrise.sunset.thunder.tide.twilight.valley.volcano.waterfall.wave.willow.wind.alpaca.axolotl.badger.bear.beaver.bee.bird.bumblebee.bunny.cat.chipmunk.crab.crane.deer.dolphin.dove.dragon.dragonfly.duckling.eagle.elephant.falcon.finch.flamingo.fox.frog.giraffe.goose.hamster.hare.hedgehog.hippo.hummingbird.jellyfish.kitten.koala.ladybug.lark.lemur.llama.lobster.lynx.manatee.meerkat.moth.narwhal.newt.octopus.otter.owl.panda.parrot.peacock.pelican.penguin.phoenix.piglet.platypus.pony.porcupine.puffin.puppy.quail.quokka.rabbit.raccoon.raven.robin.salamander.seahorse.seal.sloth.snail.sparrow.sphinx.squid.squirrel.starfish.swan.tiger.toucan.turtle.unicorn.walrus.whale.wolf.wombat.wren.yeti.zebra.acorn.anchor.balloon.beacon.biscuit.blanket.bonbon.book.boot.cake.candle.candy.castle.charm.clock.cocoa.cookie.crayon.crown.cupcake.donut.dream.fairy.fiddle.flask.flute.fountain.gadget.gem.gizmo.globe.goblet.hammock.harp.haven.hearth.honey.journal.kazoo.kettle.key.kite.lantern.lemon.lighthouse.locket.lollipop.mango.map.marble.marshmallow.melody.mitten.mochi.muffin.music.nest.noodle.oasis.origami.pancake.parasol.peach.pearl.pebble.pie.pillow.pinwheel.pixel.pizza.plum.popcorn.pretzel.prism.pudding.pumpkin.puzzle.quiche.quill.quilt.riddle.rocket.rose.scone.scroll.shell.sketch.snowglobe.sonnet.sparkle.spindle.sprout.sundae.swing.taco.teacup.teapot.thimble.toast.token.tome.tower.treasure.treehouse.trinket.truffle.tulip.umbrella.waffle.wand.whisper.whistle.widget.wreath.zephyr.abelson.adleman.aho.allen.babbage.bachman.backus.barto.bengio.bentley.blum.boole.brooks.catmull.cerf.cherny.church.clarke.cocke.codd.conway.cook.corbato.cray.curry.dahl.diffie.dijkstra.dongarra.eich.emerson.engelbart.feigenbaum.floyd.gosling.graham.gray.hamming.hanrahan.hartmanis.hejlsberg.hellman.hennessy.hickey.hinton.hoare.hollerith.hopcroft.hopper.iverson.kahan.kahn.karp.kay.kernighan.knuth.kurzweil.lamport.lampson.lecun.lerdorf.liskov.lovelace.matsumoto.mccarthy.metcalfe.micali.milner.minsky.moler.moore.naur.neumann.newell.nygaard.papert.parnas.pascal.patterson.pearl.perlis.pike.pnueli.rabin.reddy.ritchie.rivest.rossum.russell.scott.sedgewick.shamir.shannon.sifakis.simon.stallman.stearns.steele.stonebraker.stroustrup.sutherland.sutton.tarjan.thacker.thompson.torvalds.turing.ullman.valiant.wadler.wall.wigderson.wilkes.wilkinson.wirth.wozniak.yao`.split(`.`),Ed=`baking.beaming.booping.bouncing.brewing.bubbling.chasing.churning.coalescing.conjuring.cooking.crafting.crunching.cuddling.dancing.dazzling.discovering.doodling.dreaming.drifting.enchanting.exploring.finding.floating.fluttering.foraging.forging.frolicking.gathering.giggling.gliding.greeting.growing.hatching.herding.honking.hopping.hugging.humming.imagining.inventing.jingling.juggling.jumping.kindling.knitting.launching.leaping.mapping.marinating.meandering.mixing.moseying.munching.napping.nibbling.noodling.orbiting.painting.percolating.petting.plotting.pondering.popping.prancing.purring.puzzling.questing.riding.roaming.rolling.sauteeing.scribbling.seeking.shimmying.singing.skipping.sleeping.snacking.sniffing.snuggling.soaring.sparking.spinning.splashing.sprouting.squishing.stargazing.stirring.strolling.swimming.swinging.tickling.tinkering.toasting.tumbling.twirling.waddling.wandering.watching.weaving.whistling.wibbling.wiggling.wishing.wobbling.wondering.yawning.zooming`.split(`.`)}));function Dd(e){let t=e??Wr(),n=Pr().get(t);if(!n){let e=Pd();for(let t=0;t<Nd;t++){n=Tue();let t=X(e,`${n}.md`);if(!J().existsSync(t))break}Dr(t,n)}return n}function Od(e,t){Dr(e,t)}function Due(){Pr().clear()}function kd(e){let t=Dd(Wr());return e?X(Pd(),`${t}-agent-${e}.md`):X(Pd(),`${t}.md`)}function Ad(e){let t=kd(e);try{return J().readFileSync(t,{encoding:`utf-8`})}catch(e){return xi(e)||Y(e),null}}function jd(e){return e.messages.find(e=>e.slug)?.slug}async function Oue(e,t){let n=jd(e);if(!n)return!1;Od(t??Wr(),n);let r=X(Pd(),`${n}.md`);try{return await J().readFile(r,{encoding:`utf-8`}),!0}catch(t){if(!xi(t))return Y(t),!1;if(xd()===null)return!1;K(`Plan file missing during resume: ${r}. Attempting recovery.`);let n=jue(e.messages,`plan`),i=null;if(n&&n.content.length>0?(i=n.content,K(`Plan recovered from file snapshot, ${i.length} chars`,{level:`info`})):(i=Aue(e),i&&K(`Plan recovered from message history, ${i.length} chars`,{level:`info`})),i)try{return await Qc(r,i,{encoding:`utf-8`}),!0}catch(e){return Y(e),!1}return K(`Plan file recovery failed: no file snapshot or plan content found in message history`),!1}}async function kue(e,t){let n=jd(e);if(!n)return!1;let r=Pd(),i=X(r,`${n}.md`),a=X(r,`${Dd(t)}.md`);try{return await Bc(i,a),!0}catch(e){return xi(e)||Y(e),!1}}function Aue(e){for(let t=e.messages.length-1;t>=0;t--){let n=e.messages[t];if(n){if(n.type===`assistant`){let{content:e}=n.message;if(Array.isArray(e)){for(let t of e)if(t.type===`tool_use`&&t.name===`ExitPlanMode`){let e=t.input?.plan;if(typeof e==`string`&&e.length>0)return e}}}if(n.type===`user`){let e=n;if(typeof e.planContent==`string`&&e.planContent.length>0)return e.planContent}if(n.type===`attachment`){let e=n;if(e.attachment?.type===`plan_file_reference`){let t=e.attachment.planContent;if(typeof t==`string`&&t.length>0)return t}}}}return null}function jue(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];if(r?.type===`system`&&`subtype`in r&&r.subtype===`file_snapshot`&&`snapshotFiles`in r)return r.snapshotFiles.find(e=>e.key===t)}}async function Md(){if(xd()!==null)try{let e=[],t=Ad();if(t&&e.push({key:`plan`,path:kd(),content:t}),e.length===0)return;let n={type:`system`,subtype:`file_snapshot`,content:`File snapshot`,level:`info`,isMeta:!0,timestamp:new Date().toISOString(),uuid:Lc(),snapshotFiles:e},{recordTranscript:r}=await import(`./sessionStorage-Dr6JjGiG.js`);await r([n])}catch(e){Y(e)}}var Nd,Pd,Fd=n((()=>{d(),H(),Ds(),ui(),q(),g(),gi(),Sd(),ki(),wa(),Ln(),Eue(),Nd=10,Pd=u(function(){let e=rr().plansDirectory,t;if(e){let n=U(),r=yc(n,e);!r.startsWith(n+bc)&&r!==n?(Y(Error(`plansDirectory must be within project root: ${e}`)),t=X(m(),`plans`)):t=r}else t=X(m(),`plans`);try{J().mkdirSync(t)}catch(e){Y(e)}return t})})),Id,Mue=n((()=>{Id={type:`local-jsx`,name:`add-dir`,description:`添加新的工作目录`,argumentHint:`<path>`,load:()=>import(`./add-dir-CC99_pE2.js`)}})),Ld,Nue=n((()=>{Ld={type:`local-jsx`,name:`btw`,description:`快速问一个旁路问题,不打断主对话`,immediate:!0,argumentHint:`<question>`,load:()=>import(`./btw-y1tuqCvG.js`)}})),Rd,Pue=n((()=>{Rd={aliases:[`channels`],type:`local-jsx`,name:`channel`,description:`配置远程对话渠道(钉钉)`,load:()=>import(`./channel-D0MXuZ5p.js`)}})),zd,Fue=n((()=>{zd={type:`local`,name:`clear`,description:`清空对话历史并释放上下文`,aliases:[`reset`,`new`],supportsNonInteractive:!1,load:()=>import(`./clear-Dh0ZUTyq.js`)}})),Bd,Iue=n((()=>{g(),Bd={type:`local`,name:`compact`,description:`清空对话历史但保留摘要在上下文中。可选:/compact [摘要生成的指示]`,isEnabled:()=>!h(process.env.DISABLE_COMPACT),supportsNonInteractive:!0,argumentHint:`<optional custom summarization instructions>`,load:()=>import(`./compact-Drhb6hKF.js`)}})),Vd,Lue=n((()=>{Vd={aliases:[`settings`],type:`local-jsx`,name:`config`,description:`打开配置面板`,load:()=>import(`./config-DFScnxW_.js`)}})),Hd,Ud,Rue=n((()=>{H(),Hd={name:`context`,description:`以彩色网格可视化当前上下文占用`,isEnabled:()=>!kr(),type:`local-jsx`,load:()=>import(`./context-BsbQnZOh.js`)},Ud={type:`local`,name:`context`,supportsNonInteractive:!0,description:`显示当前上下文占用`,get isHidden(){return!kr()},isEnabled(){return kr()},load:()=>import(`./context-noninteractive-4Vn-NMDi.js`)}})),Wd,zue=n((()=>{Wd={type:`local-jsx`,name:`diff`,description:`查看未提交的改动以及每一轮的 diff`,load:()=>import(`./diff-DHn2Qup2.js`)}})),Gd,Bue=n((()=>{g(),Gd={name:`doctor`,description:`诊断并校验 Work Mate 的安装与设置`,isEnabled:()=>!h(process.env.DISABLE_DOCTOR_COMMAND),type:`local-jsx`,load:()=>import(`./doctor-DmJqkQqg.js`)}})),Kd,Vue=n((()=>{Kd={type:`local-jsx`,name:`memory`,description:`编辑 Work Mate 记忆文件`,load:()=>import(`./memory-CFvypHzK.js`)}})),qd,Hue=n((()=>{qd={type:`local-jsx`,name:`mode`,description:`切换交互模式(default、gentle、sharp、workhorse、token-saver、super-ai)`,isEnabled:()=>!0,argumentHint:`<mode-slug>`,load:()=>import(`./mode-CLmT-L6g.js`)}})),Jd,Uue=n((()=>{Jd={type:`local-jsx`,name:`help`,description:`显示帮助与可用命令`,load:()=>import(`./help-CYH2fCqh.js`)}}));function Wue(e,t){let n=Tse(e,t);return n===``||!n.startsWith(`..`)&&!wse(n)}function Gue(e,t){let n=Tc(e),r=Tc(t);if(!Wue(n,r))return[n];let i=[],a=r;for(;i.push(a),a!==n;){let e=Cse(a);if(e===a)break;a=e}return i.reverse()}async function Yd(e,t){try{let n=(await J().readFile(e,{encoding:`utf-8`})).trim();return n?{path:e,relativePath:Ote(Tse(t,e))||Sse(e),content:n}:null}catch{return null}}function Kue(e){return e.length===0?null:e.map(e=>`## ${e.relativePath}\n${e.content}`).join(`
122
+ `)}return h(process.env.WORKMATE_DISABLE_AUTO_MEMORY),!h(process.env.WORKMATE_DISABLE_AUTO_MEMORY)&&rr().autoMemoryEnabled,null}var dd,fd,pd,md,hd=n((()=>{ki(),zi(),La(),q(),g(),Ra(),Ln(),ad(),dd=`MEMORY.md`,fd=25e3,pd=`auto memory`,md=`This directory already exists — write to it directly with the Write tool (do not run mkdir or check for its existence).`}));function Sue(e){return e.replace(/:/g,`-`)}function gd(e){return process.env.WORKMATE_REMOTE_MEMORY_DIR?X(process.env.WORKMATE_REMOTE_MEMORY_DIR,`projects`,at(br(Hr())??Hr()),`agent-memory-local`,e)+bc:X(U(),`.workmate`,`agent-memory-local`,e)+bc}function _d(e,t){let n=Sue(e);switch(t){case`project`:return X(U(),`.workmate`,`agent-memory`,n)+bc;case`local`:return gd(n);case`user`:return X(Qi(),`agent-memory`,n)+bc}}function vd(e){let t=hc(e),n=Qi();if(t.startsWith(X(n,`agent-memory`)+bc)||t.startsWith(X(U(),`.workmate`,`agent-memory`)+bc))return!0;if(process.env.WORKMATE_REMOTE_MEMORY_DIR){if(t.includes(`${bc}agent-memory-local${bc}`)&&t.startsWith(X(process.env.WORKMATE_REMOTE_MEMORY_DIR,`projects`)+bc))return!0}else if(t.startsWith(X(U(),`.workmate`,`agent-memory-local`)+bc))return!0;return!1}function Cue(e){switch(e){case`user`:return`User (${X(Qi(),`agent-memory`)}/)`;case`project`:return`Project (.workmate/agent-memory/)`;case`local`:return`Local (${gd(`...`)})`;default:return`None`}}function yd(e,t){let n;switch(t){case`user`:n=`- Since this memory is user-scope, keep learnings general since they apply across all projects`;break;case`project`:n=`- Since this memory is project-scope and shared with your team via version control, tailor your memories to this project`;break;case`local`:n=`- Since this memory is local-scope (not checked into version control), tailor your memories to this project and machine`;break}let r=_d(e,t);sd(r);let i=process.env.WORKMATE_COWORK_MEMORY_EXTRA_GUIDELINES;return xue({displayName:`Persistent Agent Memory`,memoryDir:r,extraGuidelines:i&&i.trim().length>0?[n,i]:[n]})}var bd=n((()=>{H(),hd(),zi(),ui(),Et(),Wn()}));function xd(){let e=process.env.WORKMATE_ENVIRONMENT_KIND;return e===`byoc`||e===`anthropic_cloud`?e:null}var Sd=n((()=>{q()}));function wue(e){return Ic(4).readUInt32BE(0)%e}function Cd(e){return e[wue(e.length)]}function Tue(){return`${Cd(wd)}-${Cd(Ed)}-${Cd(Td)}`}var wd,Td,Ed,Eue=n((()=>{wd=`abundant.ancient.bright.calm.cheerful.clever.cozy.curious.dapper.dazzling.deep.delightful.eager.elegant.enchanted.fancy.fluffy.gentle.gleaming.golden.graceful.happy.hidden.humble.jolly.joyful.keen.kind.lively.lovely.lucky.luminous.magical.majestic.mellow.merry.mighty.misty.noble.peaceful.playful.polished.precious.proud.quiet.quirky.radiant.rosy.serene.shiny.silly.sleepy.smooth.snazzy.snug.snuggly.soft.sparkling.spicy.splendid.sprightly.starry.steady.sunny.swift.tender.tidy.toasty.tranquil.twinkly.valiant.vast.velvet.vivid.warm.whimsical.wild.wise.witty.wondrous.zany.zesty.zippy.breezy.bubbly.buzzing.cheeky.cosmic.cozy.crispy.crystalline.cuddly.drifting.dreamy.effervescent.ethereal.fizzy.flickering.floating.floofy.fluttering.foamy.frolicking.fuzzy.giggly.glimmering.glistening.glittery.glowing.goofy.groovy.harmonic.hazy.humming.iridescent.jaunty.jazzy.jiggly.melodic.moonlit.mossy.nifty.peppy.prancy.purrfect.purring.quizzical.rippling.rustling.shimmering.shimmying.snappy.snoopy.squishy.swirling.ticklish.tingly.twinkling.velvety.wiggly.wobbly.woolly.zazzy.abstract.adaptive.agile.async.atomic.binary.cached.compiled.composed.compressed.concurrent.cryptic.curried.declarative.delegated.distributed.dynamic.eager.elegant.encapsulated.enumerated.eventual.expressive.federated.functional.generic.greedy.hashed.idempotent.immutable.imperative.indexed.inherited.iterative.lazy.lexical.linear.linked.logical.memoized.modular.mutable.nested.optimized.parallel.parsed.partitioned.piped.polymorphic.pure.reactive.recursive.refactored.reflective.replicated.resilient.robust.scalable.sequential.serialized.sharded.sorted.staged.stateful.stateless.streamed.structured.synchronous.synthetic.temporal.transient.typed.unified.validated.vectorized.virtual`.split(`.`),Td=`aurora.avalanche.blossom.breeze.brook.bubble.canyon.cascade.cloud.clover.comet.coral.cosmos.creek.crescent.crystal.dawn.dewdrop.dusk.eclipse.ember.feather.fern.firefly.flame.flurry.fog.forest.frost.galaxy.garden.glacier.glade.grove.harbor.horizon.island.lagoon.lake.leaf.lightning.meadow.meteor.mist.moon.moonbeam.mountain.nebula.nova.ocean.orbit.pebble.petal.pine.planet.pond.puddle.quasar.rain.rainbow.reef.ripple.river.shore.sky.snowflake.spark.spring.star.stardust.starlight.storm.stream.summit.sun.sunbeam.sunrise.sunset.thunder.tide.twilight.valley.volcano.waterfall.wave.willow.wind.alpaca.axolotl.badger.bear.beaver.bee.bird.bumblebee.bunny.cat.chipmunk.crab.crane.deer.dolphin.dove.dragon.dragonfly.duckling.eagle.elephant.falcon.finch.flamingo.fox.frog.giraffe.goose.hamster.hare.hedgehog.hippo.hummingbird.jellyfish.kitten.koala.ladybug.lark.lemur.llama.lobster.lynx.manatee.meerkat.moth.narwhal.newt.octopus.otter.owl.panda.parrot.peacock.pelican.penguin.phoenix.piglet.platypus.pony.porcupine.puffin.puppy.quail.quokka.rabbit.raccoon.raven.robin.salamander.seahorse.seal.sloth.snail.sparrow.sphinx.squid.squirrel.starfish.swan.tiger.toucan.turtle.unicorn.walrus.whale.wolf.wombat.wren.yeti.zebra.acorn.anchor.balloon.beacon.biscuit.blanket.bonbon.book.boot.cake.candle.candy.castle.charm.clock.cocoa.cookie.crayon.crown.cupcake.donut.dream.fairy.fiddle.flask.flute.fountain.gadget.gem.gizmo.globe.goblet.hammock.harp.haven.hearth.honey.journal.kazoo.kettle.key.kite.lantern.lemon.lighthouse.locket.lollipop.mango.map.marble.marshmallow.melody.mitten.mochi.muffin.music.nest.noodle.oasis.origami.pancake.parasol.peach.pearl.pebble.pie.pillow.pinwheel.pixel.pizza.plum.popcorn.pretzel.prism.pudding.pumpkin.puzzle.quiche.quill.quilt.riddle.rocket.rose.scone.scroll.shell.sketch.snowglobe.sonnet.sparkle.spindle.sprout.sundae.swing.taco.teacup.teapot.thimble.toast.token.tome.tower.treasure.treehouse.trinket.truffle.tulip.umbrella.waffle.wand.whisper.whistle.widget.wreath.zephyr.abelson.adleman.aho.allen.babbage.bachman.backus.barto.bengio.bentley.blum.boole.brooks.catmull.cerf.cherny.church.clarke.cocke.codd.conway.cook.corbato.cray.curry.dahl.diffie.dijkstra.dongarra.eich.emerson.engelbart.feigenbaum.floyd.gosling.graham.gray.hamming.hanrahan.hartmanis.hejlsberg.hellman.hennessy.hickey.hinton.hoare.hollerith.hopcroft.hopper.iverson.kahan.kahn.karp.kay.kernighan.knuth.kurzweil.lamport.lampson.lecun.lerdorf.liskov.lovelace.matsumoto.mccarthy.metcalfe.micali.milner.minsky.moler.moore.naur.neumann.newell.nygaard.papert.parnas.pascal.patterson.pearl.perlis.pike.pnueli.rabin.reddy.ritchie.rivest.rossum.russell.scott.sedgewick.shamir.shannon.sifakis.simon.stallman.stearns.steele.stonebraker.stroustrup.sutherland.sutton.tarjan.thacker.thompson.torvalds.turing.ullman.valiant.wadler.wall.wigderson.wilkes.wilkinson.wirth.wozniak.yao`.split(`.`),Ed=`baking.beaming.booping.bouncing.brewing.bubbling.chasing.churning.coalescing.conjuring.cooking.crafting.crunching.cuddling.dancing.dazzling.discovering.doodling.dreaming.drifting.enchanting.exploring.finding.floating.fluttering.foraging.forging.frolicking.gathering.giggling.gliding.greeting.growing.hatching.herding.honking.hopping.hugging.humming.imagining.inventing.jingling.juggling.jumping.kindling.knitting.launching.leaping.mapping.marinating.meandering.mixing.moseying.munching.napping.nibbling.noodling.orbiting.painting.percolating.petting.plotting.pondering.popping.prancing.purring.puzzling.questing.riding.roaming.rolling.sauteeing.scribbling.seeking.shimmying.singing.skipping.sleeping.snacking.sniffing.snuggling.soaring.sparking.spinning.splashing.sprouting.squishing.stargazing.stirring.strolling.swimming.swinging.tickling.tinkering.toasting.tumbling.twirling.waddling.wandering.watching.weaving.whistling.wibbling.wiggling.wishing.wobbling.wondering.yawning.zooming`.split(`.`)}));function Dd(e){let t=e??Wr(),n=Pr().get(t);if(!n){let e=Pd();for(let t=0;t<Nd;t++){n=Tue();let t=X(e,`${n}.md`);if(!J().existsSync(t))break}Dr(t,n)}return n}function Od(e,t){Dr(e,t)}function Due(){Pr().clear()}function kd(e){let t=Dd(Wr());return e?X(Pd(),`${t}-agent-${e}.md`):X(Pd(),`${t}.md`)}function Ad(e){let t=kd(e);try{return J().readFileSync(t,{encoding:`utf-8`})}catch(e){return xi(e)||Y(e),null}}function jd(e){return e.messages.find(e=>e.slug)?.slug}async function Oue(e,t){let n=jd(e);if(!n)return!1;Od(t??Wr(),n);let r=X(Pd(),`${n}.md`);try{return await J().readFile(r,{encoding:`utf-8`}),!0}catch(t){if(!xi(t))return Y(t),!1;if(xd()===null)return!1;K(`Plan file missing during resume: ${r}. Attempting recovery.`);let n=jue(e.messages,`plan`),i=null;if(n&&n.content.length>0?(i=n.content,K(`Plan recovered from file snapshot, ${i.length} chars`,{level:`info`})):(i=Aue(e),i&&K(`Plan recovered from message history, ${i.length} chars`,{level:`info`})),i)try{return await Qc(r,i,{encoding:`utf-8`}),!0}catch(e){return Y(e),!1}return K(`Plan file recovery failed: no file snapshot or plan content found in message history`),!1}}async function kue(e,t){let n=jd(e);if(!n)return!1;let r=Pd(),i=X(r,`${n}.md`),a=X(r,`${Dd(t)}.md`);try{return await Bc(i,a),!0}catch(e){return xi(e)||Y(e),!1}}function Aue(e){for(let t=e.messages.length-1;t>=0;t--){let n=e.messages[t];if(n){if(n.type===`assistant`){let{content:e}=n.message;if(Array.isArray(e)){for(let t of e)if(t.type===`tool_use`&&t.name===`ExitPlanMode`){let e=t.input?.plan;if(typeof e==`string`&&e.length>0)return e}}}if(n.type===`user`){let e=n;if(typeof e.planContent==`string`&&e.planContent.length>0)return e.planContent}if(n.type===`attachment`){let e=n;if(e.attachment?.type===`plan_file_reference`){let t=e.attachment.planContent;if(typeof t==`string`&&t.length>0)return t}}}}return null}function jue(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];if(r?.type===`system`&&`subtype`in r&&r.subtype===`file_snapshot`&&`snapshotFiles`in r)return r.snapshotFiles.find(e=>e.key===t)}}async function Md(){if(xd()!==null)try{let e=[],t=Ad();if(t&&e.push({key:`plan`,path:kd(),content:t}),e.length===0)return;let n={type:`system`,subtype:`file_snapshot`,content:`File snapshot`,level:`info`,isMeta:!0,timestamp:new Date().toISOString(),uuid:Lc(),snapshotFiles:e},{recordTranscript:r}=await import(`./sessionStorage-DHZbnPR_.js`);await r([n])}catch(e){Y(e)}}var Nd,Pd,Fd=n((()=>{d(),H(),Ds(),ui(),q(),g(),gi(),Sd(),ki(),wa(),Ln(),Eue(),Nd=10,Pd=u(function(){let e=rr().plansDirectory,t;if(e){let n=U(),r=yc(n,e);!r.startsWith(n+bc)&&r!==n?(Y(Error(`plansDirectory must be within project root: ${e}`)),t=X(m(),`plans`)):t=r}else t=X(m(),`plans`);try{J().mkdirSync(t)}catch(e){Y(e)}return t})})),Id,Mue=n((()=>{Id={type:`local-jsx`,name:`add-dir`,description:`添加新的工作目录`,argumentHint:`<path>`,load:()=>import(`./add-dir-CnlSkl-b.js`)}})),Ld,Nue=n((()=>{Ld={type:`local-jsx`,name:`btw`,description:`快速问一个旁路问题,不打断主对话`,immediate:!0,argumentHint:`<question>`,load:()=>import(`./btw-CAeVTHuf.js`)}})),Rd,Pue=n((()=>{Rd={aliases:[`channels`],type:`local-jsx`,name:`channel`,description:`配置远程对话渠道(钉钉)`,load:()=>import(`./channel-C4416TRT.js`)}})),zd,Fue=n((()=>{zd={type:`local`,name:`clear`,description:`清空对话历史并释放上下文`,aliases:[`reset`,`new`],supportsNonInteractive:!1,load:()=>import(`./clear-DhNKs3lV.js`)}})),Bd,Iue=n((()=>{g(),Bd={type:`local`,name:`compact`,description:`清空对话历史但保留摘要在上下文中。可选:/compact [摘要生成的指示]`,isEnabled:()=>!h(process.env.DISABLE_COMPACT),supportsNonInteractive:!0,argumentHint:`<optional custom summarization instructions>`,load:()=>import(`./compact-CAig9gJw.js`)}})),Vd,Lue=n((()=>{Vd={aliases:[`settings`],type:`local-jsx`,name:`config`,description:`打开配置面板`,load:()=>import(`./config-C-sRwFEr.js`)}})),Hd,Ud,Rue=n((()=>{H(),Hd={name:`context`,description:`以彩色网格可视化当前上下文占用`,isEnabled:()=>!kr(),type:`local-jsx`,load:()=>import(`./context-BIFpient.js`)},Ud={type:`local`,name:`context`,supportsNonInteractive:!0,description:`显示当前上下文占用`,get isHidden(){return!kr()},isEnabled(){return kr()},load:()=>import(`./context-noninteractive-DotqNWvl.js`)}})),Wd,zue=n((()=>{Wd={type:`local-jsx`,name:`diff`,description:`查看未提交的改动以及每一轮的 diff`,load:()=>import(`./diff-BjodqyQk.js`)}})),Gd,Bue=n((()=>{g(),Gd={name:`doctor`,description:`诊断并校验 Work Mate 的安装与设置`,isEnabled:()=>!h(process.env.DISABLE_DOCTOR_COMMAND),type:`local-jsx`,load:()=>import(`./doctor-BiaE1VxH.js`)}})),Kd,Vue=n((()=>{Kd={type:`local-jsx`,name:`memory`,description:`编辑 Work Mate 记忆文件`,load:()=>import(`./memory-DxSaWDW2.js`)}})),qd,Hue=n((()=>{qd={type:`local-jsx`,name:`mode`,description:`切换交互模式(default、gentle、sharp、workhorse、token-saver、super-ai)`,isEnabled:()=>!0,argumentHint:`<mode-slug>`,load:()=>import(`./mode-DD9Fvft0.js`)}})),Jd,Uue=n((()=>{Jd={type:`local-jsx`,name:`help`,description:`显示帮助与可用命令`,load:()=>import(`./help-nCNtESeM.js`)}}));function Wue(e,t){let n=Tse(e,t);return n===``||!n.startsWith(`..`)&&!wse(n)}function Gue(e,t){let n=Tc(e),r=Tc(t);if(!Wue(n,r))return[n];let i=[],a=r;for(;i.push(a),a!==n;){let e=Cse(a);if(e===a)break;a=e}return i.reverse()}async function Yd(e,t){try{let n=(await J().readFile(e,{encoding:`utf-8`})).trim();return n?{path:e,relativePath:Ote(Tse(t,e))||Sse(e),content:n}:null}catch{return null}}function Kue(e){return e.length===0?null:e.map(e=>`## ${e.relativePath}\n${e.content}`).join(`
123
123
 
124
124
  `)}function que(e){let t=e.slice(),n=null,r=0;for(let e=0;e<t.length;e++){let i=t[e].trim(),a=i.match(/^([`~])\1{2,}/);if(a){let o=a[1],s=a[0].length,c=i.slice(s);n===null?(n=o,r=s):n===o&&s>=r&&c.trim()===``&&(n=null,r=0),t[e]=``;continue}n!==null&&(t[e]=``)}return t}function Jue(e){let t=[],n=que(e.split(`
125
125
  `)),r=e=>e.length-e.trimStart().length,i=(e,t)=>e.replace(t,``).trim().replace(/^["']|["']$/g,``);function a(e,t){let a=[],o=e;for(;o<n.length;){let e=n[o],s=e.trim(),c=r(e);if(!s){o+=1;continue}if(c<=t)break;if(!s.startsWith(`- name:`)){o+=1;continue}let l=c,u=i(s,`- name:`),d=``,f;for(o+=1;o<n.length;){let e=n[o],t=e.trim(),a=r(e);if(!t){o+=1;continue}if(a<=l)break;t.startsWith(`prompt:`)?d=i(t,`prompt:`):t.startsWith(`wait_for:`)&&(f=i(t,`wait_for:`)),o+=1}u&&d&&a.push({name:u,prompt:d,...f?{waitFor:f}:{}})}return{steps:a,nextIndex:o}}let o=n.findIndex(e=>e.trim()===`tasks:`);if(o===-1)return t;let s=r(n[o]),c=o+1;for(;c<n.length;){let e=n[c],o=e.trim(),l=r(e);if(!o){c+=1;continue}if(l<=s)break;if(!o.startsWith(`- name:`)){c+=1;continue}let u=l,d=i(o,`- name:`),f=``,p=``,m=[];for(c+=1;c<n.length;){let e=n[c],t=e.trim(),o=r(e);if(!t){c+=1;continue}if(o<=s||o===u&&t.startsWith(`- name:`)||o<=u)break;if(t.startsWith(`interval:`)){f=i(t,`interval:`),c+=1;continue}if(t.startsWith(`prompt:`)){p=i(t,`prompt:`),c+=1;continue}if(t===`steps:`){let e=a(c+1,o);m=e.steps,c=e.nextIndex;continue}c+=1}d&&f&&p&&t.push({name:d,interval:f,prompt:p,steps:m})}return t}function Yue(e){let t=e.trim().match(/^(\d+)\s*(ms|s|m|h|d)?$/i);if(!t)return null;let n=Number.parseInt(t[1],10);switch((t[2]??`m`).toLowerCase()){case`ms`:return n;case`s`:return n*1e3;case`m`:return n*6e4;case`h`:return n*60*6e4;case`d`:return n*24*60*6e4;default:return null}}function Xd(e,t){return`${e}::${t.name}::${t.interval}::${t.prompt}`}function Xue(e,t){let n=[];for(let r of e.heartbeatTasks){let i=Yue(r.interval);if(i==null)continue;let a=Xd(e.rootDir,r),o=af.get(a);o!==void 0&&t-o<i||n.push(r)}return n}function Zue(e,t,n){for(let r of t)af.set(Xd(e.rootDir,r),n)}async function Que(e={}){let t=Tc(e.rootDir??Hr()),n=Tc(e.currentDir??U()),r=Gue(t,n),[i,a]=await Promise.all([Promise.all(r.map(async e=>Yd(wc(e,$d,tf),t))),Yd(wc(t,$d,nf),t)]),o=i.filter(e=>e!==null);return{rootDir:t,currentDir:n,agentsFiles:o,agentsContent:Kue(o),heartbeatFile:a,heartbeatContent:a?.content??null,heartbeatTasks:a?Jue(a.content):[]}}async function $ue(e){let t=await Zd(e);return Qd(t),t.prompt}async function Zd(e){let t=await Que({rootDir:e.rootDir,currentDir:e.currentDir}),n=e.nowMs??Date.now(),r=e.trigger===`proactive-tick`?Xue(t,n):[],i=r.filter(e=>e.steps.length===0),a=[];if(t.agentsContent&&a.push(`Workspace authority from ${tf}:\n${t.agentsContent}`),t.heartbeatContent&&a.push(`Workspace heartbeat guidance from ${nf}:\n${t.heartbeatContent}`),i.length>0&&a.push([`Due ${nf} tasks:`,...i.map(e=>`- ${e.name} (${e.interval}): ${e.prompt}`)].join(`
@@ -386,9 +386,9 @@ After writing the skill file(s), inform the user:
386
386
  3. That they can edit the skills to customize them
387
387
  4. That they can run /init-verifiers again to add more verifiers for other areas
388
388
  5. That the verifier will offer to self-update if it detects its own instructions are outdated (wrong dev server command, changed ready signal, etc.)
389
- `}]}}})),uf,nde=n((()=>{uoe(),uf={name:`keybindings`,description:`打开或创建你的 keybindings 配置文件`,isEnabled:()=>foe(),supportsNonInteractive:!1,type:`local`,load:()=>import(`./keybindings-CkiE_uBG.js`)}})),df,rde=n((()=>{df={type:`local-jsx`,name:`mcp`,description:`管理 MCP 服务器`,immediate:!0,argumentHint:`[enable|disable [server-name]]`,load:()=>import(`./mcp-BQubBUXS.js`)}})),ff,ide=n((()=>{ff={type:`local-jsx`,name:`onboarding`,description:`重新运行首次启动的初始化(主题、信任、模型、MCP)`,argumentHint:`[full|theme|trust|model|mcp|status]`,isEnabled:()=>!0,isHidden:!1,load:async()=>({call:(await import(`./launchOnboarding-Km72c-fV.js`)).callOnboarding})}})),pf,ade=n((()=>{pf={type:`local-jsx`,name:`rename`,description:`重命名当前会话`,immediate:!0,argumentHint:`[name]`,load:()=>import(`./rename-D3rmIsGf.js`)}})),mf,ode=n((()=>{mf={type:`local-jsx`,name:`resume`,description:`恢复之前的会话`,aliases:[`continue`],argumentHint:`[conversation id or search term]`,load:()=>import(`./resume-Cj_JBDJU.js`)}})),hf,sde=n((()=>{hf={type:`local-jsx`,name:`skills`,description:`列出可用的 skill`,load:()=>import(`./skills-C69Im5ML.js`)}})),gf,cde=n((()=>{gf={type:`local-jsx`,name:`status`,description:`显示 Work Mate 的状态,包括版本、模型、账号、API 连通性与工具状态`,immediate:!0,load:()=>import(`./status-D2nNF67-.js`)}})),_f,lde=n((()=>{_f={type:`local-jsx`,name:`tasks`,aliases:[`bashes`],description:`列出并管理后台任务`,load:()=>import(`./tasks-CJDAZERm.js`)}})),vf,ude=n((()=>{vf={type:`local-jsx`,name:`local-memory`,aliases:[`lm`],description:`管理本地记忆存储,用于笔记和上下文。存放在 ~/.workmate/local-memory/——无需 API key`,argumentHint:`list | create STORE | store STORE KEY VALUE | fetch STORE KEY | entries STORE | archive STORE`,isHidden:!1,isEnabled:()=>!0,load:async()=>({call:(await import(`./launchLocalMemory-ClOCP1QH.js`)).callLocalMemory})}})),yf,dde=n((()=>{nn(),yf={type:`local-jsx`,name:`terminal-setup`,description:Jn.terminal===`Apple_Terminal`?`启用 Option+Enter 换行键绑定和视觉响铃`:`安装 Shift+Enter 换行键绑定`,isHidden:Jn.terminal!==null&&Jn.terminal in{ghostty:`Ghostty`,kitty:`Kitty`,"iTerm.app":`iTerm2`,WezTerm:`WezTerm`},load:()=>import(`./terminalSetup-QvvwfSGV.js`)}})),bf,fde=n((()=>{bf={type:`local-jsx`,name:`theme`,description:`切换主题`,load:()=>import(`./theme-B3baZuK8.js`)}})),xf,pde=n((()=>{xf={name:`vim`,description:`在 Vim 与普通编辑模式之间切换`,supportsNonInteractive:!1,type:`local`,load:()=>import(`./vim-BX8ljWbJ.js`)}})),Sf=i({activateProactive:()=>Tf,deactivateProactive:()=>Ef,getActivationSource:()=>mde,getNextTickAt:()=>Nf,isContextBlocked:()=>jf,isProactiveActive:()=>wf,isProactivePaused:()=>Df,pauseProactive:()=>Of,resumeProactive:()=>kf,setContextBlocked:()=>Af,setNextTickAt:()=>Mf,shouldTick:()=>Ff,subscribeToProactiveChanges:()=>Pf});function Cf(){for(let e of Vf)try{e()}catch{}}function wf(){return If}function Tf(e){If||(If=!0,Lf=!1,Rf=!1,Bf=e,Cf())}function Ef(){If&&(If=!1,Lf=!1,Rf=!1,zf=null,Bf=void 0,Cf())}function Df(){return Lf}function Of(){!If||Lf||(Lf=!0,zf=null,Cf())}function kf(){!If||!Lf||(Lf=!1,Cf())}function Af(e){Rf!==e&&(Rf=e,e&&(zf=null),Cf())}function jf(){return Rf}function Mf(e){zf=e,Cf()}function Nf(){return!If||Lf||Rf?null:zf}function mde(){return Bf}function Pf(e){return Vf.add(e),()=>{Vf.delete(e)}}function Ff(){return If&&!Lf&&!Rf}var If,Lf,Rf,zf,Bf,Vf,Hf=n((()=>{If=!1,Lf=!1,Rf=!1,zf=null,Vf=new Set})),Uf,hde=n((()=>{Uf={type:`local-jsx`,name:`proactive`,description:`切换主动(autonomous)模式`,isEnabled:()=>!0,immediate:!0,load:()=>Promise.resolve({async call(t,n){let r=(Hf(),e(Sf));return r.isProactiveActive()?(r.deactivateProactive(),t(`Proactive mode disabled`,{display:`system`})):(r.activateProactive(`slash_command`),t(`Proactive mode enabled — model will work autonomously between ticks`,{display:`system`,metaMessages:[`<system-reminder>
389
+ `}]}}})),uf,nde=n((()=>{uoe(),uf={name:`keybindings`,description:`打开或创建你的 keybindings 配置文件`,isEnabled:()=>foe(),supportsNonInteractive:!1,type:`local`,load:()=>import(`./keybindings-CkiE_uBG.js`)}})),df,rde=n((()=>{df={type:`local-jsx`,name:`mcp`,description:`管理 MCP 服务器`,immediate:!0,argumentHint:`[enable|disable [server-name]]`,load:()=>import(`./mcp-Bcb9Ge46.js`)}})),ff,ide=n((()=>{ff={type:`local-jsx`,name:`onboarding`,description:`重新运行首次启动的初始化(主题、信任、模型、MCP)`,argumentHint:`[full|theme|trust|model|mcp|status]`,isEnabled:()=>!0,isHidden:!1,load:async()=>({call:(await import(`./launchOnboarding-CQ3PM2PE.js`)).callOnboarding})}})),pf,ade=n((()=>{pf={type:`local-jsx`,name:`rename`,description:`重命名当前会话`,immediate:!0,argumentHint:`[name]`,load:()=>import(`./rename-QhD0arLJ.js`)}})),mf,ode=n((()=>{mf={type:`local-jsx`,name:`resume`,description:`恢复之前的会话`,aliases:[`continue`],argumentHint:`[conversation id or search term]`,load:()=>import(`./resume-DU7l4Z27.js`)}})),hf,sde=n((()=>{hf={type:`local-jsx`,name:`skills`,description:`列出可用的 skill`,load:()=>import(`./skills-CEup8xDF.js`)}})),gf,cde=n((()=>{gf={type:`local-jsx`,name:`status`,description:`显示 Work Mate 的状态,包括版本、模型、账号、API 连通性与工具状态`,immediate:!0,load:()=>import(`./status-Mc56SVQw.js`)}})),_f,lde=n((()=>{_f={type:`local-jsx`,name:`tasks`,aliases:[`bashes`],description:`列出并管理后台任务`,load:()=>import(`./tasks-sh5zjbfY.js`)}})),vf,ude=n((()=>{vf={type:`local-jsx`,name:`local-memory`,aliases:[`lm`],description:`管理本地记忆存储,用于笔记和上下文。存放在 ~/.workmate/local-memory/——无需 API key`,argumentHint:`list | create STORE | store STORE KEY VALUE | fetch STORE KEY | entries STORE | archive STORE`,isHidden:!1,isEnabled:()=>!0,load:async()=>({call:(await import(`./launchLocalMemory-Cpd1IKqK.js`)).callLocalMemory})}})),yf,dde=n((()=>{nn(),yf={type:`local-jsx`,name:`terminal-setup`,description:Jn.terminal===`Apple_Terminal`?`启用 Option+Enter 换行键绑定和视觉响铃`:`安装 Shift+Enter 换行键绑定`,isHidden:Jn.terminal!==null&&Jn.terminal in{ghostty:`Ghostty`,kitty:`Kitty`,"iTerm.app":`iTerm2`,WezTerm:`WezTerm`},load:()=>import(`./terminalSetup-QvvwfSGV.js`)}})),bf,fde=n((()=>{bf={type:`local-jsx`,name:`theme`,description:`切换主题`,load:()=>import(`./theme-ILQQU3Mx.js`)}})),xf,pde=n((()=>{xf={name:`vim`,description:`在 Vim 与普通编辑模式之间切换`,supportsNonInteractive:!1,type:`local`,load:()=>import(`./vim-BX8ljWbJ.js`)}})),Sf=i({activateProactive:()=>Tf,deactivateProactive:()=>Ef,getActivationSource:()=>mde,getNextTickAt:()=>Nf,isContextBlocked:()=>jf,isProactiveActive:()=>wf,isProactivePaused:()=>Df,pauseProactive:()=>Of,resumeProactive:()=>kf,setContextBlocked:()=>Af,setNextTickAt:()=>Mf,shouldTick:()=>Ff,subscribeToProactiveChanges:()=>Pf});function Cf(){for(let e of Vf)try{e()}catch{}}function wf(){return If}function Tf(e){If||(If=!0,Lf=!1,Rf=!1,Bf=e,Cf())}function Ef(){If&&(If=!1,Lf=!1,Rf=!1,zf=null,Bf=void 0,Cf())}function Df(){return Lf}function Of(){!If||Lf||(Lf=!0,zf=null,Cf())}function kf(){!If||!Lf||(Lf=!1,Cf())}function Af(e){Rf!==e&&(Rf=e,e&&(zf=null),Cf())}function jf(){return Rf}function Mf(e){zf=e,Cf()}function Nf(){return!If||Lf||Rf?null:zf}function mde(){return Bf}function Pf(e){return Vf.add(e),()=>{Vf.delete(e)}}function Ff(){return If&&!Lf&&!Rf}var If,Lf,Rf,zf,Bf,Vf,Hf=n((()=>{If=!1,Lf=!1,Rf=!1,zf=null,Vf=new Set})),Uf,hde=n((()=>{Uf={type:`local-jsx`,name:`proactive`,description:`切换主动(autonomous)模式`,isEnabled:()=>!0,immediate:!0,load:()=>Promise.resolve({async call(t,n){let r=(Hf(),e(Sf));return r.isProactiveActive()?(r.deactivateProactive(),t(`Proactive mode disabled`,{display:`system`})):(r.activateProactive(`slash_command`),t(`Proactive mode enabled — model will work autonomously between ticks`,{display:`system`,metaMessages:[`<system-reminder>
390
390
  Proactive mode is now enabled. You will receive periodic <tick> prompts. Do useful work on each tick, or call Sleep if there is nothing to do. Do not output "still waiting" — either act or sleep.
391
- </system-reminder>`]})),null}})}})),Wf,gde=n((()=>{Wf={type:`local-jsx`,name:`job`,description:`管理模板作业(job)`,argumentHint:`[list|new|reply|status]`,isEnabled:()=>!0,load:()=>import(`./job-B38MURYt.js`)}})),Gf,_de=n((()=>{Gf={type:`local-jsx`,name:`goal`,description:`设置或查看一个持久化 goal,用于驱动跨轮次的自动续作`,argumentHint:`[<objective> | status | clear | pause | resume | complete]`,load:()=>import(`./goal-DOF3kWop.js`)}})),Kf,vde=n((()=>{Kf={type:`local-jsx`,name:`permissions`,aliases:[`allowed-tools`],description:`管理允许 / 拒绝的工具权限规则`,load:()=>import(`./permissions-RfHevyA2.js`)}})),qf,yde=n((()=>{qf={type:`local-jsx`,name:`plan`,description:`启用 plan 模式或查看当前会话的 plan`,argumentHint:`[open|<description>]`,load:()=>import(`./plan-CWfN8okc.js`)}}));function Jf(){return!h(process.env.WORKMATE_DISABLE_FAST_MODE)}function Yf(){return Jf()?Xf()===null:!1}function Xf(){if(!Jf())return`Fast mode is not available`;if(Na(),kr()&&Qte()&&!$n(`flagSettings`)?.fastMode){let e=`Fast mode is not available in the Agent SDK`;return K(`Fast mode unavailable: ${e}`),e}if(lo()!==`firstParty`){let e=`Fast mode is not available on Bedrock, Vertex, or Foundry`;return K(`Fast mode unavailable: ${e}`),e}return null}function bde(){return`opus${Nie()?`[1m]`:``}`}function xde(e){if(!Jf()||!Yf()||!Zf(e))return!1;let t=rr();return!t.fastModePerSessionOptIn&&t.fastMode===!0}function Zf(e){if(!Jf())return!1;let t=Vo(e??Do());return t.toLowerCase().includes(`opus-4-7`)||t.toLowerCase().includes(`opus-4-6`)}function Qf(){return tp.status===`cooldown`&&Date.now()>=tp.resetAt&&(Jf()&&!np&&(K(`Fast mode cooldown expired, re-enabling fast mode`),np=!0,ip.emit()),tp={status:`active`}),tp}function Sde(e,t){if(!Jf())return;tp={status:`cooldown`,resetAt:e,reason:t},np=!1;let n=e-Date.now();K(`Fast mode cooldown triggered (${t}), duration ${Math.round(n/1e3)}s`),rp.emit(e,t)}function Cde(){tp={status:`active`}}function wde(e){switch(e){case`out_of_credits`:return`Fast mode disabled · extra usage credits exhausted`;case`org_level_disabled`:case`org_service_level_disabled`:return`Fast mode disabled · extra usage disabled by your organization`;case`org_level_disabled_until`:return`Fast mode disabled · extra usage spending cap reached`;case`member_level_disabled`:return`Fast mode disabled · extra usage disabled for your account`;case`seat_tier_level_disabled`:case`seat_tier_zero_credit_limit`:case`member_zero_credit_limit`:return`Fast mode disabled · extra usage not available for your plan`;case`overage_not_provisioned`:case`no_limits_configured`:return`Fast mode requires extra usage billing · check your API plan`;default:return`Fast mode disabled · extra usage not available`}}function Tde(){K(`Fast mode rejected by API, disabling`)}function Ede(e){let t=wde(e);K(`Fast mode overage rejection: ${e??`unknown`} — ${t}`),sp.emit(t)}function $f(){return Qf().status===`cooldown`}function Dde(e,t){let n=Jf()&&Yf()&&!!t&&Zf(e);return n&&$f()?`cooldown`:n?`on`:`off`}function Ode(){}async function kde(){}var ep,tp,np,rp,ip,ap,op,sp,cp,lp,up,dp=n((()=>{La(),H(),Ia(),q(),g(),wo(),mo(),Ln(),Ir(),ep=`Opus 4.7`,tp={status:`active`},np=!1,rp=jr(),ip=jr(),ap=rp.subscribe,op=ip.subscribe,sp=jr(),cp=sp.subscribe,lp=jr(),up=lp.subscribe}));function fp(){return!1}var pp=n((()=>{})),mp,Ade=n((()=>{dp(),pp(),mp={type:`local-jsx`,name:`fast`,get description(){return`Toggle fast mode (${ep} only)`},availability:[`claude-ai`,`console`],isEnabled:()=>Jf(),get isHidden(){return!Jf()},argumentHint:`[on|off]`,get immediate(){return fp()},load:()=>import(`./fast-ClJARykP.js`)}})),hp,jde=n((()=>{hp={type:`local-jsx`,name:`hooks`,description:`查看工具事件的 hook 配置`,immediate:!0,load:()=>import(`./hooks-BBL70Pl1.js`)}})),gp,Mde=n((()=>{gp={type:`local-jsx`,name:`branch`,aliases:[`fork`],description:`从当前时间点为当前会话创建一个分支`,argumentHint:`[name]`,load:()=>import(`./branch-BQ_M1T0j.js`)}})),_p,Nde=n((()=>{_p={type:`local-jsx`,name:`agents`,description:`管理智能体(agent)配置`,load:()=>import(`./agents-ByQvpZ-y.js`)}})),vp,Pde=n((()=>{vp={type:`local-jsx`,name:`plugin`,aliases:[`plugins`,`marketplace`],description:`管理 Work Mate 插件`,immediate:!0,load:()=>import(`./plugin-Bee-4gyo.js`)}})),yp,Fde=n((()=>{yp={type:`local`,name:`reload-plugins`,description:`在当前会话激活待生效的插件改动`,supportsNonInteractive:!1,load:()=>import(`./reload-plugins-C6aSczZl.js`)}})),bp,Ide=n((()=>{bp={description:`把代码和/或对话恢复到之前的某个时间点`,name:`rewind`,aliases:[`checkpoint`],argumentHint:``,type:`local`,supportsNonInteractive:!1,load:()=>import(`./rewind-D12hCfZD.js`)}})),xp,Sp,Lde=n((()=>{xp=async()=>({type:`text`,value:`0.0.32 (built 2026-09-23T14:24:20.510Z)`}),Sp={type:`local`,name:`version`,description:`打印当前会话运行的版本(不是 autoupdate 下载的版本)`,isEnabled:()=>!0,supportsNonInteractive:!0,load:()=>Promise.resolve({call:xp})}})),Cp=i({isSkillSearchCompiledIn:()=>wp,isSkillSearchEnabled:()=>Tp});function wp(){return!1}function Tp(){return process.env.SKILL_SEARCH_ENABLED===`1`}var Ep=n((()=>{})),Dp,Rde=n((()=>{Ep(),Dp={type:`local-jsx`,name:`skill-search`,description:`控制对话过程中自动进行的 skill 匹配`,argumentHint:`[start|stop|about|status]`,isEnabled:()=>wp(),isHidden:!1,load:()=>import(`./skillSearchPanel-CSm2Eq_U.js`)}}));function Z(e,t){if(!process.env.SRT_DEBUG)return;let n=t?.level||`info`,r=`[SandboxDebug]`;switch(n){case`error`:console.error(`${r} ${e}`);break;case`warn`:console.warn(`${r} ${e}`);break;default:console.error(`${r} ${e}`)}}var Op=n((()=>{}));function kp(e){let t=e?.http??process.env.HTTP_PROXY??process.env.http_proxy??void 0,n=e?.https??process.env.HTTPS_PROXY??process.env.https_proxy??t,r=e?.noProxy??process.env.NO_PROXY??process.env.no_proxy??``;if(!t&&!n)return;let i=e=>{if(!e)return;let t=/^[a-z][a-z0-9+.-]*:\/\//i.test(e)?e:`http://${e}`;try{let e=new il(t);if(e.protocol!==`http:`&&e.protocol!==`https:`||!e.hostname)throw Error(`unsupported scheme or empty host`);return e}catch{Z(`Invalid parent proxy URL, ignoring: ${Bde(e)}`,{level:`error`});return}},a=i(t),o=i(n);if(!(!a&&!o))return{httpUrl:a,httpsUrl:o,noProxy:zde(r)}}function zde(e){let t={all:!1,suffixes:[],cidr:new Dce};for(let n of e.split(`,`)){if(n=n.trim(),!n)continue;if(n===`*`){t.all=!0;continue}let e=n.indexOf(`/`);if(e!==-1){let r=n.slice(0,e),i=n.slice(e+1),a=ol(r);if(a&&i!==``&&/^\d+$/.test(i)){let e=Number(i);if(e>=0&&e<=(a===6?128:32)){try{t.cidr.addSubnet(r,e,a===6?`ipv6`:`ipv4`)}catch{}continue}}continue}let r=n.toLowerCase(),i=/^\[([^\]]+)\](?::\d+)?$/.exec(r);i&&(r=i[1]),r.startsWith(`*.`)&&(r=r.slice(1));let a=ol(r);if(a)try{t.cidr.addAddress(r,a===6?`ipv6`:`ipv4`);continue}catch{}else{let e=r.lastIndexOf(`:`);e!==-1&&/^\d+$/.test(r.slice(e+1))&&(r=r.slice(0,e))}t.suffixes.push(r)}return t}function Ap(e,t){let n=Ip(t.toLowerCase().replace(/\.$/,``));if(n===`localhost`)return!0;let r=ol(n);if(r&&Hp.check(n,r===6?`ipv6`:`ipv4`)||e.noProxy.all||r&&e.noProxy.cidr.check(n,r===6?`ipv6`:`ipv4`))return!0;for(let t of e.noProxy.suffixes)if(t.startsWith(`.`)){if(n===t.slice(1)||n.endsWith(t))return!0}else if(n===t||n.endsWith(`.`+t))return!0;return!1}function jp(e,t){return t.isHttps?e.httpsUrl??e.httpUrl:e.httpUrl}function Mp(e){let{destHost:t,destPort:n}=e,r=Ip(t);if(!Rp(r))return Promise.reject(Error(`Invalid destination host for CONNECT: ${JSON.stringify(t)}`));if(!Number.isInteger(n)||n<1||n>65535)return Promise.reject(Error(`Invalid destination port: ${n}`));let i=ol(r)===6?`[${r}]:${n}`:`${r}:${n}`;return new Promise((t,n)=>{let r=e.dial(),a=!1,o=e=>{a||(a=!0,r.destroy(),n(e))},s=()=>o(Error(`Proxy closed during CONNECT handshake`));r.setTimeout(e.timeoutMs??Bp,()=>o(Error(`CONNECT handshake timed out`))),r.once(`error`,o),r.once(`close`,s),r.once(e.readyEvent,()=>{r.write(`CONNECT ${i} HTTP/1.1\r\nHost: ${i}\r\n`+(e.authHeader?`Proxy-Authorization: ${e.authHeader}\r\n`:``)+`\r
391
+ </system-reminder>`]})),null}})}})),Wf,gde=n((()=>{Wf={type:`local-jsx`,name:`job`,description:`管理模板作业(job)`,argumentHint:`[list|new|reply|status]`,isEnabled:()=>!0,load:()=>import(`./job-C8wb0GoC.js`)}})),Gf,_de=n((()=>{Gf={type:`local-jsx`,name:`goal`,description:`设置或查看一个持久化 goal,用于驱动跨轮次的自动续作`,argumentHint:`[<objective> | status | clear | pause | resume | complete]`,load:()=>import(`./goal-BGBTyotH.js`)}})),Kf,vde=n((()=>{Kf={type:`local-jsx`,name:`permissions`,aliases:[`allowed-tools`],description:`管理允许 / 拒绝的工具权限规则`,load:()=>import(`./permissions-BUIk_6ze.js`)}})),qf,yde=n((()=>{qf={type:`local-jsx`,name:`plan`,description:`启用 plan 模式或查看当前会话的 plan`,argumentHint:`[open|<description>]`,load:()=>import(`./plan-CiL_d9-B.js`)}}));function Jf(){return!h(process.env.WORKMATE_DISABLE_FAST_MODE)}function Yf(){return Jf()?Xf()===null:!1}function Xf(){if(!Jf())return`Fast mode is not available`;if(Na(),kr()&&Qte()&&!$n(`flagSettings`)?.fastMode){let e=`Fast mode is not available in the Agent SDK`;return K(`Fast mode unavailable: ${e}`),e}if(lo()!==`firstParty`){let e=`Fast mode is not available on Bedrock, Vertex, or Foundry`;return K(`Fast mode unavailable: ${e}`),e}return null}function bde(){return`opus${Nie()?`[1m]`:``}`}function xde(e){if(!Jf()||!Yf()||!Zf(e))return!1;let t=rr();return!t.fastModePerSessionOptIn&&t.fastMode===!0}function Zf(e){if(!Jf())return!1;let t=Vo(e??Do());return t.toLowerCase().includes(`opus-4-7`)||t.toLowerCase().includes(`opus-4-6`)}function Qf(){return tp.status===`cooldown`&&Date.now()>=tp.resetAt&&(Jf()&&!np&&(K(`Fast mode cooldown expired, re-enabling fast mode`),np=!0,ip.emit()),tp={status:`active`}),tp}function Sde(e,t){if(!Jf())return;tp={status:`cooldown`,resetAt:e,reason:t},np=!1;let n=e-Date.now();K(`Fast mode cooldown triggered (${t}), duration ${Math.round(n/1e3)}s`),rp.emit(e,t)}function Cde(){tp={status:`active`}}function wde(e){switch(e){case`out_of_credits`:return`Fast mode disabled · extra usage credits exhausted`;case`org_level_disabled`:case`org_service_level_disabled`:return`Fast mode disabled · extra usage disabled by your organization`;case`org_level_disabled_until`:return`Fast mode disabled · extra usage spending cap reached`;case`member_level_disabled`:return`Fast mode disabled · extra usage disabled for your account`;case`seat_tier_level_disabled`:case`seat_tier_zero_credit_limit`:case`member_zero_credit_limit`:return`Fast mode disabled · extra usage not available for your plan`;case`overage_not_provisioned`:case`no_limits_configured`:return`Fast mode requires extra usage billing · check your API plan`;default:return`Fast mode disabled · extra usage not available`}}function Tde(){K(`Fast mode rejected by API, disabling`)}function Ede(e){let t=wde(e);K(`Fast mode overage rejection: ${e??`unknown`} — ${t}`),sp.emit(t)}function $f(){return Qf().status===`cooldown`}function Dde(e,t){let n=Jf()&&Yf()&&!!t&&Zf(e);return n&&$f()?`cooldown`:n?`on`:`off`}function Ode(){}async function kde(){}var ep,tp,np,rp,ip,ap,op,sp,cp,lp,up,dp=n((()=>{La(),H(),Ia(),q(),g(),wo(),mo(),Ln(),Ir(),ep=`Opus 4.7`,tp={status:`active`},np=!1,rp=jr(),ip=jr(),ap=rp.subscribe,op=ip.subscribe,sp=jr(),cp=sp.subscribe,lp=jr(),up=lp.subscribe}));function fp(){return!1}var pp=n((()=>{})),mp,Ade=n((()=>{dp(),pp(),mp={type:`local-jsx`,name:`fast`,get description(){return`Toggle fast mode (${ep} only)`},availability:[`claude-ai`,`console`],isEnabled:()=>Jf(),get isHidden(){return!Jf()},argumentHint:`[on|off]`,get immediate(){return fp()},load:()=>import(`./fast-CrcV5wxl.js`)}})),hp,jde=n((()=>{hp={type:`local-jsx`,name:`hooks`,description:`查看工具事件的 hook 配置`,immediate:!0,load:()=>import(`./hooks-BsmdK_In.js`)}})),gp,Mde=n((()=>{gp={type:`local-jsx`,name:`branch`,aliases:[`fork`],description:`从当前时间点为当前会话创建一个分支`,argumentHint:`[name]`,load:()=>import(`./branch-D_94wxwM.js`)}})),_p,Nde=n((()=>{_p={type:`local-jsx`,name:`agents`,description:`管理智能体(agent)配置`,load:()=>import(`./agents-BqXRXbE8.js`)}})),vp,Pde=n((()=>{vp={type:`local-jsx`,name:`plugin`,aliases:[`plugins`,`marketplace`],description:`管理 Work Mate 插件`,immediate:!0,load:()=>import(`./plugin-DQxBd6KC.js`)}})),yp,Fde=n((()=>{yp={type:`local`,name:`reload-plugins`,description:`在当前会话激活待生效的插件改动`,supportsNonInteractive:!1,load:()=>import(`./reload-plugins-IdDv2ypF.js`)}})),bp,Ide=n((()=>{bp={description:`把代码和/或对话恢复到之前的某个时间点`,name:`rewind`,aliases:[`checkpoint`],argumentHint:``,type:`local`,supportsNonInteractive:!1,load:()=>import(`./rewind-D12hCfZD.js`)}})),xp,Sp,Lde=n((()=>{xp=async()=>({type:`text`,value:`0.0.33 (built 2026-10-30T05:16:57.659Z)`}),Sp={type:`local`,name:`version`,description:`打印当前会话运行的版本(不是 autoupdate 下载的版本)`,isEnabled:()=>!0,supportsNonInteractive:!0,load:()=>Promise.resolve({call:xp})}})),Cp=i({isSkillSearchCompiledIn:()=>wp,isSkillSearchEnabled:()=>Tp});function wp(){return!1}function Tp(){return process.env.SKILL_SEARCH_ENABLED===`1`}var Ep=n((()=>{})),Dp,Rde=n((()=>{Ep(),Dp={type:`local-jsx`,name:`skill-search`,description:`控制对话过程中自动进行的 skill 匹配`,argumentHint:`[start|stop|about|status]`,isEnabled:()=>wp(),isHidden:!1,load:()=>import(`./skillSearchPanel-CsT69YTR.js`)}}));function Z(e,t){if(!process.env.SRT_DEBUG)return;let n=t?.level||`info`,r=`[SandboxDebug]`;switch(n){case`error`:console.error(`${r} ${e}`);break;case`warn`:console.warn(`${r} ${e}`);break;default:console.error(`${r} ${e}`)}}var Op=n((()=>{}));function kp(e){let t=e?.http??process.env.HTTP_PROXY??process.env.http_proxy??void 0,n=e?.https??process.env.HTTPS_PROXY??process.env.https_proxy??t,r=e?.noProxy??process.env.NO_PROXY??process.env.no_proxy??``;if(!t&&!n)return;let i=e=>{if(!e)return;let t=/^[a-z][a-z0-9+.-]*:\/\//i.test(e)?e:`http://${e}`;try{let e=new il(t);if(e.protocol!==`http:`&&e.protocol!==`https:`||!e.hostname)throw Error(`unsupported scheme or empty host`);return e}catch{Z(`Invalid parent proxy URL, ignoring: ${Bde(e)}`,{level:`error`});return}},a=i(t),o=i(n);if(!(!a&&!o))return{httpUrl:a,httpsUrl:o,noProxy:zde(r)}}function zde(e){let t={all:!1,suffixes:[],cidr:new Dce};for(let n of e.split(`,`)){if(n=n.trim(),!n)continue;if(n===`*`){t.all=!0;continue}let e=n.indexOf(`/`);if(e!==-1){let r=n.slice(0,e),i=n.slice(e+1),a=ol(r);if(a&&i!==``&&/^\d+$/.test(i)){let e=Number(i);if(e>=0&&e<=(a===6?128:32)){try{t.cidr.addSubnet(r,e,a===6?`ipv6`:`ipv4`)}catch{}continue}}continue}let r=n.toLowerCase(),i=/^\[([^\]]+)\](?::\d+)?$/.exec(r);i&&(r=i[1]),r.startsWith(`*.`)&&(r=r.slice(1));let a=ol(r);if(a)try{t.cidr.addAddress(r,a===6?`ipv6`:`ipv4`);continue}catch{}else{let e=r.lastIndexOf(`:`);e!==-1&&/^\d+$/.test(r.slice(e+1))&&(r=r.slice(0,e))}t.suffixes.push(r)}return t}function Ap(e,t){let n=Ip(t.toLowerCase().replace(/\.$/,``));if(n===`localhost`)return!0;let r=ol(n);if(r&&Hp.check(n,r===6?`ipv6`:`ipv4`)||e.noProxy.all||r&&e.noProxy.cidr.check(n,r===6?`ipv6`:`ipv4`))return!0;for(let t of e.noProxy.suffixes)if(t.startsWith(`.`)){if(n===t.slice(1)||n.endsWith(t))return!0}else if(n===t||n.endsWith(`.`+t))return!0;return!1}function jp(e,t){return t.isHttps?e.httpsUrl??e.httpUrl:e.httpUrl}function Mp(e){let{destHost:t,destPort:n}=e,r=Ip(t);if(!Rp(r))return Promise.reject(Error(`Invalid destination host for CONNECT: ${JSON.stringify(t)}`));if(!Number.isInteger(n)||n<1||n>65535)return Promise.reject(Error(`Invalid destination port: ${n}`));let i=ol(r)===6?`[${r}]:${n}`:`${r}:${n}`;return new Promise((t,n)=>{let r=e.dial(),a=!1,o=e=>{a||(a=!0,r.destroy(),n(e))},s=()=>o(Error(`Proxy closed during CONNECT handshake`));r.setTimeout(e.timeoutMs??Bp,()=>o(Error(`CONNECT handshake timed out`))),r.once(`error`,o),r.once(`close`,s),r.once(e.readyEvent,()=>{r.write(`CONNECT ${i} HTTP/1.1\r\nHost: ${i}\r\n`+(e.authHeader?`Proxy-Authorization: ${e.authHeader}\r\n`:``)+`\r
392
392
  `);let n=``,c=e=>{n+=e.toString(`latin1`);let i=n.indexOf(`\r
393
393
  \r
394
394
  `);if(i===-1){n.length>16*1024&&o(Error(`CONNECT response header too large`));return}r.pause(),r.removeListener(`data`,c);let l=n.slice(0,n.indexOf(`\r
@@ -412,7 +412,7 @@ Connection blocked by network allowlist`);return}let c=e.getMitmSocketPath?.(o),
412
412
  `);return`${o} -c ${Qm.quote([i])}`}else{let e=[...s,`eval ${Qm.quote([n])}`].join(`
413
413
  `);return`${o} -c ${Qm.quote([e])}`}}async function Ofe(e,t,n={command:`rg`},r=$m,i=!1,a){let o=[],s=[],c=[];if(t){o.push(`--ro-bind`,`/`,`/`);for(let e of t.allowOnly||[]){let t=Nm(e);if(Z(`[Sandbox Linux] Processing write path: ${e} -> ${t}`),t.startsWith(`/dev/`)){Z(`[Sandbox Linux] Skipping /dev path: ${t}`);continue}if(!Ec.existsSync(t)){Z(`[Sandbox Linux] Skipping non-existent write path: ${t}`);continue}try{let n=Ec.realpathSync(t);if(n!==t.replace(/\/+$/,``)&&Mm(t,n)){Z(`[Sandbox Linux] Skipping symlink write path pointing outside expected location: ${e} -> ${n}`);continue}}catch{Z(`[Sandbox Linux] Skipping write path that could not be resolved: ${t}`);continue}o.push(`--bind`,t,t),s.push(t)}let e=[...t.denyWithinAllow||[],...await wfe(n,r,i,a)],l=new Set;for(let t of e){let e=Nm(t);if(l.has(e)||(l.add(e),e.startsWith(`/dev/`)))continue;let n=xfe(e,s);if(n){c.push(`--ro-bind`,`/dev/null`,n),Z(`[Sandbox Linux] Mounted /dev/null at symlink ${n} to prevent symlink replacement attack`);continue}if(!Ec.existsSync(e)){if(Sfe(e)){Z(`[Sandbox Linux] Skipping deny path with file ancestor (cannot create paths under a file): ${e}`);continue}let t=Cc.dirname(e);for(;t!==`/`&&!Ec.existsSync(t);)t=Cc.dirname(t);if(s.some(n=>t.startsWith(n+`/`)||t===n||e.startsWith(n+`/`))){let t=Cfe(e);if(t!==e){let n=Ec.mkdtempSync(Cc.join(Pc(),`claude-empty-`));c.push(`--ro-bind`,n,t),th.add(t),Xm(),Z(`[Sandbox Linux] Mounted empty dir at ${t} to block creation of ${e}`)}else c.push(`--ro-bind`,`/dev/null`,t),th.add(t),Xm(),Z(`[Sandbox Linux] Mounted /dev/null at ${t} to block creation of ${e}`)}else Z(`[Sandbox Linux] Skipping non-existent deny path not within allowed paths: ${e}`);continue}s.some(t=>e.startsWith(t+`/`)||e===t)?c.push(`--ro-bind`,e,e):Z(`[Sandbox Linux] Skipping deny path not within allowed paths: ${e}`)}}else o.push(`--bind`,`/`,`/`);let l=[],u=(e?.allowWithinDeny||[]).map(e=>Nm(e)),d=new Set([`proc`,`dev`,`sys`]);for(let t of e?.denyOnly||[])if(Nm(t)===`/`)for(let e of Ec.readdirSync(`/`))d.has(e)||l.push(`/`+e);else l.push(t);Ec.existsSync(`/etc/ssh/ssh_config.d`)&&l.push(`/etc/ssh/ssh_config.d`);for(let e of l){let t=Nm(e);if(!Ec.existsSync(t)){Z(`[Sandbox Linux] Skipping non-existent read deny path: ${t}`);continue}let n=t===`/`?`/`:t+`/`;if(Ec.statSync(t).isDirectory()){o.push(`--tmpfs`,t);for(let e of s)(e.startsWith(n)||e===t)&&(o.push(`--bind`,e,e),Z(`[Sandbox Linux] Re-bound write path wiped by denyRead tmpfs: ${e}`));for(let e of u)if(e.startsWith(n)||e===t){if(!Ec.existsSync(e)){Z(`[Sandbox Linux] Skipping non-existent read allow path: ${e}`);continue}if(s.some(r=>(r.startsWith(n)||r===t)&&(e===r||e.startsWith(r+`/`))))continue;o.push(`--ro-bind`,e,e),Z(`[Sandbox Linux] Re-allowed read access within denied region: ${e}`)}}else{if(u.some(e=>t===e||t.startsWith(e+`/`))){Z(`[Sandbox Linux] Skipping read deny for re-allowed path: ${t}`);continue}o.push(`--ro-bind`,`/dev/null`,t)}}return o.push(...c),o}async function kfe(e){let{command:t,needsNetworkRestriction:n,httpSocketPath:r,socksSocketPath:i,httpProxyPort:a,socksProxyPort:o,readConfig:s,writeConfig:c,enableWeakerNestedSandbox:l,allowAllUnixSockets:u,binShell:d,ripgrepConfig:f={command:`rg`},mandatoryDenySearchDepth:p=$m,allowGitConfig:m=!1,seccompConfig:h,abortSignal:g}=e,_=s&&s.denyOnly.length>0,v=c!==void 0;if(!n&&!_&&!v)return t;let y=[`--new-session`,`--die-with-parent`],b;try{if(u)Z(`[Sandbox Linux] Skipping seccomp filter - allowAllUnixSockets is enabled`);else{b=yfe(h?.bpfPath)??void 0;let e=Km(h?.applyPath);!b||!e?(Z(`[Sandbox Linux] Seccomp binaries not available - unix socket blocking disabled. Install @anthropic-ai/sandbox-runtime globally for full protection.`,{level:`warn`}),b=void 0):(b.includes(`/vendor/seccomp/`)||(eh.add(b),Xm()),Z(`[Sandbox Linux] Generated seccomp BPF filter for Unix socket blocking`))}if(n&&(y.push(`--unshare-net`),r&&i)){if(!Ec.existsSync(r))throw Error(`Linux HTTP bridge socket does not exist: ${r}. The bridge process may have died. Try reinitializing the sandbox.`);if(!Ec.existsSync(i))throw Error(`Linux SOCKS bridge socket does not exist: ${i}. The bridge process may have died. Try reinitializing the sandbox.`);y.push(`--bind`,r,r),y.push(`--bind`,i,i);let e=Fm(3128,1080);y.push(...e.flatMap(e=>{let t=e.indexOf(`=`);return[`--setenv`,e.slice(0,t),e.slice(t+1)]})),a!==void 0&&y.push(`--setenv`,`CLAUDE_CODE_HOST_HTTP_PROXY_PORT`,String(a)),o!==void 0&&y.push(`--setenv`,`CLAUDE_CODE_HOST_SOCKS_PROXY_PORT`,String(o))}let e=await Ofe(s,c,f,p,m,g);y.push(...e),y.push(`--dev`,`/dev`),y.push(`--unshare-pid`),l||y.push(`--proc`,`/proc`);let x=d||`bash`,S=Yp(x);if(!S)throw Error(`Shell '${x}' not found in PATH`);if(y.push(`--`,S,`-c`),n&&r&&i){let e=Dfe(r,i,t,b,S,h?.applyPath);y.push(e)}else if(b){let e=Km(h?.applyPath);if(!e)throw Error(`apply-seccomp binary not found. This should have been caught earlier. Ensure vendor/seccomp/{x64,arm64}/apply-seccomp binaries are included in the package.`);let n=Qm.quote([e,b,S,`-c`,t]);y.push(n)}else y.push(t);let C=Qm.quote([`bwrap`,...y]),w=[];return n&&w.push(`network`),(_||v)&&w.push(`filesystem`),b&&w.push(`seccomp(unix-block)`),Z(`[Sandbox Linux] Wrapped command with bwrap (${w.join(`, `)} restrictions)`),C}catch(e){throw b&&!b.includes(`/vendor/seccomp/`)&&eh.delete(b),e}}var Qm,$m,eh,th,nh,Afe=n((()=>{Qm=r(Dm(),1),Op(),Xp(),hfe(),Vm(),bfe(),$m=3,eh=new Set,th=new Set,nh=!1}));function jfe(e=!1){let t=process.cwd(),n=[];for(let e of zm)n.push(uc.resolve(t,e)),n.push(`**/${e}`);for(let e of Om())n.push(uc.resolve(t,e)),n.push(`**/${e}/**`);return n.push(uc.resolve(t,`.git/hooks`)),n.push(`**/.git/hooks/**`),e||(n.push(uc.resolve(t,`.git/config`)),n.push(`**/.git/config`)),[...new Set(n)]}function Mfe(e){return`CMD64_${Im(e)}_END_${sh}`}function rh(e){let t=[],n=uc.dirname(e);for(;n!==`/`&&n!==`.`;){t.push(n);let e=uc.dirname(n);if(e===n)break;n=e}return t}function ih(e,t){let n=[];for(let r of e){let e=Nm(r);if(Am(e)){let r=Lm(e);n.push(`(deny file-write-unlink`,` (regex ${ah(r)})`,` (with message "${t}"))`);let i=e.split(/[*?[\]]/)[0];if(i&&i!==`/`){let e=i.endsWith(`/`)?i.slice(0,-1):uc.dirname(i);n.push(`(deny file-write-unlink`,` (literal ${ah(e)})`,` (with message "${t}"))`);for(let r of rh(e))n.push(`(deny file-write-unlink`,` (literal ${ah(r)})`,` (with message "${t}"))`)}}else{n.push(`(deny file-write-unlink`,` (subpath ${ah(e)})`,` (with message "${t}"))`);for(let r of rh(e))n.push(`(deny file-write-unlink`,` (literal ${ah(r)})`,` (with message "${t}"))`)}}return n}function Nfe(e,t){if(!e)return[`(allow file-read*)`];let n=[],r=!1;n.push(`(allow file-read*)`);for(let i of e.denyOnly||[]){let e=Nm(i);if(e===`/`&&(r=!0),Am(e)){let r=Lm(e);n.push(`(deny file-read*`,` (regex ${ah(r)})`,` (with message "${t}"))`)}else n.push(`(deny file-read*`,` (subpath ${ah(e)})`,` (with message "${t}"))`)}r&&n.push(`(allow file-read* (literal "/"))`);for(let r of e.allowWithinDeny||[]){let e=Nm(r);if(Am(e)){let r=Lm(e);n.push(`(allow file-read*`,` (regex ${ah(r)})`,` (with message "${t}"))`)}else n.push(`(allow file-read*`,` (subpath ${ah(e)})`,` (with message "${t}"))`)}return e.denyOnly.length>0&&n.push(`(allow file-read-metadata`,` (vnode-type DIRECTORY))`),n.push(...ih(e.denyOnly||[],t)),n}function Pfe(e,t,n=!1){if(!e)return[`(allow file-write*)`];let r=[];for(let n of e.allowOnly||[]){let e=Nm(n);if(Am(e)){let n=Lm(e);r.push(`(allow file-write*`,` (regex ${ah(n)})`,` (with message "${t}"))`)}else r.push(`(allow file-write*`,` (subpath ${ah(e)})`,` (with message "${t}"))`)}let i=[...e.denyWithinAllow||[],...jfe(n)];for(let e of i){let n=Nm(e);if(Am(n)){let e=Lm(n);r.push(`(deny file-write*`,` (regex ${ah(e)})`,` (with message "${t}"))`)}else r.push(`(deny file-write*`,` (subpath ${ah(n)})`,` (with message "${t}"))`)}return r.push(...ih(i,t)),r}function Ffe({readConfig:e,writeConfig:t,httpProxyPort:n,socksProxyPort:r,needsNetworkRestriction:i,allowUnixSockets:a,allowAllUnixSockets:o,allowLocalBinding:s,allowPty:c,allowGitConfig:l=!1,enableWeakerNetworkIsolation:u=!1,logTag:d}){let f=[`(version 1)`,`(deny default (with message "${d}"))`,``,`; LogTag: ${d}`,``,`; Essential permissions - based on Chrome sandbox policy`,`; Process permissions`,`(allow process-exec)`,`(allow process-fork)`,`(allow process-info* (target same-sandbox))`,`(allow signal (target same-sandbox))`,`(allow mach-priv-task-port (target same-sandbox))`,``,`; User preferences`,`(allow user-preference-read)`,``,`; Mach IPC - specific services only (no wildcard)`,`(allow mach-lookup`,` (global-name "com.apple.audio.systemsoundserver")`,` (global-name "com.apple.distributed_notifications@Uv3")`,` (global-name "com.apple.FontObjectsServer")`,` (global-name "com.apple.fonts")`,` (global-name "com.apple.logd")`,` (global-name "com.apple.lsd.mapdb")`,` (global-name "com.apple.PowerManagement.control")`,` (global-name "com.apple.system.logger")`,` (global-name "com.apple.system.notification_center")`,` (global-name "com.apple.system.opendirectoryd.libinfo")`,` (global-name "com.apple.system.opendirectoryd.membership")`,` (global-name "com.apple.bsd.dirhelper")`,` (global-name "com.apple.securityd.xpc")`,` (global-name "com.apple.coreservices.launchservicesd")`,`)`,``,...u?[`; trustd.agent - needed for Go TLS certificate verification (weaker network isolation)`,`(allow mach-lookup (global-name "com.apple.trustd.agent"))`]:[],``,`; POSIX IPC - shared memory`,`(allow ipc-posix-shm)`,``,`; POSIX IPC - semaphores for Python multiprocessing`,`(allow ipc-posix-sem)`,``,`; IOKit - specific operations only`,`(allow iokit-open`,` (iokit-registry-entry-class "IOSurfaceRootUserClient")`,` (iokit-registry-entry-class "RootDomainUserClient")`,` (iokit-user-client-class "IOSurfaceSendRight")`,`)`,``,`; IOKit properties`,`(allow iokit-get-properties)`,``,`; Specific safe system-sockets, doesn't allow network access`,`(allow system-socket (require-all (socket-domain AF_SYSTEM) (socket-protocol 2)))`,``,`; sysctl - specific sysctls only`,`(allow sysctl-read`,` (sysctl-name "hw.activecpu")`,` (sysctl-name "hw.busfrequency_compat")`,` (sysctl-name "hw.byteorder")`,` (sysctl-name "hw.cacheconfig")`,` (sysctl-name "hw.cachelinesize_compat")`,` (sysctl-name "hw.cpufamily")`,` (sysctl-name "hw.cpufrequency")`,` (sysctl-name "hw.cpufrequency_compat")`,` (sysctl-name "hw.cputype")`,` (sysctl-name "hw.l1dcachesize_compat")`,` (sysctl-name "hw.l1icachesize_compat")`,` (sysctl-name "hw.l2cachesize_compat")`,` (sysctl-name "hw.l3cachesize_compat")`,` (sysctl-name "hw.logicalcpu")`,` (sysctl-name "hw.logicalcpu_max")`,` (sysctl-name "hw.machine")`,` (sysctl-name "hw.memsize")`,` (sysctl-name "hw.ncpu")`,` (sysctl-name "hw.nperflevels")`,` (sysctl-name "hw.packages")`,` (sysctl-name "hw.pagesize_compat")`,` (sysctl-name "hw.pagesize")`,` (sysctl-name "hw.physicalcpu")`,` (sysctl-name "hw.physicalcpu_max")`,` (sysctl-name "hw.tbfrequency_compat")`,` (sysctl-name "hw.vectorunit")`,` (sysctl-name "kern.argmax")`,` (sysctl-name "kern.bootargs")`,` (sysctl-name "kern.hostname")`,` (sysctl-name "kern.maxfiles")`,` (sysctl-name "kern.maxfilesperproc")`,` (sysctl-name "kern.maxproc")`,` (sysctl-name "kern.ngroups")`,` (sysctl-name "kern.osproductversion")`,` (sysctl-name "kern.osrelease")`,` (sysctl-name "kern.ostype")`,` (sysctl-name "kern.osvariant_status")`,` (sysctl-name "kern.osversion")`,` (sysctl-name "kern.secure_kernel")`,` (sysctl-name "kern.tcsm_available")`,` (sysctl-name "kern.tcsm_enable")`,` (sysctl-name "kern.usrstack64")`,` (sysctl-name "kern.version")`,` (sysctl-name "kern.willshutdown")`,` (sysctl-name "machdep.cpu.brand_string")`,` (sysctl-name "machdep.ptrauth_enabled")`,` (sysctl-name "security.mac.lockdown_mode_state")`,` (sysctl-name "sysctl.proc_cputype")`,` (sysctl-name "vm.loadavg")`,` (sysctl-name-prefix "hw.optional.arm")`,` (sysctl-name-prefix "hw.optional.arm.")`,` (sysctl-name-prefix "hw.optional.armv8_")`,` (sysctl-name-prefix "hw.perflevel")`,` (sysctl-name-prefix "kern.proc.all")`,` (sysctl-name-prefix "kern.proc.pgrp.")`,` (sysctl-name-prefix "kern.proc.pid.")`,` (sysctl-name-prefix "machdep.cpu.")`,` (sysctl-name-prefix "net.routetable.")`,`)`,``,`; V8 thread calculations`,`(allow sysctl-write`,` (sysctl-name "kern.tcsm_enable")`,`)`,``,`; Distributed notifications`,`(allow distributed-notification-post)`,``,`; Specific mach-lookup permissions for security operations`,`(allow mach-lookup (global-name "com.apple.SecurityServer"))`,``,`; File I/O on device files`,`(allow file-ioctl (literal "/dev/null"))`,`(allow file-ioctl (literal "/dev/zero"))`,`(allow file-ioctl (literal "/dev/random"))`,`(allow file-ioctl (literal "/dev/urandom"))`,`(allow file-ioctl (literal "/dev/dtracehelper"))`,`(allow file-ioctl (literal "/dev/tty"))`,``,`(allow file-ioctl file-read-data file-write-data`,` (require-all`,` (literal "/dev/null")`,` (vnode-type CHARACTER-DEVICE)`,` )`,`)`,``];if(f.push(`; Network`),!i)f.push(`(allow network*)`);else{if(s&&(f.push(`(allow network-bind (local ip "*:*"))`),f.push(`(allow network-inbound (local ip "*:*"))`),f.push(`(allow network-outbound (local ip "*:*"))`)),o)f.push(`(allow system-socket (socket-domain AF_UNIX))`),f.push(`(allow network-bind (local unix-socket (path-regex #"^/")))`),f.push(`(allow network-outbound (remote unix-socket (path-regex #"^/")))`);else if(a&&a.length>0){f.push(`(allow system-socket (socket-domain AF_UNIX))`);for(let e of a){let t=Nm(e);f.push(`(allow network-bind (local unix-socket (subpath ${ah(t)})))`),f.push(`(allow network-outbound (remote unix-socket (subpath ${ah(t)})))`)}}n!==void 0&&(f.push(`(allow network-bind (local ip "localhost:${n}"))`),f.push(`(allow network-inbound (local ip "localhost:${n}"))`),f.push(`(allow network-outbound (remote ip "localhost:${n}"))`)),r!==void 0&&(f.push(`(allow network-bind (local ip "localhost:${r}"))`),f.push(`(allow network-inbound (local ip "localhost:${r}"))`),f.push(`(allow network-outbound (remote ip "localhost:${r}"))`))}return f.push(``),f.push(`; File read`),f.push(...Nfe(e,d)),f.push(``),f.push(`; File write`),f.push(...Pfe(t,d,l)),c&&(f.push(``),f.push(`; Pseudo-terminal (pty) support`),f.push(`(allow pseudo-tty)`),f.push(`(allow file-ioctl`),f.push(` (literal "/dev/ptmx")`),f.push(` (regex #"^/dev/ttys")`),f.push(`)`),f.push(`(allow file-read* file-write*`),f.push(` (literal "/dev/ptmx")`),f.push(` (regex #"^/dev/ttys")`),f.push(`)`)),f.join(`
414
414
  `)}function ah(e){return JSON.stringify(e)}function Ife(e){let{command:t,needsNetworkRestriction:n,httpProxyPort:r,socksProxyPort:i,allowUnixSockets:a,allowAllUnixSockets:o,allowLocalBinding:s,readConfig:c,writeConfig:l,allowPty:u,allowGitConfig:d=!1,enableWeakerNetworkIsolation:f=!1,binShell:p}=e,m=c&&c.denyOnly.length>0;if(!n&&!m&&l===void 0)return t;let h=Ffe({readConfig:c,writeConfig:l,httpProxyPort:r,socksProxyPort:i,needsNetworkRestriction:n,allowUnixSockets:a,allowAllUnixSockets:o,allowLocalBinding:s,allowPty:u,allowGitConfig:d,enableWeakerNetworkIsolation:f,logTag:Mfe(t)}),g=Fm(r,i),_=p||`bash`,v=Yp(_);if(!v)throw Error(`Shell '${_}' not found in PATH`);let y=oh.quote([`env`,...g,`sandbox-exec`,`-p`,h,v,`-c`,t]);return Z(`[Sandbox macOS] Applied restrictions - network: ${!!(r||i)}, read: ${c?`allowAllExcept`in c?`allowAllExcept`:`denyAllExcept`:`none`}, write: ${l?`allowAllExcept`in l?`allowAllExcept`:`denyAllExcept`:`none`}`),y}function Lfe(e,t){let n=/CMD64_(.+?)_END/,r=/Sandbox:\s+(.+)$/,i=t?.[`*`]||[],a=t?Object.entries(t).filter(([e])=>e!==`*`):[],o=$c(`log`,[`stream`,`--predicate`,`(eventMessage ENDSWITH "${sh}")`,`--style`,`compact`]);return o.stdout?.on(`data`,o=>{let s=o.toString().split(`
415
- `),c=s.find(e=>e.includes(`Sandbox:`)&&e.includes(`deny`)),l=s.find(e=>e.startsWith(`CMD64_`));if(!c)return;let u=c.match(r);if(!u?.[1])return;let d=u[1],f,p;if(l&&(p=l.match(n)?.[1],p))try{f=gfe(p)}catch{}if(!(d.includes(`mDNSResponder`)||d.includes(`mach-lookup com.apple.diagnosticd`)||d.includes(`mach-lookup com.apple.analyticsd`))){if(t&&f){if(i.length>0&&i.some(e=>d.includes(e)))return;for(let[e,t]of a)if(f.includes(e)&&t.some(e=>d.includes(e)))return}e({line:d,command:f,encodedCommand:p,timestamp:new Date})}}),o.stderr?.on(`data`,e=>{Z(`[Sandbox Monitor] Log stream stderr: ${e.toString()}`)}),o.on(`error`,e=>{Z(`[Sandbox Monitor] Failed to start log stream: ${e.message}`)}),o.on(`exit`,e=>{Z(`[Sandbox Monitor] Log stream exited with code: ${e}`)}),()=>{Z(`[Sandbox Monitor] Stopping log monitor`),o.kill(`SIGTERM`)}}var oh,sh,Rfe=n((()=>{oh=r(Dm(),1),Op(),Xp(),Vm(),sh=`_${Math.random().toString(36).slice(2,11)}_SBX`})),ch,lh=n((()=>{Vm(),ch=class{constructor(){this.violations=[],this.totalCount=0,this.maxSize=100,this.listeners=new Set}addViolation(e){this.violations.push(e),this.totalCount++,this.violations.length>this.maxSize&&(this.violations=this.violations.slice(-this.maxSize)),this.notifyListeners()}getViolations(e){return e===void 0?[...this.violations]:this.violations.slice(-e)}getCount(){return this.violations.length}getTotalCount(){return this.totalCount}getViolationsForCommand(e){let t=Im(e);return this.violations.filter(e=>e.encodedCommand===t)}clear(){this.violations=[],this.notifyListeners()}subscribe(e){return this.listeners.add(e),e(this.getViolations()),()=>{this.listeners.delete(e)}}notifyListeners(){let e=this.getViolations();this.listeners.forEach(t=>t(e))}}}));function zfe(){if(Mh)return;let e=()=>Eh().catch(e=>{Z(`Cleanup failed in registerCleanup ${e}`,{level:`error`})});process.once(`exit`,e),process.once(`SIGINT`,e),process.once(`SIGTERM`,e),Mh=!0}function uh(e,t){let n=e.toLowerCase();if(t.startsWith(`*.`)){if(ol(Ip(n)))return!1;let e=t.substring(2).toLowerCase();return n.endsWith(`.`+e)}return n===t.toLowerCase()}async function dh(e,t,n){if(!Dh)return Z(`No config available, denying network request`),!1;if(!Rp(t))return Z(`Denying malformed host: ${JSON.stringify(t)}:${e}`,{level:`error`}),!1;let r=Vde(t)??t;for(let n of Dh.network.deniedDomains)if(uh(r,n))return Z(`Denied by config rule: ${t}:${e}`),!1;for(let n of Dh.network.allowedDomains)if(uh(r,n))return Z(`Allowed by config rule: ${t}:${e}`),!0;if(!n)return Z(`No matching config rule, denying: ${t}:${e}`),!1;Z(`No matching config rule, asking user: ${t}:${e}`);try{return await n({host:t,port:e})?(Z(`User allowed: ${t}:${e}`),!0):(Z(`User denied: ${t}:${e}`),!1)}catch(e){return Z(`Error in permission callback: ${e}`,{level:`error`}),!1}}function Bfe(e){if(!Dh?.network.mitmProxy)return;let{socketPath:t,domains:n}=Dh.network.mitmProxy;for(let r of n)if(uh(e,r))return Z(`Host ${e} matches MITM pattern ${r}`),t}async function Vfe(e){return Oh=Hde({filter:(t,n)=>dh(t,n,e),getMitmSocketPath:Bfe,parentProxy:Ph}),new Promise((e,t)=>{if(!Oh){t(Error(`HTTP proxy server undefined before listen`));return}let n=Oh;n.once(`error`,t),n.once(`listening`,()=>{let r=n.address();r&&typeof r==`object`?(n.unref(),Z(`HTTP proxy listening on localhost:${r.port}`),e(r.port)):t(Error(`Failed to get proxy server address`))}),n.listen(0,`127.0.0.1`)})}async function Hfe(e){return kh=qde({filter:(t,n)=>dh(t,n,e),parentProxy:Ph}),new Promise((e,t)=>{if(!kh){t(Error(`SOCKS proxy server undefined before listen`));return}kh.listen(0,`127.0.0.1`).then(t=>{kh?.unref(),e(t)}).catch(t)})}async function Ufe(e,t,n=!1){if(jh){await jh;return}Dh=e,Ph=kp(e.network.parentProxy),Ph&&Z(`Parent proxy configured: http=${Lp(Ph.httpUrl)} https=${Lp(Ph.httpsUrl)}`);let r=ph();if(r.errors.length>0)throw Error(`Sandbox dependencies not available: ${r.errors.join(`, `)}`);n&&Tm()===`macos`&&(Nh=Lfe(Fh.addViolation.bind(Fh),Dh.ignoreViolations),Z(`Started macOS sandbox log monitor`)),zfe(),jh=(async()=>{try{let e;Dh.network.httpProxyPort===void 0?e=await Vfe(t):(e=Dh.network.httpProxyPort,Z(`Using external HTTP proxy on port ${e}`));let n;Dh.network.socksProxyPort===void 0?n=await Hfe(t):(n=Dh.network.socksProxyPort,Z(`Using external SOCKS proxy on port ${n}`));let r;Tm()===`linux`&&(r=await Efe(e,n));let i={httpProxyPort:e,socksProxyPort:n,linuxBridge:r};return Ah=i,Z(`Network infrastructure initialized`),i}catch(e){throw jh=void 0,Ah=void 0,Eh().catch(e=>{Z(`Cleanup failed in initializationPromise ${e}`,{level:`error`})}),e}})(),await jh}function fh(){let e=Tm();return e===`linux`?dfe()!==`1`:e===`macos`}function Wfe(){return Dh!==void 0}function ph(e){if(!fh())return{errors:[`Unsupported platform`],warnings:[]};let t=[],n=[],r=e??Dh?.ripgrep??{command:`rg`};if(Yp(r.command)===null&&t.push(`ripgrep (${r.command}) not found`),Tm()===`linux`){let e=Tfe(Dh?.seccomp);t.push(...e.errors),n.push(...e.warnings)}return{errors:t,warnings:n}}function Gfe(){if(!Dh)return{denyOnly:[],allowWithinDeny:[]};let e=[];for(let t of Dh.filesystem.denyRead){let n=jm(t);if(Tm()===`linux`&&Am(n)){let n=Rm(t);Z(`[Sandbox] Expanded glob pattern "${t}" to ${n.length} paths on Linux`),e.push(...n)}else e.push(n)}let t=[];for(let e of Dh.filesystem.allowRead??[]){let n=jm(e);if(Tm()===`linux`&&Am(n)){let n=Rm(e);Z(`[Sandbox] Expanded allowRead glob pattern "${e}" to ${n.length} paths on Linux`),t.push(...n)}else t.push(n)}return{denyOnly:e,allowWithinDeny:t}}function Kfe(){if(!Dh)return{allowOnly:Pm(),denyWithinAllow:[]};let e=Dh.filesystem.allowWrite.map(e=>jm(e)).filter(e=>Tm()===`linux`&&Am(e)?(Z(`Skipping glob pattern on Linux/WSL: ${e}`),!1):!0),t=Dh.filesystem.denyWrite.map(e=>jm(e)).filter(e=>Tm()===`linux`&&Am(e)?(Z(`Skipping glob pattern on Linux/WSL: ${e}`),!1):!0);return{allowOnly:[...Pm(),...e],denyWithinAllow:t}}function qfe(){if(!Dh)return{};let e=Dh.network.allowedDomains,t=Dh.network.deniedDomains;return{...e.length>0&&{allowedHosts:e},...t.length>0&&{deniedHosts:t}}}function mh(){return Dh?.network?.allowUnixSockets}function hh(){return Dh?.network?.allowAllUnixSockets}function gh(){return Dh?.network?.allowLocalBinding}function _h(){return Dh?.ignoreViolations}function vh(){return Dh?.enableWeakerNestedSandbox}function Jfe(){return Dh?.enableWeakerNetworkIsolation}function Yfe(){return Dh?.ripgrep??{command:`rg`}}function Xfe(){return Dh?.mandatoryDenySearchDepth??3}function yh(){return Dh?.filesystem?.allowGitConfig??!1}function Zfe(){return Dh?.seccomp}function bh(){return Ah?.httpProxyPort}function xh(){return Ah?.socksProxyPort}function Sh(){return Ah?.linuxBridge?.httpSocketPath}function Ch(){return Ah?.linuxBridge?.socksSocketPath}async function wh(){if(!Dh)return!1;if(jh)try{return await jh,!0}catch{return!1}return Ah!==void 0}async function Qfe(e,t,n,r){let i=Tm(),a=e=>e.map(e=>jm(e)).filter(e=>Tm()===`linux`&&Am(e)?(Z(`[Sandbox] Skipping glob write pattern on Linux: ${e}`),!1):!0),o=a(n?.filesystem?.allowWrite??Dh?.filesystem.allowWrite??[]),s={allowOnly:[...Pm(),...o],denyWithinAllow:a(n?.filesystem?.denyWrite??Dh?.filesystem.denyWrite??[])},c=n?.filesystem?.denyRead??Dh?.filesystem.denyRead??[],l=[];for(let e of c){let t=jm(e);Tm()===`linux`&&Am(t)?l.push(...Rm(e)):l.push(t)}let u=n?.filesystem?.allowRead??Dh?.filesystem.allowRead??[],d=[];for(let e of u){let t=jm(e);Tm()===`linux`&&Am(t)?d.push(...Rm(e)):d.push(t)}let f={denyOnly:l,allowWithinDeny:d},p=n?.network?.allowedDomains!==void 0||Dh?.network?.allowedDomains!==void 0,m=p,h=p;h&&await wh();let g=n?.allowPty??Dh?.allowPty;switch(i){case`macos`:return Ife({command:e,needsNetworkRestriction:m,httpProxyPort:h?bh():void 0,socksProxyPort:h?xh():void 0,readConfig:f,writeConfig:s,allowUnixSockets:mh(),allowAllUnixSockets:hh(),allowLocalBinding:gh(),ignoreViolations:_h(),allowPty:g,allowGitConfig:yh(),enableWeakerNetworkIsolation:Jfe(),binShell:t});case`linux`:return kfe({command:e,needsNetworkRestriction:m,httpSocketPath:h?Sh():void 0,socksSocketPath:h?Ch():void 0,httpProxyPort:h?Ah?.httpProxyPort:void 0,socksProxyPort:h?Ah?.socksProxyPort:void 0,readConfig:f,writeConfig:s,enableWeakerNestedSandbox:vh(),allowAllUnixSockets:hh(),binShell:t,ripgrepConfig:Yfe(),mandatoryDenySearchDepth:Xfe(),allowGitConfig:yh(),seccompConfig:Zfe(),abortSignal:r});default:throw Error(`Sandbox configuration is not supported on platform: ${i}`)}}function $fe(){return Dh}function epe(e){Dh=Gle(e),Ph=kp(e.network.parentProxy),Z(`Sandbox configuration updated`)}function Th(){Zm()}async function Eh(){if(Th(),Nh&&(Nh(),Nh=void 0),Ah?.linuxBridge){let{httpSocketPath:e,socksSocketPath:t,httpBridgeProcess:n,socksBridgeProcess:r}=Ah.linuxBridge,i=[];if(n.pid&&!n.killed)try{process.kill(n.pid,`SIGTERM`),Z(`Sent SIGTERM to HTTP bridge process`),i.push(new Promise(e=>{n.once(`exit`,()=>{Z(`HTTP bridge process exited`),e()}),setTimeout(()=>{if(!n.killed){Z(`HTTP bridge did not exit, forcing SIGKILL`,{level:`warn`});try{n.pid&&process.kill(n.pid,`SIGKILL`)}catch{}}e()},5e3)}))}catch(e){e.code!==`ESRCH`&&Z(`Error killing HTTP bridge: ${e}`,{level:`error`})}if(r.pid&&!r.killed)try{process.kill(r.pid,`SIGTERM`),Z(`Sent SIGTERM to SOCKS bridge process`),i.push(new Promise(e=>{r.once(`exit`,()=>{Z(`SOCKS bridge process exited`),e()}),setTimeout(()=>{if(!r.killed){Z(`SOCKS bridge did not exit, forcing SIGKILL`,{level:`warn`});try{r.pid&&process.kill(r.pid,`SIGKILL`)}catch{}}e()},5e3)}))}catch(e){e.code!==`ESRCH`&&Z(`Error killing SOCKS bridge: ${e}`,{level:`error`})}if(await Promise.all(i),e)try{Ec.rmSync(e,{force:!0}),Z(`Cleaned up HTTP socket`)}catch(e){Z(`HTTP socket cleanup error: ${e}`,{level:`error`})}if(t)try{Ec.rmSync(t,{force:!0}),Z(`Cleaned up SOCKS socket`)}catch(e){Z(`SOCKS socket cleanup error: ${e}`,{level:`error`})}}let e=[];if(Oh){let t=Oh,n=new Promise(e=>{t.close(t=>{t&&t.message!==`Server is not running.`&&Z(`Error closing HTTP proxy server: ${t.message}`,{level:`error`}),e()})});e.push(n)}if(kh){let t=kh.close().catch(e=>{Z(`Error closing SOCKS proxy server: ${e.message}`,{level:`error`})});e.push(t)}await Promise.all(e),Oh=void 0,kh=void 0,Ah=void 0,jh=void 0,Ph=void 0}function tpe(){return Fh}function npe(e,t){if(!Dh)return t;let n=Fh.getViolationsForCommand(e);if(n.length===0)return t;let r=t;r+=Nc+`<sandbox_violations>`+Nc;for(let e of n)r+=e.line+Nc;return r+=`</sandbox_violations>`,r}function rpe(){if(Tm()!==`linux`||!Dh)return[];let e=[],t=[...Dh.filesystem.allowWrite,...Dh.filesystem.denyWrite];for(let n of t)Am(jm(n))&&e.push(n);return e}var Dh,Oh,kh,Ah,jh,Mh,Nh,Ph,Fh,Ih,ipe=n((()=>{Wde(),Jde(),Op(),Xp(),wm(),Em(),Afe(),Rfe(),Vm(),lh(),Up(),Mh=!1,Fh=new ch,Ih={initialize:Ufe,isSupportedPlatform:fh,isSandboxingEnabled:Wfe,checkDependencies:ph,getFsReadConfig:Gfe,getFsWriteConfig:Kfe,getNetworkRestrictionConfig:qfe,getAllowUnixSockets:mh,getAllowLocalBinding:gh,getIgnoreViolations:_h,getEnableWeakerNestedSandbox:vh,getProxyPort:bh,getSocksProxyPort:xh,getLinuxHttpSocketPath:Sh,getLinuxSocksSocketPath:Ch,waitForNetworkInitialization:wh,wrapWithSandbox:Qfe,cleanupAfterCommand:Th,reset:Eh,getSandboxViolationStore:tpe,annotateStderrWithSandboxFailures:npe,getLinuxGlobPatternWarnings:rpe,getConfig:$fe,updateConfig:epe}})),Lh,Rh,zh,Bh,Vh,Hh,Uh,Wh,Gh,ape=n((()=>{N(),Lh=j().refine(e=>{if(e.includes(`://`)||e.includes(`/`)||e.includes(`:`))return!1;if(e===`localhost`)return!0;if(e.startsWith(`*.`)){let t=e.slice(2);if(!t.includes(`.`)||t.startsWith(`.`)||t.endsWith(`.`))return!1;let n=t.split(`.`);return n.length>=2&&n.every(e=>e.length>0)}return!e.includes(`*`)&&e.includes(`.`)&&!e.startsWith(`.`)&&!e.endsWith(`.`)},{message:`Invalid domain pattern. Must be a valid domain (e.g., "example.com") or wildcard (e.g., "*.example.com"). Overly broad patterns like "*.com" or "*" are not allowed for security reasons.`}),Rh=j().min(1,`Path cannot be empty`),zh=se({socketPath:j().min(1).describe(`Unix socket path to the MITM proxy`),domains:M(Lh).min(1).describe(`Domains to route through the MITM proxy (e.g., ["api.example.com", "*.internal.org"])`)}),Bh=se({http:j().url().optional().describe(`Upstream proxy URL for plain HTTP traffic`),https:j().url().optional().describe(`Upstream proxy URL for HTTPS/CONNECT traffic (falls back to http if unset)`),noProxy:j().optional().describe(`Comma-separated NO_PROXY list (hostname suffixes and CIDR ranges). Matching destinations connect directly instead of via the parent proxy.`)}),Vh=se({allowedDomains:M(Lh).describe(`List of allowed domains (e.g., ["github.com", "*.npmjs.org"])`),deniedDomains:M(Lh).describe(`List of denied domains`),allowUnixSockets:M(j()).optional().describe(`macOS only: Unix socket paths to allow. Ignored on Linux (seccomp cannot filter by path).`),allowAllUnixSockets:oe().optional().describe(`If true, allow all Unix sockets (disables blocking on both platforms).`),allowLocalBinding:oe().optional().describe(`Whether to allow binding to local ports (default: false)`),httpProxyPort:ae().int().min(1).max(65535).optional().describe(`Port of an external HTTP proxy to use instead of starting a local one. When provided, the library will skip starting its own HTTP proxy and use this port. The external proxy must handle domain filtering.`),socksProxyPort:ae().int().min(1).max(65535).optional().describe(`Port of an external SOCKS proxy to use instead of starting a local one. When provided, the library will skip starting its own SOCKS proxy and use this port. The external proxy must handle domain filtering.`),mitmProxy:zh.optional().describe(`Optional MITM proxy configuration. Routes matching domains through an upstream proxy via Unix socket while SRT still handles allow/deny filtering.`),parentProxy:Bh.optional().describe(`Upstream HTTP proxy for outbound connections. When set, SRT's proxy tunnels non-mitmProxy traffic through this parent instead of connecting directly. Falls back to HTTP_PROXY/HTTPS_PROXY/NO_PROXY env vars if unset.`)}),Hh=se({denyRead:M(Rh).describe(`Paths denied for reading`),allowRead:M(Rh).optional().describe(`Paths to re-allow reading within denied regions (takes precedence over denyRead). Use with denyRead to deny a broad region then allow back specific subdirectories.`),allowWrite:M(Rh).describe(`Paths allowed for writing`),denyWrite:M(Rh).describe(`Paths denied for writing (takes precedence over allowWrite)`),allowGitConfig:oe().optional().describe(`Allow writes to .git/config files (default: false). Enables git remote URL updates while keeping .git/hooks protected.`)}),Uh=le(j(),M(j())).describe(`Map of command patterns to filesystem paths to ignore violations for. Use "*" to match all commands`),Wh=se({command:j().describe(`The ripgrep command to execute`),args:M(j()).optional().describe(`Additional arguments to pass before ripgrep args`),argv0:j().optional().describe(`Override argv[0] when spawning (for multicall binaries that dispatch on argv[0])`)}),Gh=se({bpfPath:j().optional().describe(`Path to the unix-block.bpf filter file`),applyPath:j().optional().describe(`Path to the apply-seccomp binary`)}),se({network:Vh.describe(`Network restrictions configuration`),filesystem:Hh.describe(`Filesystem restrictions configuration`),ignoreViolations:Uh.optional().describe(`Optional configuration for ignoring specific violations`),enableWeakerNestedSandbox:oe().optional().describe(`Enable weaker nested sandbox mode (for Docker environments)`),enableWeakerNetworkIsolation:oe().optional().describe(`Enable weaker network isolation to allow access to com.apple.trustd.agent (macOS only). This is needed for Go programs (gh, gcloud, terraform, kubectl, etc.) to verify TLS certificates when using httpProxyPort with a MITM proxy and custom CA. Enabling this opens a potential data exfiltration vector through the trustd service. Only enable if you need Go TLS verification.`),ripgrep:Wh.optional().describe(`Custom ripgrep configuration (default: { command: "rg" })`),mandatoryDenySearchDepth:ae().int().min(1).max(10).optional().describe(`Maximum directory depth to search for dangerous files on Linux (default: 3). Higher values provide more protection but slower performance.`),allowPty:oe().optional().describe(`Allow pseudo-terminal (pty) operations (macOS only)`),seccomp:Gh.optional().describe(`Custom seccomp binary paths (Linux only).`)})})),ope=n((()=>{ipe(),lh(),ape(),Vm(),Em()}));async function spe(){if(ag||og)return;ag=!0,dpe(),Oi(Kh);let{dirs:e,settingsFiles:t,dropInDir:n}=await cpe();og||e.length!==0&&(K(`Watching for changes in setting files ${[...t].join(`, `)}...${n?` and drop-in directory ${n}`:``}`),ng=poe.watch(e,{persistent:!0,ignoreInitial:!0,depth:0,awaitWriteFinish:{stabilityThreshold:Zh,pollInterval:Qh},ignored:(e,r)=>{if(r&&!r.isFile()&&!r.isDirectory()||e.split(uc.sep).some(e=>e===`.git`))return!0;if(!r||r.isDirectory())return!1;let i=uc.normalize(e);return!(t.has(i)||n&&i.startsWith(n+uc.sep)&&i.endsWith(`.json`))},ignorePermissionErrors:!0,usePolling:!1,atomic:!0}),ng.on(`change`,Jh),ng.on(`unlink`,upe),ng.on(`add`,lpe))}function Kh(){og=!0,rg&&(clearInterval(rg),rg=null);for(let e of sg.values())clearTimeout(e);sg.clear(),ig=null,gte(),cg.clear();let e=ng;return ng=null,e?e.close():Promise.resolve()}async function cpe(){let e=new Map,t=new Set;for(let n of tr){if(n===`flagSettings`)continue;let r=Vn(n);if(!r)continue;let i=uc.dirname(r);e.has(i)||e.set(i,new Set),e.get(i).add(r);try{(await Yc(r)).isFile()&&t.add(i)}catch{}}let n=new Set;for(let r of t){let t=e.get(r);if(t)for(let e of t)n.add(e)}let r=null,i=zn();try{(await Yc(i)).isDirectory()&&(t.add(i),r=i)}catch{}return{dirs:[...t],settingsFiles:n,dropInDir:r}}function qh(e){switch(e){case`userSettings`:return`user_settings`;case`projectSettings`:return`project_settings`;case`localSettings`:return`local_settings`;case`flagSettings`:case`policySettings`:return`policy_settings`}}function Jh(e){let t=Yh(e);if(!t)return;let n=sg.get(e);n&&(clearTimeout(n),sg.delete(e),K(`Cancelled pending deletion of ${e} — file was recreated`)),!$ee(e,$h)&&(K(`Detected change to ${e}`),u7(qh(t),e).then(n=>{if(i7(n)){K(`ConfigChange hook blocked change to ${e}`);return}Xh(t)}))}function lpe(e){if(!Yh(e))return;let t=sg.get(e);t&&(clearTimeout(t),sg.delete(e),K(`Cancelled pending deletion of ${e} — file was re-added`)),Jh(e)}function upe(e){let t=Yh(e);if(!t||(K(`Detected deletion of ${e}`),sg.has(e)))return;let n=setTimeout((e,t)=>{sg.delete(e),u7(qh(t),e).then(n=>{if(i7(n)){K(`ConfigChange hook blocked deletion of ${e}`);return}Xh(t)})},tg,e,t);sg.set(e,n)}function Yh(e){let t=uc.normalize(e),n=zn();return t.startsWith(n+uc.sep)?`policySettings`:tr.find(e=>Vn(e)===t)}function dpe(){let e=Ree(),t=Gte();ig=W({mdm:e.settings,hkcu:t.settings}),rg=setInterval(()=>{og||(async()=>{try{let{mdm:e,hkcu:t}=await Hte();if(og)return;let n=W({mdm:e.settings,hkcu:t.settings});n!==ig&&(ig=n,Vee(e,t),K(`Detected MDM settings change via poll`),Xh(`policySettings`))}catch(e){K(`MDM poll error: ${G(e)}`)}})()},eg),rg.unref()}function Xh(e){xr(),cg.emit(e)}function fpe(e){K(`Programmatic settings change notification for ${e}`),Xh(e)}var Zh,Qh,$h,eg,tg,ng,rg,ig,ag,og,sg,cg,lg,ug,dg=n((()=>{loe(),di(),q(),gi(),_7(),Ir(),Li(),Rn(),jte(),Zn(),hee(),Ln(),zr(),Zh=1e3,Qh=500,$h=5e3,eg=1800*1e3,tg=1700,ng=null,rg=null,ig=null,ag=!1,og=!1,sg=new Map,cg=jr(),lg=cg.subscribe,ug={initialize:spe,dispose:Kh,subscribe:lg,notifyChange:fpe}}));function fg(e){let t=e.match(/^([^(]+)\(([^)]+)\)$/);if(!t)return{toolName:e};let n=t[1],r=t[2];return!n||!r?{toolName:e}:{toolName:n,ruleContent:r}}function ppe(e){return e.match(/^(.+):\*$/)?.[1]??null}function pg(e,t){return e.startsWith(`//`)?e.slice(1):e.startsWith(`/`)&&!e.startsWith(`//`)?yc(gn(t),e.slice(1)):e}function mg(e,t){return e.startsWith(`//`)?e.slice(1):xn(e,gn(t))}function hg(){return $n(`policySettings`)?.sandbox?.network?.allowManagedDomainsOnly===!0}function mpe(){return $n(`policySettings`)?.sandbox?.filesystem?.allowManagedReadPathsOnly===!0}function gg(e){let t=e.permissions||{},n=[],r=[];if(hg()){let e=$n(`policySettings`);for(let t of e?.sandbox?.network?.allowedDomains||[])n.push(t)}else for(let t of e.sandbox?.network?.allowedDomains||[])n.push(t);for(let e of t.deny||[]){let t=fg(e);t.ruleContent?.startsWith(`domain:`)&&r.push(t.ruleContent.substring(7))}let i=[`.`,R8()],a=[],o=[],s=[],c=tr.map(e=>Vn(e)).filter(e=>e!==void 0);a.push(...c),a.push(zn());let l=Vr(),u=ti();l!==u&&(a.push(yc(l,`.workmate`,`settings.json`)),a.push(yc(l,`.workmate`,`settings.local.json`))),a.push(yc(u,`.workmate`,`skills`)),l!==u&&a.push(yc(l,`.workmate`,`skills`)),Cg.length=0;let d=[`HEAD`,`objects`,`refs`,`hooks`,`config`];for(let e of l===u?[u]:[u,l])for(let t of d){let n=yc(e,t);try{zse(n),a.push(n)}catch{Cg.push(n)}}Sg&&Sg!==l&&i.push(Sg);let f=new Set([...e.permissions?.additionalDirectories||[],...Zr()]);i.push(...f);for(let e of tr){let t=$n(e);if(t?.permissions){for(let n of t.permissions.allow||[]){let t=fg(n);t.toolName===`Edit`&&t.ruleContent&&i.push(pg(t.ruleContent,e))}for(let n of t.permissions.deny||[]){let t=fg(n);t.toolName===`Edit`&&t.ruleContent&&a.push(pg(t.ruleContent,e)),t.toolName===`Read`&&t.ruleContent&&o.push(pg(t.ruleContent,e))}}let n=t?.sandbox?.filesystem;if(n){for(let t of n.allowWrite||[])i.push(mg(t,e));for(let t of n.denyWrite||[])a.push(mg(t,e));for(let t of n.denyRead||[])o.push(mg(t,e));if(!mpe()||e===`policySettings`)for(let t of n.allowRead||[])s.push(mg(t,e))}}let{rgPath:p,rgArgs:m,argv0:h}=Ks(),g=e.sandbox?.ripgrep??{command:p,args:m,argv0:h};return{network:{allowedDomains:n,deniedDomains:r,allowUnixSockets:e.sandbox?.network?.allowUnixSockets,allowAllUnixSockets:e.sandbox?.network?.allowAllUnixSockets,allowLocalBinding:e.sandbox?.network?.allowLocalBinding,httpProxyPort:e.sandbox?.network?.httpProxyPort,socksProxyPort:e.sandbox?.network?.socksProxyPort},filesystem:{denyRead:o,allowRead:s,allowWrite:i,denyWrite:a},ignoreViolations:e.sandbox?.ignoreViolations,enableWeakerNestedSandbox:e.sandbox?.enableWeakerNestedSandbox,enableWeakerNetworkIsolation:e.sandbox?.enableWeakerNetworkIsolation,ripgrep:g}}function hpe(){for(let e of Cg)try{Rse(e,{recursive:!0}),K(`[Sandbox] scrubbed planted bare-repo file: ${e}`)}catch{}}async function gpe(e){let t=X(e,`.git`);try{let n=(await Wc(t,{encoding:`utf8`})).match(/^gitdir:\s*(.+)$/m);if(!n?.[1])return null;let r=yc(e,n[1].trim()),i=`${bc}.git${bc}worktrees${bc}`,a=r.lastIndexOf(i);return a>0?r.substring(0,a):null}catch{return null}}function _g(){try{return yn()?.sandbox?.enabled??!1}catch(e){return K(`Failed to get settings for sandbox check: ${e}`),!1}}function _pe(){return yn()?.sandbox?.autoAllowBashIfSandboxed??!0}function vpe(){return yn()?.sandbox?.allowUnsandboxedCommands??!0}function ype(){let e=yn();return _g()&&(e?.sandbox?.failIfUnavailable??!1)}function vg(){try{let e=rr()?.sandbox?.enabledPlatforms;if(e===void 0)return!0;if(e.length===0)return!1;let t=Ma();return e.includes(t)}catch(e){return K(`Failed to check enabledPlatforms: ${e}`),!0}}function yg(){return!Tg()||wg().errors.length>0||!vg()?!1:_g()}function bpe(){if(!_g())return;if(!Tg()){let e=Ma();return e===`wsl`?`sandbox.enabled is set but WSL1 is not supported (requires WSL2)`:`sandbox.enabled is set but ${e} is not supported (requires macOS, Linux, or WSL2)`}if(!vg())return`sandbox.enabled is set but ${Ma()} is not in sandbox.enabledPlatforms`;let e=wg();if(e.errors.length>0){let t=Ma()===`macos`?`run /sandbox or /doctor for details`:`install missing tools (e.g. apt install bubblewrap socat) or run /sandbox for details`;return`sandbox.enabled is set but dependencies are missing: ${e.errors.join(`, `)} · ${t}`}}function xpe(){let e=Ma();if(e!==`linux`&&e!==`wsl`)return[];try{let e=yn();if(!e?.sandbox?.enabled)return[];let t=e?.permissions||{},n=[],r=e=>{let t=e.replace(/\/\*\*$/,``);return/[*?[\]]/.test(t)};for(let e of[...t.allow||[],...t.deny||[]]){let t=fg(e);(t.toolName===`Edit`||t.toolName===`Read`)&&t.ruleContent&&r(t.ruleContent)&&n.push(e)}return n}catch(e){return K(`Failed to get Linux glob pattern warnings: ${e}`),[]}}function Spe(){for(let e of[`flagSettings`,`policySettings`]){let t=$n(e);if(t?.sandbox?.enabled!==void 0||t?.sandbox?.autoAllowBashIfSandboxed!==void 0||t?.sandbox?.allowUnsandboxedCommands!==void 0)return!0}return!1}async function Cpe(e){gr(`localSettings`,{sandbox:{...$n(`localSettings`)?.sandbox,...e.enabled!==void 0&&{enabled:e.enabled},...e.autoAllowBashIfSandboxed!==void 0&&{autoAllowBashIfSandboxed:e.autoAllowBashIfSandboxed},...e.allowUnsandboxedCommands!==void 0&&{allowUnsandboxedCommands:e.allowUnsandboxedCommands}}})}function wpe(){return yn()?.sandbox?.excludedCommands??[]}async function Tpe(e,t,n,r){if(yg())if(bg)await bg;else throw Error(`Sandbox failed to initialize. `);return Ih.wrapWithSandbox(e,t,n,r)}async function Epe(e){if(bg)return bg;if(!yg())return;let t=e?async t=>hg()?(K(`[sandbox] Blocked network request to ${t.host} (allowManagedDomainsOnly)`),!1):e(t):void 0;return bg=(async()=>{try{Sg===void 0&&(Sg=await gpe(Vr()));let e=gg(yn());await Ih.initialize(e,t),xg=ug.subscribe(()=>{let e=gg(yn());Ih.updateConfig(e),K(`Sandbox configuration updated from settings change`)})}catch(e){bg=void 0,K(`Failed to initialize sandbox: ${G(e)}`)}})(),bg}function Dpe(){if(!yg())return;let e=gg(yn());Ih.updateConfig(e)}async function Ope(){return xg?.(),xg=void 0,Sg=void 0,Cg.length=0,wg.cache.clear?.(),Tg.cache.clear?.(),bg=void 0,Ih.reset()}function kpe(e,t){let n=$n(`localSettings`),r=n?.sandbox?.excludedCommands||[],i=e;if(t){let e=t.filter(e=>e.type===`addRules`&&e.rules.some(e=>e.toolName===`Bash`));if(e.length>0&&e[0].type===`addRules`){let t=e[0].rules.find(e=>e.toolName===ks);t?.ruleContent&&(i=ppe(t.ruleContent)||t.ruleContent)}}return r.includes(i)||gr(`localSettings`,{sandbox:{...n?.sandbox,excludedCommands:[...r,i]}}),i}var bg,xg,Sg,Cg,wg,Tg,Eg,Dg=n((()=>{ope(),wm(),H(),q(),Wn(),Pa(),dg(),Rn(),Zn(),Ln(),ys(),Es(),As(),gi(),B8(),Gs(),Cg=[],wg=u(()=>{let{rgPath:e,rgArgs:t}=Ks();return Ih.checkDependencies({command:e,args:t})}),Tg=u(()=>Ih.isSupportedPlatform()),Eg={initialize:Epe,isSandboxingEnabled:yg,isSandboxEnabledInSettings:_g,isPlatformInEnabledList:vg,getSandboxUnavailableReason:bpe,isAutoAllowBashIfSandboxedEnabled:_pe,areUnsandboxedCommandsAllowed:vpe,isSandboxRequired:ype,areSandboxSettingsLockedByPolicy:Spe,setSandboxSettings:Cpe,getExcludedCommands:wpe,wrapWithSandbox:Tpe,refreshConfig:Dpe,reset:Ope,checkDependencies:wg,getFsReadConfig:Ih.getFsReadConfig,getFsWriteConfig:Ih.getFsWriteConfig,getNetworkRestrictionConfig:Ih.getNetworkRestrictionConfig,getIgnoreViolations:Ih.getIgnoreViolations,getLinuxGlobPatternWarnings:xpe,isSupportedPlatform:Tg,getAllowUnixSockets:Ih.getAllowUnixSockets,getAllowLocalBinding:Ih.getAllowLocalBinding,getEnableWeakerNestedSandbox:Ih.getEnableWeakerNestedSandbox,getProxyPort:Ih.getProxyPort,getSocksProxyPort:Ih.getSocksProxyPort,getLinuxHttpSocketPath:Ih.getLinuxHttpSocketPath,getLinuxSocksSocketPath:Ih.getLinuxSocksSocketPath,waitForNetworkInitialization:Ih.waitForNetworkInitialization,getSandboxViolationStore:Ih.getSandboxViolationStore,annotateStderrWithSandboxFailures:Ih.annotateStderrWithSandboxFailures,cleanupAfterCommand:()=>{Ih.cleanupAfterCommand(),hpe()}}})),Og,Ape=n((()=>{ne(),Dg(),Og={name:`sandbox`,get description(){let e=Eg.isSandboxingEnabled(),t=Eg.isAutoAllowBashIfSandboxedEnabled(),n=Eg.areUnsandboxedCommandsAllowed(),r=Eg.areSandboxSettingsLockedByPolicy(),i=Eg.checkDependencies().errors.length===0,a;a=i?e?ie.tick:ie.circle:ie.warning;let o=`sandbox disabled`;return e&&(o=t?`sandbox enabled (auto-allow)`:`sandbox enabled`,o+=n?`, fallback allowed`:``),r&&(o+=` (managed)`),`${a} ${o} (⏎ to configure)`},argumentHint:`exclude "command pattern"`,get isHidden(){return!Eg.isSupportedPlatform()||!Eg.isPlatformInEnabledList()},immediate:!0,type:`local-jsx`,load:()=>import(`./sandbox-toggle-Dt4lDgnB.js`)}})),kg,Ag,jg,Mg=n((()=>{d(),mo(),kg=[{modelEnvVar:`ANTHROPIC_DEFAULT_OPUS_MODEL`,capabilitiesEnvVar:`ANTHROPIC_DEFAULT_OPUS_MODEL_SUPPORTED_CAPABILITIES`},{modelEnvVar:`ANTHROPIC_DEFAULT_SONNET_MODEL`,capabilitiesEnvVar:`ANTHROPIC_DEFAULT_SONNET_MODEL_SUPPORTED_CAPABILITIES`},{modelEnvVar:`ANTHROPIC_DEFAULT_HAIKU_MODEL`,capabilitiesEnvVar:`ANTHROPIC_DEFAULT_HAIKU_MODEL_SUPPORTED_CAPABILITIES`}],Ag=[{modelEnvVar:`OPENAI_DEFAULT_OPUS_MODEL`,capabilitiesEnvVar:`OPENAI_DEFAULT_OPUS_MODEL_SUPPORTED_CAPABILITIES`},{modelEnvVar:`OPENAI_DEFAULT_SONNET_MODEL`,capabilitiesEnvVar:`OPENAI_DEFAULT_SONNET_MODEL_SUPPORTED_CAPABILITIES`},{modelEnvVar:`OPENAI_DEFAULT_HAIKU_MODEL`,capabilitiesEnvVar:`OPENAI_DEFAULT_HAIKU_MODEL_SUPPORTED_CAPABILITIES`}],jg=u((e,t)=>{if(lo()===`firstParty`)return;let n=e.toLowerCase(),r=lo()===`openai`?Ag:kg;for(let e of r){let r=process.env[e.modelEnvVar],i=process.env[e.capabilitiesEnvVar];if(!(!r||i===void 0)&&n===r.toLowerCase())return i.toLowerCase().split(`,`).map(e=>e.trim()).includes(t)}},(e,t)=>`${e.toLowerCase()}:${t}`)}));function jpe(e){let t=[],n=[];for(let r of e)Bg.includes(r)?t.push(r):n.push(r);return{allowed:t,disallowed:n}}function Mpe(e){if(!e||e.length===0)return;let{allowed:t,disallowed:n}=jpe(e);for(let e of n)console.warn(`Warning: Beta header '${e}' is not allowed. Only the following betas are supported: ${Bg.join(`, `)}`);return t.length>0?t:void 0}function Ng(e){let t=jg(e,`interleaved_thinking`);if(t!==void 0)return t;let n=Mo(e),r=lo();return r===`foundry`?!0:r===`firstParty`?!n.includes(`claude-3-`):n.includes(`claude-opus-4`)||n.includes(`claude-sonnet-4`)}function Pg(e){let t=Mo(e),n=lo();return n===`foundry`?!0:n===`firstParty`?!t.includes(`claude-3-`):t.includes(`claude-opus-4`)||t.includes(`claude-sonnet-4`)||t.includes(`claude-haiku-4`)}function Fg(e){let t=Mo(e),n=lo();return n!==`firstParty`&&n!==`foundry`?!1:t.includes(`claude-sonnet-4-6`)||t.includes(`claude-sonnet-4-5`)||t.includes(`claude-opus-4-1`)||t.includes(`claude-opus-4-5`)||t.includes(`claude-opus-4-6`)||t.includes(`claude-opus-4-7`)||t.includes(`claude-haiku-4-5`)}function Ig(e){return!0}function Lg(){return(lo()===`firstParty`||lo()===`foundry`)&&!h(process.env.WORKMATE_DISABLE_EXPERIMENTAL_BETAS)&&ao()}function Rg(){return lo()===`firstParty`&&!h(process.env.WORKMATE_DISABLE_EXPERIMENTAL_BETAS)}function zg(e,t){let n=[...Hg(e)];t?.isAgenticQuery&&(n.includes(`workmate-20250219`)||n.push(no));let r=ni();return!r||r.length===0?n:[...n,...r.filter(e=>!n.includes(e))]}var Bg,Vg,Hg,Ug,Wg=n((()=>{d(),H(),po(),yo(),g(),wo(),Mg(),mo(),Ln(),Bg=[Ho],Vg=u(e=>{let t=[],n=Mo(e).includes(`haiku`);lo();let r=Lg();n||t.push(no),Pie(e)&&t.push(Ho),!h(process.env.DISABLE_INTERLEAVED_THINKING)&&Ng(e)&&t.push(Vie),r&&Ng(e)&&!kr()&&rr().showThinkingSummaries!==!0&&t.push(to);let i=h(process.env.USE_API_CONTEXT_MANAGEMENT)||Pg(e),a=Pg(e);return Lg()&&(i||a)&&t.push(Hie),r&&Fg(e),r&&t.push(ho),process.env.ANTHROPIC_BETAS&&t.push(...process.env.ANTHROPIC_BETAS.split(`,`).map(e=>e.trim()).filter(Boolean)),t}),Hg=u(e=>{let t=Vg(e);return lo()===`bedrock`?t.filter(e=>!vo.has(e)):t}),Ug=u(e=>Vg(e).filter(e=>vo.has(e)))}));function Gg(e){return e.type===`advisor_tool_result`||e.type===`server_tool_use`&&e.name===`advisor`}function Kg(){return{}}function qg(){return h(process.env.WORKMATE_DISABLE_ADVISOR_TOOL)||!Lg()?!1:Kg().enabled??!1}function Jg(){return qg()&&(Kg().canUserConfigure??!1)}function Npe(){let e=Kg();return qg()&&!Jg()&&e.baseModel&&e.advisorModel?{baseModel:e.baseModel,advisorModel:e.advisorModel}:void 0}function Yg(e){let t=e.toLowerCase();return t.includes(`opus-4-7`)||t.includes(`opus-4-6`)||t.includes(`sonnet-4-6`)}function Xg(e){let t=e.toLowerCase();return t.includes(`opus-4-7`)||t.includes(`opus-4-6`)||t.includes(`sonnet-4-6`)}function Ppe(){if(qg())return rr().advisorModel}function Fpe(e){let t=e.iterations;return t?t.filter(e=>e.type===`advisor_message`):[]}var Zg,Qg=n((()=>{Wg(),g(),Ln(),Zg=`# Advisor Tool
415
+ `),c=s.find(e=>e.includes(`Sandbox:`)&&e.includes(`deny`)),l=s.find(e=>e.startsWith(`CMD64_`));if(!c)return;let u=c.match(r);if(!u?.[1])return;let d=u[1],f,p;if(l&&(p=l.match(n)?.[1],p))try{f=gfe(p)}catch{}if(!(d.includes(`mDNSResponder`)||d.includes(`mach-lookup com.apple.diagnosticd`)||d.includes(`mach-lookup com.apple.analyticsd`))){if(t&&f){if(i.length>0&&i.some(e=>d.includes(e)))return;for(let[e,t]of a)if(f.includes(e)&&t.some(e=>d.includes(e)))return}e({line:d,command:f,encodedCommand:p,timestamp:new Date})}}),o.stderr?.on(`data`,e=>{Z(`[Sandbox Monitor] Log stream stderr: ${e.toString()}`)}),o.on(`error`,e=>{Z(`[Sandbox Monitor] Failed to start log stream: ${e.message}`)}),o.on(`exit`,e=>{Z(`[Sandbox Monitor] Log stream exited with code: ${e}`)}),()=>{Z(`[Sandbox Monitor] Stopping log monitor`),o.kill(`SIGTERM`)}}var oh,sh,Rfe=n((()=>{oh=r(Dm(),1),Op(),Xp(),Vm(),sh=`_${Math.random().toString(36).slice(2,11)}_SBX`})),ch,lh=n((()=>{Vm(),ch=class{constructor(){this.violations=[],this.totalCount=0,this.maxSize=100,this.listeners=new Set}addViolation(e){this.violations.push(e),this.totalCount++,this.violations.length>this.maxSize&&(this.violations=this.violations.slice(-this.maxSize)),this.notifyListeners()}getViolations(e){return e===void 0?[...this.violations]:this.violations.slice(-e)}getCount(){return this.violations.length}getTotalCount(){return this.totalCount}getViolationsForCommand(e){let t=Im(e);return this.violations.filter(e=>e.encodedCommand===t)}clear(){this.violations=[],this.notifyListeners()}subscribe(e){return this.listeners.add(e),e(this.getViolations()),()=>{this.listeners.delete(e)}}notifyListeners(){let e=this.getViolations();this.listeners.forEach(t=>t(e))}}}));function zfe(){if(Mh)return;let e=()=>Eh().catch(e=>{Z(`Cleanup failed in registerCleanup ${e}`,{level:`error`})});process.once(`exit`,e),process.once(`SIGINT`,e),process.once(`SIGTERM`,e),Mh=!0}function uh(e,t){let n=e.toLowerCase();if(t.startsWith(`*.`)){if(ol(Ip(n)))return!1;let e=t.substring(2).toLowerCase();return n.endsWith(`.`+e)}return n===t.toLowerCase()}async function dh(e,t,n){if(!Dh)return Z(`No config available, denying network request`),!1;if(!Rp(t))return Z(`Denying malformed host: ${JSON.stringify(t)}:${e}`,{level:`error`}),!1;let r=Vde(t)??t;for(let n of Dh.network.deniedDomains)if(uh(r,n))return Z(`Denied by config rule: ${t}:${e}`),!1;for(let n of Dh.network.allowedDomains)if(uh(r,n))return Z(`Allowed by config rule: ${t}:${e}`),!0;if(!n)return Z(`No matching config rule, denying: ${t}:${e}`),!1;Z(`No matching config rule, asking user: ${t}:${e}`);try{return await n({host:t,port:e})?(Z(`User allowed: ${t}:${e}`),!0):(Z(`User denied: ${t}:${e}`),!1)}catch(e){return Z(`Error in permission callback: ${e}`,{level:`error`}),!1}}function Bfe(e){if(!Dh?.network.mitmProxy)return;let{socketPath:t,domains:n}=Dh.network.mitmProxy;for(let r of n)if(uh(e,r))return Z(`Host ${e} matches MITM pattern ${r}`),t}async function Vfe(e){return Oh=Hde({filter:(t,n)=>dh(t,n,e),getMitmSocketPath:Bfe,parentProxy:Ph}),new Promise((e,t)=>{if(!Oh){t(Error(`HTTP proxy server undefined before listen`));return}let n=Oh;n.once(`error`,t),n.once(`listening`,()=>{let r=n.address();r&&typeof r==`object`?(n.unref(),Z(`HTTP proxy listening on localhost:${r.port}`),e(r.port)):t(Error(`Failed to get proxy server address`))}),n.listen(0,`127.0.0.1`)})}async function Hfe(e){return kh=qde({filter:(t,n)=>dh(t,n,e),parentProxy:Ph}),new Promise((e,t)=>{if(!kh){t(Error(`SOCKS proxy server undefined before listen`));return}kh.listen(0,`127.0.0.1`).then(t=>{kh?.unref(),e(t)}).catch(t)})}async function Ufe(e,t,n=!1){if(jh){await jh;return}Dh=e,Ph=kp(e.network.parentProxy),Ph&&Z(`Parent proxy configured: http=${Lp(Ph.httpUrl)} https=${Lp(Ph.httpsUrl)}`);let r=ph();if(r.errors.length>0)throw Error(`Sandbox dependencies not available: ${r.errors.join(`, `)}`);n&&Tm()===`macos`&&(Nh=Lfe(Fh.addViolation.bind(Fh),Dh.ignoreViolations),Z(`Started macOS sandbox log monitor`)),zfe(),jh=(async()=>{try{let e;Dh.network.httpProxyPort===void 0?e=await Vfe(t):(e=Dh.network.httpProxyPort,Z(`Using external HTTP proxy on port ${e}`));let n;Dh.network.socksProxyPort===void 0?n=await Hfe(t):(n=Dh.network.socksProxyPort,Z(`Using external SOCKS proxy on port ${n}`));let r;Tm()===`linux`&&(r=await Efe(e,n));let i={httpProxyPort:e,socksProxyPort:n,linuxBridge:r};return Ah=i,Z(`Network infrastructure initialized`),i}catch(e){throw jh=void 0,Ah=void 0,Eh().catch(e=>{Z(`Cleanup failed in initializationPromise ${e}`,{level:`error`})}),e}})(),await jh}function fh(){let e=Tm();return e===`linux`?dfe()!==`1`:e===`macos`}function Wfe(){return Dh!==void 0}function ph(e){if(!fh())return{errors:[`Unsupported platform`],warnings:[]};let t=[],n=[],r=e??Dh?.ripgrep??{command:`rg`};if(Yp(r.command)===null&&t.push(`ripgrep (${r.command}) not found`),Tm()===`linux`){let e=Tfe(Dh?.seccomp);t.push(...e.errors),n.push(...e.warnings)}return{errors:t,warnings:n}}function Gfe(){if(!Dh)return{denyOnly:[],allowWithinDeny:[]};let e=[];for(let t of Dh.filesystem.denyRead){let n=jm(t);if(Tm()===`linux`&&Am(n)){let n=Rm(t);Z(`[Sandbox] Expanded glob pattern "${t}" to ${n.length} paths on Linux`),e.push(...n)}else e.push(n)}let t=[];for(let e of Dh.filesystem.allowRead??[]){let n=jm(e);if(Tm()===`linux`&&Am(n)){let n=Rm(e);Z(`[Sandbox] Expanded allowRead glob pattern "${e}" to ${n.length} paths on Linux`),t.push(...n)}else t.push(n)}return{denyOnly:e,allowWithinDeny:t}}function Kfe(){if(!Dh)return{allowOnly:Pm(),denyWithinAllow:[]};let e=Dh.filesystem.allowWrite.map(e=>jm(e)).filter(e=>Tm()===`linux`&&Am(e)?(Z(`Skipping glob pattern on Linux/WSL: ${e}`),!1):!0),t=Dh.filesystem.denyWrite.map(e=>jm(e)).filter(e=>Tm()===`linux`&&Am(e)?(Z(`Skipping glob pattern on Linux/WSL: ${e}`),!1):!0);return{allowOnly:[...Pm(),...e],denyWithinAllow:t}}function qfe(){if(!Dh)return{};let e=Dh.network.allowedDomains,t=Dh.network.deniedDomains;return{...e.length>0&&{allowedHosts:e},...t.length>0&&{deniedHosts:t}}}function mh(){return Dh?.network?.allowUnixSockets}function hh(){return Dh?.network?.allowAllUnixSockets}function gh(){return Dh?.network?.allowLocalBinding}function _h(){return Dh?.ignoreViolations}function vh(){return Dh?.enableWeakerNestedSandbox}function Jfe(){return Dh?.enableWeakerNetworkIsolation}function Yfe(){return Dh?.ripgrep??{command:`rg`}}function Xfe(){return Dh?.mandatoryDenySearchDepth??3}function yh(){return Dh?.filesystem?.allowGitConfig??!1}function Zfe(){return Dh?.seccomp}function bh(){return Ah?.httpProxyPort}function xh(){return Ah?.socksProxyPort}function Sh(){return Ah?.linuxBridge?.httpSocketPath}function Ch(){return Ah?.linuxBridge?.socksSocketPath}async function wh(){if(!Dh)return!1;if(jh)try{return await jh,!0}catch{return!1}return Ah!==void 0}async function Qfe(e,t,n,r){let i=Tm(),a=e=>e.map(e=>jm(e)).filter(e=>Tm()===`linux`&&Am(e)?(Z(`[Sandbox] Skipping glob write pattern on Linux: ${e}`),!1):!0),o=a(n?.filesystem?.allowWrite??Dh?.filesystem.allowWrite??[]),s={allowOnly:[...Pm(),...o],denyWithinAllow:a(n?.filesystem?.denyWrite??Dh?.filesystem.denyWrite??[])},c=n?.filesystem?.denyRead??Dh?.filesystem.denyRead??[],l=[];for(let e of c){let t=jm(e);Tm()===`linux`&&Am(t)?l.push(...Rm(e)):l.push(t)}let u=n?.filesystem?.allowRead??Dh?.filesystem.allowRead??[],d=[];for(let e of u){let t=jm(e);Tm()===`linux`&&Am(t)?d.push(...Rm(e)):d.push(t)}let f={denyOnly:l,allowWithinDeny:d},p=n?.network?.allowedDomains!==void 0||Dh?.network?.allowedDomains!==void 0,m=p,h=p;h&&await wh();let g=n?.allowPty??Dh?.allowPty;switch(i){case`macos`:return Ife({command:e,needsNetworkRestriction:m,httpProxyPort:h?bh():void 0,socksProxyPort:h?xh():void 0,readConfig:f,writeConfig:s,allowUnixSockets:mh(),allowAllUnixSockets:hh(),allowLocalBinding:gh(),ignoreViolations:_h(),allowPty:g,allowGitConfig:yh(),enableWeakerNetworkIsolation:Jfe(),binShell:t});case`linux`:return kfe({command:e,needsNetworkRestriction:m,httpSocketPath:h?Sh():void 0,socksSocketPath:h?Ch():void 0,httpProxyPort:h?Ah?.httpProxyPort:void 0,socksProxyPort:h?Ah?.socksProxyPort:void 0,readConfig:f,writeConfig:s,enableWeakerNestedSandbox:vh(),allowAllUnixSockets:hh(),binShell:t,ripgrepConfig:Yfe(),mandatoryDenySearchDepth:Xfe(),allowGitConfig:yh(),seccompConfig:Zfe(),abortSignal:r});default:throw Error(`Sandbox configuration is not supported on platform: ${i}`)}}function $fe(){return Dh}function epe(e){Dh=Gle(e),Ph=kp(e.network.parentProxy),Z(`Sandbox configuration updated`)}function Th(){Zm()}async function Eh(){if(Th(),Nh&&(Nh(),Nh=void 0),Ah?.linuxBridge){let{httpSocketPath:e,socksSocketPath:t,httpBridgeProcess:n,socksBridgeProcess:r}=Ah.linuxBridge,i=[];if(n.pid&&!n.killed)try{process.kill(n.pid,`SIGTERM`),Z(`Sent SIGTERM to HTTP bridge process`),i.push(new Promise(e=>{n.once(`exit`,()=>{Z(`HTTP bridge process exited`),e()}),setTimeout(()=>{if(!n.killed){Z(`HTTP bridge did not exit, forcing SIGKILL`,{level:`warn`});try{n.pid&&process.kill(n.pid,`SIGKILL`)}catch{}}e()},5e3)}))}catch(e){e.code!==`ESRCH`&&Z(`Error killing HTTP bridge: ${e}`,{level:`error`})}if(r.pid&&!r.killed)try{process.kill(r.pid,`SIGTERM`),Z(`Sent SIGTERM to SOCKS bridge process`),i.push(new Promise(e=>{r.once(`exit`,()=>{Z(`SOCKS bridge process exited`),e()}),setTimeout(()=>{if(!r.killed){Z(`SOCKS bridge did not exit, forcing SIGKILL`,{level:`warn`});try{r.pid&&process.kill(r.pid,`SIGKILL`)}catch{}}e()},5e3)}))}catch(e){e.code!==`ESRCH`&&Z(`Error killing SOCKS bridge: ${e}`,{level:`error`})}if(await Promise.all(i),e)try{Ec.rmSync(e,{force:!0}),Z(`Cleaned up HTTP socket`)}catch(e){Z(`HTTP socket cleanup error: ${e}`,{level:`error`})}if(t)try{Ec.rmSync(t,{force:!0}),Z(`Cleaned up SOCKS socket`)}catch(e){Z(`SOCKS socket cleanup error: ${e}`,{level:`error`})}}let e=[];if(Oh){let t=Oh,n=new Promise(e=>{t.close(t=>{t&&t.message!==`Server is not running.`&&Z(`Error closing HTTP proxy server: ${t.message}`,{level:`error`}),e()})});e.push(n)}if(kh){let t=kh.close().catch(e=>{Z(`Error closing SOCKS proxy server: ${e.message}`,{level:`error`})});e.push(t)}await Promise.all(e),Oh=void 0,kh=void 0,Ah=void 0,jh=void 0,Ph=void 0}function tpe(){return Fh}function npe(e,t){if(!Dh)return t;let n=Fh.getViolationsForCommand(e);if(n.length===0)return t;let r=t;r+=Nc+`<sandbox_violations>`+Nc;for(let e of n)r+=e.line+Nc;return r+=`</sandbox_violations>`,r}function rpe(){if(Tm()!==`linux`||!Dh)return[];let e=[],t=[...Dh.filesystem.allowWrite,...Dh.filesystem.denyWrite];for(let n of t)Am(jm(n))&&e.push(n);return e}var Dh,Oh,kh,Ah,jh,Mh,Nh,Ph,Fh,Ih,ipe=n((()=>{Wde(),Jde(),Op(),Xp(),wm(),Em(),Afe(),Rfe(),Vm(),lh(),Up(),Mh=!1,Fh=new ch,Ih={initialize:Ufe,isSupportedPlatform:fh,isSandboxingEnabled:Wfe,checkDependencies:ph,getFsReadConfig:Gfe,getFsWriteConfig:Kfe,getNetworkRestrictionConfig:qfe,getAllowUnixSockets:mh,getAllowLocalBinding:gh,getIgnoreViolations:_h,getEnableWeakerNestedSandbox:vh,getProxyPort:bh,getSocksProxyPort:xh,getLinuxHttpSocketPath:Sh,getLinuxSocksSocketPath:Ch,waitForNetworkInitialization:wh,wrapWithSandbox:Qfe,cleanupAfterCommand:Th,reset:Eh,getSandboxViolationStore:tpe,annotateStderrWithSandboxFailures:npe,getLinuxGlobPatternWarnings:rpe,getConfig:$fe,updateConfig:epe}})),Lh,Rh,zh,Bh,Vh,Hh,Uh,Wh,Gh,ape=n((()=>{N(),Lh=j().refine(e=>{if(e.includes(`://`)||e.includes(`/`)||e.includes(`:`))return!1;if(e===`localhost`)return!0;if(e.startsWith(`*.`)){let t=e.slice(2);if(!t.includes(`.`)||t.startsWith(`.`)||t.endsWith(`.`))return!1;let n=t.split(`.`);return n.length>=2&&n.every(e=>e.length>0)}return!e.includes(`*`)&&e.includes(`.`)&&!e.startsWith(`.`)&&!e.endsWith(`.`)},{message:`Invalid domain pattern. Must be a valid domain (e.g., "example.com") or wildcard (e.g., "*.example.com"). Overly broad patterns like "*.com" or "*" are not allowed for security reasons.`}),Rh=j().min(1,`Path cannot be empty`),zh=se({socketPath:j().min(1).describe(`Unix socket path to the MITM proxy`),domains:M(Lh).min(1).describe(`Domains to route through the MITM proxy (e.g., ["api.example.com", "*.internal.org"])`)}),Bh=se({http:j().url().optional().describe(`Upstream proxy URL for plain HTTP traffic`),https:j().url().optional().describe(`Upstream proxy URL for HTTPS/CONNECT traffic (falls back to http if unset)`),noProxy:j().optional().describe(`Comma-separated NO_PROXY list (hostname suffixes and CIDR ranges). Matching destinations connect directly instead of via the parent proxy.`)}),Vh=se({allowedDomains:M(Lh).describe(`List of allowed domains (e.g., ["github.com", "*.npmjs.org"])`),deniedDomains:M(Lh).describe(`List of denied domains`),allowUnixSockets:M(j()).optional().describe(`macOS only: Unix socket paths to allow. Ignored on Linux (seccomp cannot filter by path).`),allowAllUnixSockets:oe().optional().describe(`If true, allow all Unix sockets (disables blocking on both platforms).`),allowLocalBinding:oe().optional().describe(`Whether to allow binding to local ports (default: false)`),httpProxyPort:ae().int().min(1).max(65535).optional().describe(`Port of an external HTTP proxy to use instead of starting a local one. When provided, the library will skip starting its own HTTP proxy and use this port. The external proxy must handle domain filtering.`),socksProxyPort:ae().int().min(1).max(65535).optional().describe(`Port of an external SOCKS proxy to use instead of starting a local one. When provided, the library will skip starting its own SOCKS proxy and use this port. The external proxy must handle domain filtering.`),mitmProxy:zh.optional().describe(`Optional MITM proxy configuration. Routes matching domains through an upstream proxy via Unix socket while SRT still handles allow/deny filtering.`),parentProxy:Bh.optional().describe(`Upstream HTTP proxy for outbound connections. When set, SRT's proxy tunnels non-mitmProxy traffic through this parent instead of connecting directly. Falls back to HTTP_PROXY/HTTPS_PROXY/NO_PROXY env vars if unset.`)}),Hh=se({denyRead:M(Rh).describe(`Paths denied for reading`),allowRead:M(Rh).optional().describe(`Paths to re-allow reading within denied regions (takes precedence over denyRead). Use with denyRead to deny a broad region then allow back specific subdirectories.`),allowWrite:M(Rh).describe(`Paths allowed for writing`),denyWrite:M(Rh).describe(`Paths denied for writing (takes precedence over allowWrite)`),allowGitConfig:oe().optional().describe(`Allow writes to .git/config files (default: false). Enables git remote URL updates while keeping .git/hooks protected.`)}),Uh=le(j(),M(j())).describe(`Map of command patterns to filesystem paths to ignore violations for. Use "*" to match all commands`),Wh=se({command:j().describe(`The ripgrep command to execute`),args:M(j()).optional().describe(`Additional arguments to pass before ripgrep args`),argv0:j().optional().describe(`Override argv[0] when spawning (for multicall binaries that dispatch on argv[0])`)}),Gh=se({bpfPath:j().optional().describe(`Path to the unix-block.bpf filter file`),applyPath:j().optional().describe(`Path to the apply-seccomp binary`)}),se({network:Vh.describe(`Network restrictions configuration`),filesystem:Hh.describe(`Filesystem restrictions configuration`),ignoreViolations:Uh.optional().describe(`Optional configuration for ignoring specific violations`),enableWeakerNestedSandbox:oe().optional().describe(`Enable weaker nested sandbox mode (for Docker environments)`),enableWeakerNetworkIsolation:oe().optional().describe(`Enable weaker network isolation to allow access to com.apple.trustd.agent (macOS only). This is needed for Go programs (gh, gcloud, terraform, kubectl, etc.) to verify TLS certificates when using httpProxyPort with a MITM proxy and custom CA. Enabling this opens a potential data exfiltration vector through the trustd service. Only enable if you need Go TLS verification.`),ripgrep:Wh.optional().describe(`Custom ripgrep configuration (default: { command: "rg" })`),mandatoryDenySearchDepth:ae().int().min(1).max(10).optional().describe(`Maximum directory depth to search for dangerous files on Linux (default: 3). Higher values provide more protection but slower performance.`),allowPty:oe().optional().describe(`Allow pseudo-terminal (pty) operations (macOS only)`),seccomp:Gh.optional().describe(`Custom seccomp binary paths (Linux only).`)})})),ope=n((()=>{ipe(),lh(),ape(),Vm(),Em()}));async function spe(){if(ag||og)return;ag=!0,dpe(),Oi(Kh);let{dirs:e,settingsFiles:t,dropInDir:n}=await cpe();og||e.length!==0&&(K(`Watching for changes in setting files ${[...t].join(`, `)}...${n?` and drop-in directory ${n}`:``}`),ng=poe.watch(e,{persistent:!0,ignoreInitial:!0,depth:0,awaitWriteFinish:{stabilityThreshold:Zh,pollInterval:Qh},ignored:(e,r)=>{if(r&&!r.isFile()&&!r.isDirectory()||e.split(uc.sep).some(e=>e===`.git`))return!0;if(!r||r.isDirectory())return!1;let i=uc.normalize(e);return!(t.has(i)||n&&i.startsWith(n+uc.sep)&&i.endsWith(`.json`))},ignorePermissionErrors:!0,usePolling:!1,atomic:!0}),ng.on(`change`,Jh),ng.on(`unlink`,upe),ng.on(`add`,lpe))}function Kh(){og=!0,rg&&(clearInterval(rg),rg=null);for(let e of sg.values())clearTimeout(e);sg.clear(),ig=null,gte(),cg.clear();let e=ng;return ng=null,e?e.close():Promise.resolve()}async function cpe(){let e=new Map,t=new Set;for(let n of tr){if(n===`flagSettings`)continue;let r=Vn(n);if(!r)continue;let i=uc.dirname(r);e.has(i)||e.set(i,new Set),e.get(i).add(r);try{(await Yc(r)).isFile()&&t.add(i)}catch{}}let n=new Set;for(let r of t){let t=e.get(r);if(t)for(let e of t)n.add(e)}let r=null,i=zn();try{(await Yc(i)).isDirectory()&&(t.add(i),r=i)}catch{}return{dirs:[...t],settingsFiles:n,dropInDir:r}}function qh(e){switch(e){case`userSettings`:return`user_settings`;case`projectSettings`:return`project_settings`;case`localSettings`:return`local_settings`;case`flagSettings`:case`policySettings`:return`policy_settings`}}function Jh(e){let t=Yh(e);if(!t)return;let n=sg.get(e);n&&(clearTimeout(n),sg.delete(e),K(`Cancelled pending deletion of ${e} — file was recreated`)),!$ee(e,$h)&&(K(`Detected change to ${e}`),u7(qh(t),e).then(n=>{if(i7(n)){K(`ConfigChange hook blocked change to ${e}`);return}Xh(t)}))}function lpe(e){if(!Yh(e))return;let t=sg.get(e);t&&(clearTimeout(t),sg.delete(e),K(`Cancelled pending deletion of ${e} — file was re-added`)),Jh(e)}function upe(e){let t=Yh(e);if(!t||(K(`Detected deletion of ${e}`),sg.has(e)))return;let n=setTimeout((e,t)=>{sg.delete(e),u7(qh(t),e).then(n=>{if(i7(n)){K(`ConfigChange hook blocked deletion of ${e}`);return}Xh(t)})},tg,e,t);sg.set(e,n)}function Yh(e){let t=uc.normalize(e),n=zn();return t.startsWith(n+uc.sep)?`policySettings`:tr.find(e=>Vn(e)===t)}function dpe(){let e=Ree(),t=Gte();ig=W({mdm:e.settings,hkcu:t.settings}),rg=setInterval(()=>{og||(async()=>{try{let{mdm:e,hkcu:t}=await Hte();if(og)return;let n=W({mdm:e.settings,hkcu:t.settings});n!==ig&&(ig=n,Vee(e,t),K(`Detected MDM settings change via poll`),Xh(`policySettings`))}catch(e){K(`MDM poll error: ${G(e)}`)}})()},eg),rg.unref()}function Xh(e){xr(),cg.emit(e)}function fpe(e){K(`Programmatic settings change notification for ${e}`),Xh(e)}var Zh,Qh,$h,eg,tg,ng,rg,ig,ag,og,sg,cg,lg,ug,dg=n((()=>{loe(),di(),q(),gi(),_7(),Ir(),Li(),Rn(),jte(),Zn(),hee(),Ln(),zr(),Zh=1e3,Qh=500,$h=5e3,eg=1800*1e3,tg=1700,ng=null,rg=null,ig=null,ag=!1,og=!1,sg=new Map,cg=jr(),lg=cg.subscribe,ug={initialize:spe,dispose:Kh,subscribe:lg,notifyChange:fpe}}));function fg(e){let t=e.match(/^([^(]+)\(([^)]+)\)$/);if(!t)return{toolName:e};let n=t[1],r=t[2];return!n||!r?{toolName:e}:{toolName:n,ruleContent:r}}function ppe(e){return e.match(/^(.+):\*$/)?.[1]??null}function pg(e,t){return e.startsWith(`//`)?e.slice(1):e.startsWith(`/`)&&!e.startsWith(`//`)?yc(gn(t),e.slice(1)):e}function mg(e,t){return e.startsWith(`//`)?e.slice(1):xn(e,gn(t))}function hg(){return $n(`policySettings`)?.sandbox?.network?.allowManagedDomainsOnly===!0}function mpe(){return $n(`policySettings`)?.sandbox?.filesystem?.allowManagedReadPathsOnly===!0}function gg(e){let t=e.permissions||{},n=[],r=[];if(hg()){let e=$n(`policySettings`);for(let t of e?.sandbox?.network?.allowedDomains||[])n.push(t)}else for(let t of e.sandbox?.network?.allowedDomains||[])n.push(t);for(let e of t.deny||[]){let t=fg(e);t.ruleContent?.startsWith(`domain:`)&&r.push(t.ruleContent.substring(7))}let i=[`.`,R8()],a=[],o=[],s=[],c=tr.map(e=>Vn(e)).filter(e=>e!==void 0);a.push(...c),a.push(zn());let l=Vr(),u=ti();l!==u&&(a.push(yc(l,`.workmate`,`settings.json`)),a.push(yc(l,`.workmate`,`settings.local.json`))),a.push(yc(u,`.workmate`,`skills`)),l!==u&&a.push(yc(l,`.workmate`,`skills`)),Cg.length=0;let d=[`HEAD`,`objects`,`refs`,`hooks`,`config`];for(let e of l===u?[u]:[u,l])for(let t of d){let n=yc(e,t);try{zse(n),a.push(n)}catch{Cg.push(n)}}Sg&&Sg!==l&&i.push(Sg);let f=new Set([...e.permissions?.additionalDirectories||[],...Zr()]);i.push(...f);for(let e of tr){let t=$n(e);if(t?.permissions){for(let n of t.permissions.allow||[]){let t=fg(n);t.toolName===`Edit`&&t.ruleContent&&i.push(pg(t.ruleContent,e))}for(let n of t.permissions.deny||[]){let t=fg(n);t.toolName===`Edit`&&t.ruleContent&&a.push(pg(t.ruleContent,e)),t.toolName===`Read`&&t.ruleContent&&o.push(pg(t.ruleContent,e))}}let n=t?.sandbox?.filesystem;if(n){for(let t of n.allowWrite||[])i.push(mg(t,e));for(let t of n.denyWrite||[])a.push(mg(t,e));for(let t of n.denyRead||[])o.push(mg(t,e));if(!mpe()||e===`policySettings`)for(let t of n.allowRead||[])s.push(mg(t,e))}}let{rgPath:p,rgArgs:m,argv0:h}=Ks(),g=e.sandbox?.ripgrep??{command:p,args:m,argv0:h};return{network:{allowedDomains:n,deniedDomains:r,allowUnixSockets:e.sandbox?.network?.allowUnixSockets,allowAllUnixSockets:e.sandbox?.network?.allowAllUnixSockets,allowLocalBinding:e.sandbox?.network?.allowLocalBinding,httpProxyPort:e.sandbox?.network?.httpProxyPort,socksProxyPort:e.sandbox?.network?.socksProxyPort},filesystem:{denyRead:o,allowRead:s,allowWrite:i,denyWrite:a},ignoreViolations:e.sandbox?.ignoreViolations,enableWeakerNestedSandbox:e.sandbox?.enableWeakerNestedSandbox,enableWeakerNetworkIsolation:e.sandbox?.enableWeakerNetworkIsolation,ripgrep:g}}function hpe(){for(let e of Cg)try{Rse(e,{recursive:!0}),K(`[Sandbox] scrubbed planted bare-repo file: ${e}`)}catch{}}async function gpe(e){let t=X(e,`.git`);try{let n=(await Wc(t,{encoding:`utf8`})).match(/^gitdir:\s*(.+)$/m);if(!n?.[1])return null;let r=yc(e,n[1].trim()),i=`${bc}.git${bc}worktrees${bc}`,a=r.lastIndexOf(i);return a>0?r.substring(0,a):null}catch{return null}}function _g(){try{return yn()?.sandbox?.enabled??!1}catch(e){return K(`Failed to get settings for sandbox check: ${e}`),!1}}function _pe(){return yn()?.sandbox?.autoAllowBashIfSandboxed??!0}function vpe(){return yn()?.sandbox?.allowUnsandboxedCommands??!0}function ype(){let e=yn();return _g()&&(e?.sandbox?.failIfUnavailable??!1)}function vg(){try{let e=rr()?.sandbox?.enabledPlatforms;if(e===void 0)return!0;if(e.length===0)return!1;let t=Ma();return e.includes(t)}catch(e){return K(`Failed to check enabledPlatforms: ${e}`),!0}}function yg(){return!Tg()||wg().errors.length>0||!vg()?!1:_g()}function bpe(){if(!_g())return;if(!Tg()){let e=Ma();return e===`wsl`?`sandbox.enabled is set but WSL1 is not supported (requires WSL2)`:`sandbox.enabled is set but ${e} is not supported (requires macOS, Linux, or WSL2)`}if(!vg())return`sandbox.enabled is set but ${Ma()} is not in sandbox.enabledPlatforms`;let e=wg();if(e.errors.length>0){let t=Ma()===`macos`?`run /sandbox or /doctor for details`:`install missing tools (e.g. apt install bubblewrap socat) or run /sandbox for details`;return`sandbox.enabled is set but dependencies are missing: ${e.errors.join(`, `)} · ${t}`}}function xpe(){let e=Ma();if(e!==`linux`&&e!==`wsl`)return[];try{let e=yn();if(!e?.sandbox?.enabled)return[];let t=e?.permissions||{},n=[],r=e=>{let t=e.replace(/\/\*\*$/,``);return/[*?[\]]/.test(t)};for(let e of[...t.allow||[],...t.deny||[]]){let t=fg(e);(t.toolName===`Edit`||t.toolName===`Read`)&&t.ruleContent&&r(t.ruleContent)&&n.push(e)}return n}catch(e){return K(`Failed to get Linux glob pattern warnings: ${e}`),[]}}function Spe(){for(let e of[`flagSettings`,`policySettings`]){let t=$n(e);if(t?.sandbox?.enabled!==void 0||t?.sandbox?.autoAllowBashIfSandboxed!==void 0||t?.sandbox?.allowUnsandboxedCommands!==void 0)return!0}return!1}async function Cpe(e){gr(`localSettings`,{sandbox:{...$n(`localSettings`)?.sandbox,...e.enabled!==void 0&&{enabled:e.enabled},...e.autoAllowBashIfSandboxed!==void 0&&{autoAllowBashIfSandboxed:e.autoAllowBashIfSandboxed},...e.allowUnsandboxedCommands!==void 0&&{allowUnsandboxedCommands:e.allowUnsandboxedCommands}}})}function wpe(){return yn()?.sandbox?.excludedCommands??[]}async function Tpe(e,t,n,r){if(yg())if(bg)await bg;else throw Error(`Sandbox failed to initialize. `);return Ih.wrapWithSandbox(e,t,n,r)}async function Epe(e){if(bg)return bg;if(!yg())return;let t=e?async t=>hg()?(K(`[sandbox] Blocked network request to ${t.host} (allowManagedDomainsOnly)`),!1):e(t):void 0;return bg=(async()=>{try{Sg===void 0&&(Sg=await gpe(Vr()));let e=gg(yn());await Ih.initialize(e,t),xg=ug.subscribe(()=>{let e=gg(yn());Ih.updateConfig(e),K(`Sandbox configuration updated from settings change`)})}catch(e){bg=void 0,K(`Failed to initialize sandbox: ${G(e)}`)}})(),bg}function Dpe(){if(!yg())return;let e=gg(yn());Ih.updateConfig(e)}async function Ope(){return xg?.(),xg=void 0,Sg=void 0,Cg.length=0,wg.cache.clear?.(),Tg.cache.clear?.(),bg=void 0,Ih.reset()}function kpe(e,t){let n=$n(`localSettings`),r=n?.sandbox?.excludedCommands||[],i=e;if(t){let e=t.filter(e=>e.type===`addRules`&&e.rules.some(e=>e.toolName===`Bash`));if(e.length>0&&e[0].type===`addRules`){let t=e[0].rules.find(e=>e.toolName===ks);t?.ruleContent&&(i=ppe(t.ruleContent)||t.ruleContent)}}return r.includes(i)||gr(`localSettings`,{sandbox:{...n?.sandbox,excludedCommands:[...r,i]}}),i}var bg,xg,Sg,Cg,wg,Tg,Eg,Dg=n((()=>{ope(),wm(),H(),q(),Wn(),Pa(),dg(),Rn(),Zn(),Ln(),ys(),Es(),As(),gi(),B8(),Gs(),Cg=[],wg=u(()=>{let{rgPath:e,rgArgs:t}=Ks();return Ih.checkDependencies({command:e,args:t})}),Tg=u(()=>Ih.isSupportedPlatform()),Eg={initialize:Epe,isSandboxingEnabled:yg,isSandboxEnabledInSettings:_g,isPlatformInEnabledList:vg,getSandboxUnavailableReason:bpe,isAutoAllowBashIfSandboxedEnabled:_pe,areUnsandboxedCommandsAllowed:vpe,isSandboxRequired:ype,areSandboxSettingsLockedByPolicy:Spe,setSandboxSettings:Cpe,getExcludedCommands:wpe,wrapWithSandbox:Tpe,refreshConfig:Dpe,reset:Ope,checkDependencies:wg,getFsReadConfig:Ih.getFsReadConfig,getFsWriteConfig:Ih.getFsWriteConfig,getNetworkRestrictionConfig:Ih.getNetworkRestrictionConfig,getIgnoreViolations:Ih.getIgnoreViolations,getLinuxGlobPatternWarnings:xpe,isSupportedPlatform:Tg,getAllowUnixSockets:Ih.getAllowUnixSockets,getAllowLocalBinding:Ih.getAllowLocalBinding,getEnableWeakerNestedSandbox:Ih.getEnableWeakerNestedSandbox,getProxyPort:Ih.getProxyPort,getSocksProxyPort:Ih.getSocksProxyPort,getLinuxHttpSocketPath:Ih.getLinuxHttpSocketPath,getLinuxSocksSocketPath:Ih.getLinuxSocksSocketPath,waitForNetworkInitialization:Ih.waitForNetworkInitialization,getSandboxViolationStore:Ih.getSandboxViolationStore,annotateStderrWithSandboxFailures:Ih.annotateStderrWithSandboxFailures,cleanupAfterCommand:()=>{Ih.cleanupAfterCommand(),hpe()}}})),Og,Ape=n((()=>{ne(),Dg(),Og={name:`sandbox`,get description(){let e=Eg.isSandboxingEnabled(),t=Eg.isAutoAllowBashIfSandboxedEnabled(),n=Eg.areUnsandboxedCommandsAllowed(),r=Eg.areSandboxSettingsLockedByPolicy(),i=Eg.checkDependencies().errors.length===0,a;a=i?e?ie.tick:ie.circle:ie.warning;let o=`sandbox disabled`;return e&&(o=t?`sandbox enabled (auto-allow)`:`sandbox enabled`,o+=n?`, fallback allowed`:``),r&&(o+=` (managed)`),`${a} ${o} (⏎ to configure)`},argumentHint:`exclude "command pattern"`,get isHidden(){return!Eg.isSupportedPlatform()||!Eg.isPlatformInEnabledList()},immediate:!0,type:`local-jsx`,load:()=>import(`./sandbox-toggle-Bp6S0ymp.js`)}})),kg,Ag,jg,Mg=n((()=>{d(),mo(),kg=[{modelEnvVar:`ANTHROPIC_DEFAULT_OPUS_MODEL`,capabilitiesEnvVar:`ANTHROPIC_DEFAULT_OPUS_MODEL_SUPPORTED_CAPABILITIES`},{modelEnvVar:`ANTHROPIC_DEFAULT_SONNET_MODEL`,capabilitiesEnvVar:`ANTHROPIC_DEFAULT_SONNET_MODEL_SUPPORTED_CAPABILITIES`},{modelEnvVar:`ANTHROPIC_DEFAULT_HAIKU_MODEL`,capabilitiesEnvVar:`ANTHROPIC_DEFAULT_HAIKU_MODEL_SUPPORTED_CAPABILITIES`}],Ag=[{modelEnvVar:`OPENAI_DEFAULT_OPUS_MODEL`,capabilitiesEnvVar:`OPENAI_DEFAULT_OPUS_MODEL_SUPPORTED_CAPABILITIES`},{modelEnvVar:`OPENAI_DEFAULT_SONNET_MODEL`,capabilitiesEnvVar:`OPENAI_DEFAULT_SONNET_MODEL_SUPPORTED_CAPABILITIES`},{modelEnvVar:`OPENAI_DEFAULT_HAIKU_MODEL`,capabilitiesEnvVar:`OPENAI_DEFAULT_HAIKU_MODEL_SUPPORTED_CAPABILITIES`}],jg=u((e,t)=>{if(lo()===`firstParty`)return;let n=e.toLowerCase(),r=lo()===`openai`?Ag:kg;for(let e of r){let r=process.env[e.modelEnvVar],i=process.env[e.capabilitiesEnvVar];if(!(!r||i===void 0)&&n===r.toLowerCase())return i.toLowerCase().split(`,`).map(e=>e.trim()).includes(t)}},(e,t)=>`${e.toLowerCase()}:${t}`)}));function jpe(e){let t=[],n=[];for(let r of e)Bg.includes(r)?t.push(r):n.push(r);return{allowed:t,disallowed:n}}function Mpe(e){if(!e||e.length===0)return;let{allowed:t,disallowed:n}=jpe(e);for(let e of n)console.warn(`Warning: Beta header '${e}' is not allowed. Only the following betas are supported: ${Bg.join(`, `)}`);return t.length>0?t:void 0}function Ng(e){let t=jg(e,`interleaved_thinking`);if(t!==void 0)return t;let n=Mo(e),r=lo();return r===`foundry`?!0:r===`firstParty`?!n.includes(`claude-3-`):n.includes(`claude-opus-4`)||n.includes(`claude-sonnet-4`)}function Pg(e){let t=Mo(e),n=lo();return n===`foundry`?!0:n===`firstParty`?!t.includes(`claude-3-`):t.includes(`claude-opus-4`)||t.includes(`claude-sonnet-4`)||t.includes(`claude-haiku-4`)}function Fg(e){let t=Mo(e),n=lo();return n!==`firstParty`&&n!==`foundry`?!1:t.includes(`claude-sonnet-4-6`)||t.includes(`claude-sonnet-4-5`)||t.includes(`claude-opus-4-1`)||t.includes(`claude-opus-4-5`)||t.includes(`claude-opus-4-6`)||t.includes(`claude-opus-4-7`)||t.includes(`claude-haiku-4-5`)}function Ig(e){return!0}function Lg(){return(lo()===`firstParty`||lo()===`foundry`)&&!h(process.env.WORKMATE_DISABLE_EXPERIMENTAL_BETAS)&&ao()}function Rg(){return lo()===`firstParty`&&!h(process.env.WORKMATE_DISABLE_EXPERIMENTAL_BETAS)}function zg(e,t){let n=[...Hg(e)];t?.isAgenticQuery&&(n.includes(`workmate-20250219`)||n.push(no));let r=ni();return!r||r.length===0?n:[...n,...r.filter(e=>!n.includes(e))]}var Bg,Vg,Hg,Ug,Wg=n((()=>{d(),H(),po(),yo(),g(),wo(),Mg(),mo(),Ln(),Bg=[Ho],Vg=u(e=>{let t=[],n=Mo(e).includes(`haiku`);lo();let r=Lg();n||t.push(no),Pie(e)&&t.push(Ho),!h(process.env.DISABLE_INTERLEAVED_THINKING)&&Ng(e)&&t.push(Vie),r&&Ng(e)&&!kr()&&rr().showThinkingSummaries!==!0&&t.push(to);let i=h(process.env.USE_API_CONTEXT_MANAGEMENT)||Pg(e),a=Pg(e);return Lg()&&(i||a)&&t.push(Hie),r&&Fg(e),r&&t.push(ho),process.env.ANTHROPIC_BETAS&&t.push(...process.env.ANTHROPIC_BETAS.split(`,`).map(e=>e.trim()).filter(Boolean)),t}),Hg=u(e=>{let t=Vg(e);return lo()===`bedrock`?t.filter(e=>!vo.has(e)):t}),Ug=u(e=>Vg(e).filter(e=>vo.has(e)))}));function Gg(e){return e.type===`advisor_tool_result`||e.type===`server_tool_use`&&e.name===`advisor`}function Kg(){return{}}function qg(){return h(process.env.WORKMATE_DISABLE_ADVISOR_TOOL)||!Lg()?!1:Kg().enabled??!1}function Jg(){return qg()&&(Kg().canUserConfigure??!1)}function Npe(){let e=Kg();return qg()&&!Jg()&&e.baseModel&&e.advisorModel?{baseModel:e.baseModel,advisorModel:e.advisorModel}:void 0}function Yg(e){let t=e.toLowerCase();return t.includes(`opus-4-7`)||t.includes(`opus-4-6`)||t.includes(`sonnet-4-6`)}function Xg(e){let t=e.toLowerCase();return t.includes(`opus-4-7`)||t.includes(`opus-4-6`)||t.includes(`sonnet-4-6`)}function Ppe(){if(qg())return rr().advisorModel}function Fpe(e){let t=e.iterations;return t?t.filter(e=>e.type===`advisor_message`):[]}var Zg,Qg=n((()=>{Wg(),g(),Ln(),Zg=`# Advisor Tool
416
416
 
417
417
  You have access to an \`advisor\` tool backed by a stronger reviewer model. It takes NO parameters -- when you call it, your entire conversation history is automatically forwarded. The advisor sees the task, every tool call you've made, every result you've seen.
418
418
 
@@ -729,7 +729,7 @@ Examples:
729
729
  - "重构这个模块的代码" -> refactor code modularize
730
730
  - "帮我写个 Go 单元测试" -> write test golang unit
731
731
 
732
- Output ONLY keywords. Nothing else.`,Rw=6e3,zw=500,Bw=120,Vw=200,Hw=150,Uw=new Map})),Ww=i({collectSkillDiscoveryPrefetch:()=>ECe,extractQueryFromMessages:()=>Kw,getTurnZeroSkillDiscovery:()=>DCe,startSkillDiscoveryPrefetch:()=>Yw});function Gw(e,t){if(e.add(t),e.size>Xw){let t=e.size-Zw,n=e.values();for(let r=0;r<t;r++){let t=n.next();if(t.done)break;e.delete(t.value)}}}function Kw(e,t){let n=[];e&&n.push(e);for(let e=t.length-1;e>=0;e--){let r=t[e];if(r.type!==`user`)continue;let i=r.content;if(typeof i==`string`){n.push(i.slice(0,500));break}if(Array.isArray(i)){let e=!1;for(let t of i){let r=t;if(r.type&&r.type!==`text`)continue;let i=r.text;if(typeof i==`string`&&i.trim()){n.push(i.slice(0,500)),e=!0;break}}if(e)break}}return n.join(` `)}function qw(e,t,n){return{type:`skill_discovery`,skills:e,signal:t,source:`native`,gap:n}}async function Jw(e,t){let n=0,r=[];for(let i of e){let e={name:i.name,description:i.description,score:i.score};if(n>=tT||i.score<eT){r.push(e);continue}let a=await CCe(i);if(!a){r.push(e);continue}n++,await wCe(i.name,a.path,a.content,t),r.push({...e,autoLoaded:!0,content:a.content,path:a.path})}return r}async function CCe(e){if(!e.skillRoot)return null;let t=[wc(e.skillRoot,`SKILL.md`),wc(e.skillRoot,`skill.md`)];for(let e of t)try{return{path:e,content:Mu(await nl(e,`utf8`)).content.slice(0,nT)}}catch{}return null}async function wCe(e,t,n,r){try{let{addInvokedSkill:i}=await import(`./state-DXt6rahM.js`);i(e,t,n,r.agentId??null)}catch{}}async function TCe(e,t,n,r){if(r!==`user_input`||!e.trim())return;let i=`${r}:${e.trim().toLowerCase()}`;if(!$w.has(i)){Gw($w,i);try{let[{isSkillLearningEnabled:r},{recordSkillGap:i}]=await Promise.all([import(`./featureCheck-JOur3pHb.js`),import(`./skillGapStore-BV5H9Flk.js`)]);if(!r())return;let a=await i({prompt:e,cwd:n.cwd??process.cwd(),sessionId:n.sessionId??`unknown-session`,recommendations:t}),o=a.status;return o!==`pending`&&o!==`draft`&&o!==`active`?void 0:{key:a.key,status:o,draftName:a.draft?.name,draftPath:a.draft?.skillPath,activeName:a.active?.name,activePath:a.active?.skillPath}}catch(e){K(`[skill-search] skill gap learning error: ${e}`);return}}}async function Yw(e,t,n){if(!Tp())return[];let r=Date.now(),i=Kw(e,t);if(!i.trim())return[];try{let e=await yoe(n.cwd??process.cwd()),t=Coe(i,e).filter(e=>!Qw.has(e.name));if(t.length===0)return[];for(let e of t)Gw(Qw,e.name);let a={trigger:`assistant_turn`,queryText:i.slice(0,200),startedAt:r,durationMs:Date.now()-r,indexSize:e.length,method:`tfidf`};return K(`[skill-search] prefetch found ${t.length} skills in ${a.durationMs}ms`),[qw(await Jw(t,n),a)]}catch(e){return K(`[skill-search] prefetch error: ${e}`),[]}}async function ECe(e){try{return await e}catch{return[]}}async function DCe(e,t,n){if(!Tp()||!e.trim())return null;let r=Date.now();try{let t=await yoe(n.cwd??process.cwd()),i=Coe(await _Ce(e),t),a=await Jw(i,n),o=a.some(e=>e.autoLoaded)?void 0:await TCe(e,i,n,`user_input`);if(i.length===0&&!o)return null;for(let e of i)Gw(Qw,e.name);let s={trigger:`user_input`,queryText:e.slice(0,200),startedAt:r,durationMs:Date.now()-r,indexSize:t.length,method:`tfidf`};return K(`[skill-search] turn-zero found ${i.length} skills in ${s.durationMs}ms`),qw(a,s,o)}catch(e){return K(`[skill-search] turn-zero error: ${e}`),null}}var Xw,Zw,Qw,$w,eT,tT,nT,rT=n((()=>{Ep(),Ws(),SCe(),q(),Hu(),Xw=1e3,Zw=750,Qw=new Set,$w=new Set,eT=Number(process.env.SKILL_SEARCH_AUTOLOAD_MIN_SCORE??`0.30`),tT=Number(process.env.SKILL_SEARCH_AUTOLOAD_LIMIT??`2`),nT=Number(process.env.SKILL_SEARCH_AUTOLOAD_MAX_CHARS??`12000`)}));function iT(e){return uT.test(e)}function OCe(e){if(e.startsWith(`mcp__`)){let t=e.replace(/^mcp__/,``).toLowerCase();return{parts:t.split(`__`).flatMap(e=>e.split(`_`)).filter(Boolean),full:t.replace(/__/g,` `).replace(/_/g,` `),isMcp:!0}}let t=e.replace(/([a-z])([A-Z])/g,`$1 $2`).replace(/_/g,` `).toLowerCase().split(/\s+/).filter(Boolean);return{parts:t,full:t.join(` `),isMcp:!1}}async function kCe(e){let t=e.filter(e=>vs(e)),n=[];for(let r of t){let t=``;try{t=await r.prompt({getToolPermissionContext:async()=>({mode:`default`,additionalWorkingDirectories:new Map,alwaysAllowRules:{},alwaysDenyRules:{},alwaysAskRules:{},isBypassPermissionsModeAvailable:!1}),tools:e,agents:[]})}catch{t=``}let{parts:i,full:a}=OCe(r.name),o=r.searchHint??``,s=Us(i.join(` `)),c=Us(o),l=Us(t),u=[...new Set([...s,...c,...l])],d=Soe([{tokens:s,weight:sT.name},{tokens:c,weight:sT.searchHint},{tokens:l,weight:sT.description}]),f;r.inputJSONSchema&&(f=r.inputJSONSchema),n.push({name:r.name,normalizedName:a,description:t,searchHint:r.searchHint,isMcp:r.isMcp===!0,isDeferred:!0,inputSchema:f,tokens:u,tfVector:d})}let r=xoe(n);for(let e of n)for(let[t,n]of e.tfVector)e.tfVector.set(t,n*(r.get(t)??0));return K(`[search-extra-tools] indexed ${n.length} deferred tools from ${e.length} total tools`),n}function aT(e,t,n=5){if(t.length===0||!e.trim())return[];let r=Us(e);if(r.length===0)return[];let i=new Map,a=new Map;for(let e of r)a.set(e,(a.get(e)??0)+1);let o=1;for(let e of a.values())e>o&&(o=e);for(let[e,t]of a)i.set(e,t/o);let s=xoe(t),c=new Map;for(let[e,t]of i)c.set(e,t*(s.get(e)??0));let l=r.filter(e=>iT(e[0]??``)),u=r.filter(e=>!iT(e[0]??``)),d=e.toLowerCase().replace(/[-_]/g,` `),f=[];for(let e of t){let t=boe(c,e.tfVector);l.length>0&&t>0&&l.filter(t=>e.tfVector.has(t)).length<lT&&(u.some(t=>e.tfVector.has(t))||(t=0)),d.includes(e.normalizedName)&&(t=Math.max(t,.75)),t>=cT&&f.push({name:e.name,description:e.description,searchHint:e.searchHint,score:t,isMcp:e.isMcp,isDeferred:e.isDeferred,inputSchema:e.inputSchema})}return f.sort((e,t)=>t.score-e.score),f.slice(0,n)}async function oT(e){let t=e.map(e=>e.name).sort().join(`,`);return dT&&fT===t?dT:(dT=await kCe(e),fT=t,dT)}var sT,cT,lT,uT,dT,fT,pT=n((()=>{q(),Ws(),Os(),sT={name:3,searchHint:2.5,description:1},cT=Number(process.env.SEARCH_EXTRA_TOOLS_DISPLAY_MIN_SCORE??`0.10`),lT=2,uT=/[\u4e00-\u9fff\u3400-\u4dbf]/,dT=null,fT=null})),mT=i({buildToolDiscoveryAttachment:()=>yT,clearSearchExtraToolsPrefetchResults:()=>vT,collectSearchExtraToolsPrefetch:()=>xT,getSearchExtraToolsPrefetchSnapshot:()=>_T,getTurnZeroSearchExtraToolsPrefetch:()=>MCe,startSearchExtraToolsPrefetch:()=>bT,subscribeToSearchExtraToolsPrefetch:()=>gT});function hT(){for(let e of ET)e()}function gT(e){return ET.add(e),()=>{ET.delete(e)}}function _T(){return TT}function vT(){TT=[],hT()}function ACe(e,t){if(e.add(t),e.size>ST){let t=e.size-CT,n=e.values();for(let r=0;r<t;r++){let t=n.next();if(t.done)break;e.delete(t.value)}}}function jCe(e){return{name:e.name,description:e.description,searchHint:e.searchHint,score:e.score,isMcp:e.isMcp,isDeferred:e.isDeferred,inputSchema:e.inputSchema}}function yT(e,t,n,r,i){return{type:`tool_discovery`,tools:e,trigger:t,queryText:n.slice(0,200),durationMs:r,indexSize:i}}async function bT(e,t){let n=Date.now(),r=Kw(null,t);if(!r.trim())return[];try{let t=await oT(e),i=aT(r,t,3).filter(e=>!wT.has(e.name));if(i.length===0)return[];for(let e of i)ACe(wT,e.name);let a=Date.now()-n;K(`[search-extra-tools] prefetch found ${i.length} tools in ${a}ms`);let o=i.map(jCe);return TT=o,hT(),[yT(o,`assistant_turn`,r,a,t.length)]}catch(e){return K(`[search-extra-tools] prefetch error: ${e}`),[]}}async function MCe(e,t){return null}async function xT(e){try{return await e}catch{return[]}}var ST,CT,wT,TT,ET,DT=n((()=>{pT(),q(),rT(),ST=500,CT=400,wT=new Set,TT=[],ET=new Set}));function OT(e){AT=e}function kT(){return AT}function NCe(e){jT=e}function PCe(){return jT}function FCe(e){MT=e}function ICe(){return MT}var AT,jT,MT,NT=n((()=>{AT=!1,jT=!1,MT=!1}));function PT(e,t=zT){return new BT(e,t)}function FT(e){return Object.fromEntries(e.entries())}function IT(e){return Array.from(e.keys())}function LT(e){let t=PT(e.max,e.maxSize);return t.load(e.dump()),t}function RT(e,t){let n=LT(e);for(let[e,r]of t.entries()){let t=n.get(e);(!t||r.timestamp>t.timestamp)&&n.set(e,r)}return n}var zT,BT,VT=n((()=>{Sn(),b(),zT=25*1024*1024,BT=class{constructor(e,t){x(this,`cache`,void 0),this.cache=new nt({max:e,maxSize:t,sizeCalculation:e=>{let t=e.content,n=typeof t==`string`?t:t==null?``:typeof t==`object`?JSON.stringify(t):String(t);return Math.max(1,Buffer.byteLength(n,`utf8`))}})}get(e){return this.cache.get(hc(e))}set(e,t){return this.cache.set(hc(e),t),this}has(e){return this.cache.has(hc(e))}delete(e){return this.cache.delete(hc(e))}clear(){this.cache.clear()}get size(){return this.cache.size}get max(){return this.cache.max}get maxSize(){return this.cache.maxSize}get calculatedSize(){return this.cache.calculatedSize}keys(){return this.cache.keys()}entries(){return this.cache.entries()}dump(){return this.cache.dump()}load(e){this.cache.load(e)}}}));function HT(e=WT){let t=new AbortController;return gce(e,t.signal),t}function LCe(e){let t=this.deref();e.deref()?.abort(t?.signal.reason)}function RCe(e){let t=this.deref(),n=e.deref();t&&n&&t.signal.removeEventListener(`abort`,n)}function UT(e,t){let n=HT(t);if(e.signal.aborted)return n.abort(e.signal.reason),n;let r=new WeakRef(n),i=new WeakRef(e),a=LCe.bind(i,r);return e.signal.addEventListener(`abort`,a,{once:!0}),n.signal.addEventListener(`abort`,RCe.bind(i,new WeakRef(a)),{once:!0}),n}var WT,GT=n((()=>{WT=50}));function KT(){return!1}function zCe(e){return e.some(e=>{if(e.type!==`user`)return!1;let t=e.message.content;return Array.isArray(t)?t.some(e=>e.type===`text`&&e.text.includes(`<fork-boilerplate>`)):!1})}function BCe(e,t){let n={...t,uuid:Lc(),message:{...t.message,content:[...Array.isArray(t.message.content)?t.message.content:[]]}},r=(Array.isArray(t.message.content)?t.message.content:[]).filter(e=>e.type===`tool_use`);return r.length===0?(K(`No tool_use blocks found in assistant message for fork directive: ${e.slice(0,50)}...`,{level:`error`}),[Q({content:[{type:`text`,text:qT(e)}]})]):[n,Q({content:[...r.map(e=>({type:`tool_result`,tool_use_id:e.id,content:[{type:`text`,text:XT}]})),{type:`text`,text:qT(e)}]})]}function qT(e){return`<${xa}>
732
+ Output ONLY keywords. Nothing else.`,Rw=6e3,zw=500,Bw=120,Vw=200,Hw=150,Uw=new Map})),Ww=i({collectSkillDiscoveryPrefetch:()=>ECe,extractQueryFromMessages:()=>Kw,getTurnZeroSkillDiscovery:()=>DCe,startSkillDiscoveryPrefetch:()=>Yw});function Gw(e,t){if(e.add(t),e.size>Xw){let t=e.size-Zw,n=e.values();for(let r=0;r<t;r++){let t=n.next();if(t.done)break;e.delete(t.value)}}}function Kw(e,t){let n=[];e&&n.push(e);for(let e=t.length-1;e>=0;e--){let r=t[e];if(r.type!==`user`)continue;let i=r.content;if(typeof i==`string`){n.push(i.slice(0,500));break}if(Array.isArray(i)){let e=!1;for(let t of i){let r=t;if(r.type&&r.type!==`text`)continue;let i=r.text;if(typeof i==`string`&&i.trim()){n.push(i.slice(0,500)),e=!0;break}}if(e)break}}return n.join(` `)}function qw(e,t,n){return{type:`skill_discovery`,skills:e,signal:t,source:`native`,gap:n}}async function Jw(e,t){let n=0,r=[];for(let i of e){let e={name:i.name,description:i.description,score:i.score};if(n>=tT||i.score<eT){r.push(e);continue}let a=await CCe(i);if(!a){r.push(e);continue}n++,await wCe(i.name,a.path,a.content,t),r.push({...e,autoLoaded:!0,content:a.content,path:a.path})}return r}async function CCe(e){if(!e.skillRoot)return null;let t=[wc(e.skillRoot,`SKILL.md`),wc(e.skillRoot,`skill.md`)];for(let e of t)try{return{path:e,content:Mu(await nl(e,`utf8`)).content.slice(0,nT)}}catch{}return null}async function wCe(e,t,n,r){try{let{addInvokedSkill:i}=await import(`./state-DXt6rahM.js`);i(e,t,n,r.agentId??null)}catch{}}async function TCe(e,t,n,r){if(r!==`user_input`||!e.trim())return;let i=`${r}:${e.trim().toLowerCase()}`;if(!$w.has(i)){Gw($w,i);try{let[{isSkillLearningEnabled:r},{recordSkillGap:i}]=await Promise.all([import(`./featureCheck-JOur3pHb.js`),import(`./skillGapStore-01n-MpeF.js`)]);if(!r())return;let a=await i({prompt:e,cwd:n.cwd??process.cwd(),sessionId:n.sessionId??`unknown-session`,recommendations:t}),o=a.status;return o!==`pending`&&o!==`draft`&&o!==`active`?void 0:{key:a.key,status:o,draftName:a.draft?.name,draftPath:a.draft?.skillPath,activeName:a.active?.name,activePath:a.active?.skillPath}}catch(e){K(`[skill-search] skill gap learning error: ${e}`);return}}}async function Yw(e,t,n){if(!Tp())return[];let r=Date.now(),i=Kw(e,t);if(!i.trim())return[];try{let e=await yoe(n.cwd??process.cwd()),t=Coe(i,e).filter(e=>!Qw.has(e.name));if(t.length===0)return[];for(let e of t)Gw(Qw,e.name);let a={trigger:`assistant_turn`,queryText:i.slice(0,200),startedAt:r,durationMs:Date.now()-r,indexSize:e.length,method:`tfidf`};return K(`[skill-search] prefetch found ${t.length} skills in ${a.durationMs}ms`),[qw(await Jw(t,n),a)]}catch(e){return K(`[skill-search] prefetch error: ${e}`),[]}}async function ECe(e){try{return await e}catch{return[]}}async function DCe(e,t,n){if(!Tp()||!e.trim())return null;let r=Date.now();try{let t=await yoe(n.cwd??process.cwd()),i=Coe(await _Ce(e),t),a=await Jw(i,n),o=a.some(e=>e.autoLoaded)?void 0:await TCe(e,i,n,`user_input`);if(i.length===0&&!o)return null;for(let e of i)Gw(Qw,e.name);let s={trigger:`user_input`,queryText:e.slice(0,200),startedAt:r,durationMs:Date.now()-r,indexSize:t.length,method:`tfidf`};return K(`[skill-search] turn-zero found ${i.length} skills in ${s.durationMs}ms`),qw(a,s,o)}catch(e){return K(`[skill-search] turn-zero error: ${e}`),null}}var Xw,Zw,Qw,$w,eT,tT,nT,rT=n((()=>{Ep(),Ws(),SCe(),q(),Hu(),Xw=1e3,Zw=750,Qw=new Set,$w=new Set,eT=Number(process.env.SKILL_SEARCH_AUTOLOAD_MIN_SCORE??`0.30`),tT=Number(process.env.SKILL_SEARCH_AUTOLOAD_LIMIT??`2`),nT=Number(process.env.SKILL_SEARCH_AUTOLOAD_MAX_CHARS??`12000`)}));function iT(e){return uT.test(e)}function OCe(e){if(e.startsWith(`mcp__`)){let t=e.replace(/^mcp__/,``).toLowerCase();return{parts:t.split(`__`).flatMap(e=>e.split(`_`)).filter(Boolean),full:t.replace(/__/g,` `).replace(/_/g,` `),isMcp:!0}}let t=e.replace(/([a-z])([A-Z])/g,`$1 $2`).replace(/_/g,` `).toLowerCase().split(/\s+/).filter(Boolean);return{parts:t,full:t.join(` `),isMcp:!1}}async function kCe(e){let t=e.filter(e=>vs(e)),n=[];for(let r of t){let t=``;try{t=await r.prompt({getToolPermissionContext:async()=>({mode:`default`,additionalWorkingDirectories:new Map,alwaysAllowRules:{},alwaysDenyRules:{},alwaysAskRules:{},isBypassPermissionsModeAvailable:!1}),tools:e,agents:[]})}catch{t=``}let{parts:i,full:a}=OCe(r.name),o=r.searchHint??``,s=Us(i.join(` `)),c=Us(o),l=Us(t),u=[...new Set([...s,...c,...l])],d=Soe([{tokens:s,weight:sT.name},{tokens:c,weight:sT.searchHint},{tokens:l,weight:sT.description}]),f;r.inputJSONSchema&&(f=r.inputJSONSchema),n.push({name:r.name,normalizedName:a,description:t,searchHint:r.searchHint,isMcp:r.isMcp===!0,isDeferred:!0,inputSchema:f,tokens:u,tfVector:d})}let r=xoe(n);for(let e of n)for(let[t,n]of e.tfVector)e.tfVector.set(t,n*(r.get(t)??0));return K(`[search-extra-tools] indexed ${n.length} deferred tools from ${e.length} total tools`),n}function aT(e,t,n=5){if(t.length===0||!e.trim())return[];let r=Us(e);if(r.length===0)return[];let i=new Map,a=new Map;for(let e of r)a.set(e,(a.get(e)??0)+1);let o=1;for(let e of a.values())e>o&&(o=e);for(let[e,t]of a)i.set(e,t/o);let s=xoe(t),c=new Map;for(let[e,t]of i)c.set(e,t*(s.get(e)??0));let l=r.filter(e=>iT(e[0]??``)),u=r.filter(e=>!iT(e[0]??``)),d=e.toLowerCase().replace(/[-_]/g,` `),f=[];for(let e of t){let t=boe(c,e.tfVector);l.length>0&&t>0&&l.filter(t=>e.tfVector.has(t)).length<lT&&(u.some(t=>e.tfVector.has(t))||(t=0)),d.includes(e.normalizedName)&&(t=Math.max(t,.75)),t>=cT&&f.push({name:e.name,description:e.description,searchHint:e.searchHint,score:t,isMcp:e.isMcp,isDeferred:e.isDeferred,inputSchema:e.inputSchema})}return f.sort((e,t)=>t.score-e.score),f.slice(0,n)}async function oT(e){let t=e.map(e=>e.name).sort().join(`,`);return dT&&fT===t?dT:(dT=await kCe(e),fT=t,dT)}var sT,cT,lT,uT,dT,fT,pT=n((()=>{q(),Ws(),Os(),sT={name:3,searchHint:2.5,description:1},cT=Number(process.env.SEARCH_EXTRA_TOOLS_DISPLAY_MIN_SCORE??`0.10`),lT=2,uT=/[\u4e00-\u9fff\u3400-\u4dbf]/,dT=null,fT=null})),mT=i({buildToolDiscoveryAttachment:()=>yT,clearSearchExtraToolsPrefetchResults:()=>vT,collectSearchExtraToolsPrefetch:()=>xT,getSearchExtraToolsPrefetchSnapshot:()=>_T,getTurnZeroSearchExtraToolsPrefetch:()=>MCe,startSearchExtraToolsPrefetch:()=>bT,subscribeToSearchExtraToolsPrefetch:()=>gT});function hT(){for(let e of ET)e()}function gT(e){return ET.add(e),()=>{ET.delete(e)}}function _T(){return TT}function vT(){TT=[],hT()}function ACe(e,t){if(e.add(t),e.size>ST){let t=e.size-CT,n=e.values();for(let r=0;r<t;r++){let t=n.next();if(t.done)break;e.delete(t.value)}}}function jCe(e){return{name:e.name,description:e.description,searchHint:e.searchHint,score:e.score,isMcp:e.isMcp,isDeferred:e.isDeferred,inputSchema:e.inputSchema}}function yT(e,t,n,r,i){return{type:`tool_discovery`,tools:e,trigger:t,queryText:n.slice(0,200),durationMs:r,indexSize:i}}async function bT(e,t){let n=Date.now(),r=Kw(null,t);if(!r.trim())return[];try{let t=await oT(e),i=aT(r,t,3).filter(e=>!wT.has(e.name));if(i.length===0)return[];for(let e of i)ACe(wT,e.name);let a=Date.now()-n;K(`[search-extra-tools] prefetch found ${i.length} tools in ${a}ms`);let o=i.map(jCe);return TT=o,hT(),[yT(o,`assistant_turn`,r,a,t.length)]}catch(e){return K(`[search-extra-tools] prefetch error: ${e}`),[]}}async function MCe(e,t){return null}async function xT(e){try{return await e}catch{return[]}}var ST,CT,wT,TT,ET,DT=n((()=>{pT(),q(),rT(),ST=500,CT=400,wT=new Set,TT=[],ET=new Set}));function OT(e){AT=e}function kT(){return AT}function NCe(e){jT=e}function PCe(){return jT}function FCe(e){MT=e}function ICe(){return MT}var AT,jT,MT,NT=n((()=>{AT=!1,jT=!1,MT=!1}));function PT(e,t=zT){return new BT(e,t)}function FT(e){return Object.fromEntries(e.entries())}function IT(e){return Array.from(e.keys())}function LT(e){let t=PT(e.max,e.maxSize);return t.load(e.dump()),t}function RT(e,t){let n=LT(e);for(let[e,r]of t.entries()){let t=n.get(e);(!t||r.timestamp>t.timestamp)&&n.set(e,r)}return n}var zT,BT,VT=n((()=>{Sn(),b(),zT=25*1024*1024,BT=class{constructor(e,t){x(this,`cache`,void 0),this.cache=new nt({max:e,maxSize:t,sizeCalculation:e=>{let t=e.content,n=typeof t==`string`?t:t==null?``:typeof t==`object`?JSON.stringify(t):String(t);return Math.max(1,Buffer.byteLength(n,`utf8`))}})}get(e){return this.cache.get(hc(e))}set(e,t){return this.cache.set(hc(e),t),this}has(e){return this.cache.has(hc(e))}delete(e){return this.cache.delete(hc(e))}clear(){this.cache.clear()}get size(){return this.cache.size}get max(){return this.cache.max}get maxSize(){return this.cache.maxSize}get calculatedSize(){return this.cache.calculatedSize}keys(){return this.cache.keys()}entries(){return this.cache.entries()}dump(){return this.cache.dump()}load(e){this.cache.load(e)}}}));function HT(e=WT){let t=new AbortController;return gce(e,t.signal),t}function LCe(e){let t=this.deref();e.deref()?.abort(t?.signal.reason)}function RCe(e){let t=this.deref(),n=e.deref();t&&n&&t.signal.removeEventListener(`abort`,n)}function UT(e,t){let n=HT(t);if(e.signal.aborted)return n.abort(e.signal.reason),n;let r=new WeakRef(n),i=new WeakRef(e),a=LCe.bind(i,r);return e.signal.addEventListener(`abort`,a,{once:!0}),n.signal.addEventListener(`abort`,RCe.bind(i,new WeakRef(a)),{once:!0}),n}var WT,GT=n((()=>{WT=50}));function KT(){return!1}function zCe(e){return e.some(e=>{if(e.type!==`user`)return!1;let t=e.message.content;return Array.isArray(t)?t.some(e=>e.type===`text`&&e.text.includes(`<fork-boilerplate>`)):!1})}function BCe(e,t){let n={...t,uuid:Lc(),message:{...t.message,content:[...Array.isArray(t.message.content)?t.message.content:[]]}},r=(Array.isArray(t.message.content)?t.message.content:[]).filter(e=>e.type===`tool_use`);return r.length===0?(K(`No tool_use blocks found in assistant message for fork directive: ${e.slice(0,50)}...`,{level:`error`}),[Q({content:[{type:`text`,text:qT(e)}]})]):[n,Q({content:[...r.map(e=>({type:`tool_result`,tool_use_id:e.id,content:[{type:`text`,text:XT}]})),{type:`text`,text:qT(e)}]})]}function qT(e){return`<${xa}>
733
733
  STOP. READ THIS FIRST.
734
734
 
735
735
  You are a forked worker process. You are NOT the main agent.
@@ -811,7 +811,7 @@ Usage notes:
811
811
  ... (truncated because it exceeds 2k characters. If you need more information, run "git status" using BashTool)`:i;return Cn(`info`,`git_status_completed`,{duration_ms:Date.now()-e,truncated:i.length>uO}),[`This is the git status at the start of the conversation. Note that this status is a snapshot in time, and will not update during the conversation.`,`Current branch: ${n}`,`Main branch (you will usually use this for PRs): ${r}`,...o?[`Git user: ${o}`]:[],`Status:\n${s||`(clean)`}`,`Recent commits:\n${a}`].join(`
812
812
 
813
813
  `)}catch(t){return Cn(`error`,`git_status_failed`,{duration_ms:Date.now()-e}),Y(t),null}}),fO=u(async()=>{let e=Date.now();Cn(`info`,`system_context_started`);let t=h(process.env.WORKMATE_REMOTE)||!cO()?null:await dO();return Cn(`info`,`system_context_completed`,{duration_ms:Date.now()-e,has_git_status:t!==null,has_injection:!1}),{...t&&{gitStatus:t}}}),pO=u(async()=>{let e=Date.now();Cn(`info`,`user_context_started`);let t=h(process.env.WORKMATE_DISABLE_AGENTS_MDS)||v()&&Zr().length===0,n=t?null:oSe(qxe(await VC()));return Fne(n||null),Cn(`info`,`user_context_completed`,{duration_ms:Date.now()-e,agentsmd_length:n?.length??0,agentsmd_disabled:!!t}),{...n&&{agentsMd:n},currentDate:`Today's date is ${aO()}.`}})}));function Gwe(){return wf()}function hO({mainThreadAgentDefinition:e,toolUseContext:t,customSystemPrompt:n,defaultSystemPrompt:r,appendSystemPrompt:i,overrideSystemPrompt:a}){if(a)return t_([a]);let o=e?q9(e)?e.getSystemPrompt({toolUseContext:{options:t.options}}):e.getSystemPrompt():void 0;return e?.memory&&e.memory,o&&Gwe()?t_([...r,`\n# Custom Agent Instructions\n${o}`,...i?[i]:[]]):t_([...o?[o]:n?[n]:r,...i?[i]:[]])}var gO=n((()=>{La(),$9(),Iw(),Hf()})),Kwe=i({_resetCacheWarningStateForTest:()=>qwe,calculateCacheHitRate:()=>yO,createCacheWarningMessage:()=>xO,getCacheThreshold:()=>_O,isCacheWarningEnabled:()=>vO,shouldShowCacheWarning:()=>bO});function _O(){return rr().cacheThreshold??wO}function vO(){return rr().cacheWarningEnabled??!0}function yO(e){if(!e)return null;let{input_tokens:t,cache_creation_input_tokens:n,cache_read_input_tokens:r}=e;if(r===0&&n===0)return null;let i=t+n+r;return i===0?null:r/i*100}function bO(e,t,n){let r=yO(e);if(r===null)return null;let i=SO.get(t);if(!i){if(i={lastHitRate:null,lastTimestamp:null},SO.size>=CO){let e=SO.keys().next().value;e!==void 0&&SO.delete(e)}SO.set(t,i)}if(i.lastHitRate===null)return i.lastHitRate=r,i.lastTimestamp=Date.now(),null;let a=r-i.lastHitRate;return i.lastHitRate=r,i.lastTimestamp=Date.now(),r<n?{hitRate:r,threshold:n,trend:a,shouldWarn:!0}:null}function xO(e){let{hitRate:t,threshold:n,trend:r}=e,i=`Cache hit rate ${t.toFixed(0)}%, below ${n}% threshold`;if(r!==null&&Math.abs(r)>.1){let e=r>0?`^`:`v`,t=Math.abs(r).toFixed(0);i+=` (${e}${t}%)`}return{type:`system`,subtype:`cache_warning`,level:`warning`,content:i,timestamp:new Date().toISOString(),uuid:Lc(),isMeta:!1}}function qwe(){SO.clear()}var SO,CO,wO,TO=n((()=>{Ln(),SO=new Map,CO=50,wO=80}));async function EO(e,t){try{let n=await S3(e,t);if(n!==null)return n;K(`countTokensWithFallback: API returned null, trying haiku fallback (${t.length} tools)`)}catch(e){K(`countTokensWithFallback: API failed: ${G(e)}`),Y(e)}try{let n=await Xet(e,t);return n===null&&K(`countTokensWithFallback: haiku fallback also returned null (${t.length} tools)`),n}catch(e){return K(`countTokensWithFallback: haiku fallback failed: ${G(e)}`),Y(e),null}}async function DO(e,t,n,r){let i=await EO([],await Promise.all(e.map(i=>H7(i,{getToolPermissionContext:t,tools:e,agents:n?.activeAgents??[],model:r}))));if(i===null||i===0){let t=e.map(e=>e.name).join(`, `);K(`countToolDefinitionTokens returned ${i} for ${e.length} tools: ${t.slice(0,100)}${t.length>100?`...`:``}`)}return i??0}function Jwe(e){let t=e.match(/^#+\s+(.+)$/m);if(t)return t[1].trim();let n=e.split(`
814
- `).find(e=>e.trim().length>0)??``;return n.length>40?`${n.slice(0,40)}…`:n}async function Ywe(e){let t=await fO(),n=[...e.filter(e=>e.length>0&&e!==`__SYSTEM_PROMPT_DYNAMIC_BOUNDARY__`).map(e=>({name:Jwe(e),content:e})),...Object.entries(t).filter(([,e])=>e.length>0).map(([e,t])=>({name:e,content:t}))];if(n.length<1)return{systemPromptTokens:0,systemPromptSections:[]};let r=await Promise.all(n.map(({content:e})=>EO([{role:`user`,content:e}],[]))),i=n.map((e,t)=>({name:e.name,tokens:r[t]||0}));return{systemPromptTokens:r.reduce((e,t)=>e+(t||0),0),systemPromptSections:i}}async function Xwe(){if(h(process.env.WORKMATE_SIMPLE))return{memoryFileDetails:[],agentsMdTokens:0};let e=qxe(await VC()),t=[],n=0;if(e.length<1)return{memoryFileDetails:[],agentsMdTokens:0};let r=await Promise.all(e.map(async e=>({file:e,tokens:await EO([{role:`user`,content:e.content}],[])||0})));for(let{file:e,tokens:i}of r)n+=i,t.push({path:e.path,type:e.type,tokens:i});return{agentsMdTokens:n,memoryFileDetails:t}}async function Zwe(e,t,n,r,i){let a=e.filter(e=>!e.isMcp);if(a.length<1)return{builtInToolTokens:0,deferredBuiltinDetails:[],deferredBuiltinTokens:0,systemToolDetails:[]};let o=[],{isSearchExtraToolsEnabled:s}=await import(`./searchExtraTools-C1v6F01_.js`),{isDeferredTool:c}=await import(`./prompt-Bxk7M5A5.js`),l=await s(r??``,e,t,n?.activeAgents??[],`analyzeBuiltIn`),u=a.filter(e=>!c(e)),d=a.filter(e=>c(e)),f=u.length>0?await DO(u,t,n,r):0,p=[],m=0,h=0;if(d.length>0&&l){let e=new Set;if(i){let t=new Set(d.map(e=>e.name));for(let n of i)if(n.type===`assistant`&&Array.isArray(n.message.content))for(let r of n.message.content)typeof r!=`string`&&`type`in r&&r.type===`tool_use`&&`name`in r&&typeof r.name==`string`&&t.has(r.name)&&e.add(r.name)}let a=await Promise.all(d.map(e=>DO([e],t,n,r)));for(let[t,n]of d.entries()){let r=Math.max(0,(a[t]||0)-500),i=e.has(n.name);p.push({name:n.name,tokens:r,isLoaded:i}),h+=r,i&&(m+=r)}}else if(d.length>0)return{builtInToolTokens:f+await DO(d,t,n,r),deferredBuiltinDetails:[],deferredBuiltinTokens:0,systemToolDetails:o};return{builtInToolTokens:f+m,deferredBuiltinDetails:p,deferredBuiltinTokens:h-m,systemToolDetails:o}}function OO(e){return ms(e,ns)}async function Qwe(e,t,n){let r=await uge(U()),i=OO(e);return i?{slashCommandTokens:await DO([i],t,n),commandInfo:{totalCommands:r.totalCommands,includedCommands:r.includedCommands}}:{slashCommandTokens:0,commandInfo:{totalCommands:0,includedCommands:0}}}async function $we(e,t,n){try{let r=await dge(U()),i=OO(e);if(!i)return{skillTokens:0,skillInfo:{totalSkills:0,includedSkills:0,skillFrontmatter:[]}};let a=await DO([i],t,n),o=r.map(e=>({name:G3(e),source:e.type===`prompt`?e.source:`plugin`,tokens:att(e)}));return{skillTokens:a,skillInfo:{totalSkills:r.length,includedSkills:r.length,skillFrontmatter:o}}}catch(e){return Y(wi(e)),{skillTokens:0,skillInfo:{totalSkills:0,includedSkills:0,skillFrontmatter:[]}}}}async function kO(e,t,n,r,i){let a=e.filter(e=>e.isMcp),o=[],s=await DO(a,t,n,r),c=Math.max(0,(s||0)-500),l=await Promise.all(a.map(async r=>C3(W({name:r.name,description:await r.prompt({getToolPermissionContext:t,tools:e,agents:n?.activeAgents??[]}),input_schema:r.inputJSONSchema??{}})))),u=l.reduce((e,t)=>e+t,0)||1,d=l.map(e=>Math.round(e/u*c)),{isSearchExtraToolsEnabled:f}=await import(`./searchExtraTools-C1v6F01_.js`),{isDeferredTool:p}=await import(`./prompt-Bxk7M5A5.js`),m=await f(r,e,t,n?.activeAgents??[],`analyzeMcp`),h=new Set;if(m&&i){let e=new Set(a.map(e=>e.name));for(let t of i)if(t.type===`assistant`&&Array.isArray(t.message.content))for(let n of t.message.content)typeof n!=`string`&&`type`in n&&n.type===`tool_use`&&`name`in n&&typeof n.name==`string`&&e.has(n.name)&&h.add(n.name)}for(let[e,t]of a.entries())o.push({name:t.name,serverName:t.name.split(`__`)[1]||`unknown`,tokens:d[e],isLoaded:h.has(t.name)||!p(t)});let g=0,_=0;for(let e of o)e.isLoaded?g+=e.tokens:m&&(_+=e.tokens);return{mcpToolTokens:m?g:c,mcpToolDetails:o,deferredToolTokens:_,loadedMcpToolNames:h}}async function eTe(e){let t=e.activeAgents.filter(e=>e.source!==`built-in`),n=[],r=0,i=await Promise.all(t.map(e=>EO([{role:`user`,content:[e.agentType,e.whenToUse].join(` `)}],[])));for(let[e,a]of t.entries()){let t=i[e]||0;r+=t||0,n.push({agentType:a.agentType,source:a.source,tokens:t||0})}return{agentTokens:r,agentDetails:n}}function tTe(e,t){let n=Array.isArray(e.message.content)?e.message.content:[];for(let e of n){let n=C3(W(e));if(typeof e!=`string`&&`type`in e&&e.type===`tool_use`){t.toolCallTokens+=n;let r=(`name`in e?e.name:void 0)||`unknown`;t.toolCallsByType.set(r,(t.toolCallsByType.get(r)||0)+n)}else t.assistantMessageTokens+=n}}function nTe(e,t,n){if(typeof e.message.content==`string`){let n=C3(e.message.content);t.userMessageTokens+=n;return}for(let r of e.message.content??[]){let e=C3(W(r));if(`type`in r&&r.type===`tool_result`){let i=`tool_use_id`in r?r.tool_use_id:void 0,a=(i?n.get(i):void 0)||`unknown`;t.toolResultsByType.set(a,(t.toolResultsByType.get(a)||0)+e)}else t.userMessageTokens+=e}}function rTe(e,t){let n=C3(W(e.attachment));t.attachmentTokens+=n;let r=e.attachment.type||`unknown`;t.attachmentsByType.set(r,(t.attachmentsByType.get(r)||0)+n)}async function iTe(e){let t=await eO(e),n={totalTokens:0,toolCallTokens:0,toolResultTokens:0,attachmentTokens:0,assistantMessageTokens:0,userMessageTokens:0,toolCallsByType:new Map,toolResultsByType:new Map,attachmentsByType:new Map},r=new Map;for(let e of t.messages)if(e.type===`assistant`&&Array.isArray(e.message.content)){for(let t of e.message.content)if(typeof t!=`string`&&`type`in t&&t.type===`tool_use`){let e=`id`in t?t.id:void 0,n=(`name`in t?t.name:void 0)||`unknown`;e&&r.set(e,n)}}for(let e of t.messages)e.type===`assistant`?tTe(e,n):e.type===`user`?nTe(e,n,r):e.type===`attachment`&&rTe(e,n);return n.totalTokens=await EO(d3(t.messages).map(e=>e.type===`assistant`?{role:`assistant`,content:e.message.content}:e.message),[])??0,n}async function aTe(t,n,r,i,a,o,s,c,l){let u=ko({permissionMode:(await r()).mode,mainLoopModel:n}),d=Co(u,ni()),f=await I7(i,u),p=hO({mainThreadAgentDefinition:c,toolUseContext:s??{options:{}},customSystemPrompt:s?.options.customSystemPrompt,defaultSystemPrompt:f,appendSystemPrompt:s?.options.appendSystemPrompt}),[{systemPromptTokens:m,systemPromptSections:h},{agentsMdTokens:g,memoryFileDetails:_},{builtInToolTokens:v,deferredBuiltinDetails:y,deferredBuiltinTokens:b,systemToolDetails:x},{mcpToolTokens:S,mcpToolDetails:C,deferredToolTokens:w},{agentTokens:T,agentDetails:E},{slashCommandTokens:D,commandInfo:O},k]=await Promise.all([Ywe(p),Xwe(),Zwe(i,r,a,u,t),kO(i,r,a,u,t),eTe(a),Qwe(i,r,a),iTe(t)]),A=(await $we(i,r,a)).skillInfo,ee=A.skillFrontmatter.reduce((e,t)=>e+t.tokens,0),te=k.totalTokens,ne=dV(),re=ne?cV(n)-pV:void 0,ie=[];m>0&&ie.push({name:`System prompt`,tokens:m,color:`promptBorder`});let ae=v-ee;ae>0&&ie.push({name:`System tools`,tokens:ae,color:`inactive`}),S>0&&ie.push({name:`MCP tools`,tokens:S,color:`cyan_FOR_SUBAGENTS_ONLY`}),w>0&&ie.push({name:`MCP tools (deferred)`,tokens:w,color:`inactive`,isDeferred:!0}),b>0&&ie.push({name:`System tools (deferred)`,tokens:b,color:`inactive`,isDeferred:!0}),T>0&&ie.push({name:`Custom agents`,tokens:T,color:`permission`}),g>0&&ie.push({name:`Memory files`,tokens:g,color:`claude`}),ee>0&&ie.push({name:`Skills`,tokens:ee,color:`warning`}),te!==null&&te>0&&ie.push({name:`Messages`,tokens:te,color:`purple_FOR_SUBAGENTS_ONLY`});let j=ie.reduce((e,t)=>e+(t.isDeferred?0:t.tokens),0),oe=0;ne&&re!==void 0?(oe=d-re,ie.push({name:AO,tokens:oe,color:`inactive`})):ne||(oe=gV,ie.push({name:jO,tokens:oe,color:`inactive`}));let se=Math.max(0,d-j-oe);ie.push({name:`Free space`,tokens:se,color:`promptBorder`});let ce=j,M=AD(l??t),N=(M?M.input_tokens+M.cache_creation_input_tokens+M.cache_read_input_tokens:null)??ce,le=o&&o<80,ue=d>=1e6?le?5:20:le?5:10,de=d>=1e6?10:le?5:10,fe=ue*de,pe=ie.filter(e=>!e.isDeferred).map(e=>({...e,squares:e.name===`Free space`?Math.round(e.tokens/d*fe):Math.max(1,Math.round(e.tokens/d*fe)),percentageOfTotal:Math.round(e.tokens/d*100)}));function me(e){let t=[],n=e.tokens/d*fe,r=Math.floor(n),i=n-r;for(let n=0;n<e.squares;n++){let a=1;n===r&&i>0&&(a=i),t.push({color:e.color,isFilled:!0,categoryName:e.name,tokens:e.tokens,percentage:e.percentageOfTotal,squareFullness:a})}return t}let he=[],ge=pe.find(e=>e.name===AO||e.name===jO),_e=pe.filter(e=>e.name!==AO&&e.name!==jO&&e.name!==`Free space`);for(let e of _e){let t=me(e);for(let e of t)he.length<fe&&he.push(e)}let ve=ge?ge.squares:0,ye=ie.find(e=>e.name===`Free space`),be=fe-ve;for(;he.length<be;)he.push({color:`promptBorder`,isFilled:!0,categoryName:`Free space`,tokens:ye?.tokens||0,percentage:ye?Math.round(ye.tokens/d*100):0,squareFullness:1});if(ge){let e=me(ge);for(let t of e)he.length<fe&&he.push(t)}let P=[];for(let e=0;e<de;e++)P.push(he.slice(e*ue,(e+1)*ue));let xe=new Map;for(let[e,t]of k.toolCallsByType.entries()){let n=xe.get(e)||{callTokens:0,resultTokens:0};xe.set(e,{...n,callTokens:t})}for(let[e,t]of k.toolResultsByType.entries()){let n=xe.get(e)||{callTokens:0,resultTokens:0};xe.set(e,{...n,resultTokens:t})}let Se=Array.from(xe.entries()).map(([e,{callTokens:t,resultTokens:n}])=>({name:e,callTokens:t,resultTokens:n})).sort((e,t)=>t.callTokens+t.resultTokens-(e.callTokens+e.resultTokens)),Ce=Array.from(k.attachmentsByType.entries()).map(([e,t])=>({name:e,tokens:t})).sort((e,t)=>t.tokens-e.tokens),we={toolCallTokens:k.toolCallTokens,toolResultTokens:k.toolResultTokens,attachmentTokens:k.attachmentTokens,assistantMessageTokens:k.assistantMessageTokens,userMessageTokens:k.userMessageTokens,toolCallsByType:Se,attachmentsByType:Ce};return{categories:ie,totalTokens:N,maxTokens:d,rawMaxTokens:d,percentage:Math.round(N/d*100),gridRows:P,model:u,memoryFiles:_,mcpTools:C,deferredBuiltinTools:void 0,systemTools:void 0,systemPromptSections:void 0,agents:E,slashCommands:D>0?{totalCommands:O.totalCommands,includedCommands:O.includedCommands,tokens:D}:void 0,skills:ee>0?{totalSkills:A.totalSkills,includedSkills:A.includedSkills,tokens:ee,skillFrontmatter:A.skillFrontmatter}:void 0,autoCompactThreshold:re,isAutoCompactEnabled:ne,messageBreakdown:we,apiUsage:M,...(()=>{if(!M)return{};let{calculateCacheHitRate:t,getCacheThreshold:n}=(TO(),e(Kwe)),r=t(M);return r===null?{}:{cacheHitRate:r,cacheThreshold:n()}})()}}var AO,jO,MO=n((()=>{V7(),iO(),H(),t6(),mO(),yV(),O3(),H3(),Ms(),Ls(),cy(),W7(),WC(),yo(),ui(),q(),g(),gi(),wa(),v3(),wo(),Li(),gO(),PD(),AO=`Autocompact buffer`,jO=`Compact buffer`}));function NO(e){let t=PO.get(e);if(t)return t;let n=Xee(e);return PO.set(e,n),n}var PO,FO=n((()=>{It(),PO=new WeakMap}));function IO(e){if(!e.startsWith(`auto:`))return null;let t=e.slice(5),n=parseInt(t,10);return isNaN(n)?(K(`Invalid ENABLE_SEARCH_EXTRA_TOOLS value "${e}": expected auto:N where N is a number.`),null):Math.max(0,Math.min(100,n))}function oTe(e){return e?e===`auto`||e.startsWith(`auto:`):!1}function LO(){let e=process.env.ENABLE_SEARCH_EXTRA_TOOLS;if(!e||e===`auto`)return JO;let t=IO(e);return t===null?JO:t}function RO(e){let t=Co(e,zg(e)),n=LO()/100;return Math.floor(t*n)}function zO(e){return Math.floor(RO(e)*YO)}function BO(){if(h(process.env.WORKMATE_DISABLE_EXPERIMENTAL_BETAS))return`standard`;let e=process.env.ENABLE_SEARCH_EXTRA_TOOLS,t=e?IO(e):null;return t===0?`tst`:t===100?`standard`:oTe(e)?`tst-auto`:h(e)?`tst`:f(process.env.ENABLE_SEARCH_EXTRA_TOOLS)?`standard`:`tst`}function VO(){let e=BO();return e===`standard`?(ZO||(ZO=!0,K(`[SearchExtraTools:optimistic] mode=${e}, ENABLE_SEARCH_EXTRA_TOOLS=${process.env.ENABLE_SEARCH_EXTRA_TOOLS}, result=false`)),!1):(ZO||(ZO=!0,K(`[SearchExtraTools:optimistic] mode=${e}, ENABLE_SEARCH_EXTRA_TOOLS=${process.env.ENABLE_SEARCH_EXTRA_TOOLS}, result=true`)),!0)}function HO(e){return e.some(e=>us(e,Ss))}async function sTe(e,t,n){let r=e.filter(e=>vs(e));return r.length===0?0:(await Promise.all(r.map(async r=>{let i=await r.prompt({getToolPermissionContext:t,tools:e,agents:n}),a=r.inputJSONSchema?W(r.inputJSONSchema):r.inputSchema?W(NO(r.inputSchema)):``;return r.name.length+i.length+a.length}))).reduce((e,t)=>e+t,0)}async function UO(e,t,n,r,i){zt(t,e=>e.isMcp);function a(e,t,n,r){process.env.USER_TYPE,{...r}}if(!HO(t))return K(`Tool search disabled: SearchExtraToolsTool is not available (may have been disallowed via disallowedTools).`),a(!1,`standard`,`mcp_search_unavailable`),!1;let o=BO();switch(o){case`tst`:return a(!0,o,`tst_enabled`),!0;case`tst-auto`:{let{enabled:s,debugDescription:c,metrics:l}=await fTe(t,n,r,e);return s?(K(`Auto tool search enabled: ${c}`+(i?` [source: ${i}]`:``)),a(!0,o,`auto_above_threshold`,l),!0):(K(`Auto tool search disabled: ${c}`+(i?` [source: ${i}]`:``)),a(!1,o,`auto_below_threshold`,l),!1)}case`standard`:return a(!1,o,`standard_mode`),!1}}function WO(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_reference`}function cTe(e){return WO(e)&&`tool_name`in e&&typeof e.tool_name==`string`}function lTe(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_result`&&`content`in e&&Array.isArray(e.content)}function uTe(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_result`&&`content`in e&&typeof e.content==`string`}function dTe(e){let t=QO.exec(e);return t?.[1]?t[1].split(`,`).map(e=>e.trim()).filter(Boolean):[]}function GO(e){let t=new Set,n=0;for(let r of e){if(r.type===`system`&&r.subtype===`compact_boundary`){let e=r.compactMetadata?.preCompactDiscoveredTools;if(e){for(let n of e)t.add(n);n+=e.length}continue}if(r.type===`attachment`&&r.attachment?.type===`deferred_tools_delta`){let e=r.attachment.addedNames??[];for(let n of e)t.add(n);continue}if(r.type!==`user`)continue;let e=r.message?.content;if(Array.isArray(e))for(let n of e){if(lTe(n))for(let e of n.content)cTe(e)&&t.add(e.tool_name);if(uTe(n)){let e=dTe(n.content);for(let n of e)t.add(n)}}}return t.size>0&&K(`Dynamic tool loading: found ${t.size} discovered tools in message history`+(n>0?` (${n} carried from compact boundary)`:``)),t}function KO(){return!1}function qO(e,t,n){let r=new Set,i=0,a=0,o=new Set;for(let e of t)if(e.type===`attachment`&&(i++,o.add(e.attachment.type),e.attachment.type===`deferred_tools_delta`)){a++;for(let t of e.attachment.addedNames)r.add(t);for(let t of e.attachment.removedNames)r.delete(t)}let s=e.filter(vs),c=new Set(s.map(e=>e.name)),l=new Set(e.map(e=>e.name)),u=s.filter(e=>!r.has(e.name)),d=[];for(let e of r)c.has(e)||l.has(e)||d.push(e);return u.length===0&&d.length===0?null:(u.length,d.length,r.size,t.length,n?.callSite,n?.querySource,[...o].sort().join(`,`),{addedNames:u.map(e=>e.name).sort(),addedLines:u.map(Jae).sort(),removedNames:d.sort()})}async function fTe(e,t,n,r){let i=await XO(e,t,n,r);if(i!==null){let e=RO(r);return{enabled:i>=e,debugDescription:`${i} tokens (threshold: ${e}, ${LO()}% of context)`,metrics:{deferredToolTokens:i,threshold:e}}}let a=await sTe(e,t,n),o=zO(r);return{enabled:a>=o,debugDescription:`${a} chars (threshold: ${o}, ${LO()}% of context) (char fallback)`,metrics:{deferredToolDescriptionChars:a,charThreshold:o}}}var JO,YO,XO,ZO,QO,$O=n((()=>{d(),La(),Ms(),Os(),MO(),tt(),Wg(),yo(),q(),g(),Li(),FO(),JO=10,YO=2.5,XO=u(async(e,t,n,r)=>{let i=e.filter(e=>vs(e));if(i.length===0)return 0;try{let e=await DO(i,t,{activeAgents:n,allAgents:n},r);return e===0?null:Math.max(0,e-500)}catch{return null}},e=>e.filter(e=>vs(e)).map(e=>e.name).join(`,`)),ZO=!1,QO=/^Found \d+ deferred tool\(s\): (.+)\.$/m}));function pTe(e){return e.map(e=>e.name).sort().join(`,`)}function mTe(e){let t=pTe(e);ok!==t&&(K(`SearchExtraToolsTool: cache invalidated - deferred tools changed`),sk.cache.clear?.(),ok=t)}function hTe(){sk.cache.clear?.(),ok=null}function ek(e,t,n,r,i){return{data:{matches:e,query:t,total_deferred_tools:n,...r&&r.length>0?{pending_mcp_servers:r}:{},...i&&i.length>0?{already_loaded:i}:{}}}}function tk(e){if(e.startsWith(`mcp__`)){let t=e.replace(/^mcp__/,``).toLowerCase();return{parts:t.split(`__`).flatMap(e=>e.split(`_`)).filter(Boolean),full:t.replace(/__/g,` `).replace(/_/g,` `),isMcp:!0}}let t=e.replace(/([a-z])([A-Z])/g,`$1 $2`).replace(/_/g,` `).toLowerCase().split(/\s+/).filter(Boolean);return{parts:t,full:t.join(` `),isMcp:!1}}function gTe(e){let t=new Map;for(let n of e)t.has(n)||t.set(n,RegExp(`\\b${Ya(n)}\\b`));return t}async function _Te(e,t,n,r){let i=e.toLowerCase().trim(),a=t.find(e=>e.name.toLowerCase()===i)??n.find(e=>e.name.toLowerCase()===i);if(a)return[a.name];if(i.startsWith(`mcp__`)&&i.length>5){let e=t.filter(e=>e.name.toLowerCase().startsWith(i)).slice(0,r).map(e=>e.name);if(e.length>0)return e}let o=i.split(/\s+/).filter(e=>e.length>0),s=[],c=[];for(let e of o)e.startsWith(`+`)&&e.length>1?s.push(e.slice(1)):c.push(e);let l=s.length>0?[...s,...c]:o,u=gTe(l),d=t;return s.length>0&&(d=(await Promise.all(t.map(async e=>{let t=tk(e.name),r=(await sk(e.name,n)).toLowerCase(),i=e.searchHint?.toLowerCase()??``;return s.every(e=>{let n=u.get(e);return t.parts.includes(e)||t.parts.some(t=>t.includes(e))||n.test(r)||i&&n.test(i)})?e:null}))).filter(e=>e!==null)),(await Promise.all(d.map(async e=>{let t=tk(e.name),r=(await sk(e.name,n)).toLowerCase(),i=e.searchHint?.toLowerCase()??``,a=0;for(let e of l){let n=u.get(e);t.parts.includes(e)?a+=t.isMcp?12:10:t.parts.some(t=>t.includes(e))&&(a+=t.isMcp?6:5),t.full.includes(e)&&a===0&&(a+=3),i&&n.test(i)&&(a+=4),n.test(r)&&(a+=2)}return{name:e.name,score:a}}))).filter(e=>e.score>0).sort((e,t)=>t.score-e.score).slice(0,r).map(e=>e.name)}var nk,rk,ik,ak,ok,sk,ck,lk=n((()=>{d(),It(),La(),Ms(),q(),rt(),Za(),$O(),Os(),pT(),nk=Number(process.env.SEARCH_EXTRA_TOOLS_WEIGHT_KEYWORD??`0.4`),rk=Number(process.env.SEARCH_EXTRA_TOOLS_WEIGHT_TFIDF??`0.6`),ik=R(()=>z({query:B().describe(`Query to find deferred tools. Use "select:<tool_name>" for direct selection, or keywords to search.`),max_results:V().optional().default(5).describe(`Maximum number of results to return (default: 5)`)})),ak=R(()=>z({matches:I(B()),query:B(),total_deferred_tools:V(),pending_mcp_servers:I(B()).optional(),already_loaded:I(B()).optional()})),ok=null,sk=u(async(e,t)=>{let n=ms(t,e);return n?n.prompt({getToolPermissionContext:async()=>({mode:`default`,additionalWorkingDirectories:new Map,alwaysAllowRules:{},alwaysDenyRules:{},alwaysAskRules:{},isBypassPermissionsModeAvailable:!1}),tools:t,agents:[]}):``},e=>e),ck=Cs({isEnabled(){return VO()},isConcurrencySafe(){return!0},isReadOnly(){return!0},name:Ss,maxResultSizeChars:1e5,async description(){return Rae()},async prompt(){return Rae()},get inputSchema(){return ik()},get outputSchema(){return ak()},async call(e,{options:{tools:t},getAppState:n}){let{query:r,max_results:i=5}=e,a=t.filter(vs);mTe(a);function o(){let e=n().mcp.clients.filter(e=>e.type===`pending`);return e.length>0?e.map(e=>e.name):void 0}function s(e,t){e.length,a.length,e.length}let c=r.match(/^select:(.+)$/i);if(c){let e=c[1].split(`,`).map(e=>e.trim()).filter(Boolean),n=[],i=[],l=[];for(let r of e){let e=ms(a,r),o=e??ms(t,r);o?n.includes(o.name)||(n.push(o.name),e||i.push(o.name)):l.push(r)}if(n.length===0){K(`SearchExtraToolsTool: select failed — none found: ${l.join(`, `)}`),s([],`select`);let e=o();return ek([],r,a.length,e)}return l.length>0?K(`SearchExtraToolsTool: partial select — found: ${n.join(`, `)}, missing: ${l.join(`, `)}`):K(`SearchExtraToolsTool: selected ${n.join(`, `)}`),s(n,`select`),ek(n,r,a.length,void 0,i.length>0?i:void 0)}let l=r.match(/^discover:(.+)$/i);if(l){let e=aT(l[1].trim(),await oT(a),i),t=e.map(e=>{let t=`**${e.name}** (score: ${e.score.toFixed(2)})\n${e.description}`;return e.inputSchema&&(t+=`\nSchema: ${JSON.stringify(e.inputSchema)}`),t});return t.length>0&&`${t.length}${t.join(`
814
+ `).find(e=>e.trim().length>0)??``;return n.length>40?`${n.slice(0,40)}…`:n}async function Ywe(e){let t=await fO(),n=[...e.filter(e=>e.length>0&&e!==`__SYSTEM_PROMPT_DYNAMIC_BOUNDARY__`).map(e=>({name:Jwe(e),content:e})),...Object.entries(t).filter(([,e])=>e.length>0).map(([e,t])=>({name:e,content:t}))];if(n.length<1)return{systemPromptTokens:0,systemPromptSections:[]};let r=await Promise.all(n.map(({content:e})=>EO([{role:`user`,content:e}],[]))),i=n.map((e,t)=>({name:e.name,tokens:r[t]||0}));return{systemPromptTokens:r.reduce((e,t)=>e+(t||0),0),systemPromptSections:i}}async function Xwe(){if(h(process.env.WORKMATE_SIMPLE))return{memoryFileDetails:[],agentsMdTokens:0};let e=qxe(await VC()),t=[],n=0;if(e.length<1)return{memoryFileDetails:[],agentsMdTokens:0};let r=await Promise.all(e.map(async e=>({file:e,tokens:await EO([{role:`user`,content:e.content}],[])||0})));for(let{file:e,tokens:i}of r)n+=i,t.push({path:e.path,type:e.type,tokens:i});return{agentsMdTokens:n,memoryFileDetails:t}}async function Zwe(e,t,n,r,i){let a=e.filter(e=>!e.isMcp);if(a.length<1)return{builtInToolTokens:0,deferredBuiltinDetails:[],deferredBuiltinTokens:0,systemToolDetails:[]};let o=[],{isSearchExtraToolsEnabled:s}=await import(`./searchExtraTools-CuTtZ-Me.js`),{isDeferredTool:c}=await import(`./prompt-DF4VkaNR.js`),l=await s(r??``,e,t,n?.activeAgents??[],`analyzeBuiltIn`),u=a.filter(e=>!c(e)),d=a.filter(e=>c(e)),f=u.length>0?await DO(u,t,n,r):0,p=[],m=0,h=0;if(d.length>0&&l){let e=new Set;if(i){let t=new Set(d.map(e=>e.name));for(let n of i)if(n.type===`assistant`&&Array.isArray(n.message.content))for(let r of n.message.content)typeof r!=`string`&&`type`in r&&r.type===`tool_use`&&`name`in r&&typeof r.name==`string`&&t.has(r.name)&&e.add(r.name)}let a=await Promise.all(d.map(e=>DO([e],t,n,r)));for(let[t,n]of d.entries()){let r=Math.max(0,(a[t]||0)-500),i=e.has(n.name);p.push({name:n.name,tokens:r,isLoaded:i}),h+=r,i&&(m+=r)}}else if(d.length>0)return{builtInToolTokens:f+await DO(d,t,n,r),deferredBuiltinDetails:[],deferredBuiltinTokens:0,systemToolDetails:o};return{builtInToolTokens:f+m,deferredBuiltinDetails:p,deferredBuiltinTokens:h-m,systemToolDetails:o}}function OO(e){return ms(e,ns)}async function Qwe(e,t,n){let r=await uge(U()),i=OO(e);return i?{slashCommandTokens:await DO([i],t,n),commandInfo:{totalCommands:r.totalCommands,includedCommands:r.includedCommands}}:{slashCommandTokens:0,commandInfo:{totalCommands:0,includedCommands:0}}}async function $we(e,t,n){try{let r=await dge(U()),i=OO(e);if(!i)return{skillTokens:0,skillInfo:{totalSkills:0,includedSkills:0,skillFrontmatter:[]}};let a=await DO([i],t,n),o=r.map(e=>({name:G3(e),source:e.type===`prompt`?e.source:`plugin`,tokens:att(e)}));return{skillTokens:a,skillInfo:{totalSkills:r.length,includedSkills:r.length,skillFrontmatter:o}}}catch(e){return Y(wi(e)),{skillTokens:0,skillInfo:{totalSkills:0,includedSkills:0,skillFrontmatter:[]}}}}async function kO(e,t,n,r,i){let a=e.filter(e=>e.isMcp),o=[],s=await DO(a,t,n,r),c=Math.max(0,(s||0)-500),l=await Promise.all(a.map(async r=>C3(W({name:r.name,description:await r.prompt({getToolPermissionContext:t,tools:e,agents:n?.activeAgents??[]}),input_schema:r.inputJSONSchema??{}})))),u=l.reduce((e,t)=>e+t,0)||1,d=l.map(e=>Math.round(e/u*c)),{isSearchExtraToolsEnabled:f}=await import(`./searchExtraTools-CuTtZ-Me.js`),{isDeferredTool:p}=await import(`./prompt-DF4VkaNR.js`),m=await f(r,e,t,n?.activeAgents??[],`analyzeMcp`),h=new Set;if(m&&i){let e=new Set(a.map(e=>e.name));for(let t of i)if(t.type===`assistant`&&Array.isArray(t.message.content))for(let n of t.message.content)typeof n!=`string`&&`type`in n&&n.type===`tool_use`&&`name`in n&&typeof n.name==`string`&&e.has(n.name)&&h.add(n.name)}for(let[e,t]of a.entries())o.push({name:t.name,serverName:t.name.split(`__`)[1]||`unknown`,tokens:d[e],isLoaded:h.has(t.name)||!p(t)});let g=0,_=0;for(let e of o)e.isLoaded?g+=e.tokens:m&&(_+=e.tokens);return{mcpToolTokens:m?g:c,mcpToolDetails:o,deferredToolTokens:_,loadedMcpToolNames:h}}async function eTe(e){let t=e.activeAgents.filter(e=>e.source!==`built-in`),n=[],r=0,i=await Promise.all(t.map(e=>EO([{role:`user`,content:[e.agentType,e.whenToUse].join(` `)}],[])));for(let[e,a]of t.entries()){let t=i[e]||0;r+=t||0,n.push({agentType:a.agentType,source:a.source,tokens:t||0})}return{agentTokens:r,agentDetails:n}}function tTe(e,t){let n=Array.isArray(e.message.content)?e.message.content:[];for(let e of n){let n=C3(W(e));if(typeof e!=`string`&&`type`in e&&e.type===`tool_use`){t.toolCallTokens+=n;let r=(`name`in e?e.name:void 0)||`unknown`;t.toolCallsByType.set(r,(t.toolCallsByType.get(r)||0)+n)}else t.assistantMessageTokens+=n}}function nTe(e,t,n){if(typeof e.message.content==`string`){let n=C3(e.message.content);t.userMessageTokens+=n;return}for(let r of e.message.content??[]){let e=C3(W(r));if(`type`in r&&r.type===`tool_result`){let i=`tool_use_id`in r?r.tool_use_id:void 0,a=(i?n.get(i):void 0)||`unknown`;t.toolResultsByType.set(a,(t.toolResultsByType.get(a)||0)+e)}else t.userMessageTokens+=e}}function rTe(e,t){let n=C3(W(e.attachment));t.attachmentTokens+=n;let r=e.attachment.type||`unknown`;t.attachmentsByType.set(r,(t.attachmentsByType.get(r)||0)+n)}async function iTe(e){let t=await eO(e),n={totalTokens:0,toolCallTokens:0,toolResultTokens:0,attachmentTokens:0,assistantMessageTokens:0,userMessageTokens:0,toolCallsByType:new Map,toolResultsByType:new Map,attachmentsByType:new Map},r=new Map;for(let e of t.messages)if(e.type===`assistant`&&Array.isArray(e.message.content)){for(let t of e.message.content)if(typeof t!=`string`&&`type`in t&&t.type===`tool_use`){let e=`id`in t?t.id:void 0,n=(`name`in t?t.name:void 0)||`unknown`;e&&r.set(e,n)}}for(let e of t.messages)e.type===`assistant`?tTe(e,n):e.type===`user`?nTe(e,n,r):e.type===`attachment`&&rTe(e,n);return n.totalTokens=await EO(d3(t.messages).map(e=>e.type===`assistant`?{role:`assistant`,content:e.message.content}:e.message),[])??0,n}async function aTe(t,n,r,i,a,o,s,c,l){let u=ko({permissionMode:(await r()).mode,mainLoopModel:n}),d=Co(u,ni()),f=await I7(i,u),p=hO({mainThreadAgentDefinition:c,toolUseContext:s??{options:{}},customSystemPrompt:s?.options.customSystemPrompt,defaultSystemPrompt:f,appendSystemPrompt:s?.options.appendSystemPrompt}),[{systemPromptTokens:m,systemPromptSections:h},{agentsMdTokens:g,memoryFileDetails:_},{builtInToolTokens:v,deferredBuiltinDetails:y,deferredBuiltinTokens:b,systemToolDetails:x},{mcpToolTokens:S,mcpToolDetails:C,deferredToolTokens:w},{agentTokens:T,agentDetails:E},{slashCommandTokens:D,commandInfo:O},k]=await Promise.all([Ywe(p),Xwe(),Zwe(i,r,a,u,t),kO(i,r,a,u,t),eTe(a),Qwe(i,r,a),iTe(t)]),A=(await $we(i,r,a)).skillInfo,ee=A.skillFrontmatter.reduce((e,t)=>e+t.tokens,0),te=k.totalTokens,ne=dV(),re=ne?cV(n)-pV:void 0,ie=[];m>0&&ie.push({name:`System prompt`,tokens:m,color:`promptBorder`});let ae=v-ee;ae>0&&ie.push({name:`System tools`,tokens:ae,color:`inactive`}),S>0&&ie.push({name:`MCP tools`,tokens:S,color:`cyan_FOR_SUBAGENTS_ONLY`}),w>0&&ie.push({name:`MCP tools (deferred)`,tokens:w,color:`inactive`,isDeferred:!0}),b>0&&ie.push({name:`System tools (deferred)`,tokens:b,color:`inactive`,isDeferred:!0}),T>0&&ie.push({name:`Custom agents`,tokens:T,color:`permission`}),g>0&&ie.push({name:`Memory files`,tokens:g,color:`claude`}),ee>0&&ie.push({name:`Skills`,tokens:ee,color:`warning`}),te!==null&&te>0&&ie.push({name:`Messages`,tokens:te,color:`purple_FOR_SUBAGENTS_ONLY`});let j=ie.reduce((e,t)=>e+(t.isDeferred?0:t.tokens),0),oe=0;ne&&re!==void 0?(oe=d-re,ie.push({name:AO,tokens:oe,color:`inactive`})):ne||(oe=gV,ie.push({name:jO,tokens:oe,color:`inactive`}));let se=Math.max(0,d-j-oe);ie.push({name:`Free space`,tokens:se,color:`promptBorder`});let ce=j,M=AD(l??t),N=(M?M.input_tokens+M.cache_creation_input_tokens+M.cache_read_input_tokens:null)??ce,le=o&&o<80,ue=d>=1e6?le?5:20:le?5:10,de=d>=1e6?10:le?5:10,fe=ue*de,pe=ie.filter(e=>!e.isDeferred).map(e=>({...e,squares:e.name===`Free space`?Math.round(e.tokens/d*fe):Math.max(1,Math.round(e.tokens/d*fe)),percentageOfTotal:Math.round(e.tokens/d*100)}));function me(e){let t=[],n=e.tokens/d*fe,r=Math.floor(n),i=n-r;for(let n=0;n<e.squares;n++){let a=1;n===r&&i>0&&(a=i),t.push({color:e.color,isFilled:!0,categoryName:e.name,tokens:e.tokens,percentage:e.percentageOfTotal,squareFullness:a})}return t}let he=[],ge=pe.find(e=>e.name===AO||e.name===jO),_e=pe.filter(e=>e.name!==AO&&e.name!==jO&&e.name!==`Free space`);for(let e of _e){let t=me(e);for(let e of t)he.length<fe&&he.push(e)}let ve=ge?ge.squares:0,ye=ie.find(e=>e.name===`Free space`),be=fe-ve;for(;he.length<be;)he.push({color:`promptBorder`,isFilled:!0,categoryName:`Free space`,tokens:ye?.tokens||0,percentage:ye?Math.round(ye.tokens/d*100):0,squareFullness:1});if(ge){let e=me(ge);for(let t of e)he.length<fe&&he.push(t)}let P=[];for(let e=0;e<de;e++)P.push(he.slice(e*ue,(e+1)*ue));let xe=new Map;for(let[e,t]of k.toolCallsByType.entries()){let n=xe.get(e)||{callTokens:0,resultTokens:0};xe.set(e,{...n,callTokens:t})}for(let[e,t]of k.toolResultsByType.entries()){let n=xe.get(e)||{callTokens:0,resultTokens:0};xe.set(e,{...n,resultTokens:t})}let Se=Array.from(xe.entries()).map(([e,{callTokens:t,resultTokens:n}])=>({name:e,callTokens:t,resultTokens:n})).sort((e,t)=>t.callTokens+t.resultTokens-(e.callTokens+e.resultTokens)),Ce=Array.from(k.attachmentsByType.entries()).map(([e,t])=>({name:e,tokens:t})).sort((e,t)=>t.tokens-e.tokens),we={toolCallTokens:k.toolCallTokens,toolResultTokens:k.toolResultTokens,attachmentTokens:k.attachmentTokens,assistantMessageTokens:k.assistantMessageTokens,userMessageTokens:k.userMessageTokens,toolCallsByType:Se,attachmentsByType:Ce};return{categories:ie,totalTokens:N,maxTokens:d,rawMaxTokens:d,percentage:Math.round(N/d*100),gridRows:P,model:u,memoryFiles:_,mcpTools:C,deferredBuiltinTools:void 0,systemTools:void 0,systemPromptSections:void 0,agents:E,slashCommands:D>0?{totalCommands:O.totalCommands,includedCommands:O.includedCommands,tokens:D}:void 0,skills:ee>0?{totalSkills:A.totalSkills,includedSkills:A.includedSkills,tokens:ee,skillFrontmatter:A.skillFrontmatter}:void 0,autoCompactThreshold:re,isAutoCompactEnabled:ne,messageBreakdown:we,apiUsage:M,...(()=>{if(!M)return{};let{calculateCacheHitRate:t,getCacheThreshold:n}=(TO(),e(Kwe)),r=t(M);return r===null?{}:{cacheHitRate:r,cacheThreshold:n()}})()}}var AO,jO,MO=n((()=>{V7(),iO(),H(),t6(),mO(),yV(),O3(),H3(),Ms(),Ls(),cy(),W7(),WC(),yo(),ui(),q(),g(),gi(),wa(),v3(),wo(),Li(),gO(),PD(),AO=`Autocompact buffer`,jO=`Compact buffer`}));function NO(e){let t=PO.get(e);if(t)return t;let n=Xee(e);return PO.set(e,n),n}var PO,FO=n((()=>{It(),PO=new WeakMap}));function IO(e){if(!e.startsWith(`auto:`))return null;let t=e.slice(5),n=parseInt(t,10);return isNaN(n)?(K(`Invalid ENABLE_SEARCH_EXTRA_TOOLS value "${e}": expected auto:N where N is a number.`),null):Math.max(0,Math.min(100,n))}function oTe(e){return e?e===`auto`||e.startsWith(`auto:`):!1}function LO(){let e=process.env.ENABLE_SEARCH_EXTRA_TOOLS;if(!e||e===`auto`)return JO;let t=IO(e);return t===null?JO:t}function RO(e){let t=Co(e,zg(e)),n=LO()/100;return Math.floor(t*n)}function zO(e){return Math.floor(RO(e)*YO)}function BO(){if(h(process.env.WORKMATE_DISABLE_EXPERIMENTAL_BETAS))return`standard`;let e=process.env.ENABLE_SEARCH_EXTRA_TOOLS,t=e?IO(e):null;return t===0?`tst`:t===100?`standard`:oTe(e)?`tst-auto`:h(e)?`tst`:f(process.env.ENABLE_SEARCH_EXTRA_TOOLS)?`standard`:`tst`}function VO(){let e=BO();return e===`standard`?(ZO||(ZO=!0,K(`[SearchExtraTools:optimistic] mode=${e}, ENABLE_SEARCH_EXTRA_TOOLS=${process.env.ENABLE_SEARCH_EXTRA_TOOLS}, result=false`)),!1):(ZO||(ZO=!0,K(`[SearchExtraTools:optimistic] mode=${e}, ENABLE_SEARCH_EXTRA_TOOLS=${process.env.ENABLE_SEARCH_EXTRA_TOOLS}, result=true`)),!0)}function HO(e){return e.some(e=>us(e,Ss))}async function sTe(e,t,n){let r=e.filter(e=>vs(e));return r.length===0?0:(await Promise.all(r.map(async r=>{let i=await r.prompt({getToolPermissionContext:t,tools:e,agents:n}),a=r.inputJSONSchema?W(r.inputJSONSchema):r.inputSchema?W(NO(r.inputSchema)):``;return r.name.length+i.length+a.length}))).reduce((e,t)=>e+t,0)}async function UO(e,t,n,r,i){zt(t,e=>e.isMcp);function a(e,t,n,r){process.env.USER_TYPE,{...r}}if(!HO(t))return K(`Tool search disabled: SearchExtraToolsTool is not available (may have been disallowed via disallowedTools).`),a(!1,`standard`,`mcp_search_unavailable`),!1;let o=BO();switch(o){case`tst`:return a(!0,o,`tst_enabled`),!0;case`tst-auto`:{let{enabled:s,debugDescription:c,metrics:l}=await fTe(t,n,r,e);return s?(K(`Auto tool search enabled: ${c}`+(i?` [source: ${i}]`:``)),a(!0,o,`auto_above_threshold`,l),!0):(K(`Auto tool search disabled: ${c}`+(i?` [source: ${i}]`:``)),a(!1,o,`auto_below_threshold`,l),!1)}case`standard`:return a(!1,o,`standard_mode`),!1}}function WO(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_reference`}function cTe(e){return WO(e)&&`tool_name`in e&&typeof e.tool_name==`string`}function lTe(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_result`&&`content`in e&&Array.isArray(e.content)}function uTe(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_result`&&`content`in e&&typeof e.content==`string`}function dTe(e){let t=QO.exec(e);return t?.[1]?t[1].split(`,`).map(e=>e.trim()).filter(Boolean):[]}function GO(e){let t=new Set,n=0;for(let r of e){if(r.type===`system`&&r.subtype===`compact_boundary`){let e=r.compactMetadata?.preCompactDiscoveredTools;if(e){for(let n of e)t.add(n);n+=e.length}continue}if(r.type===`attachment`&&r.attachment?.type===`deferred_tools_delta`){let e=r.attachment.addedNames??[];for(let n of e)t.add(n);continue}if(r.type!==`user`)continue;let e=r.message?.content;if(Array.isArray(e))for(let n of e){if(lTe(n))for(let e of n.content)cTe(e)&&t.add(e.tool_name);if(uTe(n)){let e=dTe(n.content);for(let n of e)t.add(n)}}}return t.size>0&&K(`Dynamic tool loading: found ${t.size} discovered tools in message history`+(n>0?` (${n} carried from compact boundary)`:``)),t}function KO(){return!1}function qO(e,t,n){let r=new Set,i=0,a=0,o=new Set;for(let e of t)if(e.type===`attachment`&&(i++,o.add(e.attachment.type),e.attachment.type===`deferred_tools_delta`)){a++;for(let t of e.attachment.addedNames)r.add(t);for(let t of e.attachment.removedNames)r.delete(t)}let s=e.filter(vs),c=new Set(s.map(e=>e.name)),l=new Set(e.map(e=>e.name)),u=s.filter(e=>!r.has(e.name)),d=[];for(let e of r)c.has(e)||l.has(e)||d.push(e);return u.length===0&&d.length===0?null:(u.length,d.length,r.size,t.length,n?.callSite,n?.querySource,[...o].sort().join(`,`),{addedNames:u.map(e=>e.name).sort(),addedLines:u.map(Jae).sort(),removedNames:d.sort()})}async function fTe(e,t,n,r){let i=await XO(e,t,n,r);if(i!==null){let e=RO(r);return{enabled:i>=e,debugDescription:`${i} tokens (threshold: ${e}, ${LO()}% of context)`,metrics:{deferredToolTokens:i,threshold:e}}}let a=await sTe(e,t,n),o=zO(r);return{enabled:a>=o,debugDescription:`${a} chars (threshold: ${o}, ${LO()}% of context) (char fallback)`,metrics:{deferredToolDescriptionChars:a,charThreshold:o}}}var JO,YO,XO,ZO,QO,$O=n((()=>{d(),La(),Ms(),Os(),MO(),tt(),Wg(),yo(),q(),g(),Li(),FO(),JO=10,YO=2.5,XO=u(async(e,t,n,r)=>{let i=e.filter(e=>vs(e));if(i.length===0)return 0;try{let e=await DO(i,t,{activeAgents:n,allAgents:n},r);return e===0?null:Math.max(0,e-500)}catch{return null}},e=>e.filter(e=>vs(e)).map(e=>e.name).join(`,`)),ZO=!1,QO=/^Found \d+ deferred tool\(s\): (.+)\.$/m}));function pTe(e){return e.map(e=>e.name).sort().join(`,`)}function mTe(e){let t=pTe(e);ok!==t&&(K(`SearchExtraToolsTool: cache invalidated - deferred tools changed`),sk.cache.clear?.(),ok=t)}function hTe(){sk.cache.clear?.(),ok=null}function ek(e,t,n,r,i){return{data:{matches:e,query:t,total_deferred_tools:n,...r&&r.length>0?{pending_mcp_servers:r}:{},...i&&i.length>0?{already_loaded:i}:{}}}}function tk(e){if(e.startsWith(`mcp__`)){let t=e.replace(/^mcp__/,``).toLowerCase();return{parts:t.split(`__`).flatMap(e=>e.split(`_`)).filter(Boolean),full:t.replace(/__/g,` `).replace(/_/g,` `),isMcp:!0}}let t=e.replace(/([a-z])([A-Z])/g,`$1 $2`).replace(/_/g,` `).toLowerCase().split(/\s+/).filter(Boolean);return{parts:t,full:t.join(` `),isMcp:!1}}function gTe(e){let t=new Map;for(let n of e)t.has(n)||t.set(n,RegExp(`\\b${Ya(n)}\\b`));return t}async function _Te(e,t,n,r){let i=e.toLowerCase().trim(),a=t.find(e=>e.name.toLowerCase()===i)??n.find(e=>e.name.toLowerCase()===i);if(a)return[a.name];if(i.startsWith(`mcp__`)&&i.length>5){let e=t.filter(e=>e.name.toLowerCase().startsWith(i)).slice(0,r).map(e=>e.name);if(e.length>0)return e}let o=i.split(/\s+/).filter(e=>e.length>0),s=[],c=[];for(let e of o)e.startsWith(`+`)&&e.length>1?s.push(e.slice(1)):c.push(e);let l=s.length>0?[...s,...c]:o,u=gTe(l),d=t;return s.length>0&&(d=(await Promise.all(t.map(async e=>{let t=tk(e.name),r=(await sk(e.name,n)).toLowerCase(),i=e.searchHint?.toLowerCase()??``;return s.every(e=>{let n=u.get(e);return t.parts.includes(e)||t.parts.some(t=>t.includes(e))||n.test(r)||i&&n.test(i)})?e:null}))).filter(e=>e!==null)),(await Promise.all(d.map(async e=>{let t=tk(e.name),r=(await sk(e.name,n)).toLowerCase(),i=e.searchHint?.toLowerCase()??``,a=0;for(let e of l){let n=u.get(e);t.parts.includes(e)?a+=t.isMcp?12:10:t.parts.some(t=>t.includes(e))&&(a+=t.isMcp?6:5),t.full.includes(e)&&a===0&&(a+=3),i&&n.test(i)&&(a+=4),n.test(r)&&(a+=2)}return{name:e.name,score:a}}))).filter(e=>e.score>0).sort((e,t)=>t.score-e.score).slice(0,r).map(e=>e.name)}var nk,rk,ik,ak,ok,sk,ck,lk=n((()=>{d(),It(),La(),Ms(),q(),rt(),Za(),$O(),Os(),pT(),nk=Number(process.env.SEARCH_EXTRA_TOOLS_WEIGHT_KEYWORD??`0.4`),rk=Number(process.env.SEARCH_EXTRA_TOOLS_WEIGHT_TFIDF??`0.6`),ik=R(()=>z({query:B().describe(`Query to find deferred tools. Use "select:<tool_name>" for direct selection, or keywords to search.`),max_results:V().optional().default(5).describe(`Maximum number of results to return (default: 5)`)})),ak=R(()=>z({matches:I(B()),query:B(),total_deferred_tools:V(),pending_mcp_servers:I(B()).optional(),already_loaded:I(B()).optional()})),ok=null,sk=u(async(e,t)=>{let n=ms(t,e);return n?n.prompt({getToolPermissionContext:async()=>({mode:`default`,additionalWorkingDirectories:new Map,alwaysAllowRules:{},alwaysDenyRules:{},alwaysAskRules:{},isBypassPermissionsModeAvailable:!1}),tools:t,agents:[]}):``},e=>e),ck=Cs({isEnabled(){return VO()},isConcurrencySafe(){return!0},isReadOnly(){return!0},name:Ss,maxResultSizeChars:1e5,async description(){return Rae()},async prompt(){return Rae()},get inputSchema(){return ik()},get outputSchema(){return ak()},async call(e,{options:{tools:t},getAppState:n}){let{query:r,max_results:i=5}=e,a=t.filter(vs);mTe(a);function o(){let e=n().mcp.clients.filter(e=>e.type===`pending`);return e.length>0?e.map(e=>e.name):void 0}function s(e,t){e.length,a.length,e.length}let c=r.match(/^select:(.+)$/i);if(c){let e=c[1].split(`,`).map(e=>e.trim()).filter(Boolean),n=[],i=[],l=[];for(let r of e){let e=ms(a,r),o=e??ms(t,r);o?n.includes(o.name)||(n.push(o.name),e||i.push(o.name)):l.push(r)}if(n.length===0){K(`SearchExtraToolsTool: select failed — none found: ${l.join(`, `)}`),s([],`select`);let e=o();return ek([],r,a.length,e)}return l.length>0?K(`SearchExtraToolsTool: partial select — found: ${n.join(`, `)}, missing: ${l.join(`, `)}`):K(`SearchExtraToolsTool: selected ${n.join(`, `)}`),s(n,`select`),ek(n,r,a.length,void 0,i.length>0?i:void 0)}let l=r.match(/^discover:(.+)$/i);if(l){let e=aT(l[1].trim(),await oT(a),i),t=e.map(e=>{let t=`**${e.name}** (score: ${e.score.toFixed(2)})\n${e.description}`;return e.inputSchema&&(t+=`\nSchema: ${JSON.stringify(e.inputSchema)}`),t});return t.length>0&&`${t.length}${t.join(`
815
815
 
816
816
  `)}`,s(e.map(e=>e.name),`keyword`),ek(e.map(e=>e.name),r,a.length)}let u=new Set(a.map(e=>e.name)),[d,f]=await Promise.all([_Te(r,a,t,i),oT(a)]),p=aT(r,f,i),m=new Map;d.forEach((e,t)=>{let n=(d.length-t)/d.length;m.set(e,(m.get(e)??0)+n*nk)}),p.forEach(e=>{m.set(e.name,(m.get(e.name)??0)+e.score*rk)});let h=[...m.entries()].sort((e,t)=>t[1]-e[1]).slice(0,i).map(([e])=>e),g=h.filter(e=>!u.has(e));if(K(`SearchExtraToolsTool: keyword search for "${r}", found ${h.length} matches`),s(h,`keyword`),h.length===0){let e=o();return ek(h,r,a.length,e)}return ek(h,r,a.length,void 0,g.length>0?g:void 0)},renderToolUseMessage(e){return e.query?`"${e.query}"`:null},userFacingName(){return`SearchExtraTools`},mapToolResultToToolResultBlockParam(e,t,n){if(e.matches.length===0){let n=`No matching deferred tools found`;return e.pending_mcp_servers&&e.pending_mcp_servers.length>0&&(n+=`. Some MCP servers are still connecting: ${e.pending_mcp_servers.join(`, `)}. Their tools will become available shortly — try searching again.`),{type:`tool_result`,tool_use_id:t,content:n}}let r=e.already_loaded??[],i=e.matches.filter(e=>!r.includes(e));if(i.length===0&&r.length>0)return{type:`tool_result`,tool_use_id:t,content:`No deferred tools found. ${r.join(`, `)} ${r.length===1?`is`:`are`} already loaded as core tool(s) — call directly, do NOT search for or wrap in ExecuteExtraTool. SearchExtraTools is only for discovering tools NOT already in your tool list.`};let a=[];return r.length>0&&a.push(`Already loaded as core tool(s): ${r.join(`, `)}. Call these directly using your normal tool interface — do NOT use ExecuteExtraTool for them.`),i.length>0&&a.push(`Found ${i.length} deferred tool(s): ${i.join(`, `)}.\nUse ExecuteExtraTool with {"tool_name": "<name>", "params": {...}} to invoke any of these deferred tools.`),{type:`tool_result`,tool_use_id:t,content:a.join(`
817
817
  `)}}})}));function vTe(e){let t={toolRequests:new Map,toolResults:new Map,humanMessages:0,assistantMessages:0,localCommandOutputs:0,other:0,attachments:new Map,duplicateFileReads:new Map,total:0},n=new Map,r=new Map,i=new Map;return e.forEach(e=>{if(e.type===`attachment`){let n=e.attachment.type||`unknown`;t.attachments.set(n,(t.attachments.get(n)||0)+1)}}),d3(e).forEach(e=>{let{content:a}=e.message;if(typeof a==`string`){let n=C3(a);t.total+=n,e.type===`user`&&a.includes(`local-command-stdout`)?t.localCommandOutputs+=n:t[e.type===`user`?`humanMessages`:`assistantMessages`]+=n}else a.forEach(a=>yTe(a,e,t,n,r,i))}),i.forEach((e,n)=>{if(e.count>1){let r=Math.floor(e.totalTokens/e.count)*(e.count-1);t.duplicateFileReads.set(n,{count:e.count,tokens:r})}}),t}function yTe(e,t,n,r,i,a){let o=C3(W(e));switch(n.total+=o,e.type){case`text`:t.type===`user`&&`text`in e&&e.text.includes(`local-command-stdout`)?n.localCommandOutputs+=o:n[t.type===`user`?`humanMessages`:`assistantMessages`]+=o;break;case`tool_use`:if(`name`in e&&`id`in e){let t=e.name||`unknown`;if(uk(n.toolRequests,t,o),r.set(e.id,t),t===`Read`&&`input`in e&&e.input&&typeof e.input==`object`&&`file_path`in e.input){let t=String(e.input.file_path);i.set(e.id,t)}}break;case`tool_result`:if(`tool_use_id`in e){let t=r.get(e.tool_use_id)||`unknown`;if(uk(n.toolResults,t,o),t===`Read`){let t=i.get(e.tool_use_id);if(t){let e=a.get(t)||{count:0,totalTokens:0};a.set(t,{count:e.count+1,totalTokens:e.totalTokens+o})}}}break;case`image`:case`server_tool_use`:case`web_search_tool_result`:case`search_result`:case`document`:case`thinking`:case`redacted_thinking`:case`code_execution_tool_result`:case`mcp_tool_use`:case`mcp_tool_result`:case`container_upload`:case`web_fetch_tool_result`:case`bash_code_execution_tool_result`:case`text_editor_code_execution_tool_result`:case`tool_search_tool_result`:case`compaction`:n.other+=o;break}}function uk(e,t,n){e.set(t,(e.get(t)||0)+n)}function bTe(e){let t={total_tokens:e.total,human_message_tokens:e.humanMessages,assistant_message_tokens:e.assistantMessages,local_command_output_tokens:e.localCommandOutputs,other_tokens:e.other};e.attachments.forEach((e,n)=>{t[`attachment_${n}_count`]=e}),e.toolRequests.forEach((e,n)=>{t[`tool_request_${n}_tokens`]=e}),e.toolResults.forEach((e,n)=>{t[`tool_result_${n}_tokens`]=e});let n=[...e.duplicateFileReads.values()].reduce((e,t)=>e+t.tokens,0);if(t.duplicate_read_tokens=n,t.duplicate_read_file_count=e.duplicateFileReads.size,e.total>0){t.human_message_percent=Math.round(e.humanMessages/e.total*100),t.assistant_message_percent=Math.round(e.assistantMessages/e.total*100),t.local_command_output_percent=Math.round(e.localCommandOutputs/e.total*100),t.duplicate_read_percent=Math.round(n/e.total*100);let r=[...e.toolRequests.values()].reduce((e,t)=>e+t,0),i=[...e.toolResults.values()].reduce((e,t)=>e+t,0);t.tool_request_percent=Math.round(r/e.total*100),t.tool_result_percent=Math.round(i/e.total*100),e.toolRequests.forEach((n,r)=>{t[`tool_request_${r}_percent`]=Math.round(n/e.total*100)}),e.toolResults.forEach((n,r)=>{t[`tool_result_${r}_percent`]=Math.round(n/e.total*100)})}return t}var xTe=n((()=>{O3(),v3(),Li()}));function STe(){dk(),yk=setInterval(()=>{Cn(`debug`,`session_keepalive_heartbeat`,{refcount:gk}),h(process.env.WORKMATE_REMOTE_SEND_KEEPALIVES)&&hk?.()},mk)}function CTe(){dk(),hk!==null&&(bk=setTimeout(()=>{Cn(`info`,`session_idle_30s`),bk=null},mk))}function dk(){bk!==null&&(clearTimeout(bk),bk=null)}function wTe(){h(process.env.WORKMATE_REMOTE_SEND_KEEPALIVES)&&hk?.()}function TTe(){return hk!==null}function fk(e){gk++,_k.set(e,(_k.get(e)??0)+1),gk===1&&(vk=Date.now(),hk!==null&&yk===null&&STe()),xk||(xk=!0,Oi(async()=>{Cn(`info`,`session_activity_at_shutdown`,{refcount:gk,active:Object.fromEntries(_k),oldest_activity_ms:gk>0&&vk!==null?Date.now()-vk:null})}))}function pk(e){gk>0&&gk--;let t=(_k.get(e)??0)-1;t>0?_k.set(e,t):_k.delete(e),gk===0&&yk!==null&&(clearInterval(yk),yk=null,CTe())}var mk,hk,gk,_k,vk,yk,bk,xk,Sk=n((()=>{di(),bn(),g(),mk=3e4,hk=null,gk=0,_k=new Map,vk=null,yk=null,bk=null,xk=!1}));function ETe(e){let t={PreToolUse:[],PostToolUse:[],PostToolUseFailure:[],PermissionDenied:[],Notification:[],UserPromptSubmit:[],SessionStart:[],SessionEnd:[],Stop:[],StopFailure:[],SubagentStart:[],SubagentStop:[],PreCompact:[],PostCompact:[],PermissionRequest:[],Setup:[],TeammateIdle:[],TaskCreated:[],TaskCompleted:[],Elicitation:[],ElicitationResult:[],ConfigChange:[],WorktreeCreate:[],WorktreeRemove:[],InstructionsLoaded:[],CwdChanged:[],FileChanged:[]};if(!e.hooksConfig)return t;for(let[n,r]of Object.entries(e.hooksConfig)){let i=n;if(t[i])for(let n of r??[])n.hooks.length>0&&t[i].push({matcher:n.matcher,hooks:n.hooks,pluginRoot:e.path,pluginName:e.name,pluginId:e.source})}return t}function Ck(){Ok.cache?.clear?.()}async function wk(){if(!ri())return;let{enabled:e}=await R4(),t=new Set(e.map(e=>e.path)),n=ri();if(!n)return;let r={};for(let[e,i]of Object.entries(n)){let n=(i??[]).filter(e=>`pluginRoot`in e&&t.has(e.pluginRoot));n.length>0&&(r[e]=n)}Kne(),Mr(r)}function Tk(){let e=yn(),t=$n(`policySettings`),n=e=>e?Object.fromEntries(Object.entries(e).sort()):{};return W({enabledPlugins:n(e.enabledPlugins),extraKnownMarketplaces:n(e.extraKnownMarketplaces),strictKnownMarketplaces:t?.strictKnownMarketplaces??[],blockedMarketplaces:t?.blockedMarketplaces??[]})}function DTe(){Ek||(Ek=!0,Dk=Tk(),ug.subscribe(e=>{if(e===`policySettings`){let e=Tk();if(e===Dk){K(`Plugin hooks: skipping reload, plugin-affecting settings unchanged`);return}Dk=e,K(`Plugin hooks: reloading due to plugin-affecting settings change`),I4(`loadPluginHooks: plugin-affecting settings changed`),Ck(),Ok()}}))}var Ek,Dk,Ok,kk=n((()=>{d(),H(),q(),dg(),Ln(),Li(),z4(),Ek=!1,Ok=u(async()=>{let{enabled:e}=await R4(),t={PreToolUse:[],PostToolUse:[],PostToolUseFailure:[],PermissionDenied:[],Notification:[],UserPromptSubmit:[],SessionStart:[],SessionEnd:[],Stop:[],StopFailure:[],SubagentStart:[],SubagentStop:[],PreCompact:[],PostCompact:[],PermissionRequest:[],Setup:[],TeammateIdle:[],TaskCreated:[],TaskCompleted:[],Elicitation:[],ElicitationResult:[],ConfigChange:[],WorktreeCreate:[],WorktreeRemove:[],InstructionsLoaded:[],CwdChanged:[],FileChanged:[]};for(let n of e){if(!n.hooksConfig)continue;K(`Loading hooks from plugin: ${n.name}`);let e=ETe(n);for(let n of Object.keys(e))t[n].push(...e[n])}Kne(),Mr(t),K(`Registered ${Object.values(t).reduce((e,t)=>e+t.reduce((e,t)=>e+t.hooks.length,0),0)} hooks from ${e.length} plugins`)})}));function OTe(){let e=jk;return jk=void 0,e}async function Ak(e,{sessionId:t,agentType:n,model:r,forceSyncExecution:i}={}){if(v())return[];let a=[],o=[],s=[];if(cb())K(`Skipping plugin hooks - allowManagedHooksOnly is enabled`);else try{await Fte(`load_plugin_hooks`,()=>Ok())}catch(t){let n=t instanceof Error?Error(`Failed to load plugin hooks during ${e}: ${t.message}`):Error(`Failed to load plugin hooks during ${e}: ${String(t)}`);t instanceof Error&&t.stack&&(n.stack=t.stack),Y(n);let r=t instanceof Error?t.message:String(t),i=``;i=r.includes(`Failed to clone`)||r.includes(`network`)||r.includes(`ETIMEDOUT`)||r.includes(`ENOTFOUND`)?`This appears to be a network issue. Check your internet connection and try again.`:r.includes(`Permission denied`)||r.includes(`EACCES`)||r.includes(`EPERM`)?`This appears to be a permissions issue. Check file permissions on ~/.workmate/plugins/`:r.includes(`Invalid`)||r.includes(`parse`)||r.includes(`JSON`)||r.includes(`schema`)?`This appears to be a configuration issue. Check your plugin settings in .workmate/settings.json`:`Please fix the plugin configuration or remove problematic plugins from your settings.`,K(`Warning: Failed to load plugin hooks. SessionStart hooks from plugins will not execute. Error: ${r}. ${i}`,{level:`warn`})}let c=n??jne();for await(let n of wat(e,t,c,r,void 0,void 0,i))n.message&&a.push(n.message),n.additionalContexts&&n.additionalContexts.length>0&&o.push(...n.additionalContexts),n.initialUserMessage&&(jk=n.initialUserMessage),n.watchPaths&&n.watchPaths.length>0&&s.push(...n.watchPaths);if(s.length>0&&g_e(s),o.length>0){let e=a2({type:`hook_additional_context`,content:o,hookName:`SessionStart`,toolUseID:`SessionStart`,hookEvent:`SessionStart`});a.push(e)}return a}async function kTe(e,{forceSyncExecution:t}={}){if(v())return[];let n=[],r=[];if(cb())K(`Skipping plugin hooks - allowManagedHooksOnly is enabled`);else try{await Ok()}catch(e){K(`Warning: Failed to load plugin hooks. Setup hooks from plugins will not execute. Error: ${e instanceof Error?e.message:String(e)}`,{level:`warn`})}for await(let i of Tat(e,void 0,void 0,t))i.message&&n.push(i.message),i.additionalContexts&&i.additionalContexts.length>0&&r.push(...i.additionalContexts);if(r.length>0){let e=a2({type:`hook_additional_context`,content:r,hookName:`Setup`,toolUseID:`Setup`,hookEvent:`Setup`});n.push(e)}return n}var jk,Mk=n((()=>{H(),g2(),q(),bn(),g(),Sb(),pb(),_7(),wa(),kk()}));async function ATe(e,t){}var Nk=n((()=>{}));function jTe(e){let t=[],n=[],r;for(let i of e)i.type===`assistant`&&i.message.id!==r&&n.length>0?(t.push(n),n=[i]):n.push(i),i.type===`assistant`&&(r=i.message.id);return n.length>0&&t.push(n),t}var MTe=n((()=>{}));function NTe(e,t=`from`){let n=Fk+(t===`up_to`?Bk:zk);return e&&e.trim()!==``&&(n+=`\n\nAdditional Instructions:\n${e}`),n+=Vk,n}function PTe(e){let t=Fk+Rk;return e&&e.trim()!==``&&(t+=`\n\nAdditional Instructions:\n${e}`),t+=Vk,t}function FTe(e){let t=e;t=t.replace(/<analysis>[\s\S]*?<\/analysis>/,``);let n=t.match(/<summary>([\s\S]*?)<\/summary>/);if(n){let e=n[1]||``;t=t.replace(/<summary>[\s\S]*?<\/summary>/,`Summary:\n${e.trim()}`)}return t=t.replace(/\n\n+/g,`
@@ -1110,7 +1110,7 @@ https://github.com/highlightjs/highlight.js/issues/2277`),i=e,r=t),n===void 0&&(
1110
1110
  `),`utf8`)),p=AP(s,a,f),m=a.length),p!==-1)return await _je(e,s,c-u+p,m,n,l+jP(s,0,p));c+=d;let h=Math.min(o,f);l+=jP(s,0,f-h),u=h,s.copyWithin(0,f-u,f)}return{content:``,lineOffset:1,truncated:c>=PP}}async function kP(e){let t=Buffer.allocUnsafe(NP),n=0;for(;;){if(n===t.length){let e=Buffer.allocUnsafe(Math.min(t.length*2,10493952));t.copy(e,0,0,n),t=e}let{bytesRead:r}=await e.read(t,n,t.length-n,n);if(r===0)break;if(n+=r,n>10485760)return null}return MP(t,n)}function AP(e,t,n){let r=e.indexOf(t);return r===-1||r+t.length>n?-1:r}function jP(e,t,n){let r=0;for(let i=t;i<n;i++)e[i]===FP&&r++;return r}function MP(e,t){let n=e.toString(`utf8`,0,t);return n.includes(`\r`)?n.replaceAll(`\r
1111
1111
  `,`
1112
1112
  `):n}async function _je(e,t,n,r,i,a){let o=Math.min(n,NP),{bytesRead:s}=await e.read(t,0,o,n-o),c=n,l=0;for(let e=s-1;e>=0&&l<=i&&!(t[e]===FP&&(l++,l>i));e--)c--;let u=a-jP(t,s-(n-c),s)+1,d=n+r,{bytesRead:f}=await e.read(t,0,NP,d),p=d;l=0;for(let e=0;e<f&&(p++,!(t[e]===FP&&(l++,l>=i+1)));e++);let m=p-c,h=m<=t.length?t:Buffer.allocUnsafe(m),{bytesRead:g}=await e.read(h,0,m,c);return{content:MP(h,g),lineOffset:u,truncated:!1}}var NP,PP,FP,IP=n((()=>{gi(),NP=8*1024,PP=10*1024*1024,FP=10}));function LP(e){return e?e.file_path?.startsWith(Pd())?`Updated plan`:e.edits==null&&e.old_string===``?`Create`:`Update`:`Update`}function RP(e){return e?.file_path?Mt(e.file_path):null}function vje({file_path:e},{verbose:t}){return e?e.startsWith(Pd())?``:(0,BP.jsx)(bS,{filePath:e,children:t?e:Mt(e)}):null}function yje({filePath:e,structuredPatch:t,originalFile:n},r,{style:i,verbose:a}){let o=e.startsWith(Pd());return(0,BP.jsx)(wP,{filePath:e,structuredPatch:t,firstLine:n.split(`
1113
- `)[0]??null,fileContent:n,style:i,verbose:a,previewHint:o?`/plan to preview`:void 0})}function bje(e,t){let{style:n,verbose:r}=t,i=e.file_path,a=e.old_string??``,o=e.new_string??``,s=e.replace_all??!1;return`edits`in e&&e.edits!=null?(0,BP.jsx)(bP,{file_path:i,operation:`update`,firstLine:null,verbose:r}):a===``?(0,BP.jsx)(bP,{file_path:i,operation:`write`,content:o,firstLine:Ja(o),verbose:r}):(0,BP.jsx)(Sje,{filePath:i,oldString:a,newString:o,replaceAll:s,style:n,verbose:r})}function xje(e,t){let{verbose:n}=t;return!n&&typeof e==`string`&&ev(e,`tool_use_error`)?ev(e,`tool_use_error`)?.includes(`Note: your current working directory is`)?(0,BP.jsx)($,{children:(0,BP.jsx)(F,{color:`error`,children:`File not found`})}):(0,BP.jsx)($,{children:(0,BP.jsx)(F,{color:`error`,children:`Error editing file`})}):(0,BP.jsx)(gS,{result:e,verbose:n})}function Sje({filePath:e,oldString:t,newString:n,replaceAll:r,style:i,verbose:a}){let[o]=(0,zP.useState)(()=>wje(e,t,n,r));return(0,BP.jsx)(zP.Suspense,{fallback:(0,BP.jsx)(bP,{file_path:e,operation:`update`,firstLine:null,verbose:a}),children:(0,BP.jsx)(Cje,{promise:o,filePath:e,style:i,verbose:a})})}function Cje({promise:e,filePath:t,style:n,verbose:r}){let{patch:i,firstLine:a,fileContent:o}=(0,zP.use)(e);return(0,BP.jsx)(bP,{file_path:t,operation:`update`,patch:i,firstLine:a,fileContent:o,style:n,verbose:r})}async function wje(e,t,n,r){try{let i=await gje(e,t,3);if(i===null||i.truncated||i.content===``){let{patch:r}=jw({filePath:e,fileContents:t,oldString:t,newString:n});return{patch:r,firstLine:null,fileContent:void 0}}let a=Aw(i.content,t)||t,{patch:o}=jw({filePath:e,fileContents:i.content,oldString:a,newString:n,replaceAll:r});return{patch:oCe(o,i.lineOffset-1),firstLine:i.lineOffset===1?Ja(i.content):null,fileContent:i.content}}catch(e){return Y(e),{patch:[],firstLine:null,fileContent:void 0}}}var zP,BP,VP=n((()=>{zP=r(Ie(),1),CP(),dS(),v3(),yS(),EP(),Ze(),xS(),Ow(),Ct(),wa(),Fd(),IP(),Za(),Fw(),BP=$e()}));function HP(e,t=``){return RegExp(`\\bgit(?:\\s+-[cC]\\s+\\S+|\\s+--\\S+=\\S+)*\\s+${e}\\b${t}`)}function Tje(e){let t=e.match(/https:\/\/github\.com\/([^/]+\/[^/]+)\/pull\/(\d+)/);return t?.[1]&&t?.[2]?{prNumber:parseInt(t[2],10),prUrl:e,prRepository:t[1]}:null}function UP(e){let t=e.match(/https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/\d+/);return t?Tje(t[0]):null}function WP(e){return e.match(/\[[\w./-]+(?: \(root-commit\))? ([0-9a-f]+)\]/)?.[1]}function Eje(e){return e.match(/^\s*[+\-*!= ]?\s*(?:\[new branch\]|\S+\.\.+\S+)\s+\S+\s*->\s*(\S+)/m)?.[1]}function Dje(e){let t=e.match(/[Pp]ull request (?:\S+#)?#?(\d+)/);return t?.[1]?parseInt(t[1],10):void 0}function GP(e,t){let n=e.split(HP(t))[1];if(n)for(let e of n.trim().split(/\s+/)){if(/^[&|;><]/.test(e))break;if(!e.startsWith(`-`))return e}}function Oje(e,t){let n={},r=YP.test(e);if(qP.test(e)||r){let i=WP(t);i&&(n.commit={sha:i.slice(0,6),kind:r?`cherry-picked`:/--amend\b/.test(e)?`amended`:`committed`})}if(JP.test(e)){let e=Eje(t);e&&(n.push={branch:e})}if(XP.test(e)&&/(Fast-forward|Merge made by)/.test(t)){let t=GP(e,`merge`);t&&(n.branch={ref:t,action:`merged`})}if(ZP.test(e)&&/Successfully rebased/.test(t)){let t=GP(e,`rebase`);t&&(n.branch={ref:t,action:`rebased`})}let i=QP.find(t=>t.re.test(e))?.action;if(i){let e=UP(t);if(e)n.pr={number:e.prNumber,url:e.prUrl,action:i};else{let e=Dje(t);e&&(n.pr={number:e,action:i})}}return n}function KP(e,t,n){if(t!==0)return;qP.test(e)&&(e.match(/--amend\b/),wne()?.add(1)),JP.test(e);let r=QP.find(t=>t.re.test(e));if(r&&r.op,r?.action===`created`&&(Ur()?.add(1),n)){let e=UP(n);e&&import(`./sessionStorage-Dr6JjGiG.js`).then(({linkSessionToPR:t})=>{import(`./state-DXt6rahM.js`).then(({getSessionId:n})=>{let r=n();r&&t(r,e.prNumber,e.prUrl,e.prRepository)})})}e.match(/\bglab\s+mr\s+create\b/)&&Ur()?.add(1);let i=e.match(/\bcurl\b/)&&(e.match(/-X\s*POST\b/i)||e.match(/--request\s*=?\s*POST\b/i)||e.match(/\s-d\s/)),a=e.match(/https?:\/\/[^\s'"]*\/(pulls|pull-requests|merge[-_]requests)(?!\/\d)/i);i&&a&&Ur()?.add(1)}var qP,JP,YP,XP,ZP,QP,$P=n((()=>{H(),La(),qP=HP(`commit`),JP=HP(`push`),YP=HP(`cherry-pick`),XP=HP(`merge`,`(?!-)`),ZP=HP(`rebase`),QP=[{re:/\bgh\s+pr\s+create\b/,action:`created`,op:`pr_create`},{re:/\bgh\s+pr\s+edit\b/,action:`edited`,op:`pr_edit`},{re:/\bgh\s+pr\s+merge\b/,action:`merged`,op:`pr_merge`},{re:/\bgh\s+pr\s+comment\b/,action:`commented`,op:`pr_comment`},{re:/\bgh\s+pr\s+close\b/,action:`closed`,op:`pr_close`},{re:/\bgh\s+pr\s+ready\b/,action:`ready`,op:`pr_ready`}]}));function kje(e){let t=jje(e),n=tF.get(t);return n===void 0?eF:n}function Aje(e){return e.trim().split(/\s+/)[0]||``}function jje(e){let t=a9(e);return Aje(t[t.length-1]||e)}function Mje(e,t,n,r){let i=kje(e)(t,n,r);return{isError:i.isError,message:i.message}}var eF,tF,Nje=n((()=>{g9(),eF=(e,t,n)=>({isError:e!==0,message:e===0?void 0:`Command failed with exit code ${e}`}),tF=new Map([[`grep`,(e,t,n)=>({isError:e>=2,message:e===1?`No matches found`:void 0})],[`rg`,(e,t,n)=>({isError:e>=2,message:e===1?`No matches found`:void 0})],[`find`,(e,t,n)=>({isError:e>=2,message:e===1?`Some directories were inaccessible`:void 0})],[`diff`,(e,t,n)=>({isError:e>=2,message:e===1?`Files differ`:void 0})],[`test`,(e,t,n)=>({isError:e>=2,message:e===1?`Condition is false`:void 0})],[`[`,(e,t,n)=>({isError:e>=2,message:e===1?`Condition is false`:void 0})]])})),nF,rF=n((()=>{nF=`https://github.com/readmagic/workMate`}));function Pje(){return lt(U())??ti()}function Fje(){return process.env.WORKMATE_ENTRYPOINT??`cli`}function iF(){return{fileStates:new Map,sessionBaselines:new Map,surface:Fje(),startingHeadSha:null,promptCount:0,promptCountAtLastCommit:0,permissionPromptCount:0,permissionPromptCountAtLastCommit:0,escapeCount:0,escapeCountAtLastCommit:0}}function Ije(e,t){let n={};for(let[t,r]of e.fileStates)n[t]=r;return{type:`attribution-snapshot`,messageId:t,surface:e.surface,fileStates:n,promptCount:e.promptCount,promptCountAtLastCommit:e.promptCountAtLastCommit,permissionPromptCount:e.permissionPromptCount,permissionPromptCountAtLastCommit:e.permissionPromptCountAtLastCommit,escapeCount:e.escapeCount,escapeCountAtLastCommit:e.escapeCountAtLastCommit}}function Lje(e,t){let n={...e,promptCount:e.promptCount+1};return t(Ije(n,Lc())),n}var aF,oF,sF=n((()=>{H(),ui(),q(),Da(),ki(),fn(),Et(),wa(),Die(),aF=`github.com:anthropics/claude-cli-internal,github.com/anthropics/claude-cli-internal,github.com:anthropics/anthropic,github.com/anthropics/anthropic,github.com:anthropics/apps,github.com/anthropics/apps,github.com:anthropics/casino,github.com/anthropics/casino,github.com:anthropics/dbt,github.com/anthropics/dbt,github.com:anthropics/dotfiles,github.com/anthropics/dotfiles,github.com:anthropics/terraform-config,github.com/anthropics/terraform-config,github.com:anthropics/hex-export,github.com/anthropics/hex-export,github.com:anthropics/feedback-v2,github.com/anthropics/feedback-v2,github.com:anthropics/labs,github.com/anthropics/labs,github.com:anthropics/argo-rollouts,github.com/anthropics/argo-rollouts,github.com:anthropics/starling-configs,github.com/anthropics/starling-configs,github.com:anthropics/ts-tools,github.com/anthropics/ts-tools,github.com:anthropics/ts-capsules,github.com/anthropics/ts-capsules,github.com:anthropics/feldspar-testing,github.com/anthropics/feldspar-testing,github.com:anthropics/trellis,github.com/anthropics/trellis,github.com:anthropics/claude-for-hiring,github.com/anthropics/claude-for-hiring,github.com:anthropics/forge-web,github.com/anthropics/forge-web,github.com:anthropics/infra-manifests,github.com/anthropics/infra-manifests,github.com:anthropics/mycro_manifests,github.com/anthropics/mycro_manifests,github.com:anthropics/mycro_configs,github.com/anthropics/mycro_configs,github.com:anthropics/mobile-apps,github.com/anthropics/mobile-apps`.split(`,`),oF=null,Eie(async()=>{if(oF!==null)return oF===`internal`;let e=await hte(Pje());if(!e)return oF=`none`,!1;let t=aF.some(t=>e.includes(t));return oF=t?`internal`:`external`,t})}));function Rje(e){let t=e.toLowerCase();for(let{keywords:e,email:n}of cF)if(e.some(e=>t.includes(e)))return n;return`noreply@anthropic.com`}var cF,zje=n((()=>{cF=[{keywords:[`claude`],email:`noreply@anthropic.com`},{keywords:[`gpt`,`dall-e`,`o1-`,`o3-`,`o4-`],email:`openai@readmagic.workmate.win`},{keywords:[`gemini`],email:`google-gemini@readmagic.workmate.win`},{keywords:[`grok`],email:`xai-org@readmagic.workmate.win`},{keywords:[`glm`],email:`zai-org@readmagic.workmate.win`},{keywords:[`deepseek`],email:`deepseek-ai@readmagic.workmate.win`},{keywords:[`qwen`],email:`QwenLM@readmagic.workmate.win`},{keywords:[`minimax`],email:`MiniMax-AI@readmagic.workmate.win`},{keywords:[`mimo`],email:`XiaomiMiMo@readmagic.workmate.win`},{keywords:[`kimi`],email:`MoonshotAI@readmagic.workmate.win`}]}));function Bje(e){switch(lo()){case`openai`:return r_(e);case`gemini`:return u_(e);case`grok`:return o_(e);default:return e}}function Vje(){return Bje(Lo())}var Hje=n((()=>{E_(),wo(),mo()})),lF,uF,dF,fF,pF=n((()=>{It(),rt(),RM(),lF=R(()=>Hn({file_path:B().describe(`The absolute path to the file to modify`),old_string:B().describe(`The text to replace`),new_string:B().describe(`The text to replace it with (must be different from old_string)`),replace_all:LM(Ot().default(!1).optional()).describe(`Replace all occurrences of old_string (default false)`)})),uF=R(()=>z({oldStart:V(),oldLines:V(),newStart:V(),newLines:V(),lines:I(B())})),dF=R(()=>z({filename:B(),status:bt([`modified`,`added`]),additions:V(),deletions:V(),changes:V(),patch:B(),repository:B().nullable().optional().describe(`GitHub owner/repo when available`)})),fF=R(()=>z({filePath:B().describe(`The file path that was edited`),oldString:B().describe(`The original string that was replaced`),newString:B().describe(`The new string that replaced it`),originalFile:B().describe(`The original file contents before editing`),structuredPatch:I(uF()).describe(`Diff patch showing the changes`),userModified:Ot().describe(`Whether the user modified the proposed changes`),replaceAll:Ot().describe(`Whether all occurrences were replaced`),gitDiff:dF().optional()}))}));function Uje({serverName:e,files:t}){let n=Lc();K(`LSP Diagnostics: Registering ${t.length} diagnostic file(s) from ${e} (ID: ${n})`),bF.set(n,{serverName:e,files:t,timestamp:Date.now(),attachmentSent:!1})}function mF(e){switch(e){case`Error`:return 1;case`Warning`:return 2;case`Info`:return 3;case`Hint`:return 4;default:return 4}}function hF(e){return W({message:e.message,severity:e.severity,range:e.range,source:e.source||null,code:e.code||null})}function Wje(e){let t=new Map,n=[];for(let r of e){t.has(r.uri)||(t.set(r.uri,new Set),n.push({uri:r.uri,diagnostics:[]}));let e=t.get(r.uri),i=n.find(e=>e.uri===r.uri),a=xF.get(r.uri)||new Set;for(let t of r.diagnostics)try{let n=hF(t);if(e.has(n)||a.has(n))continue;e.add(n),i.diagnostics.push(t)}catch(e){let n=wi(e),a=t.message?.substring(0,100)||`<no message>`;Y(Error(`Failed to deduplicate diagnostic in ${r.uri}: ${n.message}. Diagnostic message: ${a}`)),i.diagnostics.push(t)}}return n.filter(e=>e.diagnostics.length>0)}function Gje(){K(`LSP Diagnostics: Checking registry - ${bF.size} pending`);let e=[],t=new Set,n=[];for(let r of bF.values())r.attachmentSent||(e.push(...r.files),t.add(r.serverName),n.push(r));if(e.length===0)return[];let r;try{r=Wje(e)}catch(t){let n=wi(t);Y(Error(`Failed to deduplicate LSP diagnostics: ${n.message}`)),r=e}for(let e of n)e.attachmentSent=!0;for(let[e,t]of bF)t.attachmentSent&&bF.delete(e);let i=e.reduce((e,t)=>e+t.diagnostics.length,0),a=r.reduce((e,t)=>e+t.diagnostics.length,0);i>a&&K(`LSP Diagnostics: Deduplication removed ${i-a} duplicate diagnostic(s)`);let o=0,s=0;for(let e of r){e.diagnostics.sort((e,t)=>mF(e.severity)-mF(t.severity)),e.diagnostics.length>_F&&(s+=e.diagnostics.length-_F,e.diagnostics=e.diagnostics.slice(0,_F));let t=vF-o;e.diagnostics.length>t&&(s+=e.diagnostics.length-t,e.diagnostics=e.diagnostics.slice(0,t)),o+=e.diagnostics.length}r=r.filter(e=>e.diagnostics.length>0),s>0&&K(`LSP Diagnostics: Volume limiting removed ${s} diagnostic(s) (max ${_F}/file, ${vF} total)`);for(let e of r){xF.has(e.uri)||xF.set(e.uri,new Set);let t=xF.get(e.uri);for(let n of e.diagnostics)try{t.add(hF(n))}catch(t){let r=wi(t),i=n.message?.substring(0,100)||`<no message>`;Y(Error(`Failed to track delivered diagnostic in ${e.uri}: ${r.message}. Diagnostic message: ${i}`))}}let c=r.reduce((e,t)=>e+t.diagnostics.length,0);return c===0?(K(`LSP Diagnostics: No new diagnostics to deliver (all filtered by deduplication)`),[]):(K(`LSP Diagnostics: Delivering ${r.length} file(s) with ${c} diagnostic(s) from ${t.size} server(s)`),[{serverName:Array.from(t).join(`, `),files:r}])}function Kje(){K(`LSP Diagnostics: Clearing ${bF.size} pending diagnostic(s)`),bF.clear()}function qje(){K(`LSP Diagnostics: Resetting all state (${bF.size} pending, ${xF.size} files tracked)`),bF.clear(),xF.clear()}function gF(e){xF.has(e)&&(K(`LSP Diagnostics: Clearing delivered diagnostics for ${e}`),xF.delete(e))}var _F,vF,yF,bF,xF,SF=n((()=>{Sn(),q(),gi(),wa(),Li(),_F=10,vF=30,yF=500,bF=new Map,xF=new nt({max:yF})}));function CF(e){let t=[];return{expanded:e.replace(/\$\{([^}]+)\}/g,(e,n)=>{let[r,i]=n.split(`:-`,2),a=process.env[r];return a===void 0?i===void 0?(t.push(r),e):i:a}),missingVars:t}}var wF=n((()=>{}));function Jje(e,t){return{name:`${e.name}-with-${t.name}-fallback`,read(){return e.read()??(t.read()||{})},async readAsync(){return await e.readAsync()??(await t.readAsync()||{})},update(n){let r=e.read(),i=e.update(n);if(i.success)return r===null&&t.delete(),i;let a=t.update(n);return a.success?(r!==null&&e.delete(),{success:!0,warning:a.warning}):{success:!1}},delete(){let n=e.delete(),r=t.delete();return n||r}}}var Yje=n((()=>{}));function TF(e=``){let t=m(),n=process.env.WORKMATE_CONFIG_DIR?`-${Fc(`sha256`).update(t).digest(`hex`).substring(0,8)}`:``;return`Work Mate${Yee().OAUTH_FILE_SUFFIX}${e}${n}`}function EF(){try{return process.env.USER||yse().username}catch{return`workmate-user`}}function DF(){kF.cache={data:null,cachedAt:0},kF.generation++,kF.readInFlight=null}function Xje(e){if(kF.cache.cachedAt!==0)return;let t=null;if(e)try{t=JSON.parse(e)}catch{return}kF.cache={data:t,cachedAt:Date.now()}}var OF,kF,AF=n((()=>{Lee(),g(),OF=`-credentials`,kF={cache:{data:null,cachedAt:0},generation:0,readInFlight:null}}));async function Zje(){try{let e=TF(OF),{stdout:t,code:n}=await Aa(`security`,[`find-generic-password`,`-a`,EF(),`-w`,`-s`,e],{useCwd:!1,preserveOutputOnError:!1});if(n===0&&t)return Si(t.trim())}catch{}return null}function Qje(){if(NF!==void 0)return NF;if(process.platform!==`darwin`)return NF=!1,!1;try{NF=ea(`security`,[`show-keychain-info`],{reject:!1,stdio:[`ignore`,`pipe`,`pipe`]}).exitCode===36}catch{NF=!1}return NF}var jF,MF,NF,PF=n((()=>{ta(),q(),Da(),Li(),AF(),jF=4032,MF={name:`keychain`,read(){let e=kF.cache;if(Date.now()-e.cachedAt<3e4)return e.data;try{let e=TF(OF),t=ka(`security find-generic-password -a "${EF()}" -w -s "${e}"`);if(t){let e=Si(t);return kF.cache={data:e,cachedAt:Date.now()},e}}catch{}return e.data===null?(kF.cache={data:null,cachedAt:Date.now()},null):(K(`[keychain] read failed; serving stale cache`,{level:`warn`}),kF.cache={data:e.data,cachedAt:Date.now()},e.data)},async readAsync(){let e=kF.cache;if(Date.now()-e.cachedAt<3e4)return e.data;if(kF.readInFlight)return kF.readInFlight;let t=kF.generation,n=Zje().then(n=>{if(t===kF.generation){n===null&&e.data!==null&&K(`[keychain] readAsync failed; serving stale cache`,{level:`warn`});let t=n??e.data;return kF.cache={data:t,cachedAt:Date.now()},kF.readInFlight=null,t}return n});return kF.readInFlight=n,n},update(e){DF();try{let t=TF(OF),n=EF(),r=W(e),i=Buffer.from(r,`utf-8`).toString(`hex`),a=`add-generic-password -U -a "${n}" -s "${t}" -X "${i}"\n`,o;return a.length<=jF?o=ea(`security`,[`-i`],{input:a,stdio:[`pipe`,`pipe`,`pipe`],reject:!1}):(K(`Keychain payload (${r.length}B JSON) exceeds security -i stdin limit; using argv`,{level:`warn`}),o=ea(`security`,[`add-generic-password`,`-U`,`-a`,n,`-s`,t,`-X`,i],{stdio:[`ignore`,`pipe`,`pipe`],reject:!1})),o.exitCode===0?(kF.cache={data:e,cachedAt:Date.now()},{success:!0}):{success:!1}}catch{return{success:!1}}},delete(){DF();try{let e=TF(OF);return ka(`security delete-generic-password -a "${EF()}" -s "${e}"`),!0}catch{return!1}}}}));function FF(){let e=m();return{storageDir:e,storagePath:X(e,`.credentials.json`)}}var IF,$je=n((()=>{g(),gi(),ki(),Li(),IF={name:`plaintext`,read(){let{storagePath:e}=FF();try{return Si(J().readFileSync(e,{encoding:`utf8`}))}catch{return null}},async readAsync(){let{storagePath:e}=FF();try{return Si(await J().readFile(e,{encoding:`utf8`}))}catch{return null}},update(e){try{let{storageDir:t,storagePath:n}=FF();try{J().mkdirSync(t)}catch(e){if(yi(e)!==`EEXIST`)throw e}return Ci(n,W(e),{encoding:`utf8`,flush:!1}),Dse(n,384),{success:!0,warning:`Warning: Storing credentials in plaintext.`}}catch{return{success:!1}}},delete(){let{storagePath:e}=FF();try{return J().unlinkSync(e),!0}catch(e){return yi(e)===`ENOENT`}}}}));function LF(){return process.platform===`darwin`?Jje(MF,IF):IF}var RF=n((()=>{Yje(),PF(),$je()}));async function eMe(e){let{vAny:t}=await import(`./dist-DIee4wq1.js`),n=t.McpbManifestSchema.safeParse(e);if(!n.success){let e=n.error.flatten(),t=[...Object.entries(e.fieldErrors).map(([e,t])=>`${e}: ${t?.join(`, `)}`),...e.formErrors||[]].filter(Boolean).join(`; `);throw Error(`Invalid manifest: ${t}`)}return n.data}async function tMe(e){let t;try{t=Si(e)}catch(e){throw Error(`Invalid JSON in manifest.json: ${G(e)}`)}return eMe(t)}async function zF(e){return tMe(new TextDecoder().decode(e))}var nMe=n((()=>{gi(),Li()}));function rMe(e){return!(sr(e)||mc(hc(e)))}function iMe(e,t){t.fileCount++;let n;t.fileCount>HF.MAX_FILE_COUNT&&(n=`Archive contains too many files: ${t.fileCount} (max: ${HF.MAX_FILE_COUNT})`),rMe(e.name)||(n=`Unsafe file path detected: "${e.name}". Path traversal or absolute paths are not allowed.`);let r=e.originalSize||0;r>HF.MAX_FILE_SIZE&&(n=`File "${e.name}" is too large: ${Math.round(r/1024/1024)}MB (max: ${Math.round(HF.MAX_FILE_SIZE/1024/1024)}MB)`),t.totalUncompressedSize+=r,t.totalUncompressedSize>HF.MAX_TOTAL_SIZE&&(n=`Archive total size is too large: ${Math.round(t.totalUncompressedSize/1024/1024)}MB (max: ${Math.round(HF.MAX_TOTAL_SIZE/1024/1024)}MB)`);let i=t.totalUncompressedSize/t.compressedSize;return i>HF.MAX_COMPRESSION_RATIO&&(n=`Suspicious compression ratio detected: ${i.toFixed(1)}:1 (max: ${HF.MAX_COMPRESSION_RATIO}:1). This may be a zip bomb.`),n?{isValid:!1,error:n}:{isValid:!0}}async function BF(e){let{unzipSync:t}=await import(`./esm-wGnzjq4Z.js`),n={fileCount:0,totalUncompressedSize:0,compressedSize:e.length,errors:[]},r=t(new Uint8Array(e),{filter:e=>{let t=iMe(e,n);if(!t.isValid)throw Error(t.error);return!0}});return K(`Zip extraction completed: ${n.fileCount} files, ${Math.round(n.totalUncompressedSize/1024)}KB uncompressed`),r}function VF(e){let t=Buffer.from(e.buffer,e.byteOffset,e.byteLength),n={},r=Math.max(0,t.length-22-65535),i=-1;for(let e=t.length-22;e>=r;e--)if(t.readUInt32LE(e)===101010256){i=e;break}if(i<0)return n;let a=t.readUInt16LE(i+10),o=t.readUInt32LE(i+16);for(let e=0;e<a&&!(o+46>t.length||t.readUInt32LE(o)!==33639248);e++){let e=t.readUInt16LE(o+4),r=t.readUInt16LE(o+28),i=t.readUInt16LE(o+30),a=t.readUInt16LE(o+32),s=t.readUInt32LE(o+38),c=t.toString(`utf8`,o+46,o+46+r);if(e>>8==3){let e=s>>>16&65535;e&&(n[c]=e)}o+=46+r+i+a}return n}var HF,UF=n((()=>{q(),gi(),ki(),Wn(),HF={MAX_FILE_SIZE:512*1024*1024,MAX_TOTAL_SIZE:1024*1024*1024,MAX_FILE_COUNT:1e5,MAX_COMPRESSION_RATIO:50,MIN_COMPRESSION_RATIO:.5}}));function aMe(e){let t=e?.platform??Ma(),n=e?.homedir??cc(),r=e?.env??process.env,i={HOME:n,DESKTOP:X(n,`Desktop`),DOCUMENTS:X(n,`Documents`),DOWNLOADS:X(n,`Downloads`)};switch(t){case`windows`:{let e=r.USERPROFILE||n;return{HOME:n,DESKTOP:X(e,`Desktop`),DOCUMENTS:X(e,`Documents`),DOWNLOADS:X(e,`Downloads`)}}case`linux`:case`wsl`:return{HOME:n,DESKTOP:r.XDG_DESKTOP_DIR||i.DESKTOP,DOCUMENTS:r.XDG_DOCUMENTS_DIR||i.DOCUMENTS,DOWNLOADS:r.XDG_DOWNLOAD_DIR||i.DOWNLOADS};default:return t===`unknown`&&K(`Unknown platform detected, using default paths`),i}}var oMe=n((()=>{q(),Pa()}));function WF(e){return e.endsWith(`.mcpb`)||e.endsWith(`.dxt`)}function GF(e){return e.startsWith(`http://`)||e.startsWith(`https://`)}function sMe(e){return Fc(`sha256`).update(e).digest(`hex`).substring(0,16)}function KF(e){return X(e,`.mcpb-cache`)}function qF(e,t){return X(e,`${Fc(`md5`).update(t).digest(`hex`).substring(0,8)}.metadata.json`)}function JF(e,t){return`${e}/${t}`}function YF(e,t){try{let n=yn().pluginConfigs?.[e]?.mcpServers?.[t],r=LF().read()?.pluginSecrets?.[JF(e,t)];return!n&&!r?null:(K(`Loaded user config for ${e}/${t} (settings + secureStorage)`),{...n,...r})}catch(n){return Y(wi(n)),K(`Failed to load user config for ${e}/${t}: ${n}`,{level:`error`}),null}}function XF(e,t,n,r){try{let i={},a={};for(let[e,t]of Object.entries(n))r[e]?.sensitive===!0?a[e]=String(t):i[e]=t;let o=new Set(Object.keys(a)),s=new Set(Object.keys(i)),c=LF(),l=JF(e,t),u=c.read()?.pluginSecrets?.[l]??void 0,d=u?Object.fromEntries(Object.entries(u).filter(([e])=>!s.has(e))):void 0,f=d&&u&&Object.keys(d).length!==Object.keys(u).length;if(Object.keys(a).length>0||f){let e=c.read()??{};e.pluginSecrets||(e.pluginSecrets={}),e.pluginSecrets[l]={...d,...a};let t=c.update(e);if(!t.success)throw Error(`Failed to save sensitive config to secure storage for ${l}`);t.warning&&K(`Server secrets save warning: ${t.warning}`,{level:`warn`}),f&&K(`saveMcpServerUserConfig: scrubbed ${Object.keys(u).length-Object.keys(d).length} stale non-sensitive key(s) from secureStorage for ${l}`)}let p=yn(),m=p.pluginConfigs?.[e]?.mcpServers?.[t]??{},h=Object.keys(m).filter(e=>o.has(e));if(Object.keys(i).length>0||h.length>0){p.pluginConfigs||(p.pluginConfigs={}),p.pluginConfigs[e]||(p.pluginConfigs[e]={}),p.pluginConfigs[e].mcpServers||(p.pluginConfigs[e].mcpServers={});let n=Object.fromEntries(h.map(e=>[e,void 0]));p.pluginConfigs[e].mcpServers[t]={...i,...n};let r=gr(`userSettings`,p);if(r.error)throw r.error;h.length>0&&K(`saveMcpServerUserConfig: scrubbed ${h.length} plaintext sensitive key(s) from settings.json for ${e}/${t}`)}K(`Saved user config for ${e}/${t} (${Object.keys(i).length} non-sensitive, ${Object.keys(a).length} sensitive)`)}catch(n){let r=wi(n);throw Y(r),Error(`Failed to save user configuration for ${e}/${t}: ${r.message}`)}}function ZF(e,t){let n=[];for(let[r,i]of Object.entries(t)){let t=e[r];if(i.required&&(t===void 0||t===``)){n.push(`${i.title||r} is required but not provided`);continue}t===void 0||t===``||(i.type===`string`?Array.isArray(t)?i.multiple?t.every(e=>typeof e==`string`)||n.push(`${i.title||r} must be an array of strings`):n.push(`${i.title||r} must be a string, not an array`):typeof t!=`string`&&n.push(`${i.title||r} must be a string`):i.type===`number`&&typeof t!=`number`?n.push(`${i.title||r} must be a number`):i.type===`boolean`&&typeof t!=`boolean`?n.push(`${i.title||r} must be a boolean`):(i.type===`file`||i.type===`directory`)&&typeof t!=`string`&&n.push(`${i.title||r} must be a path string`),i.type===`number`&&typeof t==`number`&&(i.min!==void 0&&t<i.min&&n.push(`${i.title||r} must be at least ${i.min}`),i.max!==void 0&&t>i.max&&n.push(`${i.title||r} must be at most ${i.max}`)))}return{valid:n.length===0,errors:n}}async function QF(e,t,n={}){let{getMcpConfigForManifest:r}=await import(`./dist-DIee4wq1.js`),i=await r({manifest:e,extensionPath:t,systemDirs:aMe(),userConfig:n,pathSeparator:`/`});if(!i){let t=Error(`Failed to generate MCP server configuration from manifest "${e.name}"`);throw Y(t),t}return i}async function $F(e,t){let n=J(),r=qF(e,t);try{return Si(await n.readFile(r,{encoding:`utf-8`}))}catch(e){return yi(e)===`ENOENT`?null:(Y(wi(e)),K(`Failed to load MCPB cache metadata: ${e}`,{level:`error`}),null)}}async function eI(e,t,n){let r=qF(e,t);await J().mkdir(e),await Qc(r,W(n,null,2),`utf-8`)}async function cMe(e,t,n){K(`Downloading MCPB from ${e}`),n&&n(`Downloading ${e}...`);let r=performance.now(),i=!1;try{let a=await ue.get(e,{timeout:12e4,responseType:`arraybuffer`,maxRedirects:5,onDownloadProgress:e=>{e.total&&n&&n(`Downloading... ${Math.round(e.loaded/e.total*100)}%`)}}),o=new Uint8Array(a.data);return Ev(`mcpb`,e,`success`,performance.now()-r),i=!0,await Qc(t,Buffer.from(o)),K(`Downloaded ${o.length} bytes to ${t}`),n&&n(`Download complete`),o}catch(t){i||Ev(`mcpb`,e,`failure`,performance.now()-r,Dv(t));let n=G(t),a=Error(`Failed to download MCPB file from ${e}: ${n}`);throw Y(a),a}}async function lMe(e,t,n,r){r&&r(`Extracting files...`),await J().mkdir(t);let i=0,a=Object.entries(e).filter(([e])=>!e.endsWith(`/`)),o=a.length;for(let[e,s]of a){let a=X(t,e),c=fc(a);c!==t&&await J().mkdir(c),e.endsWith(`.json`)||e.endsWith(`.js`)||e.endsWith(`.ts`)||e.endsWith(`.txt`)||e.endsWith(`.md`)||e.endsWith(`.yml`)||e.endsWith(`.yaml`)?await Qc(a,new TextDecoder().decode(s),`utf-8`):await Qc(a,Buffer.from(s));let l=n[e];l&&l&73&&await zc(a,l&511).catch(()=>{}),i++,r&&i%10==0&&r(`Extracted ${i}/${o} files`)}K(`Extracted ${i} files to ${t}`),r&&r(`Extraction complete (${i} files)`)}async function uMe(e,t){let n=J(),r=await $F(KF(t),e);if(!r)return!0;try{await n.stat(r.extractedPath)}catch(e){return yi(e)===`ENOENT`?K(`MCPB extraction path missing: ${r.extractedPath}`):K(`MCPB extraction path inaccessible: ${r.extractedPath}: ${e}`,{level:`error`}),!0}if(!GF(e)){let i=X(t,e),a;try{a=await n.stat(i)}catch(e){return yi(e)===`ENOENT`?K(`MCPB source file missing: ${i}`):K(`MCPB source file inaccessible: ${i}: ${e}`,{level:`error`}),!0}let o=new Date(r.cachedAt).getTime(),s=Math.floor(a.mtimeMs);if(s>o)return K(`MCPB file modified: ${new Date(s)} > ${new Date(o)}`),!0}return!1}async function tI(e,t,n,r,i,a){let o=J(),s=KF(t);await o.mkdir(s),K(`Loading MCPB from source: ${e}`);let c=await $F(s,e);if(c&&!await uMe(e,t)){K(`Using cached MCPB from ${c.extractedPath} (hash: ${c.contentHash})`);let e=X(c.extractedPath,`manifest.json`),t;try{t=await o.readFile(e,{encoding:`utf-8`})}catch(t){if(xi(t)){let t=Error(`Cached manifest not found: ${e}`);throw Y(t),t}throw t}let r=await zF(new TextEncoder().encode(t));if(r.user_config&&Object.keys(r.user_config).length>0){let e=r.name,t=YF(n,e),o=i||t||{},s=ZF(o,r.user_config);return a||!s.valid?{status:`needs-config`,manifest:r,extractedPath:c.extractedPath,contentHash:c.contentHash,configSchema:r.user_config,existingConfig:t||{},validationErrors:s.valid?[]:s.errors}:(i&&XF(n,e,i,r.user_config??{}),{manifest:r,mcpConfig:await QF(r,c.extractedPath,o),extractedPath:c.extractedPath,contentHash:c.contentHash})}return{manifest:r,mcpConfig:await QF(r,c.extractedPath),extractedPath:c.extractedPath,contentHash:c.contentHash}}let l,u;if(GF(e))u=X(s,`${Fc(`md5`).update(e).digest(`hex`).substring(0,8)}.mcpb`),l=await cMe(e,u,r);else{let n=X(t,e);r&&r(`Loading ${e}...`);try{l=await o.readFileBytes(n),u=n}catch(e){if(xi(e)){let e=Error(`MCPB file not found: ${n}`);throw Y(e),e}throw e}}let d=sMe(l);K(`MCPB content hash: ${d}`),r&&r(`Extracting MCPB archive...`);let f=await BF(Buffer.from(l)),p=VF(l),m=f[`manifest.json`];if(!m){let e=Error(`No manifest.json found in MCPB file`);throw Y(e),e}let h=await zF(m);if(K(`MCPB manifest: ${h.name} v${h.version} by ${h.author.name}`),!h.server){let e=Error(`MCPB manifest for "${h.name}" does not define a server configuration`);throw Y(e),e}let g=X(s,d);if(await lMe(f,g,p,r),h.user_config&&Object.keys(h.user_config).length>0){let t=h.name,a=YF(n,t),o=i||a||{},c=ZF(o,h.user_config);if(!c.valid)return await eI(s,e,{source:e,contentHash:d,extractedPath:g,cachedAt:new Date().toISOString(),lastChecked:new Date().toISOString()}),{status:`needs-config`,manifest:h,extractedPath:g,contentHash:d,configSchema:h.user_config,existingConfig:a||{},validationErrors:c.errors};i&&XF(n,t,i,h.user_config??{}),r&&r(`Generating MCP server configuration...`);let l=await QF(h,g,o);return await eI(s,e,{source:e,contentHash:d,extractedPath:g,cachedAt:new Date().toISOString(),lastChecked:new Date().toISOString()}),{manifest:h,mcpConfig:l,extractedPath:g,contentHash:d}}r&&r(`Generating MCP server configuration...`);let _=await QF(h,g);return await eI(s,e,{source:e,contentHash:d,extractedPath:g,cachedAt:new Date().toISOString(),lastChecked:new Date().toISOString()}),K(`Successfully loaded MCPB: ${h.name} (extracted to ${g})`),{manifest:h,mcpConfig:_,extractedPath:g,contentHash:d}}var nI=n((()=>{de(),q(),nMe(),UF(),gi(),ki(),wa(),RF(),Ln(),Li(),oMe(),Ov()}));function rI(e){return e.source}function iI(){lI.cache?.clear?.()}function dMe(e,t,n){let r={},i={};for(let[e,a]of Object.entries(t))n[e]?.sensitive===!0?i[e]=String(a):r[e]=a;let a=new Set(Object.keys(i)),o=new Set(Object.keys(r)),s=LF(),c=s.read()?.pluginSecrets?.[e]??void 0,l=c?Object.fromEntries(Object.entries(c).filter(([e])=>!o.has(e))):void 0,u=l&&c&&Object.keys(l).length!==Object.keys(c).length;if(Object.keys(i).length>0||u){let t=s.read()??{};t.pluginSecrets||(t.pluginSecrets={}),t.pluginSecrets[e]={...l,...i};let n=s.update(t);if(!n.success){let t=Error(`Failed to save sensitive plugin options for ${e} to secure storage`);throw Y(t),t}n.warning&&K(`Plugin secrets save warning: ${n.warning}`,{level:`warn`})}let d=yn(),f=d.pluginConfigs?.[e]?.options??{},p=Object.keys(f).filter(e=>a.has(e));if(Object.keys(r).length>0||p.length>0){d.pluginConfigs||(d.pluginConfigs={}),d.pluginConfigs[e]||(d.pluginConfigs[e]={});let t=Object.fromEntries(p.map(e=>[e,void 0]));d.pluginConfigs[e].options={...r,...t};let n=gr(`userSettings`,d);if(n.error)throw Y(n.error),Error(`Failed to save plugin options for ${e}: ${n.error.message}`)}iI()}function aI(e){if(yn().pluginConfigs?.[e]){let{error:t}=gr(`userSettings`,{pluginConfigs:{[e]:void 0}});t&&K(`deletePluginOptions: failed to clear settings.pluginConfigs[${e}]: ${t.message}`,{level:`warn`})}let t=LF(),n=t.read();if(n?.pluginSecrets){let r=`${e}/`,i=Object.entries(n.pluginSecrets).filter(([t])=>t!==e&&!t.startsWith(r));i.length!==Object.keys(n.pluginSecrets).length&&(t.update({...n,pluginSecrets:i.length>0?Object.fromEntries(i):void 0}).success||K(`deletePluginOptions: failed to clear pluginSecrets for ${e} from keychain`,{level:`warn`}))}iI()}function fMe(e){let t=e.manifest.userConfig;if(!t||Object.keys(t).length===0)return{};let n=lI(rI(e));if(ZF(n,t).valid)return{};let r={};for(let[e,i]of Object.entries(t))ZF({[e]:n[e]},{[e]:i}).valid||(r[e]=i);return r}function oI(e,t){let n=e=>process.platform===`win32`?e.replace(/\\/g,`/`):e,r=e.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g,()=>n(t.path));if(t.source){let e=t.source;r=r.replace(/\$\{CLAUDE_PLUGIN_DATA\}/g,()=>n(ny(e)))}return r}function sI(e,t){return e.replace(/\$\{user_config\.([^}]+)\}/g,(e,n)=>{let r=t[n];if(r===void 0)throw Error(`Missing required user configuration value: ${n}. This should have been validated before variable substitution.`);return String(r)})}function cI(e,t,n){return e.replace(/\$\{user_config\.([^}]+)\}/g,(e,r)=>{if(n[r]?.sensitive===!0)return`[sensitive option '${r}' not available in skill content]`;let i=t[r];return i===void 0?e:String(i)})}var lI,uI=n((()=>{d(),q(),wa(),RF(),Ln(),nI(),ry(),lI=u(e=>{let t=yn().pluginConfigs?.[e]?.options??{},n=LF().read()?.pluginSecrets?.[e]??{};return{...t,...n}})}));function pMe(e,t){let n=yc(e),r=yc(e,t),i=vc(n,r);return i.startsWith(`..`)||yc(i)===i?null:r}async function dI(e,t=[]){let n={},r=X(e.path,`.lsp.json`);try{let i=Si(await Wc(r,`utf-8`)),a=dn(B(),cr()).safeParse(i);if(a.success)Object.assign(n,a.data);else{let n=`LSP config validation failed for .lsp.json in plugin ${e.name}: ${a.error.message}`;Y(Error(n)),t.push({type:`lsp-config-invalid`,plugin:e.name,serverName:`.lsp.json`,validationError:a.error.message,source:`plugin`})}}catch(n){xi(n)||(n instanceof Error?`${e.name}${n.message}`:`${e.name}`,Y(wi(n)),t.push({type:`lsp-config-invalid`,plugin:e.name,serverName:`.lsp.json`,validationError:n instanceof Error?`Failed to parse JSON: ${n.message}`:`Failed to parse JSON file`,source:`plugin`}))}if(e.manifest.lspServers){let r=await mMe(e.manifest.lspServers,e.path,e.name,t);r&&Object.assign(n,r)}return Object.keys(n).length>0?n:void 0}async function mMe(e,t,n,r){let i={},a=Array.isArray(e)?e:[e];for(let e of a)if(typeof e==`string`){let a=pMe(t,e);if(!a){let t=`Security: Path traversal attempt blocked in plugin ${n}: ${e}`;Y(Error(t)),K(t,{level:`warn`}),r.push({type:`lsp-config-invalid`,plugin:n,serverName:e,validationError:`Invalid path: must be relative and within plugin directory`,source:`plugin`});continue}try{let t=Si(await Wc(a,`utf-8`)),o=dn(B(),cr()).safeParse(t);if(o.success)Object.assign(i,o.data);else{let t=`LSP config validation failed for ${e} in plugin ${n}: ${o.error.message}`;Y(Error(t)),r.push({type:`lsp-config-invalid`,plugin:n,serverName:e,validationError:o.error.message,source:`plugin`})}}catch(t){t instanceof Error?`${e}${n}${t.message}`:`${e}${n}`,Y(wi(t)),r.push({type:`lsp-config-invalid`,plugin:n,serverName:e,validationError:t instanceof Error?`Failed to parse JSON: ${t.message}`:`Failed to parse JSON file`,source:`plugin`})}}else for(let[t,a]of Object.entries(e)){let e=cr().safeParse(a);if(e.success)i[t]=e.data;else{let i=`LSP config validation failed for inline server "${t}" in plugin ${n}: ${e.error.message}`;Y(Error(i)),r.push({type:`lsp-config-invalid`,plugin:n,serverName:t,validationError:e.error.message,source:`plugin`})}}return Object.keys(i).length>0?i:void 0}function hMe(e,t,n,r){let i=[],a=e=>{let r=oI(e,t);n&&(r=sI(r,n));let{expanded:a,missingVars:o}=CF(r);return i.push(...o),a},o={...e};o.command&&(o.command=a(o.command)),o.args&&(o.args=o.args.map(e=>a(e)));let s={CLAUDE_PLUGIN_ROOT:t.path,CLAUDE_PLUGIN_DATA:ny(t.source),...o.env||{}};for(let[e,t]of Object.entries(s))e!==`CLAUDE_PLUGIN_ROOT`&&e!==`CLAUDE_PLUGIN_DATA`&&(s[e]=a(t));if(o.env=s,o.workspaceFolder&&(o.workspaceFolder=a(o.workspaceFolder)),i.length>0){let e=`Missing environment variables in plugin LSP config: ${[...new Set(i)].join(`, `)}`;Y(Error(e)),K(e,{level:`warn`})}return o}function gMe(e,t){let n={};for(let[r,i]of Object.entries(e)){let e=`plugin:${t}:${r}`;n[e]={...i,scope:`dynamic`,source:t}}return n}async function _Me(e,t=[]){if(!e.enabled)return;let n=e.lspServers||await dI(e,t);if(!n)return;let r=e.manifest.userConfig?lI(rI(e)):void 0,i={};for(let[a,o]of Object.entries(n))i[a]=hMe(o,e,r,t);return gMe(i,e.name)}var fI=n((()=>{It(),wF(),q(),gi(),wa(),Li(),ry(),uI(),En()}));async function vMe(){let e={};try{let{enabled:t}=await R4(),n=await Promise.all(t.map(async e=>{let t=[];try{return{plugin:e,scopedServers:await _Me(e,t),errors:t}}catch(n){return K(`Failed to load LSP servers for plugin ${e.name}: ${n}`,{level:`error`}),{plugin:e,scopedServers:void 0,errors:t}}}));for(let{plugin:t,scopedServers:r,errors:i}of n){let n=r?Object.keys(r).length:0;n>0&&(Object.assign(e,r),K(`Loaded ${n} LSP server(s) from plugin: ${t.name}`)),i.length>0&&K(`${i.length} error(s) loading LSP servers from plugin: ${t.name}`)}K(`Total LSP servers loaded: ${Object.keys(e).length}`)}catch(e){Y(wi(e)),K(`Error loading LSP servers: ${G(e)}`)}return{servers:e}}var yMe=n((()=>{q(),gi(),wa(),fI(),z4()})),pI=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.stringArray=e.array=e.func=e.error=e.number=e.string=e.boolean=void 0;function t(e){return e===!0||e===!1}e.boolean=t;function n(e){return typeof e==`string`||e instanceof String}e.string=n;function r(e){return typeof e==`number`||e instanceof Number}e.number=r;function i(e){return e instanceof Error}e.error=i;function a(e){return typeof e==`function`}e.func=a;function o(e){return Array.isArray(e)}e.array=o;function s(e){return o(e)&&e.every(e=>n(e))}e.stringArray=s})),mI=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Message=e.NotificationType9=e.NotificationType8=e.NotificationType7=e.NotificationType6=e.NotificationType5=e.NotificationType4=e.NotificationType3=e.NotificationType2=e.NotificationType1=e.NotificationType0=e.NotificationType=e.RequestType9=e.RequestType8=e.RequestType7=e.RequestType6=e.RequestType5=e.RequestType4=e.RequestType3=e.RequestType2=e.RequestType1=e.RequestType=e.RequestType0=e.AbstractMessageSignature=e.ParameterStructures=e.ResponseError=e.ErrorCodes=void 0;var t=pI(),n;(function(e){e.ParseError=-32700,e.InvalidRequest=-32600,e.MethodNotFound=-32601,e.InvalidParams=-32602,e.InternalError=-32603,e.jsonrpcReservedErrorRangeStart=-32099,e.serverErrorStart=-32099,e.MessageWriteError=-32099,e.MessageReadError=-32098,e.PendingResponseRejected=-32097,e.ConnectionInactive=-32096,e.ServerNotInitialized=-32002,e.UnknownErrorCode=-32001,e.jsonrpcReservedErrorRangeEnd=-32e3,e.serverErrorEnd=-32e3})(n||(e.ErrorCodes=n={})),e.ResponseError=class e extends Error{constructor(r,i,a){super(i),this.code=t.number(r)?r:n.UnknownErrorCode,this.data=a,Object.setPrototypeOf(this,e.prototype)}toJson(){let e={code:this.code,message:this.message};return this.data!==void 0&&(e.data=this.data),e}};var r=class e{constructor(e){this.kind=e}static is(t){return t===e.auto||t===e.byName||t===e.byPosition}toString(){return this.kind}};e.ParameterStructures=r,r.auto=new r(`auto`),r.byPosition=new r(`byPosition`),r.byName=new r(`byName`);var i=class{constructor(e,t){this.method=e,this.numberOfParams=t}get parameterStructures(){return r.auto}};e.AbstractMessageSignature=i,e.RequestType0=class extends i{constructor(e){super(e,0)}},e.RequestType=class extends i{constructor(e,t=r.auto){super(e,1),this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}},e.RequestType1=class extends i{constructor(e,t=r.auto){super(e,1),this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}},e.RequestType2=class extends i{constructor(e){super(e,2)}},e.RequestType3=class extends i{constructor(e){super(e,3)}},e.RequestType4=class extends i{constructor(e){super(e,4)}},e.RequestType5=class extends i{constructor(e){super(e,5)}},e.RequestType6=class extends i{constructor(e){super(e,6)}},e.RequestType7=class extends i{constructor(e){super(e,7)}},e.RequestType8=class extends i{constructor(e){super(e,8)}},e.RequestType9=class extends i{constructor(e){super(e,9)}},e.NotificationType=class extends i{constructor(e,t=r.auto){super(e,1),this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}},e.NotificationType0=class extends i{constructor(e){super(e,0)}},e.NotificationType1=class extends i{constructor(e,t=r.auto){super(e,1),this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}},e.NotificationType2=class extends i{constructor(e){super(e,2)}},e.NotificationType3=class extends i{constructor(e){super(e,3)}},e.NotificationType4=class extends i{constructor(e){super(e,4)}},e.NotificationType5=class extends i{constructor(e){super(e,5)}},e.NotificationType6=class extends i{constructor(e){super(e,6)}},e.NotificationType7=class extends i{constructor(e){super(e,7)}},e.NotificationType8=class extends i{constructor(e){super(e,8)}},e.NotificationType9=class extends i{constructor(e){super(e,9)}};var a;(function(e){function n(e){let n=e;return n&&t.string(n.method)&&(t.string(n.id)||t.number(n.id))}e.isRequest=n;function r(e){let n=e;return n&&t.string(n.method)&&e.id===void 0}e.isNotification=r;function i(e){let n=e;return n&&(n.result!==void 0||!!n.error)&&(t.string(n.id)||t.number(n.id)||n.id===null)}e.isResponse=i})(a||(e.Message=a={}))})),hI=a((e=>{var t;Object.defineProperty(e,"__esModule",{value:!0}),e.LRUCache=e.LinkedMap=e.Touch=void 0;var n;(function(e){e.None=0,e.First=1,e.AsOld=e.First,e.Last=2,e.AsNew=e.Last})(n||(e.Touch=n={}));var r=class{constructor(){this[t]=`LinkedMap`,this._map=new Map,this._head=void 0,this._tail=void 0,this._size=0,this._state=0}clear(){this._map.clear(),this._head=void 0,this._tail=void 0,this._size=0,this._state++}isEmpty(){return!this._head&&!this._tail}get size(){return this._size}get first(){return this._head?.value}get last(){return this._tail?.value}has(e){return this._map.has(e)}get(e,t=n.None){let r=this._map.get(e);if(r)return t!==n.None&&this.touch(r,t),r.value}set(e,t,r=n.None){let i=this._map.get(e);if(i)i.value=t,r!==n.None&&this.touch(i,r);else{switch(i={key:e,value:t,next:void 0,previous:void 0},r){case n.None:this.addItemLast(i);break;case n.First:this.addItemFirst(i);break;case n.Last:this.addItemLast(i);break;default:this.addItemLast(i);break}this._map.set(e,i),this._size++}return this}delete(e){return!!this.remove(e)}remove(e){let t=this._map.get(e);if(t)return this._map.delete(e),this.removeItem(t),this._size--,t.value}shift(){if(!this._head&&!this._tail)return;if(!this._head||!this._tail)throw Error(`Invalid list`);let e=this._head;return this._map.delete(e.key),this.removeItem(e),this._size--,e.value}forEach(e,t){let n=this._state,r=this._head;for(;r;){if(t?e.bind(t)(r.value,r.key,this):e(r.value,r.key,this),this._state!==n)throw Error(`LinkedMap got modified during iteration.`);r=r.next}}keys(){let e=this._state,t=this._head,n={[Symbol.iterator]:()=>n,next:()=>{if(this._state!==e)throw Error(`LinkedMap got modified during iteration.`);if(t){let e={value:t.key,done:!1};return t=t.next,e}else return{value:void 0,done:!0}}};return n}values(){let e=this._state,t=this._head,n={[Symbol.iterator]:()=>n,next:()=>{if(this._state!==e)throw Error(`LinkedMap got modified during iteration.`);if(t){let e={value:t.value,done:!1};return t=t.next,e}else return{value:void 0,done:!0}}};return n}entries(){let e=this._state,t=this._head,n={[Symbol.iterator]:()=>n,next:()=>{if(this._state!==e)throw Error(`LinkedMap got modified during iteration.`);if(t){let e={value:[t.key,t.value],done:!1};return t=t.next,e}else return{value:void 0,done:!0}}};return n}[(t=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}trimOld(e){if(e>=this.size)return;if(e===0){this.clear();return}let t=this._head,n=this.size;for(;t&&n>e;)this._map.delete(t.key),t=t.next,n--;this._head=t,this._size=n,t&&(t.previous=void 0),this._state++}addItemFirst(e){if(!this._head&&!this._tail)this._tail=e;else if(this._head)e.next=this._head,this._head.previous=e;else throw Error(`Invalid list`);this._head=e,this._state++}addItemLast(e){if(!this._head&&!this._tail)this._head=e;else if(this._tail)e.previous=this._tail,this._tail.next=e;else throw Error(`Invalid list`);this._tail=e,this._state++}removeItem(e){if(e===this._head&&e===this._tail)this._head=void 0,this._tail=void 0;else if(e===this._head){if(!e.next)throw Error(`Invalid list`);e.next.previous=void 0,this._head=e.next}else if(e===this._tail){if(!e.previous)throw Error(`Invalid list`);e.previous.next=void 0,this._tail=e.previous}else{let t=e.next,n=e.previous;if(!t||!n)throw Error(`Invalid list`);t.previous=n,n.next=t}e.next=void 0,e.previous=void 0,this._state++}touch(e,t){if(!this._head||!this._tail)throw Error(`Invalid list`);if(!(t!==n.First&&t!==n.Last)){if(t===n.First){if(e===this._head)return;let t=e.next,n=e.previous;e===this._tail?(n.next=void 0,this._tail=n):(t.previous=n,n.next=t),e.previous=void 0,e.next=this._head,this._head.previous=e,this._head=e,this._state++}else if(t===n.Last){if(e===this._tail)return;let t=e.next,n=e.previous;e===this._head?(t.previous=void 0,this._head=t):(t.previous=n,n.next=t),e.next=void 0,e.previous=this._tail,this._tail.next=e,this._tail=e,this._state++}}}toJSON(){let e=[];return this.forEach((t,n)=>{e.push([n,t])}),e}fromJSON(e){this.clear();for(let[t,n]of e)this.set(t,n)}};e.LinkedMap=r,e.LRUCache=class extends r{constructor(e,t=1){super(),this._limit=e,this._ratio=Math.min(Math.max(0,t),1)}get limit(){return this._limit}set limit(e){this._limit=e,this.checkTrim()}get ratio(){return this._ratio}set ratio(e){this._ratio=Math.min(Math.max(0,e),1),this.checkTrim()}get(e,t=n.AsNew){return super.get(e,t)}peek(e){return super.get(e,n.None)}set(e,t){return super.set(e,t,n.Last),this.checkTrim(),this}checkTrim(){this.size>this._limit&&this.trimOld(Math.round(this._limit*this._ratio))}}})),bMe=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Disposable=void 0;var t;(function(e){function t(e){return{dispose:e}}e.create=t})(t||(e.Disposable=t={}))})),gI=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t;function n(){if(t===void 0)throw Error(`No runtime abstraction layer installed`);return t}(function(e){function n(e){if(e===void 0)throw Error(`No runtime abstraction layer provided`);t=e}e.install=n})(n||(n={})),e.default=n})),_I=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Emitter=e.Event=void 0;var t=gI(),n;(function(e){let t={dispose(){}};e.None=function(){return t}})(n||(e.Event=n={}));var r=class{add(e,t=null,n){this._callbacks||(this._callbacks=[],this._contexts=[]),this._callbacks.push(e),this._contexts.push(t),Array.isArray(n)&&n.push({dispose:()=>this.remove(e,t)})}remove(e,t=null){if(!this._callbacks)return;let n=!1;for(let r=0,i=this._callbacks.length;r<i;r++)if(this._callbacks[r]===e)if(this._contexts[r]===t){this._callbacks.splice(r,1),this._contexts.splice(r,1);return}else n=!0;if(n)throw Error(`When adding a listener with a context, you should remove it with the same context`)}invoke(...e){if(!this._callbacks)return[];let n=[],r=this._callbacks.slice(0),i=this._contexts.slice(0);for(let a=0,o=r.length;a<o;a++)try{n.push(r[a].apply(i[a],e))}catch(e){(0,t.default)().console.error(e)}return n}isEmpty(){return!this._callbacks||this._callbacks.length===0}dispose(){this._callbacks=void 0,this._contexts=void 0}},i=class e{constructor(e){this._options=e}get event(){return this._event||(this._event=(t,n,i)=>{this._callbacks||(this._callbacks=new r),this._options&&this._options.onFirstListenerAdd&&this._callbacks.isEmpty()&&this._options.onFirstListenerAdd(this),this._callbacks.add(t,n);let a={dispose:()=>{this._callbacks&&(this._callbacks.remove(t,n),a.dispose=e._noop,this._options&&this._options.onLastListenerRemove&&this._callbacks.isEmpty()&&this._options.onLastListenerRemove(this))}};return Array.isArray(i)&&i.push(a),a}),this._event}fire(e){this._callbacks&&this._callbacks.invoke.call(this._callbacks,e)}dispose(){this._callbacks&&(this._callbacks.dispose(),this._callbacks=void 0)}};e.Emitter=i,i._noop=function(){}})),vI=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CancellationTokenSource=e.CancellationToken=void 0;var t=gI(),n=pI(),r=_I(),i;(function(e){e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:r.Event.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:r.Event.None});function t(t){let r=t;return r&&(r===e.None||r===e.Cancelled||n.boolean(r.isCancellationRequested)&&!!r.onCancellationRequested)}e.is=t})(i||(e.CancellationToken=i={}));var a=Object.freeze(function(e,n){let r=(0,t.default)().timer.setTimeout(e.bind(n),0);return{dispose(){r.dispose()}}}),o=class{constructor(){this._isCancelled=!1}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?a:(this._emitter||(this._emitter=new r.Emitter),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=void 0)}};e.CancellationTokenSource=class{get token(){return this._token||(this._token=new o),this._token}cancel(){this._token?this._token.cancel():this._token=i.Cancelled}dispose(){this._token?this._token instanceof o&&this._token.dispose():this._token=i.None}}})),xMe=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SharedArrayReceiverStrategy=e.SharedArraySenderStrategy=void 0;var t=vI(),n;(function(e){e.Continue=0,e.Cancelled=1})(n||(n={})),e.SharedArraySenderStrategy=class{constructor(){this.buffers=new Map}enableCancellation(e){if(e.id===null)return;let t=new SharedArrayBuffer(4),r=new Int32Array(t,0,1);r[0]=n.Continue,this.buffers.set(e.id,t),e.$cancellationData=t}async sendCancellation(e,t){let r=this.buffers.get(t);if(r===void 0)return;let i=new Int32Array(r,0,1);Atomics.store(i,0,n.Cancelled)}cleanup(e){this.buffers.delete(e)}dispose(){this.buffers.clear()}};var r=class{constructor(e){this.data=new Int32Array(e,0,1)}get isCancellationRequested(){return Atomics.load(this.data,0)===n.Cancelled}get onCancellationRequested(){throw Error(`Cancellation over SharedArrayBuffer doesn't support cancellation events`)}},i=class{constructor(e){this.token=new r(e)}cancel(){}dispose(){}};e.SharedArrayReceiverStrategy=class{constructor(){this.kind=`request`}createCancellationTokenSource(e){let n=e.$cancellationData;return n===void 0?new t.CancellationTokenSource:new i(n)}}})),yI=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Semaphore=void 0;var t=gI();e.Semaphore=class{constructor(e=1){if(e<=0)throw Error(`Capacity must be greater than 0`);this._capacity=e,this._active=0,this._waiting=[]}lock(e){return new Promise((t,n)=>{this._waiting.push({thunk:e,resolve:t,reject:n}),this.runNext()})}get active(){return this._active}runNext(){this._waiting.length===0||this._active===this._capacity||(0,t.default)().timer.setImmediate(()=>this.doRunNext())}doRunNext(){if(this._waiting.length===0||this._active===this._capacity)return;let e=this._waiting.shift();if(this._active++,this._active>this._capacity)throw Error(`To many thunks active`);try{let t=e.thunk();t instanceof Promise?t.then(t=>{this._active--,e.resolve(t),this.runNext()},t=>{this._active--,e.reject(t),this.runNext()}):(this._active--,e.resolve(t),this.runNext())}catch(t){this._active--,e.reject(t),this.runNext()}}}})),SMe=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ReadableStreamMessageReader=e.AbstractMessageReader=e.MessageReader=void 0;var t=gI(),n=pI(),r=_I(),i=yI(),a;(function(e){function t(e){let t=e;return t&&n.func(t.listen)&&n.func(t.dispose)&&n.func(t.onError)&&n.func(t.onClose)&&n.func(t.onPartialMessage)}e.is=t})(a||(e.MessageReader=a={}));var o=class{constructor(){this.errorEmitter=new r.Emitter,this.closeEmitter=new r.Emitter,this.partialMessageEmitter=new r.Emitter}dispose(){this.errorEmitter.dispose(),this.closeEmitter.dispose()}get onError(){return this.errorEmitter.event}fireError(e){this.errorEmitter.fire(this.asError(e))}get onClose(){return this.closeEmitter.event}fireClose(){this.closeEmitter.fire(void 0)}get onPartialMessage(){return this.partialMessageEmitter.event}firePartialMessage(e){this.partialMessageEmitter.fire(e)}asError(e){return e instanceof Error?e:Error(`Reader received error. Reason: ${n.string(e.message)?e.message:`unknown`}`)}};e.AbstractMessageReader=o;var s;(function(e){function n(e){let n,r,i=new Map,a,o=new Map;if(e===void 0||typeof e==`string`)n=e??`utf-8`;else{if(n=e.charset??`utf-8`,e.contentDecoder!==void 0&&(r=e.contentDecoder,i.set(r.name,r)),e.contentDecoders!==void 0)for(let t of e.contentDecoders)i.set(t.name,t);if(e.contentTypeDecoder!==void 0&&(a=e.contentTypeDecoder,o.set(a.name,a)),e.contentTypeDecoders!==void 0)for(let t of e.contentTypeDecoders)o.set(t.name,t)}return a===void 0&&(a=(0,t.default)().applicationJson.decoder,o.set(a.name,a)),{charset:n,contentDecoder:r,contentDecoders:i,contentTypeDecoder:a,contentTypeDecoders:o}}e.fromOptions=n})(s||(s={})),e.ReadableStreamMessageReader=class extends o{constructor(e,n){super(),this.readable=e,this.options=s.fromOptions(n),this.buffer=(0,t.default)().messageBuffer.create(this.options.charset),this._partialMessageTimeout=1e4,this.nextMessageLength=-1,this.messageToken=0,this.readSemaphore=new i.Semaphore(1)}set partialMessageTimeout(e){this._partialMessageTimeout=e}get partialMessageTimeout(){return this._partialMessageTimeout}listen(e){this.nextMessageLength=-1,this.messageToken=0,this.partialMessageTimer=void 0,this.callback=e;let t=this.readable.onData(e=>{this.onData(e)});return this.readable.onError(e=>this.fireError(e)),this.readable.onClose(()=>this.fireClose()),t}onData(e){try{for(this.buffer.append(e);;){if(this.nextMessageLength===-1){let e=this.buffer.tryReadHeaders(!0);if(!e)return;let t=e.get(`content-length`);if(!t){this.fireError(Error(`Header must provide a Content-Length property.\n${JSON.stringify(Object.fromEntries(e))}`));return}let n=parseInt(t);if(isNaN(n)){this.fireError(Error(`Content-Length value must be a number. Got ${t}`));return}this.nextMessageLength=n}let e=this.buffer.tryReadBody(this.nextMessageLength);if(e===void 0){this.setPartialMessageTimer();return}this.clearPartialMessageTimer(),this.nextMessageLength=-1,this.readSemaphore.lock(async()=>{let t=this.options.contentDecoder===void 0?e:await this.options.contentDecoder.decode(e),n=await this.options.contentTypeDecoder.decode(t,this.options);this.callback(n)}).catch(e=>{this.fireError(e)})}}catch(e){this.fireError(e)}}clearPartialMessageTimer(){this.partialMessageTimer&&(this.partialMessageTimer.dispose(),this.partialMessageTimer=void 0)}setPartialMessageTimer(){this.clearPartialMessageTimer(),!(this._partialMessageTimeout<=0)&&(this.partialMessageTimer=(0,t.default)().timer.setTimeout((e,t)=>{this.partialMessageTimer=void 0,e===this.messageToken&&(this.firePartialMessage({messageToken:e,waitingTime:t}),this.setPartialMessageTimer())},this._partialMessageTimeout,this.messageToken,this._partialMessageTimeout))}}})),CMe=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.WriteableStreamMessageWriter=e.AbstractMessageWriter=e.MessageWriter=void 0;var t=gI(),n=pI(),r=yI(),i=_I(),a=`Content-Length: `,o=`\r
1113
+ `)[0]??null,fileContent:n,style:i,verbose:a,previewHint:o?`/plan to preview`:void 0})}function bje(e,t){let{style:n,verbose:r}=t,i=e.file_path,a=e.old_string??``,o=e.new_string??``,s=e.replace_all??!1;return`edits`in e&&e.edits!=null?(0,BP.jsx)(bP,{file_path:i,operation:`update`,firstLine:null,verbose:r}):a===``?(0,BP.jsx)(bP,{file_path:i,operation:`write`,content:o,firstLine:Ja(o),verbose:r}):(0,BP.jsx)(Sje,{filePath:i,oldString:a,newString:o,replaceAll:s,style:n,verbose:r})}function xje(e,t){let{verbose:n}=t;return!n&&typeof e==`string`&&ev(e,`tool_use_error`)?ev(e,`tool_use_error`)?.includes(`Note: your current working directory is`)?(0,BP.jsx)($,{children:(0,BP.jsx)(F,{color:`error`,children:`File not found`})}):(0,BP.jsx)($,{children:(0,BP.jsx)(F,{color:`error`,children:`Error editing file`})}):(0,BP.jsx)(gS,{result:e,verbose:n})}function Sje({filePath:e,oldString:t,newString:n,replaceAll:r,style:i,verbose:a}){let[o]=(0,zP.useState)(()=>wje(e,t,n,r));return(0,BP.jsx)(zP.Suspense,{fallback:(0,BP.jsx)(bP,{file_path:e,operation:`update`,firstLine:null,verbose:a}),children:(0,BP.jsx)(Cje,{promise:o,filePath:e,style:i,verbose:a})})}function Cje({promise:e,filePath:t,style:n,verbose:r}){let{patch:i,firstLine:a,fileContent:o}=(0,zP.use)(e);return(0,BP.jsx)(bP,{file_path:t,operation:`update`,patch:i,firstLine:a,fileContent:o,style:n,verbose:r})}async function wje(e,t,n,r){try{let i=await gje(e,t,3);if(i===null||i.truncated||i.content===``){let{patch:r}=jw({filePath:e,fileContents:t,oldString:t,newString:n});return{patch:r,firstLine:null,fileContent:void 0}}let a=Aw(i.content,t)||t,{patch:o}=jw({filePath:e,fileContents:i.content,oldString:a,newString:n,replaceAll:r});return{patch:oCe(o,i.lineOffset-1),firstLine:i.lineOffset===1?Ja(i.content):null,fileContent:i.content}}catch(e){return Y(e),{patch:[],firstLine:null,fileContent:void 0}}}var zP,BP,VP=n((()=>{zP=r(Ie(),1),CP(),dS(),v3(),yS(),EP(),Ze(),xS(),Ow(),Ct(),wa(),Fd(),IP(),Za(),Fw(),BP=$e()}));function HP(e,t=``){return RegExp(`\\bgit(?:\\s+-[cC]\\s+\\S+|\\s+--\\S+=\\S+)*\\s+${e}\\b${t}`)}function Tje(e){let t=e.match(/https:\/\/github\.com\/([^/]+\/[^/]+)\/pull\/(\d+)/);return t?.[1]&&t?.[2]?{prNumber:parseInt(t[2],10),prUrl:e,prRepository:t[1]}:null}function UP(e){let t=e.match(/https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/\d+/);return t?Tje(t[0]):null}function WP(e){return e.match(/\[[\w./-]+(?: \(root-commit\))? ([0-9a-f]+)\]/)?.[1]}function Eje(e){return e.match(/^\s*[+\-*!= ]?\s*(?:\[new branch\]|\S+\.\.+\S+)\s+\S+\s*->\s*(\S+)/m)?.[1]}function Dje(e){let t=e.match(/[Pp]ull request (?:\S+#)?#?(\d+)/);return t?.[1]?parseInt(t[1],10):void 0}function GP(e,t){let n=e.split(HP(t))[1];if(n)for(let e of n.trim().split(/\s+/)){if(/^[&|;><]/.test(e))break;if(!e.startsWith(`-`))return e}}function Oje(e,t){let n={},r=YP.test(e);if(qP.test(e)||r){let i=WP(t);i&&(n.commit={sha:i.slice(0,6),kind:r?`cherry-picked`:/--amend\b/.test(e)?`amended`:`committed`})}if(JP.test(e)){let e=Eje(t);e&&(n.push={branch:e})}if(XP.test(e)&&/(Fast-forward|Merge made by)/.test(t)){let t=GP(e,`merge`);t&&(n.branch={ref:t,action:`merged`})}if(ZP.test(e)&&/Successfully rebased/.test(t)){let t=GP(e,`rebase`);t&&(n.branch={ref:t,action:`rebased`})}let i=QP.find(t=>t.re.test(e))?.action;if(i){let e=UP(t);if(e)n.pr={number:e.prNumber,url:e.prUrl,action:i};else{let e=Dje(t);e&&(n.pr={number:e,action:i})}}return n}function KP(e,t,n){if(t!==0)return;qP.test(e)&&(e.match(/--amend\b/),wne()?.add(1)),JP.test(e);let r=QP.find(t=>t.re.test(e));if(r&&r.op,r?.action===`created`&&(Ur()?.add(1),n)){let e=UP(n);e&&import(`./sessionStorage-DHZbnPR_.js`).then(({linkSessionToPR:t})=>{import(`./state-DXt6rahM.js`).then(({getSessionId:n})=>{let r=n();r&&t(r,e.prNumber,e.prUrl,e.prRepository)})})}e.match(/\bglab\s+mr\s+create\b/)&&Ur()?.add(1);let i=e.match(/\bcurl\b/)&&(e.match(/-X\s*POST\b/i)||e.match(/--request\s*=?\s*POST\b/i)||e.match(/\s-d\s/)),a=e.match(/https?:\/\/[^\s'"]*\/(pulls|pull-requests|merge[-_]requests)(?!\/\d)/i);i&&a&&Ur()?.add(1)}var qP,JP,YP,XP,ZP,QP,$P=n((()=>{H(),La(),qP=HP(`commit`),JP=HP(`push`),YP=HP(`cherry-pick`),XP=HP(`merge`,`(?!-)`),ZP=HP(`rebase`),QP=[{re:/\bgh\s+pr\s+create\b/,action:`created`,op:`pr_create`},{re:/\bgh\s+pr\s+edit\b/,action:`edited`,op:`pr_edit`},{re:/\bgh\s+pr\s+merge\b/,action:`merged`,op:`pr_merge`},{re:/\bgh\s+pr\s+comment\b/,action:`commented`,op:`pr_comment`},{re:/\bgh\s+pr\s+close\b/,action:`closed`,op:`pr_close`},{re:/\bgh\s+pr\s+ready\b/,action:`ready`,op:`pr_ready`}]}));function kje(e){let t=jje(e),n=tF.get(t);return n===void 0?eF:n}function Aje(e){return e.trim().split(/\s+/)[0]||``}function jje(e){let t=a9(e);return Aje(t[t.length-1]||e)}function Mje(e,t,n,r){let i=kje(e)(t,n,r);return{isError:i.isError,message:i.message}}var eF,tF,Nje=n((()=>{g9(),eF=(e,t,n)=>({isError:e!==0,message:e===0?void 0:`Command failed with exit code ${e}`}),tF=new Map([[`grep`,(e,t,n)=>({isError:e>=2,message:e===1?`No matches found`:void 0})],[`rg`,(e,t,n)=>({isError:e>=2,message:e===1?`No matches found`:void 0})],[`find`,(e,t,n)=>({isError:e>=2,message:e===1?`Some directories were inaccessible`:void 0})],[`diff`,(e,t,n)=>({isError:e>=2,message:e===1?`Files differ`:void 0})],[`test`,(e,t,n)=>({isError:e>=2,message:e===1?`Condition is false`:void 0})],[`[`,(e,t,n)=>({isError:e>=2,message:e===1?`Condition is false`:void 0})]])})),nF,rF=n((()=>{nF=`https://github.com/readmagic/workMate`}));function Pje(){return lt(U())??ti()}function Fje(){return process.env.WORKMATE_ENTRYPOINT??`cli`}function iF(){return{fileStates:new Map,sessionBaselines:new Map,surface:Fje(),startingHeadSha:null,promptCount:0,promptCountAtLastCommit:0,permissionPromptCount:0,permissionPromptCountAtLastCommit:0,escapeCount:0,escapeCountAtLastCommit:0}}function Ije(e,t){let n={};for(let[t,r]of e.fileStates)n[t]=r;return{type:`attribution-snapshot`,messageId:t,surface:e.surface,fileStates:n,promptCount:e.promptCount,promptCountAtLastCommit:e.promptCountAtLastCommit,permissionPromptCount:e.permissionPromptCount,permissionPromptCountAtLastCommit:e.permissionPromptCountAtLastCommit,escapeCount:e.escapeCount,escapeCountAtLastCommit:e.escapeCountAtLastCommit}}function Lje(e,t){let n={...e,promptCount:e.promptCount+1};return t(Ije(n,Lc())),n}var aF,oF,sF=n((()=>{H(),ui(),q(),Da(),ki(),fn(),Et(),wa(),Die(),aF=`github.com:anthropics/claude-cli-internal,github.com/anthropics/claude-cli-internal,github.com:anthropics/anthropic,github.com/anthropics/anthropic,github.com:anthropics/apps,github.com/anthropics/apps,github.com:anthropics/casino,github.com/anthropics/casino,github.com:anthropics/dbt,github.com/anthropics/dbt,github.com:anthropics/dotfiles,github.com/anthropics/dotfiles,github.com:anthropics/terraform-config,github.com/anthropics/terraform-config,github.com:anthropics/hex-export,github.com/anthropics/hex-export,github.com:anthropics/feedback-v2,github.com/anthropics/feedback-v2,github.com:anthropics/labs,github.com/anthropics/labs,github.com:anthropics/argo-rollouts,github.com/anthropics/argo-rollouts,github.com:anthropics/starling-configs,github.com/anthropics/starling-configs,github.com:anthropics/ts-tools,github.com/anthropics/ts-tools,github.com:anthropics/ts-capsules,github.com/anthropics/ts-capsules,github.com:anthropics/feldspar-testing,github.com/anthropics/feldspar-testing,github.com:anthropics/trellis,github.com/anthropics/trellis,github.com:anthropics/claude-for-hiring,github.com/anthropics/claude-for-hiring,github.com:anthropics/forge-web,github.com/anthropics/forge-web,github.com:anthropics/infra-manifests,github.com/anthropics/infra-manifests,github.com:anthropics/mycro_manifests,github.com/anthropics/mycro_manifests,github.com:anthropics/mycro_configs,github.com/anthropics/mycro_configs,github.com:anthropics/mobile-apps,github.com/anthropics/mobile-apps`.split(`,`),oF=null,Eie(async()=>{if(oF!==null)return oF===`internal`;let e=await hte(Pje());if(!e)return oF=`none`,!1;let t=aF.some(t=>e.includes(t));return oF=t?`internal`:`external`,t})}));function Rje(e){let t=e.toLowerCase();for(let{keywords:e,email:n}of cF)if(e.some(e=>t.includes(e)))return n;return`noreply@anthropic.com`}var cF,zje=n((()=>{cF=[{keywords:[`claude`],email:`noreply@anthropic.com`},{keywords:[`gpt`,`dall-e`,`o1-`,`o3-`,`o4-`],email:`openai@readmagic.workmate.win`},{keywords:[`gemini`],email:`google-gemini@readmagic.workmate.win`},{keywords:[`grok`],email:`xai-org@readmagic.workmate.win`},{keywords:[`glm`],email:`zai-org@readmagic.workmate.win`},{keywords:[`deepseek`],email:`deepseek-ai@readmagic.workmate.win`},{keywords:[`qwen`],email:`QwenLM@readmagic.workmate.win`},{keywords:[`minimax`],email:`MiniMax-AI@readmagic.workmate.win`},{keywords:[`mimo`],email:`XiaomiMiMo@readmagic.workmate.win`},{keywords:[`kimi`],email:`MoonshotAI@readmagic.workmate.win`}]}));function Bje(e){switch(lo()){case`openai`:return r_(e);case`gemini`:return u_(e);case`grok`:return o_(e);default:return e}}function Vje(){return Bje(Lo())}var Hje=n((()=>{E_(),wo(),mo()})),lF,uF,dF,fF,pF=n((()=>{It(),rt(),RM(),lF=R(()=>Hn({file_path:B().describe(`The absolute path to the file to modify`),old_string:B().describe(`The text to replace`),new_string:B().describe(`The text to replace it with (must be different from old_string)`),replace_all:LM(Ot().default(!1).optional()).describe(`Replace all occurrences of old_string (default false)`)})),uF=R(()=>z({oldStart:V(),oldLines:V(),newStart:V(),newLines:V(),lines:I(B())})),dF=R(()=>z({filename:B(),status:bt([`modified`,`added`]),additions:V(),deletions:V(),changes:V(),patch:B(),repository:B().nullable().optional().describe(`GitHub owner/repo when available`)})),fF=R(()=>z({filePath:B().describe(`The file path that was edited`),oldString:B().describe(`The original string that was replaced`),newString:B().describe(`The new string that replaced it`),originalFile:B().describe(`The original file contents before editing`),structuredPatch:I(uF()).describe(`Diff patch showing the changes`),userModified:Ot().describe(`Whether the user modified the proposed changes`),replaceAll:Ot().describe(`Whether all occurrences were replaced`),gitDiff:dF().optional()}))}));function Uje({serverName:e,files:t}){let n=Lc();K(`LSP Diagnostics: Registering ${t.length} diagnostic file(s) from ${e} (ID: ${n})`),bF.set(n,{serverName:e,files:t,timestamp:Date.now(),attachmentSent:!1})}function mF(e){switch(e){case`Error`:return 1;case`Warning`:return 2;case`Info`:return 3;case`Hint`:return 4;default:return 4}}function hF(e){return W({message:e.message,severity:e.severity,range:e.range,source:e.source||null,code:e.code||null})}function Wje(e){let t=new Map,n=[];for(let r of e){t.has(r.uri)||(t.set(r.uri,new Set),n.push({uri:r.uri,diagnostics:[]}));let e=t.get(r.uri),i=n.find(e=>e.uri===r.uri),a=xF.get(r.uri)||new Set;for(let t of r.diagnostics)try{let n=hF(t);if(e.has(n)||a.has(n))continue;e.add(n),i.diagnostics.push(t)}catch(e){let n=wi(e),a=t.message?.substring(0,100)||`<no message>`;Y(Error(`Failed to deduplicate diagnostic in ${r.uri}: ${n.message}. Diagnostic message: ${a}`)),i.diagnostics.push(t)}}return n.filter(e=>e.diagnostics.length>0)}function Gje(){K(`LSP Diagnostics: Checking registry - ${bF.size} pending`);let e=[],t=new Set,n=[];for(let r of bF.values())r.attachmentSent||(e.push(...r.files),t.add(r.serverName),n.push(r));if(e.length===0)return[];let r;try{r=Wje(e)}catch(t){let n=wi(t);Y(Error(`Failed to deduplicate LSP diagnostics: ${n.message}`)),r=e}for(let e of n)e.attachmentSent=!0;for(let[e,t]of bF)t.attachmentSent&&bF.delete(e);let i=e.reduce((e,t)=>e+t.diagnostics.length,0),a=r.reduce((e,t)=>e+t.diagnostics.length,0);i>a&&K(`LSP Diagnostics: Deduplication removed ${i-a} duplicate diagnostic(s)`);let o=0,s=0;for(let e of r){e.diagnostics.sort((e,t)=>mF(e.severity)-mF(t.severity)),e.diagnostics.length>_F&&(s+=e.diagnostics.length-_F,e.diagnostics=e.diagnostics.slice(0,_F));let t=vF-o;e.diagnostics.length>t&&(s+=e.diagnostics.length-t,e.diagnostics=e.diagnostics.slice(0,t)),o+=e.diagnostics.length}r=r.filter(e=>e.diagnostics.length>0),s>0&&K(`LSP Diagnostics: Volume limiting removed ${s} diagnostic(s) (max ${_F}/file, ${vF} total)`);for(let e of r){xF.has(e.uri)||xF.set(e.uri,new Set);let t=xF.get(e.uri);for(let n of e.diagnostics)try{t.add(hF(n))}catch(t){let r=wi(t),i=n.message?.substring(0,100)||`<no message>`;Y(Error(`Failed to track delivered diagnostic in ${e.uri}: ${r.message}. Diagnostic message: ${i}`))}}let c=r.reduce((e,t)=>e+t.diagnostics.length,0);return c===0?(K(`LSP Diagnostics: No new diagnostics to deliver (all filtered by deduplication)`),[]):(K(`LSP Diagnostics: Delivering ${r.length} file(s) with ${c} diagnostic(s) from ${t.size} server(s)`),[{serverName:Array.from(t).join(`, `),files:r}])}function Kje(){K(`LSP Diagnostics: Clearing ${bF.size} pending diagnostic(s)`),bF.clear()}function qje(){K(`LSP Diagnostics: Resetting all state (${bF.size} pending, ${xF.size} files tracked)`),bF.clear(),xF.clear()}function gF(e){xF.has(e)&&(K(`LSP Diagnostics: Clearing delivered diagnostics for ${e}`),xF.delete(e))}var _F,vF,yF,bF,xF,SF=n((()=>{Sn(),q(),gi(),wa(),Li(),_F=10,vF=30,yF=500,bF=new Map,xF=new nt({max:yF})}));function CF(e){let t=[];return{expanded:e.replace(/\$\{([^}]+)\}/g,(e,n)=>{let[r,i]=n.split(`:-`,2),a=process.env[r];return a===void 0?i===void 0?(t.push(r),e):i:a}),missingVars:t}}var wF=n((()=>{}));function Jje(e,t){return{name:`${e.name}-with-${t.name}-fallback`,read(){return e.read()??(t.read()||{})},async readAsync(){return await e.readAsync()??(await t.readAsync()||{})},update(n){let r=e.read(),i=e.update(n);if(i.success)return r===null&&t.delete(),i;let a=t.update(n);return a.success?(r!==null&&e.delete(),{success:!0,warning:a.warning}):{success:!1}},delete(){let n=e.delete(),r=t.delete();return n||r}}}var Yje=n((()=>{}));function TF(e=``){let t=m(),n=process.env.WORKMATE_CONFIG_DIR?`-${Fc(`sha256`).update(t).digest(`hex`).substring(0,8)}`:``;return`Work Mate${Yee().OAUTH_FILE_SUFFIX}${e}${n}`}function EF(){try{return process.env.USER||yse().username}catch{return`workmate-user`}}function DF(){kF.cache={data:null,cachedAt:0},kF.generation++,kF.readInFlight=null}function Xje(e){if(kF.cache.cachedAt!==0)return;let t=null;if(e)try{t=JSON.parse(e)}catch{return}kF.cache={data:t,cachedAt:Date.now()}}var OF,kF,AF=n((()=>{Lee(),g(),OF=`-credentials`,kF={cache:{data:null,cachedAt:0},generation:0,readInFlight:null}}));async function Zje(){try{let e=TF(OF),{stdout:t,code:n}=await Aa(`security`,[`find-generic-password`,`-a`,EF(),`-w`,`-s`,e],{useCwd:!1,preserveOutputOnError:!1});if(n===0&&t)return Si(t.trim())}catch{}return null}function Qje(){if(NF!==void 0)return NF;if(process.platform!==`darwin`)return NF=!1,!1;try{NF=ea(`security`,[`show-keychain-info`],{reject:!1,stdio:[`ignore`,`pipe`,`pipe`]}).exitCode===36}catch{NF=!1}return NF}var jF,MF,NF,PF=n((()=>{ta(),q(),Da(),Li(),AF(),jF=4032,MF={name:`keychain`,read(){let e=kF.cache;if(Date.now()-e.cachedAt<3e4)return e.data;try{let e=TF(OF),t=ka(`security find-generic-password -a "${EF()}" -w -s "${e}"`);if(t){let e=Si(t);return kF.cache={data:e,cachedAt:Date.now()},e}}catch{}return e.data===null?(kF.cache={data:null,cachedAt:Date.now()},null):(K(`[keychain] read failed; serving stale cache`,{level:`warn`}),kF.cache={data:e.data,cachedAt:Date.now()},e.data)},async readAsync(){let e=kF.cache;if(Date.now()-e.cachedAt<3e4)return e.data;if(kF.readInFlight)return kF.readInFlight;let t=kF.generation,n=Zje().then(n=>{if(t===kF.generation){n===null&&e.data!==null&&K(`[keychain] readAsync failed; serving stale cache`,{level:`warn`});let t=n??e.data;return kF.cache={data:t,cachedAt:Date.now()},kF.readInFlight=null,t}return n});return kF.readInFlight=n,n},update(e){DF();try{let t=TF(OF),n=EF(),r=W(e),i=Buffer.from(r,`utf-8`).toString(`hex`),a=`add-generic-password -U -a "${n}" -s "${t}" -X "${i}"\n`,o;return a.length<=jF?o=ea(`security`,[`-i`],{input:a,stdio:[`pipe`,`pipe`,`pipe`],reject:!1}):(K(`Keychain payload (${r.length}B JSON) exceeds security -i stdin limit; using argv`,{level:`warn`}),o=ea(`security`,[`add-generic-password`,`-U`,`-a`,n,`-s`,t,`-X`,i],{stdio:[`ignore`,`pipe`,`pipe`],reject:!1})),o.exitCode===0?(kF.cache={data:e,cachedAt:Date.now()},{success:!0}):{success:!1}}catch{return{success:!1}}},delete(){DF();try{let e=TF(OF);return ka(`security delete-generic-password -a "${EF()}" -s "${e}"`),!0}catch{return!1}}}}));function FF(){let e=m();return{storageDir:e,storagePath:X(e,`.credentials.json`)}}var IF,$je=n((()=>{g(),gi(),ki(),Li(),IF={name:`plaintext`,read(){let{storagePath:e}=FF();try{return Si(J().readFileSync(e,{encoding:`utf8`}))}catch{return null}},async readAsync(){let{storagePath:e}=FF();try{return Si(await J().readFile(e,{encoding:`utf8`}))}catch{return null}},update(e){try{let{storageDir:t,storagePath:n}=FF();try{J().mkdirSync(t)}catch(e){if(yi(e)!==`EEXIST`)throw e}return Ci(n,W(e),{encoding:`utf8`,flush:!1}),Dse(n,384),{success:!0,warning:`Warning: Storing credentials in plaintext.`}}catch{return{success:!1}}},delete(){let{storagePath:e}=FF();try{return J().unlinkSync(e),!0}catch(e){return yi(e)===`ENOENT`}}}}));function LF(){return process.platform===`darwin`?Jje(MF,IF):IF}var RF=n((()=>{Yje(),PF(),$je()}));async function eMe(e){let{vAny:t}=await import(`./dist-DIee4wq1.js`),n=t.McpbManifestSchema.safeParse(e);if(!n.success){let e=n.error.flatten(),t=[...Object.entries(e.fieldErrors).map(([e,t])=>`${e}: ${t?.join(`, `)}`),...e.formErrors||[]].filter(Boolean).join(`; `);throw Error(`Invalid manifest: ${t}`)}return n.data}async function tMe(e){let t;try{t=Si(e)}catch(e){throw Error(`Invalid JSON in manifest.json: ${G(e)}`)}return eMe(t)}async function zF(e){return tMe(new TextDecoder().decode(e))}var nMe=n((()=>{gi(),Li()}));function rMe(e){return!(sr(e)||mc(hc(e)))}function iMe(e,t){t.fileCount++;let n;t.fileCount>HF.MAX_FILE_COUNT&&(n=`Archive contains too many files: ${t.fileCount} (max: ${HF.MAX_FILE_COUNT})`),rMe(e.name)||(n=`Unsafe file path detected: "${e.name}". Path traversal or absolute paths are not allowed.`);let r=e.originalSize||0;r>HF.MAX_FILE_SIZE&&(n=`File "${e.name}" is too large: ${Math.round(r/1024/1024)}MB (max: ${Math.round(HF.MAX_FILE_SIZE/1024/1024)}MB)`),t.totalUncompressedSize+=r,t.totalUncompressedSize>HF.MAX_TOTAL_SIZE&&(n=`Archive total size is too large: ${Math.round(t.totalUncompressedSize/1024/1024)}MB (max: ${Math.round(HF.MAX_TOTAL_SIZE/1024/1024)}MB)`);let i=t.totalUncompressedSize/t.compressedSize;return i>HF.MAX_COMPRESSION_RATIO&&(n=`Suspicious compression ratio detected: ${i.toFixed(1)}:1 (max: ${HF.MAX_COMPRESSION_RATIO}:1). This may be a zip bomb.`),n?{isValid:!1,error:n}:{isValid:!0}}async function BF(e){let{unzipSync:t}=await import(`./esm-wGnzjq4Z.js`),n={fileCount:0,totalUncompressedSize:0,compressedSize:e.length,errors:[]},r=t(new Uint8Array(e),{filter:e=>{let t=iMe(e,n);if(!t.isValid)throw Error(t.error);return!0}});return K(`Zip extraction completed: ${n.fileCount} files, ${Math.round(n.totalUncompressedSize/1024)}KB uncompressed`),r}function VF(e){let t=Buffer.from(e.buffer,e.byteOffset,e.byteLength),n={},r=Math.max(0,t.length-22-65535),i=-1;for(let e=t.length-22;e>=r;e--)if(t.readUInt32LE(e)===101010256){i=e;break}if(i<0)return n;let a=t.readUInt16LE(i+10),o=t.readUInt32LE(i+16);for(let e=0;e<a&&!(o+46>t.length||t.readUInt32LE(o)!==33639248);e++){let e=t.readUInt16LE(o+4),r=t.readUInt16LE(o+28),i=t.readUInt16LE(o+30),a=t.readUInt16LE(o+32),s=t.readUInt32LE(o+38),c=t.toString(`utf8`,o+46,o+46+r);if(e>>8==3){let e=s>>>16&65535;e&&(n[c]=e)}o+=46+r+i+a}return n}var HF,UF=n((()=>{q(),gi(),ki(),Wn(),HF={MAX_FILE_SIZE:512*1024*1024,MAX_TOTAL_SIZE:1024*1024*1024,MAX_FILE_COUNT:1e5,MAX_COMPRESSION_RATIO:50,MIN_COMPRESSION_RATIO:.5}}));function aMe(e){let t=e?.platform??Ma(),n=e?.homedir??cc(),r=e?.env??process.env,i={HOME:n,DESKTOP:X(n,`Desktop`),DOCUMENTS:X(n,`Documents`),DOWNLOADS:X(n,`Downloads`)};switch(t){case`windows`:{let e=r.USERPROFILE||n;return{HOME:n,DESKTOP:X(e,`Desktop`),DOCUMENTS:X(e,`Documents`),DOWNLOADS:X(e,`Downloads`)}}case`linux`:case`wsl`:return{HOME:n,DESKTOP:r.XDG_DESKTOP_DIR||i.DESKTOP,DOCUMENTS:r.XDG_DOCUMENTS_DIR||i.DOCUMENTS,DOWNLOADS:r.XDG_DOWNLOAD_DIR||i.DOWNLOADS};default:return t===`unknown`&&K(`Unknown platform detected, using default paths`),i}}var oMe=n((()=>{q(),Pa()}));function WF(e){return e.endsWith(`.mcpb`)||e.endsWith(`.dxt`)}function GF(e){return e.startsWith(`http://`)||e.startsWith(`https://`)}function sMe(e){return Fc(`sha256`).update(e).digest(`hex`).substring(0,16)}function KF(e){return X(e,`.mcpb-cache`)}function qF(e,t){return X(e,`${Fc(`md5`).update(t).digest(`hex`).substring(0,8)}.metadata.json`)}function JF(e,t){return`${e}/${t}`}function YF(e,t){try{let n=yn().pluginConfigs?.[e]?.mcpServers?.[t],r=LF().read()?.pluginSecrets?.[JF(e,t)];return!n&&!r?null:(K(`Loaded user config for ${e}/${t} (settings + secureStorage)`),{...n,...r})}catch(n){return Y(wi(n)),K(`Failed to load user config for ${e}/${t}: ${n}`,{level:`error`}),null}}function XF(e,t,n,r){try{let i={},a={};for(let[e,t]of Object.entries(n))r[e]?.sensitive===!0?a[e]=String(t):i[e]=t;let o=new Set(Object.keys(a)),s=new Set(Object.keys(i)),c=LF(),l=JF(e,t),u=c.read()?.pluginSecrets?.[l]??void 0,d=u?Object.fromEntries(Object.entries(u).filter(([e])=>!s.has(e))):void 0,f=d&&u&&Object.keys(d).length!==Object.keys(u).length;if(Object.keys(a).length>0||f){let e=c.read()??{};e.pluginSecrets||(e.pluginSecrets={}),e.pluginSecrets[l]={...d,...a};let t=c.update(e);if(!t.success)throw Error(`Failed to save sensitive config to secure storage for ${l}`);t.warning&&K(`Server secrets save warning: ${t.warning}`,{level:`warn`}),f&&K(`saveMcpServerUserConfig: scrubbed ${Object.keys(u).length-Object.keys(d).length} stale non-sensitive key(s) from secureStorage for ${l}`)}let p=yn(),m=p.pluginConfigs?.[e]?.mcpServers?.[t]??{},h=Object.keys(m).filter(e=>o.has(e));if(Object.keys(i).length>0||h.length>0){p.pluginConfigs||(p.pluginConfigs={}),p.pluginConfigs[e]||(p.pluginConfigs[e]={}),p.pluginConfigs[e].mcpServers||(p.pluginConfigs[e].mcpServers={});let n=Object.fromEntries(h.map(e=>[e,void 0]));p.pluginConfigs[e].mcpServers[t]={...i,...n};let r=gr(`userSettings`,p);if(r.error)throw r.error;h.length>0&&K(`saveMcpServerUserConfig: scrubbed ${h.length} plaintext sensitive key(s) from settings.json for ${e}/${t}`)}K(`Saved user config for ${e}/${t} (${Object.keys(i).length} non-sensitive, ${Object.keys(a).length} sensitive)`)}catch(n){let r=wi(n);throw Y(r),Error(`Failed to save user configuration for ${e}/${t}: ${r.message}`)}}function ZF(e,t){let n=[];for(let[r,i]of Object.entries(t)){let t=e[r];if(i.required&&(t===void 0||t===``)){n.push(`${i.title||r} is required but not provided`);continue}t===void 0||t===``||(i.type===`string`?Array.isArray(t)?i.multiple?t.every(e=>typeof e==`string`)||n.push(`${i.title||r} must be an array of strings`):n.push(`${i.title||r} must be a string, not an array`):typeof t!=`string`&&n.push(`${i.title||r} must be a string`):i.type===`number`&&typeof t!=`number`?n.push(`${i.title||r} must be a number`):i.type===`boolean`&&typeof t!=`boolean`?n.push(`${i.title||r} must be a boolean`):(i.type===`file`||i.type===`directory`)&&typeof t!=`string`&&n.push(`${i.title||r} must be a path string`),i.type===`number`&&typeof t==`number`&&(i.min!==void 0&&t<i.min&&n.push(`${i.title||r} must be at least ${i.min}`),i.max!==void 0&&t>i.max&&n.push(`${i.title||r} must be at most ${i.max}`)))}return{valid:n.length===0,errors:n}}async function QF(e,t,n={}){let{getMcpConfigForManifest:r}=await import(`./dist-DIee4wq1.js`),i=await r({manifest:e,extensionPath:t,systemDirs:aMe(),userConfig:n,pathSeparator:`/`});if(!i){let t=Error(`Failed to generate MCP server configuration from manifest "${e.name}"`);throw Y(t),t}return i}async function $F(e,t){let n=J(),r=qF(e,t);try{return Si(await n.readFile(r,{encoding:`utf-8`}))}catch(e){return yi(e)===`ENOENT`?null:(Y(wi(e)),K(`Failed to load MCPB cache metadata: ${e}`,{level:`error`}),null)}}async function eI(e,t,n){let r=qF(e,t);await J().mkdir(e),await Qc(r,W(n,null,2),`utf-8`)}async function cMe(e,t,n){K(`Downloading MCPB from ${e}`),n&&n(`Downloading ${e}...`);let r=performance.now(),i=!1;try{let a=await ue.get(e,{timeout:12e4,responseType:`arraybuffer`,maxRedirects:5,onDownloadProgress:e=>{e.total&&n&&n(`Downloading... ${Math.round(e.loaded/e.total*100)}%`)}}),o=new Uint8Array(a.data);return Ev(`mcpb`,e,`success`,performance.now()-r),i=!0,await Qc(t,Buffer.from(o)),K(`Downloaded ${o.length} bytes to ${t}`),n&&n(`Download complete`),o}catch(t){i||Ev(`mcpb`,e,`failure`,performance.now()-r,Dv(t));let n=G(t),a=Error(`Failed to download MCPB file from ${e}: ${n}`);throw Y(a),a}}async function lMe(e,t,n,r){r&&r(`Extracting files...`),await J().mkdir(t);let i=0,a=Object.entries(e).filter(([e])=>!e.endsWith(`/`)),o=a.length;for(let[e,s]of a){let a=X(t,e),c=fc(a);c!==t&&await J().mkdir(c),e.endsWith(`.json`)||e.endsWith(`.js`)||e.endsWith(`.ts`)||e.endsWith(`.txt`)||e.endsWith(`.md`)||e.endsWith(`.yml`)||e.endsWith(`.yaml`)?await Qc(a,new TextDecoder().decode(s),`utf-8`):await Qc(a,Buffer.from(s));let l=n[e];l&&l&73&&await zc(a,l&511).catch(()=>{}),i++,r&&i%10==0&&r(`Extracted ${i}/${o} files`)}K(`Extracted ${i} files to ${t}`),r&&r(`Extraction complete (${i} files)`)}async function uMe(e,t){let n=J(),r=await $F(KF(t),e);if(!r)return!0;try{await n.stat(r.extractedPath)}catch(e){return yi(e)===`ENOENT`?K(`MCPB extraction path missing: ${r.extractedPath}`):K(`MCPB extraction path inaccessible: ${r.extractedPath}: ${e}`,{level:`error`}),!0}if(!GF(e)){let i=X(t,e),a;try{a=await n.stat(i)}catch(e){return yi(e)===`ENOENT`?K(`MCPB source file missing: ${i}`):K(`MCPB source file inaccessible: ${i}: ${e}`,{level:`error`}),!0}let o=new Date(r.cachedAt).getTime(),s=Math.floor(a.mtimeMs);if(s>o)return K(`MCPB file modified: ${new Date(s)} > ${new Date(o)}`),!0}return!1}async function tI(e,t,n,r,i,a){let o=J(),s=KF(t);await o.mkdir(s),K(`Loading MCPB from source: ${e}`);let c=await $F(s,e);if(c&&!await uMe(e,t)){K(`Using cached MCPB from ${c.extractedPath} (hash: ${c.contentHash})`);let e=X(c.extractedPath,`manifest.json`),t;try{t=await o.readFile(e,{encoding:`utf-8`})}catch(t){if(xi(t)){let t=Error(`Cached manifest not found: ${e}`);throw Y(t),t}throw t}let r=await zF(new TextEncoder().encode(t));if(r.user_config&&Object.keys(r.user_config).length>0){let e=r.name,t=YF(n,e),o=i||t||{},s=ZF(o,r.user_config);return a||!s.valid?{status:`needs-config`,manifest:r,extractedPath:c.extractedPath,contentHash:c.contentHash,configSchema:r.user_config,existingConfig:t||{},validationErrors:s.valid?[]:s.errors}:(i&&XF(n,e,i,r.user_config??{}),{manifest:r,mcpConfig:await QF(r,c.extractedPath,o),extractedPath:c.extractedPath,contentHash:c.contentHash})}return{manifest:r,mcpConfig:await QF(r,c.extractedPath),extractedPath:c.extractedPath,contentHash:c.contentHash}}let l,u;if(GF(e))u=X(s,`${Fc(`md5`).update(e).digest(`hex`).substring(0,8)}.mcpb`),l=await cMe(e,u,r);else{let n=X(t,e);r&&r(`Loading ${e}...`);try{l=await o.readFileBytes(n),u=n}catch(e){if(xi(e)){let e=Error(`MCPB file not found: ${n}`);throw Y(e),e}throw e}}let d=sMe(l);K(`MCPB content hash: ${d}`),r&&r(`Extracting MCPB archive...`);let f=await BF(Buffer.from(l)),p=VF(l),m=f[`manifest.json`];if(!m){let e=Error(`No manifest.json found in MCPB file`);throw Y(e),e}let h=await zF(m);if(K(`MCPB manifest: ${h.name} v${h.version} by ${h.author.name}`),!h.server){let e=Error(`MCPB manifest for "${h.name}" does not define a server configuration`);throw Y(e),e}let g=X(s,d);if(await lMe(f,g,p,r),h.user_config&&Object.keys(h.user_config).length>0){let t=h.name,a=YF(n,t),o=i||a||{},c=ZF(o,h.user_config);if(!c.valid)return await eI(s,e,{source:e,contentHash:d,extractedPath:g,cachedAt:new Date().toISOString(),lastChecked:new Date().toISOString()}),{status:`needs-config`,manifest:h,extractedPath:g,contentHash:d,configSchema:h.user_config,existingConfig:a||{},validationErrors:c.errors};i&&XF(n,t,i,h.user_config??{}),r&&r(`Generating MCP server configuration...`);let l=await QF(h,g,o);return await eI(s,e,{source:e,contentHash:d,extractedPath:g,cachedAt:new Date().toISOString(),lastChecked:new Date().toISOString()}),{manifest:h,mcpConfig:l,extractedPath:g,contentHash:d}}r&&r(`Generating MCP server configuration...`);let _=await QF(h,g);return await eI(s,e,{source:e,contentHash:d,extractedPath:g,cachedAt:new Date().toISOString(),lastChecked:new Date().toISOString()}),K(`Successfully loaded MCPB: ${h.name} (extracted to ${g})`),{manifest:h,mcpConfig:_,extractedPath:g,contentHash:d}}var nI=n((()=>{de(),q(),nMe(),UF(),gi(),ki(),wa(),RF(),Ln(),Li(),oMe(),Ov()}));function rI(e){return e.source}function iI(){lI.cache?.clear?.()}function dMe(e,t,n){let r={},i={};for(let[e,a]of Object.entries(t))n[e]?.sensitive===!0?i[e]=String(a):r[e]=a;let a=new Set(Object.keys(i)),o=new Set(Object.keys(r)),s=LF(),c=s.read()?.pluginSecrets?.[e]??void 0,l=c?Object.fromEntries(Object.entries(c).filter(([e])=>!o.has(e))):void 0,u=l&&c&&Object.keys(l).length!==Object.keys(c).length;if(Object.keys(i).length>0||u){let t=s.read()??{};t.pluginSecrets||(t.pluginSecrets={}),t.pluginSecrets[e]={...l,...i};let n=s.update(t);if(!n.success){let t=Error(`Failed to save sensitive plugin options for ${e} to secure storage`);throw Y(t),t}n.warning&&K(`Plugin secrets save warning: ${n.warning}`,{level:`warn`})}let d=yn(),f=d.pluginConfigs?.[e]?.options??{},p=Object.keys(f).filter(e=>a.has(e));if(Object.keys(r).length>0||p.length>0){d.pluginConfigs||(d.pluginConfigs={}),d.pluginConfigs[e]||(d.pluginConfigs[e]={});let t=Object.fromEntries(p.map(e=>[e,void 0]));d.pluginConfigs[e].options={...r,...t};let n=gr(`userSettings`,d);if(n.error)throw Y(n.error),Error(`Failed to save plugin options for ${e}: ${n.error.message}`)}iI()}function aI(e){if(yn().pluginConfigs?.[e]){let{error:t}=gr(`userSettings`,{pluginConfigs:{[e]:void 0}});t&&K(`deletePluginOptions: failed to clear settings.pluginConfigs[${e}]: ${t.message}`,{level:`warn`})}let t=LF(),n=t.read();if(n?.pluginSecrets){let r=`${e}/`,i=Object.entries(n.pluginSecrets).filter(([t])=>t!==e&&!t.startsWith(r));i.length!==Object.keys(n.pluginSecrets).length&&(t.update({...n,pluginSecrets:i.length>0?Object.fromEntries(i):void 0}).success||K(`deletePluginOptions: failed to clear pluginSecrets for ${e} from keychain`,{level:`warn`}))}iI()}function fMe(e){let t=e.manifest.userConfig;if(!t||Object.keys(t).length===0)return{};let n=lI(rI(e));if(ZF(n,t).valid)return{};let r={};for(let[e,i]of Object.entries(t))ZF({[e]:n[e]},{[e]:i}).valid||(r[e]=i);return r}function oI(e,t){let n=e=>process.platform===`win32`?e.replace(/\\/g,`/`):e,r=e.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g,()=>n(t.path));if(t.source){let e=t.source;r=r.replace(/\$\{CLAUDE_PLUGIN_DATA\}/g,()=>n(ny(e)))}return r}function sI(e,t){return e.replace(/\$\{user_config\.([^}]+)\}/g,(e,n)=>{let r=t[n];if(r===void 0)throw Error(`Missing required user configuration value: ${n}. This should have been validated before variable substitution.`);return String(r)})}function cI(e,t,n){return e.replace(/\$\{user_config\.([^}]+)\}/g,(e,r)=>{if(n[r]?.sensitive===!0)return`[sensitive option '${r}' not available in skill content]`;let i=t[r];return i===void 0?e:String(i)})}var lI,uI=n((()=>{d(),q(),wa(),RF(),Ln(),nI(),ry(),lI=u(e=>{let t=yn().pluginConfigs?.[e]?.options??{},n=LF().read()?.pluginSecrets?.[e]??{};return{...t,...n}})}));function pMe(e,t){let n=yc(e),r=yc(e,t),i=vc(n,r);return i.startsWith(`..`)||yc(i)===i?null:r}async function dI(e,t=[]){let n={},r=X(e.path,`.lsp.json`);try{let i=Si(await Wc(r,`utf-8`)),a=dn(B(),cr()).safeParse(i);if(a.success)Object.assign(n,a.data);else{let n=`LSP config validation failed for .lsp.json in plugin ${e.name}: ${a.error.message}`;Y(Error(n)),t.push({type:`lsp-config-invalid`,plugin:e.name,serverName:`.lsp.json`,validationError:a.error.message,source:`plugin`})}}catch(n){xi(n)||(n instanceof Error?`${e.name}${n.message}`:`${e.name}`,Y(wi(n)),t.push({type:`lsp-config-invalid`,plugin:e.name,serverName:`.lsp.json`,validationError:n instanceof Error?`Failed to parse JSON: ${n.message}`:`Failed to parse JSON file`,source:`plugin`}))}if(e.manifest.lspServers){let r=await mMe(e.manifest.lspServers,e.path,e.name,t);r&&Object.assign(n,r)}return Object.keys(n).length>0?n:void 0}async function mMe(e,t,n,r){let i={},a=Array.isArray(e)?e:[e];for(let e of a)if(typeof e==`string`){let a=pMe(t,e);if(!a){let t=`Security: Path traversal attempt blocked in plugin ${n}: ${e}`;Y(Error(t)),K(t,{level:`warn`}),r.push({type:`lsp-config-invalid`,plugin:n,serverName:e,validationError:`Invalid path: must be relative and within plugin directory`,source:`plugin`});continue}try{let t=Si(await Wc(a,`utf-8`)),o=dn(B(),cr()).safeParse(t);if(o.success)Object.assign(i,o.data);else{let t=`LSP config validation failed for ${e} in plugin ${n}: ${o.error.message}`;Y(Error(t)),r.push({type:`lsp-config-invalid`,plugin:n,serverName:e,validationError:o.error.message,source:`plugin`})}}catch(t){t instanceof Error?`${e}${n}${t.message}`:`${e}${n}`,Y(wi(t)),r.push({type:`lsp-config-invalid`,plugin:n,serverName:e,validationError:t instanceof Error?`Failed to parse JSON: ${t.message}`:`Failed to parse JSON file`,source:`plugin`})}}else for(let[t,a]of Object.entries(e)){let e=cr().safeParse(a);if(e.success)i[t]=e.data;else{let i=`LSP config validation failed for inline server "${t}" in plugin ${n}: ${e.error.message}`;Y(Error(i)),r.push({type:`lsp-config-invalid`,plugin:n,serverName:t,validationError:e.error.message,source:`plugin`})}}return Object.keys(i).length>0?i:void 0}function hMe(e,t,n,r){let i=[],a=e=>{let r=oI(e,t);n&&(r=sI(r,n));let{expanded:a,missingVars:o}=CF(r);return i.push(...o),a},o={...e};o.command&&(o.command=a(o.command)),o.args&&(o.args=o.args.map(e=>a(e)));let s={CLAUDE_PLUGIN_ROOT:t.path,CLAUDE_PLUGIN_DATA:ny(t.source),...o.env||{}};for(let[e,t]of Object.entries(s))e!==`CLAUDE_PLUGIN_ROOT`&&e!==`CLAUDE_PLUGIN_DATA`&&(s[e]=a(t));if(o.env=s,o.workspaceFolder&&(o.workspaceFolder=a(o.workspaceFolder)),i.length>0){let e=`Missing environment variables in plugin LSP config: ${[...new Set(i)].join(`, `)}`;Y(Error(e)),K(e,{level:`warn`})}return o}function gMe(e,t){let n={};for(let[r,i]of Object.entries(e)){let e=`plugin:${t}:${r}`;n[e]={...i,scope:`dynamic`,source:t}}return n}async function _Me(e,t=[]){if(!e.enabled)return;let n=e.lspServers||await dI(e,t);if(!n)return;let r=e.manifest.userConfig?lI(rI(e)):void 0,i={};for(let[a,o]of Object.entries(n))i[a]=hMe(o,e,r,t);return gMe(i,e.name)}var fI=n((()=>{It(),wF(),q(),gi(),wa(),Li(),ry(),uI(),En()}));async function vMe(){let e={};try{let{enabled:t}=await R4(),n=await Promise.all(t.map(async e=>{let t=[];try{return{plugin:e,scopedServers:await _Me(e,t),errors:t}}catch(n){return K(`Failed to load LSP servers for plugin ${e.name}: ${n}`,{level:`error`}),{plugin:e,scopedServers:void 0,errors:t}}}));for(let{plugin:t,scopedServers:r,errors:i}of n){let n=r?Object.keys(r).length:0;n>0&&(Object.assign(e,r),K(`Loaded ${n} LSP server(s) from plugin: ${t.name}`)),i.length>0&&K(`${i.length} error(s) loading LSP servers from plugin: ${t.name}`)}K(`Total LSP servers loaded: ${Object.keys(e).length}`)}catch(e){Y(wi(e)),K(`Error loading LSP servers: ${G(e)}`)}return{servers:e}}var yMe=n((()=>{q(),gi(),wa(),fI(),z4()})),pI=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.stringArray=e.array=e.func=e.error=e.number=e.string=e.boolean=void 0;function t(e){return e===!0||e===!1}e.boolean=t;function n(e){return typeof e==`string`||e instanceof String}e.string=n;function r(e){return typeof e==`number`||e instanceof Number}e.number=r;function i(e){return e instanceof Error}e.error=i;function a(e){return typeof e==`function`}e.func=a;function o(e){return Array.isArray(e)}e.array=o;function s(e){return o(e)&&e.every(e=>n(e))}e.stringArray=s})),mI=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Message=e.NotificationType9=e.NotificationType8=e.NotificationType7=e.NotificationType6=e.NotificationType5=e.NotificationType4=e.NotificationType3=e.NotificationType2=e.NotificationType1=e.NotificationType0=e.NotificationType=e.RequestType9=e.RequestType8=e.RequestType7=e.RequestType6=e.RequestType5=e.RequestType4=e.RequestType3=e.RequestType2=e.RequestType1=e.RequestType=e.RequestType0=e.AbstractMessageSignature=e.ParameterStructures=e.ResponseError=e.ErrorCodes=void 0;var t=pI(),n;(function(e){e.ParseError=-32700,e.InvalidRequest=-32600,e.MethodNotFound=-32601,e.InvalidParams=-32602,e.InternalError=-32603,e.jsonrpcReservedErrorRangeStart=-32099,e.serverErrorStart=-32099,e.MessageWriteError=-32099,e.MessageReadError=-32098,e.PendingResponseRejected=-32097,e.ConnectionInactive=-32096,e.ServerNotInitialized=-32002,e.UnknownErrorCode=-32001,e.jsonrpcReservedErrorRangeEnd=-32e3,e.serverErrorEnd=-32e3})(n||(e.ErrorCodes=n={})),e.ResponseError=class e extends Error{constructor(r,i,a){super(i),this.code=t.number(r)?r:n.UnknownErrorCode,this.data=a,Object.setPrototypeOf(this,e.prototype)}toJson(){let e={code:this.code,message:this.message};return this.data!==void 0&&(e.data=this.data),e}};var r=class e{constructor(e){this.kind=e}static is(t){return t===e.auto||t===e.byName||t===e.byPosition}toString(){return this.kind}};e.ParameterStructures=r,r.auto=new r(`auto`),r.byPosition=new r(`byPosition`),r.byName=new r(`byName`);var i=class{constructor(e,t){this.method=e,this.numberOfParams=t}get parameterStructures(){return r.auto}};e.AbstractMessageSignature=i,e.RequestType0=class extends i{constructor(e){super(e,0)}},e.RequestType=class extends i{constructor(e,t=r.auto){super(e,1),this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}},e.RequestType1=class extends i{constructor(e,t=r.auto){super(e,1),this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}},e.RequestType2=class extends i{constructor(e){super(e,2)}},e.RequestType3=class extends i{constructor(e){super(e,3)}},e.RequestType4=class extends i{constructor(e){super(e,4)}},e.RequestType5=class extends i{constructor(e){super(e,5)}},e.RequestType6=class extends i{constructor(e){super(e,6)}},e.RequestType7=class extends i{constructor(e){super(e,7)}},e.RequestType8=class extends i{constructor(e){super(e,8)}},e.RequestType9=class extends i{constructor(e){super(e,9)}},e.NotificationType=class extends i{constructor(e,t=r.auto){super(e,1),this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}},e.NotificationType0=class extends i{constructor(e){super(e,0)}},e.NotificationType1=class extends i{constructor(e,t=r.auto){super(e,1),this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}},e.NotificationType2=class extends i{constructor(e){super(e,2)}},e.NotificationType3=class extends i{constructor(e){super(e,3)}},e.NotificationType4=class extends i{constructor(e){super(e,4)}},e.NotificationType5=class extends i{constructor(e){super(e,5)}},e.NotificationType6=class extends i{constructor(e){super(e,6)}},e.NotificationType7=class extends i{constructor(e){super(e,7)}},e.NotificationType8=class extends i{constructor(e){super(e,8)}},e.NotificationType9=class extends i{constructor(e){super(e,9)}};var a;(function(e){function n(e){let n=e;return n&&t.string(n.method)&&(t.string(n.id)||t.number(n.id))}e.isRequest=n;function r(e){let n=e;return n&&t.string(n.method)&&e.id===void 0}e.isNotification=r;function i(e){let n=e;return n&&(n.result!==void 0||!!n.error)&&(t.string(n.id)||t.number(n.id)||n.id===null)}e.isResponse=i})(a||(e.Message=a={}))})),hI=a((e=>{var t;Object.defineProperty(e,"__esModule",{value:!0}),e.LRUCache=e.LinkedMap=e.Touch=void 0;var n;(function(e){e.None=0,e.First=1,e.AsOld=e.First,e.Last=2,e.AsNew=e.Last})(n||(e.Touch=n={}));var r=class{constructor(){this[t]=`LinkedMap`,this._map=new Map,this._head=void 0,this._tail=void 0,this._size=0,this._state=0}clear(){this._map.clear(),this._head=void 0,this._tail=void 0,this._size=0,this._state++}isEmpty(){return!this._head&&!this._tail}get size(){return this._size}get first(){return this._head?.value}get last(){return this._tail?.value}has(e){return this._map.has(e)}get(e,t=n.None){let r=this._map.get(e);if(r)return t!==n.None&&this.touch(r,t),r.value}set(e,t,r=n.None){let i=this._map.get(e);if(i)i.value=t,r!==n.None&&this.touch(i,r);else{switch(i={key:e,value:t,next:void 0,previous:void 0},r){case n.None:this.addItemLast(i);break;case n.First:this.addItemFirst(i);break;case n.Last:this.addItemLast(i);break;default:this.addItemLast(i);break}this._map.set(e,i),this._size++}return this}delete(e){return!!this.remove(e)}remove(e){let t=this._map.get(e);if(t)return this._map.delete(e),this.removeItem(t),this._size--,t.value}shift(){if(!this._head&&!this._tail)return;if(!this._head||!this._tail)throw Error(`Invalid list`);let e=this._head;return this._map.delete(e.key),this.removeItem(e),this._size--,e.value}forEach(e,t){let n=this._state,r=this._head;for(;r;){if(t?e.bind(t)(r.value,r.key,this):e(r.value,r.key,this),this._state!==n)throw Error(`LinkedMap got modified during iteration.`);r=r.next}}keys(){let e=this._state,t=this._head,n={[Symbol.iterator]:()=>n,next:()=>{if(this._state!==e)throw Error(`LinkedMap got modified during iteration.`);if(t){let e={value:t.key,done:!1};return t=t.next,e}else return{value:void 0,done:!0}}};return n}values(){let e=this._state,t=this._head,n={[Symbol.iterator]:()=>n,next:()=>{if(this._state!==e)throw Error(`LinkedMap got modified during iteration.`);if(t){let e={value:t.value,done:!1};return t=t.next,e}else return{value:void 0,done:!0}}};return n}entries(){let e=this._state,t=this._head,n={[Symbol.iterator]:()=>n,next:()=>{if(this._state!==e)throw Error(`LinkedMap got modified during iteration.`);if(t){let e={value:[t.key,t.value],done:!1};return t=t.next,e}else return{value:void 0,done:!0}}};return n}[(t=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}trimOld(e){if(e>=this.size)return;if(e===0){this.clear();return}let t=this._head,n=this.size;for(;t&&n>e;)this._map.delete(t.key),t=t.next,n--;this._head=t,this._size=n,t&&(t.previous=void 0),this._state++}addItemFirst(e){if(!this._head&&!this._tail)this._tail=e;else if(this._head)e.next=this._head,this._head.previous=e;else throw Error(`Invalid list`);this._head=e,this._state++}addItemLast(e){if(!this._head&&!this._tail)this._head=e;else if(this._tail)e.previous=this._tail,this._tail.next=e;else throw Error(`Invalid list`);this._tail=e,this._state++}removeItem(e){if(e===this._head&&e===this._tail)this._head=void 0,this._tail=void 0;else if(e===this._head){if(!e.next)throw Error(`Invalid list`);e.next.previous=void 0,this._head=e.next}else if(e===this._tail){if(!e.previous)throw Error(`Invalid list`);e.previous.next=void 0,this._tail=e.previous}else{let t=e.next,n=e.previous;if(!t||!n)throw Error(`Invalid list`);t.previous=n,n.next=t}e.next=void 0,e.previous=void 0,this._state++}touch(e,t){if(!this._head||!this._tail)throw Error(`Invalid list`);if(!(t!==n.First&&t!==n.Last)){if(t===n.First){if(e===this._head)return;let t=e.next,n=e.previous;e===this._tail?(n.next=void 0,this._tail=n):(t.previous=n,n.next=t),e.previous=void 0,e.next=this._head,this._head.previous=e,this._head=e,this._state++}else if(t===n.Last){if(e===this._tail)return;let t=e.next,n=e.previous;e===this._head?(t.previous=void 0,this._head=t):(t.previous=n,n.next=t),e.next=void 0,e.previous=this._tail,this._tail.next=e,this._tail=e,this._state++}}}toJSON(){let e=[];return this.forEach((t,n)=>{e.push([n,t])}),e}fromJSON(e){this.clear();for(let[t,n]of e)this.set(t,n)}};e.LinkedMap=r,e.LRUCache=class extends r{constructor(e,t=1){super(),this._limit=e,this._ratio=Math.min(Math.max(0,t),1)}get limit(){return this._limit}set limit(e){this._limit=e,this.checkTrim()}get ratio(){return this._ratio}set ratio(e){this._ratio=Math.min(Math.max(0,e),1),this.checkTrim()}get(e,t=n.AsNew){return super.get(e,t)}peek(e){return super.get(e,n.None)}set(e,t){return super.set(e,t,n.Last),this.checkTrim(),this}checkTrim(){this.size>this._limit&&this.trimOld(Math.round(this._limit*this._ratio))}}})),bMe=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Disposable=void 0;var t;(function(e){function t(e){return{dispose:e}}e.create=t})(t||(e.Disposable=t={}))})),gI=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t;function n(){if(t===void 0)throw Error(`No runtime abstraction layer installed`);return t}(function(e){function n(e){if(e===void 0)throw Error(`No runtime abstraction layer provided`);t=e}e.install=n})(n||(n={})),e.default=n})),_I=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Emitter=e.Event=void 0;var t=gI(),n;(function(e){let t={dispose(){}};e.None=function(){return t}})(n||(e.Event=n={}));var r=class{add(e,t=null,n){this._callbacks||(this._callbacks=[],this._contexts=[]),this._callbacks.push(e),this._contexts.push(t),Array.isArray(n)&&n.push({dispose:()=>this.remove(e,t)})}remove(e,t=null){if(!this._callbacks)return;let n=!1;for(let r=0,i=this._callbacks.length;r<i;r++)if(this._callbacks[r]===e)if(this._contexts[r]===t){this._callbacks.splice(r,1),this._contexts.splice(r,1);return}else n=!0;if(n)throw Error(`When adding a listener with a context, you should remove it with the same context`)}invoke(...e){if(!this._callbacks)return[];let n=[],r=this._callbacks.slice(0),i=this._contexts.slice(0);for(let a=0,o=r.length;a<o;a++)try{n.push(r[a].apply(i[a],e))}catch(e){(0,t.default)().console.error(e)}return n}isEmpty(){return!this._callbacks||this._callbacks.length===0}dispose(){this._callbacks=void 0,this._contexts=void 0}},i=class e{constructor(e){this._options=e}get event(){return this._event||(this._event=(t,n,i)=>{this._callbacks||(this._callbacks=new r),this._options&&this._options.onFirstListenerAdd&&this._callbacks.isEmpty()&&this._options.onFirstListenerAdd(this),this._callbacks.add(t,n);let a={dispose:()=>{this._callbacks&&(this._callbacks.remove(t,n),a.dispose=e._noop,this._options&&this._options.onLastListenerRemove&&this._callbacks.isEmpty()&&this._options.onLastListenerRemove(this))}};return Array.isArray(i)&&i.push(a),a}),this._event}fire(e){this._callbacks&&this._callbacks.invoke.call(this._callbacks,e)}dispose(){this._callbacks&&(this._callbacks.dispose(),this._callbacks=void 0)}};e.Emitter=i,i._noop=function(){}})),vI=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CancellationTokenSource=e.CancellationToken=void 0;var t=gI(),n=pI(),r=_I(),i;(function(e){e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:r.Event.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:r.Event.None});function t(t){let r=t;return r&&(r===e.None||r===e.Cancelled||n.boolean(r.isCancellationRequested)&&!!r.onCancellationRequested)}e.is=t})(i||(e.CancellationToken=i={}));var a=Object.freeze(function(e,n){let r=(0,t.default)().timer.setTimeout(e.bind(n),0);return{dispose(){r.dispose()}}}),o=class{constructor(){this._isCancelled=!1}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?a:(this._emitter||(this._emitter=new r.Emitter),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=void 0)}};e.CancellationTokenSource=class{get token(){return this._token||(this._token=new o),this._token}cancel(){this._token?this._token.cancel():this._token=i.Cancelled}dispose(){this._token?this._token instanceof o&&this._token.dispose():this._token=i.None}}})),xMe=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SharedArrayReceiverStrategy=e.SharedArraySenderStrategy=void 0;var t=vI(),n;(function(e){e.Continue=0,e.Cancelled=1})(n||(n={})),e.SharedArraySenderStrategy=class{constructor(){this.buffers=new Map}enableCancellation(e){if(e.id===null)return;let t=new SharedArrayBuffer(4),r=new Int32Array(t,0,1);r[0]=n.Continue,this.buffers.set(e.id,t),e.$cancellationData=t}async sendCancellation(e,t){let r=this.buffers.get(t);if(r===void 0)return;let i=new Int32Array(r,0,1);Atomics.store(i,0,n.Cancelled)}cleanup(e){this.buffers.delete(e)}dispose(){this.buffers.clear()}};var r=class{constructor(e){this.data=new Int32Array(e,0,1)}get isCancellationRequested(){return Atomics.load(this.data,0)===n.Cancelled}get onCancellationRequested(){throw Error(`Cancellation over SharedArrayBuffer doesn't support cancellation events`)}},i=class{constructor(e){this.token=new r(e)}cancel(){}dispose(){}};e.SharedArrayReceiverStrategy=class{constructor(){this.kind=`request`}createCancellationTokenSource(e){let n=e.$cancellationData;return n===void 0?new t.CancellationTokenSource:new i(n)}}})),yI=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Semaphore=void 0;var t=gI();e.Semaphore=class{constructor(e=1){if(e<=0)throw Error(`Capacity must be greater than 0`);this._capacity=e,this._active=0,this._waiting=[]}lock(e){return new Promise((t,n)=>{this._waiting.push({thunk:e,resolve:t,reject:n}),this.runNext()})}get active(){return this._active}runNext(){this._waiting.length===0||this._active===this._capacity||(0,t.default)().timer.setImmediate(()=>this.doRunNext())}doRunNext(){if(this._waiting.length===0||this._active===this._capacity)return;let e=this._waiting.shift();if(this._active++,this._active>this._capacity)throw Error(`To many thunks active`);try{let t=e.thunk();t instanceof Promise?t.then(t=>{this._active--,e.resolve(t),this.runNext()},t=>{this._active--,e.reject(t),this.runNext()}):(this._active--,e.resolve(t),this.runNext())}catch(t){this._active--,e.reject(t),this.runNext()}}}})),SMe=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ReadableStreamMessageReader=e.AbstractMessageReader=e.MessageReader=void 0;var t=gI(),n=pI(),r=_I(),i=yI(),a;(function(e){function t(e){let t=e;return t&&n.func(t.listen)&&n.func(t.dispose)&&n.func(t.onError)&&n.func(t.onClose)&&n.func(t.onPartialMessage)}e.is=t})(a||(e.MessageReader=a={}));var o=class{constructor(){this.errorEmitter=new r.Emitter,this.closeEmitter=new r.Emitter,this.partialMessageEmitter=new r.Emitter}dispose(){this.errorEmitter.dispose(),this.closeEmitter.dispose()}get onError(){return this.errorEmitter.event}fireError(e){this.errorEmitter.fire(this.asError(e))}get onClose(){return this.closeEmitter.event}fireClose(){this.closeEmitter.fire(void 0)}get onPartialMessage(){return this.partialMessageEmitter.event}firePartialMessage(e){this.partialMessageEmitter.fire(e)}asError(e){return e instanceof Error?e:Error(`Reader received error. Reason: ${n.string(e.message)?e.message:`unknown`}`)}};e.AbstractMessageReader=o;var s;(function(e){function n(e){let n,r,i=new Map,a,o=new Map;if(e===void 0||typeof e==`string`)n=e??`utf-8`;else{if(n=e.charset??`utf-8`,e.contentDecoder!==void 0&&(r=e.contentDecoder,i.set(r.name,r)),e.contentDecoders!==void 0)for(let t of e.contentDecoders)i.set(t.name,t);if(e.contentTypeDecoder!==void 0&&(a=e.contentTypeDecoder,o.set(a.name,a)),e.contentTypeDecoders!==void 0)for(let t of e.contentTypeDecoders)o.set(t.name,t)}return a===void 0&&(a=(0,t.default)().applicationJson.decoder,o.set(a.name,a)),{charset:n,contentDecoder:r,contentDecoders:i,contentTypeDecoder:a,contentTypeDecoders:o}}e.fromOptions=n})(s||(s={})),e.ReadableStreamMessageReader=class extends o{constructor(e,n){super(),this.readable=e,this.options=s.fromOptions(n),this.buffer=(0,t.default)().messageBuffer.create(this.options.charset),this._partialMessageTimeout=1e4,this.nextMessageLength=-1,this.messageToken=0,this.readSemaphore=new i.Semaphore(1)}set partialMessageTimeout(e){this._partialMessageTimeout=e}get partialMessageTimeout(){return this._partialMessageTimeout}listen(e){this.nextMessageLength=-1,this.messageToken=0,this.partialMessageTimer=void 0,this.callback=e;let t=this.readable.onData(e=>{this.onData(e)});return this.readable.onError(e=>this.fireError(e)),this.readable.onClose(()=>this.fireClose()),t}onData(e){try{for(this.buffer.append(e);;){if(this.nextMessageLength===-1){let e=this.buffer.tryReadHeaders(!0);if(!e)return;let t=e.get(`content-length`);if(!t){this.fireError(Error(`Header must provide a Content-Length property.\n${JSON.stringify(Object.fromEntries(e))}`));return}let n=parseInt(t);if(isNaN(n)){this.fireError(Error(`Content-Length value must be a number. Got ${t}`));return}this.nextMessageLength=n}let e=this.buffer.tryReadBody(this.nextMessageLength);if(e===void 0){this.setPartialMessageTimer();return}this.clearPartialMessageTimer(),this.nextMessageLength=-1,this.readSemaphore.lock(async()=>{let t=this.options.contentDecoder===void 0?e:await this.options.contentDecoder.decode(e),n=await this.options.contentTypeDecoder.decode(t,this.options);this.callback(n)}).catch(e=>{this.fireError(e)})}}catch(e){this.fireError(e)}}clearPartialMessageTimer(){this.partialMessageTimer&&(this.partialMessageTimer.dispose(),this.partialMessageTimer=void 0)}setPartialMessageTimer(){this.clearPartialMessageTimer(),!(this._partialMessageTimeout<=0)&&(this.partialMessageTimer=(0,t.default)().timer.setTimeout((e,t)=>{this.partialMessageTimer=void 0,e===this.messageToken&&(this.firePartialMessage({messageToken:e,waitingTime:t}),this.setPartialMessageTimer())},this._partialMessageTimeout,this.messageToken,this._partialMessageTimeout))}}})),CMe=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.WriteableStreamMessageWriter=e.AbstractMessageWriter=e.MessageWriter=void 0;var t=gI(),n=pI(),r=yI(),i=_I(),a=`Content-Length: `,o=`\r
1114
1114
  `,s;(function(e){function t(e){let t=e;return t&&n.func(t.dispose)&&n.func(t.onClose)&&n.func(t.onError)&&n.func(t.write)}e.is=t})(s||(e.MessageWriter=s={}));var c=class{constructor(){this.errorEmitter=new i.Emitter,this.closeEmitter=new i.Emitter}dispose(){this.errorEmitter.dispose(),this.closeEmitter.dispose()}get onError(){return this.errorEmitter.event}fireError(e,t,n){this.errorEmitter.fire([this.asError(e),t,n])}get onClose(){return this.closeEmitter.event}fireClose(){this.closeEmitter.fire(void 0)}asError(e){return e instanceof Error?e:Error(`Writer received error. Reason: ${n.string(e.message)?e.message:`unknown`}`)}};e.AbstractMessageWriter=c;var l;(function(e){function n(e){return e===void 0||typeof e==`string`?{charset:e??`utf-8`,contentTypeEncoder:(0,t.default)().applicationJson.encoder}:{charset:e.charset??`utf-8`,contentEncoder:e.contentEncoder,contentTypeEncoder:e.contentTypeEncoder??(0,t.default)().applicationJson.encoder}}e.fromOptions=n})(l||(l={})),e.WriteableStreamMessageWriter=class extends c{constructor(e,t){super(),this.writable=e,this.options=l.fromOptions(t),this.errorCount=0,this.writeSemaphore=new r.Semaphore(1),this.writable.onError(e=>this.fireError(e)),this.writable.onClose(()=>this.fireClose())}async write(e){return this.writeSemaphore.lock(async()=>this.options.contentTypeEncoder.encode(e,this.options).then(e=>this.options.contentEncoder===void 0?e:this.options.contentEncoder.encode(e)).then(t=>{let n=[];return n.push(a,t.byteLength.toString(),o),n.push(o),this.doWrite(e,n,t)},e=>{throw this.fireError(e),e}))}async doWrite(e,t,n){try{return await this.writable.write(t.join(``),`ascii`),this.writable.write(n)}catch(t){return this.handleError(t,e),Promise.reject(t)}}handleError(e,t){this.errorCount++,this.fireError(e,t,this.errorCount)}end(){this.writable.end()}}})),wMe=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AbstractMessageBuffer=void 0;var t=13,n=10,r=`\r
1115
1115
  `;e.AbstractMessageBuffer=class{constructor(e=`utf-8`){this._encoding=e,this._chunks=[],this._totalLength=0}get encoding(){return this._encoding}append(e){let t=typeof e==`string`?this.fromString(e,this._encoding):e;this._chunks.push(t),this._totalLength+=t.byteLength}tryReadHeaders(e=!1){if(this._chunks.length===0)return;let i=0,a=0,o=0,s=0;row:for(;a<this._chunks.length;){let e=this._chunks[a];o=0;column:for(;o<e.length;){switch(e[o]){case t:switch(i){case 0:i=1;break;case 2:i=3;break;default:i=0}break;case n:switch(i){case 1:i=2;break;case 3:i=4,o++;break row;default:i=0}break;default:i=0}o++}s+=e.byteLength,a++}if(i!==4)return;let c=this._read(s+o),l=new Map,u=this.toString(c,`ascii`).split(r);if(u.length<2)return l;for(let t=0;t<u.length-2;t++){let n=u[t],r=n.indexOf(`:`);if(r===-1)throw Error(`Message header must separate key and value using ':'\n${n}`);let i=n.substr(0,r),a=n.substr(r+1).trim();l.set(e?i.toLowerCase():i,a)}return l}tryReadBody(e){if(!(this._totalLength<e))return this._read(e)}get numberOfBytes(){return this._totalLength}_read(e){if(e===0)return this.emptyBuffer();if(e>this._totalLength)throw Error(`Cannot read so many bytes!`);if(this._chunks[0].byteLength===e){let t=this._chunks[0];return this._chunks.shift(),this._totalLength-=e,this.asNative(t)}if(this._chunks[0].byteLength>e){let t=this._chunks[0],n=this.asNative(t,e);return this._chunks[0]=t.slice(e),this._totalLength-=e,n}let t=this.allocNative(e),n=0;for(;e>0;){let r=this._chunks[0];if(r.byteLength>e){let i=r.slice(0,e);t.set(i,n),n+=e,this._chunks[0]=r.slice(e),this._totalLength-=e,e-=e}else t.set(r,n),n+=r.byteLength,this._chunks.shift(),this._totalLength-=r.byteLength,e-=r.byteLength}return t}}})),TMe=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.createMessageConnection=e.ConnectionOptions=e.MessageStrategy=e.CancellationStrategy=e.CancellationSenderStrategy=e.CancellationReceiverStrategy=e.RequestCancellationReceiverStrategy=e.IdCancellationReceiverStrategy=e.ConnectionStrategy=e.ConnectionError=e.ConnectionErrors=e.LogTraceNotification=e.SetTraceNotification=e.TraceFormat=e.TraceValues=e.Trace=e.NullLogger=e.ProgressType=e.ProgressToken=void 0;var t=gI(),n=pI(),r=mI(),i=hI(),a=_I(),o=vI(),s;(function(e){e.type=new r.NotificationType(`$/cancelRequest`)})(s||(s={}));var c;(function(e){function t(e){return typeof e==`string`||typeof e==`number`}e.is=t})(c||(e.ProgressToken=c={}));var l;(function(e){e.type=new r.NotificationType(`$/progress`)})(l||(l={})),e.ProgressType=class{constructor(){}};var u;(function(e){function t(e){return n.func(e)}e.is=t})(u||(u={})),e.NullLogger=Object.freeze({error:()=>{},warn:()=>{},info:()=>{},log:()=>{}});var d;(function(e){e[e.Off=0]=`Off`,e[e.Messages=1]=`Messages`,e[e.Compact=2]=`Compact`,e[e.Verbose=3]=`Verbose`})(d||(e.Trace=d={}));var f;(function(e){e.Off=`off`,e.Messages=`messages`,e.Compact=`compact`,e.Verbose=`verbose`})(f||(e.TraceValues=f={})),(function(e){function t(t){if(!n.string(t))return e.Off;switch(t=t.toLowerCase(),t){case`off`:return e.Off;case`messages`:return e.Messages;case`compact`:return e.Compact;case`verbose`:return e.Verbose;default:return e.Off}}e.fromString=t;function r(t){switch(t){case e.Off:return`off`;case e.Messages:return`messages`;case e.Compact:return`compact`;case e.Verbose:return`verbose`;default:return`off`}}e.toString=r})(d||(e.Trace=d={}));var p;(function(e){e.Text=`text`,e.JSON=`json`})(p||(e.TraceFormat=p={})),(function(e){function t(t){return n.string(t)?(t=t.toLowerCase(),t===`json`?e.JSON:e.Text):e.Text}e.fromString=t})(p||(e.TraceFormat=p={}));var m;(function(e){e.type=new r.NotificationType(`$/setTrace`)})(m||(e.SetTraceNotification=m={}));var h;(function(e){e.type=new r.NotificationType(`$/logTrace`)})(h||(e.LogTraceNotification=h={}));var g;(function(e){e[e.Closed=1]=`Closed`,e[e.Disposed=2]=`Disposed`,e[e.AlreadyListening=3]=`AlreadyListening`})(g||(e.ConnectionErrors=g={}));var _=class e extends Error{constructor(t,n){super(n),this.code=t,Object.setPrototypeOf(this,e.prototype)}};e.ConnectionError=_;var v;(function(e){function t(e){let t=e;return t&&n.func(t.cancelUndispatched)}e.is=t})(v||(e.ConnectionStrategy=v={}));var y;(function(e){function t(e){let t=e;return t&&(t.kind===void 0||t.kind===`id`)&&n.func(t.createCancellationTokenSource)&&(t.dispose===void 0||n.func(t.dispose))}e.is=t})(y||(e.IdCancellationReceiverStrategy=y={}));var b;(function(e){function t(e){let t=e;return t&&t.kind===`request`&&n.func(t.createCancellationTokenSource)&&(t.dispose===void 0||n.func(t.dispose))}e.is=t})(b||(e.RequestCancellationReceiverStrategy=b={}));var x;(function(e){e.Message=Object.freeze({createCancellationTokenSource(e){return new o.CancellationTokenSource}});function t(e){return y.is(e)||b.is(e)}e.is=t})(x||(e.CancellationReceiverStrategy=x={}));var S;(function(e){e.Message=Object.freeze({sendCancellation(e,t){return e.sendNotification(s.type,{id:t})},cleanup(e){}});function t(e){let t=e;return t&&n.func(t.sendCancellation)&&n.func(t.cleanup)}e.is=t})(S||(e.CancellationSenderStrategy=S={}));var C;(function(e){e.Message=Object.freeze({receiver:x.Message,sender:S.Message});function t(e){let t=e;return t&&x.is(t.receiver)&&S.is(t.sender)}e.is=t})(C||(e.CancellationStrategy=C={}));var w;(function(e){function t(e){let t=e;return t&&n.func(t.handleMessage)}e.is=t})(w||(e.MessageStrategy=w={}));var T;(function(e){function t(e){let t=e;return t&&(C.is(t.cancellationStrategy)||v.is(t.connectionStrategy)||w.is(t.messageStrategy))}e.is=t})(T||(e.ConnectionOptions=T={}));var E;(function(e){e[e.New=1]=`New`,e[e.Listening=2]=`Listening`,e[e.Closed=3]=`Closed`,e[e.Disposed=4]=`Disposed`})(E||(E={}));function D(f,v,b,x){let S=b===void 0?e.NullLogger:b,T=0,D=0,O=0,k,A=new Map,ee,te=new Map,ne=new Map,re,ie=new i.LinkedMap,ae=new Map,j=new Set,oe=new Map,se=d.Off,ce=p.Text,M,N=E.New,le=new a.Emitter,ue=new a.Emitter,de=new a.Emitter,fe=new a.Emitter,pe=new a.Emitter,me=x&&x.cancellationStrategy?x.cancellationStrategy:C.Message;function he(e){if(e===null)throw Error(`Can't send requests with id null since the response can't be correlated.`);return`req-`+e.toString()}function ge(e){return e===null?`res-unknown-`+(++O).toString():`res-`+e.toString()}function _e(){return`not-`+(++D).toString()}function ve(e,t){r.Message.isRequest(t)?e.set(he(t.id),t):r.Message.isResponse(t)?e.set(ge(t.id),t):e.set(_e(),t)}function ye(e){}function be(){return N===E.Listening}function P(){return N===E.Closed}function xe(){return N===E.Disposed}function Se(){(N===E.New||N===E.Listening)&&(N=E.Closed,ue.fire(void 0))}function Ce(e){le.fire([e,void 0,void 0])}function we(e){le.fire(e)}f.onClose(Se),f.onError(Ce),v.onClose(Se),v.onError(we);function F(){re||ie.size===0||(re=(0,t.default)().timer.setImmediate(()=>{re=void 0,Ee()}))}function Te(e){r.Message.isRequest(e)?Oe(e):r.Message.isNotification(e)?Ae(e):r.Message.isResponse(e)?ke(e):je(e)}function Ee(){if(ie.size===0)return;let e=ie.shift();try{let t=x?.messageStrategy;w.is(t)?t.handleMessage(e,Te):Te(e)}finally{F()}}let De=e=>{try{if(r.Message.isNotification(e)&&e.method===s.type.method){let t=e.params.id,n=he(t),i=ie.get(n);if(r.Message.isRequest(i)){let r=x?.connectionStrategy,a=r&&r.cancelUndispatched?r.cancelUndispatched(i,ye):void 0;if(a&&(a.error!==void 0||a.result!==void 0)){ie.delete(n),oe.delete(t),a.id=i.id,Fe(a,e.method,Date.now()),v.write(a).catch(()=>S.error(`Sending response for canceled message failed.`));return}}let a=oe.get(t);if(a!==void 0){a.cancel(),Le(e);return}else j.add(t)}ve(ie,e)}finally{F()}};function Oe(e){if(xe())return;function t(t,n,i){let a={jsonrpc:`2.0`,id:e.id};t instanceof r.ResponseError?a.error=t.toJson():a.result=t===void 0?null:t,Fe(a,n,i),v.write(a).catch(()=>S.error(`Sending response failed.`))}function i(t,n,r){let i={jsonrpc:`2.0`,id:e.id,error:t.toJson()};Fe(i,n,r),v.write(i).catch(()=>S.error(`Sending response failed.`))}function a(t,n,r){t===void 0&&(t=null);let i={jsonrpc:`2.0`,id:e.id,result:t};Fe(i,n,r),v.write(i).catch(()=>S.error(`Sending response failed.`))}Ie(e);let o=A.get(e.method),s,c;o&&(s=o.type,c=o.handler);let l=Date.now();if(c||k){let o=e.id??String(Date.now()),u=y.is(me.receiver)?me.receiver.createCancellationTokenSource(o):me.receiver.createCancellationTokenSource(e);e.id!==null&&j.has(e.id)&&u.cancel(),e.id!==null&&oe.set(o,u);try{let d;if(c)if(e.params===void 0){if(s!==void 0&&s.numberOfParams!==0){i(new r.ResponseError(r.ErrorCodes.InvalidParams,`Request ${e.method} defines ${s.numberOfParams} params but received none.`),e.method,l);return}d=c(u.token)}else if(Array.isArray(e.params)){if(s!==void 0&&s.parameterStructures===r.ParameterStructures.byName){i(new r.ResponseError(r.ErrorCodes.InvalidParams,`Request ${e.method} defines parameters by name but received parameters by position`),e.method,l);return}d=c(...e.params,u.token)}else{if(s!==void 0&&s.parameterStructures===r.ParameterStructures.byPosition){i(new r.ResponseError(r.ErrorCodes.InvalidParams,`Request ${e.method} defines parameters by position but received parameters by name`),e.method,l);return}d=c(e.params,u.token)}else k&&(d=k(e.method,e.params,u.token));let f=d;d?f.then?f.then(n=>{oe.delete(o),t(n,e.method,l)},t=>{oe.delete(o),t instanceof r.ResponseError?i(t,e.method,l):t&&n.string(t.message)?i(new r.ResponseError(r.ErrorCodes.InternalError,`Request ${e.method} failed with message: ${t.message}`),e.method,l):i(new r.ResponseError(r.ErrorCodes.InternalError,`Request ${e.method} failed unexpectedly without providing any details.`),e.method,l)}):(oe.delete(o),t(d,e.method,l)):(oe.delete(o),a(d,e.method,l))}catch(a){oe.delete(o),a instanceof r.ResponseError?t(a,e.method,l):a&&n.string(a.message)?i(new r.ResponseError(r.ErrorCodes.InternalError,`Request ${e.method} failed with message: ${a.message}`),e.method,l):i(new r.ResponseError(r.ErrorCodes.InternalError,`Request ${e.method} failed unexpectedly without providing any details.`),e.method,l)}}else i(new r.ResponseError(r.ErrorCodes.MethodNotFound,`Unhandled method ${e.method}`),e.method,l)}function ke(e){if(!xe())if(e.id===null)e.error?S.error(`Received response message without id: Error is: \n${JSON.stringify(e.error,void 0,4)}`):S.error(`Received response message without id. No further error information provided.`);else{let t=e.id,n=ae.get(t);if(Re(e,n),n!==void 0){ae.delete(t);try{if(e.error){let t=e.error;n.reject(new r.ResponseError(t.code,t.message,t.data))}else if(e.result!==void 0)n.resolve(e.result);else throw Error(`Should never happen.`)}catch(e){e.message?S.error(`Response handler '${n.method}' failed with message: ${e.message}`):S.error(`Response handler '${n.method}' failed unexpectedly.`)}}}}function Ae(e){if(xe())return;let t,n;if(e.method===s.type.method){let t=e.params.id;j.delete(t),Le(e);return}else{let r=te.get(e.method);r&&(n=r.handler,t=r.type)}if(n||ee)try{if(Le(e),n)if(e.params===void 0)t!==void 0&&t.numberOfParams!==0&&t.parameterStructures!==r.ParameterStructures.byName&&S.error(`Notification ${e.method} defines ${t.numberOfParams} params but received none.`),n();else if(Array.isArray(e.params)){let i=e.params;e.method===l.type.method&&i.length===2&&c.is(i[0])?n({token:i[0],value:i[1]}):(t!==void 0&&(t.parameterStructures===r.ParameterStructures.byName&&S.error(`Notification ${e.method} defines parameters by name but received parameters by position`),t.numberOfParams!==e.params.length&&S.error(`Notification ${e.method} defines ${t.numberOfParams} params but received ${i.length} arguments`)),n(...i))}else t!==void 0&&t.parameterStructures===r.ParameterStructures.byPosition&&S.error(`Notification ${e.method} defines parameters by position but received parameters by name`),n(e.params);else ee&&ee(e.method,e.params)}catch(t){t.message?S.error(`Notification handler '${e.method}' failed with message: ${t.message}`):S.error(`Notification handler '${e.method}' failed unexpectedly.`)}else de.fire(e)}function je(e){if(!e){S.error(`Received empty message.`);return}S.error(`Received message which is neither a response nor a notification message:\n${JSON.stringify(e,null,4)}`);let t=e;if(n.string(t.id)||n.number(t.id)){let e=t.id,n=ae.get(e);n&&n.reject(Error(`The received response has neither a result nor an error property.`))}}function Me(e){if(e!=null)switch(se){case d.Verbose:return JSON.stringify(e,null,4);case d.Compact:return JSON.stringify(e);default:return}}function Ne(e){if(!(se===d.Off||!M))if(ce===p.Text){let t;(se===d.Verbose||se===d.Compact)&&e.params&&(t=`Params: ${Me(e.params)}\n\n`),M.log(`Sending request '${e.method} - (${e.id})'.`,t)}else ze(`send-request`,e)}function Pe(e){if(!(se===d.Off||!M))if(ce===p.Text){let t;(se===d.Verbose||se===d.Compact)&&(t=e.params?`Params: ${Me(e.params)}\n\n`:`No parameters provided.
1116
1116
 
@@ -1591,7 +1591,7 @@ Reads a specific resource from an MCP server, identified by server name and reso
1591
1591
  Parameters:
1592
1592
  - server (required): The name of the MCP server from which to read the resource
1593
1593
  - uri (required): The URI of the resource to read
1594
- `}));function Gze(e){return!e.uri||!e.server?null:`Read resource "${e.uri}" from server "${e.server}"`}function Kze(){return`readMcpResource`}function qze(e,t,{verbose:n}){return!e?.contents||e.contents.length===0?(0,FJ.jsx)(P,{justifyContent:`space-between`,overflowX:`hidden`,width:`100%`,children:(0,FJ.jsx)($,{height:1,children:(0,FJ.jsx)(F,{dimColor:!0,children:`(No content)`})})}):(0,FJ.jsx)(pS,{content:W(e,null,2),verbose:n})}var FJ,Jze=n((()=>{dS(),hS(),Ze(),Li(),FJ=$e()})),Yze,Xze,IJ,LJ=n((()=>{Ms(),LK(),It(),wY(),rt(),Vze(),Li(),cS(),Wze(),Jze(),Yze=R(()=>z({server:B().describe(`The MCP server name`),uri:B().describe(`The resource URI to read`)})),Xze=R(()=>z({contents:I(z({uri:B().describe(`Resource URI`),mimeType:B().optional().describe(`MIME type of the content`),text:B().optional().describe(`Text content of the resource`),blobSavedTo:B().optional().describe(`Path where binary blob content was saved`)}))})),IJ=Cs({isConcurrencySafe(){return!0},isReadOnly(){return!0},toAutoClassifierInput(e){return`${e.server} ${e.uri}`},shouldDefer:!0,name:`ReadMcpResourceTool`,searchHint:`read a specific MCP resource by URI`,maxResultSizeChars:1e5,async description(){return Hze},async prompt(){return Uze},get inputSchema(){return Yze()},get outputSchema(){return Xze()},async call(e,{options:{mcpClients:t}}){let{server:n,uri:r}=e,i=t.find(e=>e.name===n);if(!i)throw Error(`Server "${n}" not found. Available servers: ${t.map(e=>e.name).join(`, `)}`);if(i.type!==`connected`)throw Error(`Server "${n}" is not connected`);if(!i.capabilities?.resources)throw Error(`Server "${n}" does not support resources`);let a=await(await fY(i)).client.request({method:`resources/read`,params:{uri:r}},dG);return{data:{contents:await Promise.all(a.contents.map(async(e,t)=>{if(`text`in e)return{uri:e.uri,mimeType:e.mimeType,text:e.text};if(!(`blob`in e)||typeof e.blob!=`string`)return{uri:e.uri,mimeType:e.mimeType};let r=`mcp-resource-${Date.now()}-${t}-${Math.random().toString(36).slice(2,8)}`,i=await zze(Buffer.from(e.blob,`base64`),e.mimeType,r);return`error`in i?{uri:e.uri,mimeType:e.mimeType,text:`Binary content could not be saved to disk: ${i.error}`}:{uri:e.uri,mimeType:e.mimeType,blobSavedTo:i.filepath,text:Bze(i.filepath,e.mimeType,i.size,`[Resource from ${n} at ${e.uri}] `)}}))}}},renderToolUseMessage:Gze,userFacingName:Kze,renderToolResultMessage:qze,isResultTruncated(e){return oS(W(e))},mapToolResultToToolResultBlockParam(e,t){return Fs(t,W(e))}})})),Zze,RJ,zJ,Qze=n((()=>{LK(),bn(),gi(),Li(),b(),Zze=0,RJ=1,zJ=class{constructor(e){if(x(this,`ws`,void 0),x(this,`started`,!1),x(this,`opened`,void 0),x(this,`isBun`,typeof Bun<`u`),x(this,`onclose`,void 0),x(this,`onerror`,void 0),x(this,`onmessage`,void 0),x(this,`onBunMessage`,e=>{try{let t=Si(typeof e.data==`string`?e.data:String(e.data)),n=fW.parse(t);this.onmessage?.(n)}catch(e){this.handleError(e)}}),x(this,`onBunError`,()=>{this.handleError(Error(`WebSocket error`))}),x(this,`onBunClose`,()=>{this.handleCloseCleanup()}),x(this,`onNodeMessage`,e=>{try{let t=Si(e.toString(`utf-8`)),n=fW.parse(t);this.onmessage?.(n)}catch(e){this.handleError(e)}}),x(this,`onNodeError`,e=>{this.handleError(e)}),x(this,`onNodeClose`,()=>{this.handleCloseCleanup()}),this.ws=e,this.opened=new Promise((e,t)=>{if(this.ws.readyState===RJ)e();else if(this.isBun){let n=this.ws,r=()=>{n.removeEventListener(`open`,r),n.removeEventListener(`error`,i),e()},i=e=>{n.removeEventListener(`open`,r),n.removeEventListener(`error`,i),Cn(`error`,`mcp_websocket_connect_fail`),t(e)};n.addEventListener(`open`,r),n.addEventListener(`error`,i)}else{let n=this.ws;n.on(`open`,()=>{e()}),n.on(`error`,e=>{Cn(`error`,`mcp_websocket_connect_fail`),t(e)})}}),this.isBun){let e=this.ws;e.addEventListener(`message`,this.onBunMessage),e.addEventListener(`error`,this.onBunError),e.addEventListener(`close`,this.onBunClose)}else{let e=this.ws;e.on(`message`,this.onNodeMessage),e.on(`error`,this.onNodeError),e.on(`close`,this.onNodeClose)}}handleError(e){Cn(`error`,`mcp_websocket_message_fail`),this.onerror?.(wi(e))}handleCloseCleanup(){if(this.onclose?.(),this.isBun){let e=this.ws;e.removeEventListener(`message`,this.onBunMessage),e.removeEventListener(`error`,this.onBunError),e.removeEventListener(`close`,this.onBunClose)}else{let e=this.ws;e.off(`message`,this.onNodeMessage),e.off(`error`,this.onNodeError),e.off(`close`,this.onNodeClose)}}async start(){if(this.started)throw Error(`Start can only be called once per transport.`);if(await this.opened,this.ws.readyState!==RJ)throw Cn(`error`,`mcp_websocket_start_not_opened`),Error(`WebSocket is not open. Cannot start transport.`);this.started=!0}async close(){(this.ws.readyState===RJ||this.ws.readyState===Zze)&&this.ws.close(),this.handleCloseCleanup()}async send(e){if(this.ws.readyState!==RJ)throw Cn(`error`,`mcp_websocket_send_not_opened`),Error(`WebSocket is not open. Cannot send message.`);let t=W(e);try{this.isBun?this.ws.send(t):await new Promise((e,n)=>{this.ws.send(t,t=>{t?n(t):e()})})}catch(e){throw this.handleError(e),e}}}}));function $ze(e){return e.mode===`url`?`url`:`form`}function eBe(e,t,n){return e.findIndex(e=>e.serverName===t&&e.params.mode===`url`&&`elicitationId`in e.params&&e.params.elicitationId===n)}function tBe(e,t,n){try{e.setRequestHandler(SK,async(e,r)=>{ba(t,`Received elicitation request: ${W(e)}`);let i=$ze(e.params);try{let a=await BJ(t,e.params,r.signal);if(a)return ba(t,`Elicitation resolved by hook: ${W(a)}`),a.action,a;let o=i===`url`&&`elicitationId`in e.params?e.params.elicitationId:void 0,s=await new Promise(i=>{let a=()=>{i({action:`cancel`})};if(r.signal.aborted){a();return}let s=o?{actionLabel:`Skip confirmation`}:void 0;n(n=>({...n,elicitation:{queue:[...n.elicitation.queue,{serverName:t,requestId:r.requestId,params:e.params,signal:r.signal,waitingState:s,respond:e=>{r.signal.removeEventListener(`abort`,a),e.action,i(e)}}]}})),r.signal.addEventListener(`abort`,a,{once:!0})});return ba(t,`Elicitation response: ${W(s)}`),await VJ(t,s,r.signal,i,o)}catch(e){return Sa(t,`Elicitation error: ${e}`),{action:`cancel`}}}),e.setNotificationHandler(wK,e=>{let{elicitationId:r}=e.params;ba(t,`Received elicitation completion notification: ${r}`),o7({message:`MCP server "${t}" confirmed elicitation ${r} complete`,notificationType:`elicitation_complete`});let i=!1;n(e=>{let n=eBe(e.elicitation.queue,t,r);if(n===-1)return e;i=!0;let a=[...e.elicitation.queue];return a[n]={...a[n],completed:!0},{...e,elicitation:{queue:a}}}),i||ba(t,`Ignoring completion notification for unknown elicitation: ${r}`)})}catch{return}}async function BJ(e,t,n){try{let r=t.mode===`url`?`url`:`form`,i=`url`in t?t.url:void 0,a=`elicitationId`in t?t.elicitationId:void 0,{elicitationResponse:o,blockingError:s}=await Nat({serverName:e,message:t.message,requestedSchema:`requestedSchema`in t?t.requestedSchema:void 0,signal:n,mode:r,url:i,elicitationId:a});return s?{action:`decline`}:o?{action:o.action,content:o.content}:void 0}catch(t){Sa(e,`Elicitation hook error: ${t}`);return}}async function VJ(e,t,n,r,i){try{let{elicitationResultResponse:a,blockingError:o}=await Pat({serverName:e,action:t.action,content:t.content,signal:n,mode:r,elicitationId:i});if(o)return o7({message:`Elicitation response for server "${e}": decline`,notificationType:`elicitation_response`}),{action:`decline`};let s=a?{action:a.action,content:a.content??t.content}:t;return o7({message:`Elicitation response for server "${e}": ${s.action}`,notificationType:`elicitation_response`}),s}catch(n){return Sa(e,`ElicitationResult hook error: ${n}`),o7({message:`Elicitation response for server "${e}": ${t.action}`,notificationType:`elicitation_response`}),t}}var nBe=n((()=>{LK(),_7(),wa(),Li(),La()}));async function rBe(e,t,n){try{K(`Loading MCP servers from MCPB: ${t}`);let n=e.repository,r=await tI(t,e.path,n,t=>{K(`MCPB [${e.name}]: ${t}`)});if(`status`in r&&r.status===`needs-config`)return K(`MCPB ${t} requires user configuration. User can configure via: /plugin → Manage plugins → ${e.name} → Configure`),null;let i=r,a=i.manifest.name;return K(`Loaded MCP server "${a}" from MCPB (extracted to ${i.extractedPath})`),{[a]:i.mcpConfig}}catch(r){let i=G(r);K(`Failed to load MCPB ${t}: ${i}`,{level:`error`});let a=`${e.name}@${e.repository}`;return t.startsWith(`http`)&&(i.includes(`download`)||i.includes(`network`))?n.push({type:`mcpb-download-failed`,source:a,plugin:e.name,url:t,reason:i}):i.includes(`manifest`)||i.includes(`user configuration`)?n.push({type:`mcpb-invalid-manifest`,source:a,plugin:e.name,mcpbPath:t,validationError:i}):n.push({type:`mcpb-extract-failed`,source:a,plugin:e.name,mcpbPath:t,reason:i}),null}}async function iBe(e,t=[]){let n={},r=await HJ(e.path,`.mcp.json`);if(r&&(n={...n,...r}),e.manifest.mcpServers){let r=e.manifest.mcpServers;if(typeof r==`string`)if(WF(r)){let i=await rBe(e,r,t);i&&(n={...n,...i})}else{let t=await HJ(e.path,r);t&&(n={...n,...t})}else if(Array.isArray(r)){let i=await Promise.all(r.map(async n=>{try{return typeof n==`string`?WF(n)?await rBe(e,n,t):await HJ(e.path,n):n}catch(t){return K(`Failed to load MCP servers from spec for plugin ${e.name}: ${t}`,{level:`error`}),null}}));for(let e of i)e&&(n={...n,...e})}else n={...n,...r}}return Object.keys(n).length>0?n:void 0}async function HJ(e,t){let n=J(),r=X(e,t),i;try{i=await n.readFile(r,{encoding:`utf-8`})}catch(e){return xi(e)||K(`Failed to load MCP servers from ${r}: ${e}`,{level:`error`}),null}try{let e=Si(i),t=e.mcpServers||e,n={};for(let[e,i]of Object.entries(t)){let t=ut().safeParse(i);t.success?n[e]=t.data:K(`Invalid MCP server config for ${e} in ${r}: ${t.error.message}`,{level:`error`})}return n}catch(e){return K(`Failed to load MCP servers from ${r}: ${e}`,{level:`error`}),null}}function aBe(e){let t=e.manifest.channels;if(!t||t.length===0)return[];let n=e.repository,r=[];for(let e of t)!e.userConfig||Object.keys(e.userConfig).length===0||ZF(YF(n,e.server)??{},e.userConfig).valid||r.push({server:e.server,displayName:e.displayName??e.server,configSchema:e.userConfig});return r}function oBe(e,t){if(e.manifest.channels?.find(e=>e.server===t)?.userConfig)return YF(e.repository,t)??void 0}function sBe(e,t,n){let r={};for(let[i,a]of Object.entries(e)){let e=`plugin:${t}:${i}`;r[e]={...a,scope:`dynamic`,pluginSource:n}}return r}function cBe(e,t){let n=e.manifest.userConfig?lI(rI(e)):void 0,r=oBe(e,t);if(!(!n&&!r))return{...n,...r}}function lBe(e,t,n,r,i,a){let o=[],s=e=>{let r=oI(e,t);n&&(r=sI(r,n));let{expanded:i,missingVars:a}=CF(r);return o.push(...a),i},c;switch(e.type){case void 0:case`stdio`:{let n={...e};n.command&&(n.command=s(n.command)),n.args&&(n.args=n.args.map(e=>s(e)));let r={CLAUDE_PLUGIN_ROOT:t.path,CLAUDE_PLUGIN_DATA:ny(t.source),...n.env||{}};for(let[e,t]of Object.entries(r))e!==`CLAUDE_PLUGIN_ROOT`&&e!==`CLAUDE_PLUGIN_DATA`&&(r[e]=s(t));n.env=r,c=n;break}case`sse`:case`http`:case`ws`:{let t={...e};if(t.url&&(t.url=s(t.url)),t.headers){let e={};for(let[n,r]of Object.entries(t.headers))e[n]=s(r);t.headers=e}c=t;break}case`sse-ide`:case`ws-ide`:case`sdk`:case`claudeai-proxy`:c=e;break}if(r&&o.length>0){let e=[...new Set(o)].join(`, `);K(`Missing environment variables in plugin MCP config: ${e}`,{level:`warn`}),i&&a&&r.push({type:`mcp-config-invalid`,source:`plugin:${i}`,plugin:i,serverName:a,validationError:`Missing environment variables: ${e}`})}return c}async function uBe(e,t=[]){if(!e.enabled)return;let n=e.mcpServers||await iBe(e,t);if(!n)return;let r={};for(let[i,a]of Object.entries(n)){let n=cBe(e,i);try{r[i]=lBe(a,e,n,t,e.name,i)}catch(n){t?.push({type:`generic-error`,source:i,plugin:e.name,error:G(n)})}}return sBe(r,e.name,e.source)}var dBe=n((()=>{wF(),pr(),q(),gi(),ki(),Li(),nI(),ry(),uI()}));function UJ(){return X(ir(),`managed-mcp.json`)}function WJ(e,t){if(!e)return{};let n={};for(let[r,i]of Object.entries(e))n[r]={...i,scope:t};return n}async function fBe(e){let t=X(U(),`.mcp.json`),n;try{n=(await Yc(t)).mode}catch(e){if(yi(e)!==`ENOENT`)throw e}let r=`${t}.tmp.${process.pid}.${Date.now()}`,i=await Uc(r,`w`,n??420);try{await i.writeFile(W(e,null,2),{encoding:`utf8`}),await i.datasync()}finally{await i.close()}try{n!==void 0&&await zc(r,n),await qc(r,t)}catch(e){try{await Zc(r)}catch{}throw e}}function GJ(e){if(e.type!==void 0&&e.type!==`stdio`)return null;let t=e;return[t.command,...t.args??[]]}function pBe(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function KJ(e){return`url`in e?e.url:null}function mBe(e){if(!jBe.some(t=>e.includes(t)))return e;try{return new URL(e).searchParams.get(`mcp_url`)||e}catch{return e}}function hBe(e){let t=GJ(e);if(t)return`stdio:${W(t)}`;let n=KJ(e);return n?`url:${mBe(n)}`:null}function gBe(e,t){let n=new Map;for(let[e,r]of Object.entries(t)){let t=hBe(r);t&&!n.has(t)&&n.set(t,e)}let r={},i=[],a=new Map;for(let[t,o]of Object.entries(e)){let e=hBe(o);if(e===null){r[t]=o;continue}let s=n.get(e);if(s!==void 0){K(`Suppressing plugin MCP server "${t}": duplicates manually-configured "${s}"`),i.push({name:t,duplicateOf:s});continue}let c=a.get(e);if(c!==void 0){K(`Suppressing plugin MCP server "${t}": duplicates earlier plugin server "${c}"`),i.push({name:t,duplicateOf:c});continue}a.set(e,t),r[t]=o}return{servers:r,suppressed:i}}function _Be(e){let t=e.replace(/[.+?^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`.*`);return RegExp(`^${t}$`)}function vBe(e,t){return _Be(t).test(e)}function yBe(){return DBe()?$n(`policySettings`)??{}:rr()}function bBe(){return rr()}function xBe(e,t){let n=bBe();if(!n.deniedMcpServers)return!1;for(let t of n.deniedMcpServers)if(Ft(t)&&t.serverName===e)return!0;if(t){let e=GJ(t);if(e){for(let t of n.deniedMcpServers)if(jt(t)&&pBe(t.serverCommand,e))return!0}let r=KJ(t);if(r){for(let e of n.deniedMcpServers)if(ft(e)&&vBe(r,e.serverUrl))return!0}}return!1}function qJ(e,t){if(xBe(e,t))return!1;let n=yBe();if(!n.allowedMcpServers)return!0;if(n.allowedMcpServers.length===0)return!1;let r=n.allowedMcpServers.some(jt),i=n.allowedMcpServers.some(ft);if(t){let a=GJ(t),o=KJ(t);if(a)if(r){for(let e of n.allowedMcpServers)if(jt(e)&&pBe(e.serverCommand,a))return!0;return!1}else{for(let t of n.allowedMcpServers)if(Ft(t)&&t.serverName===e)return!0;return!1}else if(o)if(i){for(let e of n.allowedMcpServers)if(ft(e)&&vBe(o,e.serverUrl))return!0;return!1}else{for(let t of n.allowedMcpServers)if(Ft(t)&&t.serverName===e)return!0;return!1}else{for(let t of n.allowedMcpServers)if(Ft(t)&&t.serverName===e)return!0;return!1}}for(let t of n.allowedMcpServers)if(Ft(t)&&t.serverName===e)return!0;return!1}function SBe(e){let t={},n=[];for(let[r,i]of Object.entries(e)){let e=i;e.type===`sdk`||qJ(r,e)?t[r]=i:n.push(r)}return{allowed:t,blocked:n}}function CBe(e){let t=[];function n(e){let{expanded:n,missingVars:r}=CF(e);return t.push(...r),n}let r;switch(e.type){case void 0:case`stdio`:{let t=e;r={...t,command:n(t.command),args:t.args.map(n),env:t.env?cm(t.env,n):void 0};break}case`sse`:case`http`:case`ws`:{let t=e;r={...t,url:n(t.url),headers:t.headers?cm(t.headers,n):void 0};break}case`sse-ide`:case`ws-ide`:r=e;break;case`sdk`:r=e;break;case`claudeai-proxy`:r=e;break}return{expanded:r,missingVars:[...new Set(t)]}}async function wBe(e,t,n){if(e.match(/[^a-zA-Z0-9_-]/))throw Error(`Invalid name ${e}. Names can only contain letters, numbers, hyphens, and underscores.`);if(nY())throw Error(`Cannot add MCP server: enterprise MCP configuration is active and has exclusive control over MCP servers`);let r=ut().safeParse(t);if(!r.success){let e=r.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`, `);throw Error(`Invalid configuration: ${e}`)}let i=r.data;if(xBe(e,i))throw Error(`Cannot add MCP server "${e}": server is explicitly blocked by enterprise policy`);if(!qJ(e,i))throw Error(`Cannot add MCP server "${e}": not allowed by enterprise policy`);switch(n){case`project`:{let{servers:t}=JJ();if(t[e])throw Error(`MCP server ${e} already exists in .mcp.json`);break}case`user`:if(qi().mcpServers?.[e])throw Error(`MCP server ${e} already exists in user config`);break;case`local`:if(Vi().mcpServers?.[e])throw Error(`MCP server ${e} already exists in local config`);break;case`dynamic`:throw Error(`Cannot add MCP server to scope: dynamic`);case`enterprise`:throw Error(`Cannot add MCP server to scope: enterprise`);case`claudeai`:throw Error(`Cannot add MCP server to scope: claudeai`)}switch(n){case`project`:{let{servers:t}=JJ(),n={};for(let[e,r]of Object.entries(t)){let{scope:t,...i}=r;n[e]=i}n[e]=i;let r={mcpServers:n};try{await fBe(r)}catch(e){throw Error(`Failed to write to .mcp.json: ${e}`)}break}case`user`:Gi(t=>({...t,mcpServers:{...t.mcpServers,[e]:i}}));break;case`local`:Ki(t=>({...t,mcpServers:{...t.mcpServers,[e]:i}}));break;default:throw Error(`Cannot add MCP server to scope: ${n}`)}}async function TBe(e,t){switch(t){case`project`:{let{servers:t}=JJ();if(!t[e])throw Error(`No MCP server found with name: ${e} in .mcp.json`);let n={};for(let[r,i]of Object.entries(t))if(r!==e){let{scope:e,...t}=i;n[r]=t}let r={mcpServers:n};try{await fBe(r)}catch(e){throw Error(`Failed to remove from .mcp.json: ${e}`)}break}case`user`:if(!qi().mcpServers?.[e])throw Error(`No user-scoped MCP server found with name: ${e}`);Gi(t=>{let{[e]:n,...r}=t.mcpServers??{};return{...t,mcpServers:r}});break;case`local`:if(!Vi().mcpServers?.[e])throw Error(`No project-local MCP server found with name: ${e}`);Ki(t=>{let{[e]:n,...r}=t.mcpServers??{};return{...t,mcpServers:r}});break;default:throw Error(`Cannot remove MCP server from scope: ${t}`)}}function JJ(){if(!Dn(`projectSettings`))return{servers:{},errors:[]};let e=X(U(),`.mcp.json`),{config:t,errors:n}=$J({filePath:e,expandVars:!0,scope:`project`});if(!t){let t=n.filter(e=>!e.message.startsWith(`MCP config file not found`));return t.length>0?(K(`MCP config errors for ${e}: ${W(t.map(e=>e.message))}`,{level:`error`}),{servers:{},errors:t}):{servers:{},errors:[]}}return{servers:t.mcpServers?WJ(t.mcpServers,`project`):{},errors:n||[]}}function YJ(e){let t={project:`projectSettings`,user:`userSettings`,local:`localSettings`};if(e in t&&!Dn(t[e]))return{servers:{},errors:[]};switch(e){case`project`:{let t={},n=[],r=[],i=U();for(;i!==gc(i).root;)r.push(i),i=fc(i);for(let i of r.reverse()){let r=X(i,`.mcp.json`),{config:a,errors:o}=$J({filePath:r,expandVars:!0,scope:`project`});if(!a){let e=o.filter(e=>!e.message.startsWith(`MCP config file not found`));e.length>0&&(K(`MCP config errors for ${r}: ${W(e.map(e=>e.message))}`,{level:`error`}),n.push(...e));continue}a.mcpServers&&Object.assign(t,WJ(a.mcpServers,e)),o.length>0&&n.push(...o)}return{servers:t,errors:n}}case`user`:{let t=qi().mcpServers;if(!t)return{servers:{},errors:[]};let{config:n,errors:r}=QJ({configObject:{mcpServers:t},expandVars:!0,scope:`user`});return{servers:WJ(n?.mcpServers,e),errors:r}}case`local`:{let t=Vi().mcpServers;if(!t)return{servers:{},errors:[]};let{config:n,errors:r}=QJ({configObject:{mcpServers:t},expandVars:!0,scope:`local`});return{servers:WJ(n?.mcpServers,e),errors:r}}case`enterprise`:{let t=UJ(),{config:n,errors:r}=$J({filePath:t,expandVars:!0,scope:`enterprise`});if(!n){let e=r.filter(e=>!e.message.startsWith(`MCP config file not found`));return e.length>0?(K(`Enterprise MCP config errors for ${t}: ${W(e.map(e=>e.message))}`,{level:`error`}),{servers:{},errors:e}):{servers:{},errors:[]}}return{servers:WJ(n.mcpServers,e),errors:r}}}}function XJ(e){let{servers:t}=YJ(`enterprise`);if(ab(`mcp`))return t[e]??null;let{servers:n}=YJ(`user`),{servers:r}=YJ(`project`),{servers:i}=YJ(`local`);return t[e]?t[e]:i[e]?i[e]:r[e]?r[e]:n[e]?n[e]:null}async function ZJ(e={},t=Promise.resolve({})){let{servers:n}=YJ(`enterprise`);if(nY()){let e={};for(let[t,r]of Object.entries(n))qJ(t,r)&&(e[t]=r);return{servers:e,errors:[]}}let r=ab(`mcp`),i={servers:{}},{servers:a}=r?i:YJ(`user`),{servers:o}=r?i:YJ(`project`),{servers:s}=r?i:YJ(`local`),c={},l=await R4(),u=[];if(l.errors.length>0)for(let e of l.errors)if(e.type===`mcp-config-invalid`||e.type===`mcpb-download-failed`||e.type===`mcpb-extract-failed`||e.type===`mcpb-invalid-manifest`){let t=`Plugin MCP loading error - ${e.type}: ${uv(e)}`;Y(Error(t))}else{let t=e.type;K(`Plugin not available for MCP: ${e.source} - error type: ${t}`)}let d=await Promise.all(l.enabled.map(e=>uBe(e,u)));for(let e of d)e&&Object.assign(c,e);if(u.length>0)for(let e of u){let t=`Plugin MCP server error - ${e.type}: ${uv(e)}`;Y(Error(t))}let f={};for(let[e,t]of Object.entries(o))GBe(e)===`approved`&&(f[e]=t);let p=await t,m={};for(let[t,n]of Object.entries({...a,...f,...s,...e,...p}))!tY(t)&&qJ(t,n)&&(m[t]=n);let h={},g={};for(let[e,t]of Object.entries(c))tY(e)||!qJ(e,t)?g[e]=t:h[e]=t;let{servers:_,suppressed:v}=gBe(h,m);Object.assign(_,g);for(let{name:e,duplicateOf:t}of v){let n=e.split(`:`);n[0]!==`plugin`||n.length<3||u.push({type:`mcp-server-suppressed-duplicate`,source:e,plugin:n[1],serverName:n.slice(2).join(`:`),duplicateOf:t})}let y=Object.assign({},_,a,f,s),b={};for(let[e,t]of Object.entries(y))qJ(e,t)&&(b[e]=t);return{servers:b,errors:u}}async function EBe(){if(nY())return ZJ();let{servers:e,errors:t}=await ZJ();return{servers:e,errors:t}}function QJ(e){let{configObject:t,expandVars:n,scope:r,filePath:i}=e,a=Bee().safeParse(t);if(!a.success)return{config:null,errors:a.error.issues.map(e=>({...i&&{file:i},path:e.path.join(`.`),message:`Does not adhere to MCP server configuration schema`,mcpErrorMetadata:{scope:r,severity:`fatal`}}))};let o=[],s={};for(let[e,t]of Object.entries(a.data.mcpServers)){let a=t;if(n){let{expanded:n,missingVars:s}=CBe(t);s.length>0&&o.push({...i&&{file:i},path:`mcpServers.${e}`,message:`Missing environment variables: ${s.join(`, `)}`,suggestion:`Set the following environment variables: ${s.join(`, `)}`,mcpErrorMetadata:{scope:r,serverName:e,severity:`warning`}}),a=n}Ma()===`windows`&&(!a.type||a.type===`stdio`)&&`command`in a&&(a.command===`npx`||a.command.endsWith(`\\npx`)||a.command.endsWith(`/npx`))&&o.push({...i&&{file:i},path:`mcpServers.${e}`,message:`Windows requires 'cmd /c' wrapper to execute npx`,suggestion:`Change command to "cmd" with args ["/c", "npx", ...]. See: https://code.workmate.com/docs/en/mcp#configure-mcp-servers`,mcpErrorMetadata:{scope:r,serverName:e,severity:`warning`}}),s[e]=a}return{config:{mcpServers:s},errors:o}}function $J(e){let{filePath:t,expandVars:n,scope:r}=e,i=J(),a;try{a=i.readFileSync(t,{encoding:`utf8`})}catch(e){return yi(e)===`ENOENT`?{config:null,errors:[{file:t,path:``,message:`MCP config file not found: ${t}`,suggestion:`Check that the file path is correct`,mcpErrorMetadata:{scope:r,severity:`fatal`}}]}:(K(`MCP config read error for ${t} (scope=${r}): ${e}`,{level:`error`}),{config:null,errors:[{file:t,path:``,message:`Failed to read file: ${e}`,suggestion:`Check file permissions and ensure the file exists`,mcpErrorMetadata:{scope:r,severity:`fatal`}}]})}let o=mn(a);return o?QJ({configObject:o,expandVars:n,scope:r,filePath:t}):(K(`MCP config is not valid JSON: ${t} (scope=${r}, length=${a.length}, first100=${W(a.slice(0,100))})`,{level:`error`}),{config:null,errors:[{file:t,path:``,message:`MCP config is not a valid JSON`,suggestion:`Fix the JSON syntax errors in the file`,mcpErrorMetadata:{scope:r,severity:`fatal`}}]})}function DBe(){return $n(`policySettings`)?.allowManagedMcpServersOnly===!0}function OBe(e){return Object.values(e).every(e=>e.type===`sdk`&&e.name===`claude-vscode`)}function eY(e){return MBe.has(e)}function tY(e){let t=Vi();return eY(e)?!(t.enabledMcpServers||[]).includes(e):(t.disabledMcpServers||[]).includes(e)}function kBe(e,t,n){return e.includes(t)===n?e:n?[...e,t]:e.filter(e=>e!==t)}function ABe(e,t){eY(e)&&tY(e),Ki(n=>{if(eY(e)){let r=n.enabledMcpServers||[],i=kBe(r,e,t);return i===r?n:{...n,enabledMcpServers:i}}let r=n.disabledMcpServers||[],i=kBe(r,e,!t);return i===r?n:{...n,disabledMcpServers:i}})}var jBe,nY,MBe,rY=n((()=>{lm(),d(),Pa(),dv(),Wi(),ui(),q(),gi(),ki(),ur(),wa(),dBe(),z4(),Rn(),Zn(),sb(),Ln(),At(),Li(),La(),wF(),pr(),oY(),jBe=[`/v2/session_ingress/shttp/mcp/`,`/v2/ccr-sessions/`],nY=u(()=>{let{config:e}=$J({filePath:UJ(),expandVars:!0,scope:`enterprise`});return e!==null}),MBe=new Set([])}));function NBe(e,t){let n=`mcp__${pn(t)}__`;return e.filter(e=>e.name?.startsWith(n))}function iY(e,t){let n=pn(t),r=e.name;return r?r.startsWith(`mcp__${n}__`)||r.startsWith(`${n}:`):!1}function PBe(e,t){return e.filter(e=>iY(e,t)&&!(e.type===`prompt`&&e.loadedFrom===`mcp`))}function FBe(e,t){let n=`mcp__${pn(t)}__`;return e.filter(e=>!e.name?.startsWith(n))}function IBe(e,t){return e.filter(e=>!iY(e,t))}function LBe(e,t){let n={...e};return delete n[t],n}function RBe(e){let{scope:t,...n}=e,r=W(n,(e,t)=>{if(t&&typeof t==`object`&&!Array.isArray(t)){let e=t,n={};for(let t of Object.keys(e).sort())n[t]=e[t];return n}return t});return Fc(`sha256`).update(r).digest(`hex`).slice(0,16)}function zBe(e,t){let n=e.clients.filter(e=>{let n=t[e.name];return n?RBe(e.config)!==RBe(n):e.config.scope===`dynamic`});if(n.length===0)return{...e,stale:[]};let{tools:r,commands:i,resources:a}=e;for(let e of n)r=FBe(r,e.name),i=IBe(i,e.name),a=LBe(a,e.name);let o=new Set(n.map(e=>e.name));return{clients:e.clients.filter(e=>!o.has(e.name)),tools:r,commands:i,resources:a,stale:n}}function aY(e){return e.name?.startsWith(`mcp__`)||e.isMcp===!0}function BBe(e){switch(e){case`user`:return sn();case`project`:return X(U(),`.mcp.json`);case`local`:return`${sn()} [project: ${U()}]`;case`dynamic`:return`Dynamically configured`;case`enterprise`:return UJ();case`claudeai`:return`claude.ai`;default:return e}}function VBe(e){switch(e){case`local`:return`Local config (private to you in this project)`;case`project`:return`Project config (shared via .mcp.json)`;case`user`:return`User config (available in all your projects)`;case`dynamic`:return`Dynamic config (from command line)`;case`enterprise`:return`Enterprise config (managed by your organization)`;case`claudeai`:return`claude.ai config`;default:return e}}function HBe(e){if(!e)return`local`;if(!hr().options.includes(e))throw Error(`Invalid scope: ${e}. Must be one of: ${hr().options.join(`, `)}`);return e}function UBe(e){if(!e)return`stdio`;if(e!==`stdio`&&e!==`sse`&&e!==`http`)throw Error(`Invalid transport type: ${e}. Must be one of: stdio, sse, http`);return e}function WBe(e){let t={};for(let n of e){let e=n.indexOf(`:`);if(e===-1)throw Error(`Invalid header format: "${n}". Expected format: "Header-Name: value"`);let r=n.substring(0,e).trim(),i=n.substring(e+1).trim();if(!r)throw Error(`Invalid header: "${n}". Header name cannot be empty.`);t[r]=i}return t}function GBe(e){let t=yn(),n=pn(e);return t?.disabledMcpjsonServers?.some(e=>pn(e)===n)?`rejected`:t?.enabledMcpjsonServers?.some(e=>pn(e)===n)||t?.enableAllProjectMcpServers||Nte()&&Dn(`projectSettings`)||kr()&&Dn(`projectSettings`)?`approved`:`pending`}function KBe(e){if(!aY({name:e}))return null;let t=Qn(e);if(!t)return null;let n=XJ(t.serverName);return!n&&t.serverName.startsWith(`claude_ai_`)?`claudeai`:n?.scope??null}function qBe(e){return e.type===`stdio`||e.type===void 0}function JBe(e){return e.type===`sse`}function YBe(e){return e.type===`http`}function XBe(e){return e.type===`ws`}function ZBe(e){let t=new Map;for(let n of e)if(n.mcpServers?.length)for(let e of n.mcpServers){if(typeof e==`string`)continue;let r=Object.entries(e);if(r.length!==1)continue;let[i,a]=r[0],o=t.get(i);o?o.sourceAgents.includes(n.agentType)||o.sourceAgents.push(n.agentType):t.set(i,{config:{...a,name:i},sourceAgents:[n.agentType]})}let n=[];for(let[e,{config:r,sourceAgents:i}]of t)qBe(r)?n.push({name:e,sourceAgents:i,transport:`stdio`,command:r.command,needsAuth:!1}):JBe(r)?n.push({name:e,sourceAgents:i,transport:`sse`,url:r.url,needsAuth:!0}):YBe(r)?n.push({name:e,sourceAgents:i,transport:`http`,url:r.url,needsAuth:!0}):XBe(r)&&n.push({name:e,sourceAgents:i,transport:`ws`,url:r.url,needsAuth:!1});return n.sort((e,t)=>e.name.localeCompare(t.name))}function QBe(e){if(!(!(`url`in e)||typeof e.url!=`string`))try{let t=new URL(e.url);return t.search=``,t.toString().replace(/\/$/,``)}catch{return}}var oY=n((()=>{H(),ui(),nn(),Rn(),Ln(),Li(),rY(),Bn(),jn(),pr()}));function $Be(e){return e.replace(/([a-z])([A-Z])/g,`$1_$2`).replace(/-/g,`_`).toLowerCase()}function eVe(e,t){let n=$Be(t);return{isSearch:tVe.has(n),isRead:nVe.has(n)}}var tVe,nVe,rVe=n((()=>{tVe=new Set(`slack_search_public.slack_search_public_and_private.slack_search_channels.slack_search_users.search_code.search_repositories.search_issues.search_pull_requests.search_orgs.search_users.search_documentation.search_logs.search_spans.search_rum_events.search_audit_logs.search_monitors.search_monitor_groups.find_slow_spans.find_monitors_matching_pattern.search_docs.search_events.search_issue_events.find_organizations.find_teams.find_projects.find_releases.find_dsns.search.gmail_search_messages.google_drive_search.gcal_find_my_free_time.gcal_find_meeting_times.gcal_find_user_emails.search_jira_issues_using_jql.search_confluence_using_cql.lookup_jira_account_id.confluence_search.jira_search.jira_search_fields.asana_search_tasks.asana_typeahead_search.search_files.search_nodes.brave_web_search.brave_local_search.search_dashboards.search_folders.search_docs.search_stripe_resources.search_stripe_documentation.search_articles.find_related_articles.lookup_article_by_citation.search_papers.search_pubmed.search_pubmed_key_words.search_pubmed_advanced.pubmed_search.pubmed_mesh_lookup.firecrawl_search.web_search_exa.web_search_advanced_exa.people_search_exa.linkedin_search_exa.deep_search_exa.perplexity_search.perplexity_search_web.tavily_search.obsidian_simple_search.obsidian_complex_search.find.search_knowledge.search_memories.find_memories_by_name.search_records.find_tasks.find_tasks_by_date.find_completed_tasks.find_projects.find_sections.find_comments.find_project_collaborators.find_activity.find_labels.find_filters.search_documentation.search_catalog.search_modules.search_providers.search_policies`.split(`.`)),nVe=new Set(`slack_read_channel.slack_read_thread.slack_read_canvas.slack_read_user_profile.slack_list_channels.slack_get_channel_history.slack_get_thread_replies.slack_get_users.slack_get_user_profile.get_me.get_team_members.get_teams.get_commit.get_file_contents.get_repository_tree.list_branches.list_commits.list_releases.list_tags.get_latest_release.get_release_by_tag.get_tag.list_issues.issue_read.list_issue_types.get_label.list_label.pull_request_read.get_gist.list_gists.list_notifications.get_notification_details.projects_list.projects_get.actions_get.actions_list.get_job_logs.get_code_scanning_alert.list_code_scanning_alerts.get_dependabot_alert.list_dependabot_alerts.get_secret_scanning_alert.list_secret_scanning_alerts.get_global_security_advisory.list_global_security_advisories.list_org_repository_security_advisories.list_repository_security_advisories.get_discussion.get_discussion_comments.list_discussion_categories.list_discussions.list_starred_repositories.get_issue.get_pull_request.list_pull_requests.get_pull_request_files.get_pull_request_status.get_pull_request_comments.get_pull_request_reviews.list_comments.list_cycles.get_document.list_documents.list_issue_statuses.get_issue_status.list_my_issues.list_issue_labels.list_projects.get_project.list_project_labels.list_teams.get_team.list_users.get_user.aggregate_logs.list_spans.aggregate_spans.analyze_trace.trace_critical_path.query_metrics.aggregate_rum_events.list_rum_metrics.get_rum_metric.list_monitors.get_monitor.check_can_delete_monitor.validate_monitor.validate_existing_monitor.list_dashboards.get_dashboard.query_dashboard_widget.list_notebooks.get_notebook.query_notebook_cell.get_profiling_metrics.compare_profiling_metrics.whoami.get_issue_details.get_issue_tag_values.get_trace_details.get_event_attachment.get_doc.get_sentry_resource.list_events.list_issue_events.get_sentry_issue.fetch.get_comments.get_users.get_self.gmail_get_profile.gmail_read_message.gmail_read_thread.gmail_list_drafts.gmail_list_labels.google_drive_fetch.google_drive_export.gcal_list_calendars.gcal_list_events.gcal_get_event.atlassian_user_info.get_accessible_atlassian_resources.get_visible_jira_projects.get_jira_project_issue_types_metadata.get_jira_issue.get_transitions_for_jira_issue.get_jira_issue_remote_issue_links.get_confluence_spaces.get_confluence_page.get_pages_in_confluence_space.get_confluence_page_ancestors.get_confluence_page_descendants.get_confluence_page_footer_comments.get_confluence_page_inline_comments.confluence_get_page.confluence_get_page_children.confluence_get_comments.confluence_get_labels.jira_get_issue.jira_get_transitions.jira_get_worklog.jira_get_agile_boards.jira_get_board_issues.jira_get_sprints_from_board.jira_get_sprint_issues.jira_get_link_types.jira_download_attachments.jira_batch_get_changelogs.jira_get_user_profile.jira_get_project_issues.jira_get_project_versions.asana_get_attachment.asana_get_attachments_for_object.asana_get_goal.asana_get_goals.asana_get_parent_goals_for_goal.asana_get_portfolio.asana_get_portfolios.asana_get_items_for_portfolio.asana_get_project.asana_get_projects.asana_get_project_sections.asana_get_project_status.asana_get_project_statuses.asana_get_project_task_counts.asana_get_projects_for_team.asana_get_projects_for_workspace.asana_get_task.asana_get_tasks.asana_get_stories_for_task.asana_get_teams_for_workspace.asana_get_teams_for_user.asana_get_team_users.asana_get_time_period.asana_get_time_periods.asana_get_user.asana_get_workspace_users.asana_list_workspaces.read_file.read_text_file.read_media_file.read_multiple_files.list_directory.list_directory_with_sizes.directory_tree.get_file_info.list_allowed_directories.read_graph.open_nodes.query.read_query.list_tables.describe_table.git_status.git_diff.git_diff_unstaged.git_diff_staged.git_log.git_show.git_branch.list_teams.list_users_by_org.get_dashboard_by_uid.get_dashboard_summary.get_dashboard_property.get_dashboard_panel_queries.run_panel_query.list_datasources.get_datasource.get_query_examples.query_prometheus.query_prometheus_histogram.list_prometheus_metric_metadata.list_prometheus_metric_names.list_prometheus_label_names.list_prometheus_label_values.query_loki_logs.query_loki_stats.query_loki_patterns.list_loki_label_names.list_loki_label_values.list_incidents.get_incident.list_sift_investigations.get_sift_investigation.get_sift_analysis.list_oncall_schedules.get_oncall_shift.get_current_oncall_users.list_oncall_teams.list_oncall_users.list_alert_groups.get_alert_group.get_annotations.get_annotation_tags.get_panel_image.list_incidents.get_incident.get_outlier_incident.get_past_incidents.get_related_incidents.list_incident_notes.list_incident_workflows.get_incident_workflow.list_services.get_service.list_team_members.get_user_data.list_schedules.get_schedule.list_schedule_users.list_oncalls.list_log_entries.get_log_entry.list_escalation_policies.get_escalation_policy.list_event_orchestrations.get_event_orchestration.list_status_pages.get_status_page_post.list_alerts_from_incident.get_alert_from_incident.list_change_events.get_change_event.list_organizations.get_organization.get_cost.list_extensions.list_migrations.get_logs.get_advisors.get_project_url.get_publishable_keys.generate_typescript_types.list_edge_functions.get_edge_function.list_storage_buckets.get_storage_config.get_stripe_account_info.retrieve_balance.list_customers.list_products.list_prices.list_invoices.list_payment_intents.list_subscriptions.list_coupons.list_disputes.fetch_stripe_resources.get_article_metadata.get_full_text_article.convert_article_ids.get_copyright_status.download_paper.list_papers.read_paper.get_paper_fulltext.get_pubmed_article_metadata.download_pubmed_pdf.pubmed_fetch.pubmed_pmc_fetch.pubmed_spell.pubmed_cite.pubmed_related.bigquery_query.bigquery_schema.list_dataset_ids.list_table_ids.get_dataset_info.get_table_info.firecrawl_scrape.firecrawl_map.firecrawl_crawl.firecrawl_check_crawl_status.firecrawl_extract.get_code_context_exa.company_research_exa.crawling_exa.deep_researcher_check.perplexity_ask.perplexity_research.perplexity_reason.tavily_extract.tavily_crawl.tavily_map.tavily_research.obsidian_list_files_in_vault.obsidian_list_files_in_dir.obsidian_get_file_contents.obsidian_batch_get_file_contents.obsidian_get_periodic_note.obsidian_get_recent_periodic_notes.obsidian_get_recent_changes.get_figma_data.download_figma_images.browser_console_messages.browser_network_requests.browser_take_screenshot.browser_snapshot.browser_get_config.browser_route_list.browser_cookie_list.browser_cookie_get.browser_localstorage_list.browser_localstorage_get.browser_sessionstorage_list.browser_sessionstorage_get.browser_storage_state.puppeteer_screenshot.list_databases.list_collections.collection_indexes.collection_schema.collection_storage_size.db_stats.explain.mongodb_logs.aggregate.count.export.get_neo4j_schema.read_neo4j_cypher.list_instances.get_instance_details.get_instance_by_name.list_indices.get_mappings.esql.get_shards.list_records.list_bases.get_record.get_productivity_stats.get_overview.fetch_object.user_info.list_workspaces.view_attachment.get_available_services.read_documentation.read_sections.recommend.analyze_log_group.analyze_metric.describe_log_groups.get_active_alarms.get_alarm_history.get_metric_data.get_metric_metadata.kubectl_get.kubectl_describe.kubectl_logs.kubectl_context.explain_resource.list_api_resources.namespaces_list.nodes_log.nodes_top.pods_get.pods_list.pods_list_in_namespace.pods_log.pods_top.resources_get.resources_list`.split(`.`))}));function iVe(e){return e.scope===`project`||e.scope===`local`}async function aVe(e,t){if(!t.headersHelper)return null;if(`scope`in t&&iVe(t)&&!kr()&&!Yi())return Ii(`MCP headersHelper invoked before trust check`,Error(`Security: headersHelper for MCP server '${e}' executed before workspace trust is confirmed. If you see this message, post in .`)),null;try{ba(e,`Executing headersHelper to get dynamic headers`);let n=await Oa(t.headersHelper,[],{shell:!0,timeout:1e4,env:{...process.env,WORKMATE_MCP_SERVER_NAME:e,WORKMATE_MCP_SERVER_URL:t.url}});if(n.code!==0||!n.stdout)throw Error(`headersHelper for MCP server '${e}' did not return a valid value`);let r=Si(n.stdout.trim());if(typeof r!=`object`||!r||Array.isArray(r))throw Error(`headersHelper for MCP server '${e}' must return a JSON object with string key-value pairs`);for(let[t,n]of Object.entries(r))if(typeof n!=`string`)throw Error(`headersHelper for MCP server '${e}' returned non-string value for key "${t}": ${typeof n}`);return ba(e,`Successfully retrieved ${Object.keys(r).length} headers from headersHelper`),r}catch(t){return Sa(e,`Error getting headers from headersHelper: ${G(t)}`),Y(Error(`Error getting MCP headers from headersHelper for server '${e}': ${G(t)}`)),null}}async function sY(e,t){let n=t.headers||{},r=await aVe(e,t)||{};return{...n,...r}}var oVe=n((()=>{H(),Wi(),q(),gi(),Da(),wa(),Li(),La()})),sVe,cVe=n((()=>{b(),sVe=class{constructor(e,t){x(this,`serverName`,void 0),x(this,`sendMcpMessage`,void 0),x(this,`isClosed`,!1),x(this,`onclose`,void 0),x(this,`onerror`,void 0),x(this,`onmessage`,void 0),this.serverName=e,this.sendMcpMessage=t}async start(){}async send(e){if(this.isClosed)throw Error(`Transport is closed`);let t=await this.sendMcpMessage(this.serverName,e);this.onmessage&&this.onmessage(t)}async close(){this.isClosed||(this.isClosed=!0,this.onclose?.())}}}));function lVe(e){return(`code`in e?e.code:void 0)===404?e.message.includes(`"code":-32001`)||e.message.includes(`"code": -32001`):!1}function uVe(){return parseInt(process.env.MCP_TOOL_TIMEOUT||``,10)||FVe}function cY(e){let t=QBe(e);return t?{mcpServerBaseUrl:t}:{}}function dVe(e,t,n){return{...cY(t)},ba(e,`Authentication required for ${{sse:`SSE`,http:`HTTP`,"claudeai-proxy":`claude.ai proxy`}[n]} server`),{name:e,type:`needs-auth`,config:t}}async function fVe(e,t){let n=(await import(`./wrapper-B-Q3Illb.js`)).default;return new n(e,[`mcp`],t)}function lY(){return parseInt(process.env.MCP_TIMEOUT||``,10)||3e4}function pVe(e){return async(t,n)=>{if((n?.method??`GET`).toUpperCase()===`GET`)return e(t,n);let r=new Headers(n?.headers);r.has(`accept`)||r.set(`accept`,LVe);let i=new AbortController,a=setTimeout(e=>e.abort(new DOMException(`The operation timed out.`,`TimeoutError`)),vY,i);a.unref?.();let o=n?.signal,s=()=>i.abort(o?.reason);o?.addEventListener(`abort`,s),o?.aborted&&i.abort(o.reason);let c=()=>{clearTimeout(a),o?.removeEventListener(`abort`,s)};try{let a=await e(t,{...n,headers:r,signal:i.signal});return c(),a}catch(e){throw c(),e}}}function mVe(){return parseInt(process.env.MCP_SERVER_CONNECTION_BATCH_SIZE||``,10)||3}function hVe(){return parseInt(process.env.MCP_REMOTE_SERVER_CONNECTION_BATCH_SIZE||``,10)||20}function gVe(e){return!e.type||e.type===`stdio`||e.type===`sdk`}function _Ve(e){return!e.name.startsWith(`mcp__ide__`)||RVe.includes(e.name)}function uY(e,t){return`${e}-${W(t)}`}async function dY(e,t){let n=uY(e,t);try{let n=await yY(e,t);n.type===`connected`&&await n.cleanup()}catch{}yY.cache.delete(n),xY.cache.delete(e),SY.cache.delete(e),CY.cache.delete(e)}async function fY(e){if(e.config.type===`sdk`)return e;let t=await yY(e.name,e.config);if(t.type!==`connected`)throw new ji(`MCP server "${e.name}" is not connected`,`MCP server not connected`);return t}function vVe(e,t){if(e.type!==t.type)return!1;let{scope:n,...r}=e,{scope:i,...a}=t;return W(r)===W(a)}function yVe(e,t){let n=Object.keys(e);return n.length>0?n.map(t=>`${t}=${String(e[t])}`).join(` `):t}async function bVe(e,t){try{DF(),await dY(e,t);let n=await yY(e,t);if(n.type!==`connected`)return{client:n,tools:[],commands:[]};let r=!!n.capabilities?.resources,[i,a,o]=await Promise.all([xY(n),CY(n),r?SY(n):Promise.resolve([])]),s=[...a],c=[];return r&&([kJ,IJ].some(e=>i.some(t=>us(t,e.name)))||c.push(kJ,IJ)),{client:n,tools:[...i,...c],commands:s,resources:o.length>0?o:void 0}}catch(n){return Sa(e,`Error during reconnection: ${G(n)}`),{client:{name:e,type:`failed`,config:t},tools:[],commands:[]}}}async function xVe(e,t,n){await tze(e,n,{concurrency:t})}async function SVe(e,t){let n=!1,r=Object.entries(t??(await EBe()).servers),i=[];for(let t of r)tY(t[0])?e({client:{name:t[0],type:`disabled`,config:t[1]},tools:[],commands:[]}):i.push(t);let a=i.length,o=zt(i,([e,t])=>t.type===`stdio`),s=zt(i,([e,t])=>t.type===`sse`),c=zt(i,([e,t])=>t.type===`http`),l=zt(i,([e,t])=>t.type===`sse-ide`),u=zt(i,([e,t])=>t.type===`ws-ide`),d=i.filter(([e,t])=>gVe(t)),f=i.filter(([e,t])=>!gVe(t)),p={totalServers:a,stdioCount:o,sseCount:s,httpCount:c,sseIdeCount:l,wsIdeCount:u},m=async([t,r])=>{try{if(tY(t)){e({client:{name:t,type:`disabled`,config:r},tools:[],commands:[]});return}let i=await yY(t,r,p);if(i.type!==`connected`){e({client:i,tools:[],commands:[]});return}let a=!!i.capabilities?.resources,[o,s,c]=await Promise.all([xY(i),CY(i),a?SY(i):Promise.resolve([])]),l=[...s],u=[];a&&!n&&(n=!0,u.push(kJ,IJ)),e({client:i,tools:[...o,...u],commands:l,resources:c.length>0?c:void 0})}catch(n){Sa(t,`Error fetching tools/commands/resources: ${G(n)}`),e({client:{name:t,type:`failed`,config:r},tools:[],commands:[]})}};await Promise.all([xVe(d,mVe(),m),xVe(f,hVe(),m)])}function CVe(e){return new Promise(t=>{let n=0,r=0;if(n=Object.keys(e).length,n===0){t({clients:[],tools:[],commands:[]});return}let i=[],a=[],o=[];SVe(e=>{i.push(e.client),a.push(...e.tools),o.push(...e.commands),r++,r>=n&&(o.reduce((e,t)=>e+(t.name.length+(t.description??``).length+(t.argumentHint??``).length),0),a.length,o.length,t({clients:i,tools:a,commands:o}))},e).catch(e=>{Sa(`prefetchAllMcpResources`,`Failed to get MCP resources: ${G(e)}`),t({clients:[],tools:[],commands:[]})})})}async function wVe(e,t,n,r=!1){switch(e.type){case`text`:{let t={type:`text`,text:e.text};if(r){let n=e._meta;n&&(t._meta=n)}return[t]}case`audio`:{let n=e;return await TVe(Buffer.from(n.data,`base64`),n.mimeType,t,`[Audio from ${t}] `)}case`image`:{let t=Buffer.from(String(e.data),`base64`),r=e.mimeType?.split(`/`)[1]||`png`,i=await _y(t,t.length,r,n);return[{type:`image`,source:{data:i.buffer.toString(`base64`),media_type:`image/${i.mediaType}`,type:`base64`}}]}case`resource`:{let r=e.resource,i=`[Resource from ${t} at ${r.uri}] `;if(`text`in r)return[{type:`text`,text:`${i}${r.text}`}];if(`blob`in r)if(IVe.has(r.mimeType??``)){let e=Buffer.from(r.blob,`base64`),t=r.mimeType?.split(`/`)[1]||`png`,a=await _y(e,e.length,t,n),o=[];return i&&o.push({type:`text`,text:i}),o.push({type:`image`,source:{data:a.buffer.toString(`base64`),media_type:`image/${a.mediaType}`,type:`base64`}}),o}else return await TVe(Buffer.from(r.blob,`base64`),r.mimeType,t,i);return[]}case`resource_link`:{let t=e,n=`[Resource link: ${t.name}] ${t.uri}`;return t.description&&(n+=` (${t.description})`),[{type:`text`,text:n}]}default:return[]}}async function TVe(e,t,n,r){let i=await zze(e,t,`mcp-${pn(n)}-blob-${Date.now()}-${Math.random().toString(36).slice(2,8)}`);return`error`in i?[{type:`text`,text:`${r}Binary content (${t||`unknown type`}, ${e.length} bytes) could not be saved to disk: ${i.error}`}]:[{type:`text`,text:Bze(i.filepath,t,i.size,r)}]}function pY(e,t=2){if(e===null)return`null`;if(Array.isArray(e))return e.length===0?`[]`:`[${pY(e[0],t-1)}]`;if(typeof e==`object`){if(t<=0)return`{...}`;let n=Object.entries(e).slice(0,10).map(([e,n])=>`${e}: ${pY(n,t-1)}`),r=Object.keys(e).length>10?`, ...`:``;return`{${n.join(`, `)}${r}}`}return typeof e}async function EVe(e,t,n,r){if(e&&typeof e==`object`){if(`toolResult`in e)return{content:String(e.toolResult),type:`toolResult`};if(`structuredContent`in e&&e.structuredContent!==void 0)return{content:W(e.structuredContent),type:`structuredContent`,schema:pY(e.structuredContent)};if(`content`in e&&Array.isArray(e.content)){let t=(await Promise.all(e.content.map(e=>wVe(e,n,r,!0)))).flat();return{content:t,type:`contentArray`,schema:pY(t)}}}let i=`MCP server "${n}" tool "${t}": unexpected response format`;throw Sa(n,i),new ji(i,`MCP tool unexpected response format`)}function DVe(e){return!e||typeof e==`string`?!1:e.some(e=>e.type===`image`)}async function OVe(e,t,n,r,i=!1){let{content:a,type:o,schema:s}=await EVe(e,t,n,r);if(i&&!DVe(a)||!await vze(a))return a;if(MJ(a),f(process.env.ENABLE_MCP_LARGE_OUTPUT_FILES))return await bze(a);if(!a)return a;if(DVe(a))return await bze(a);let c=Date.now(),l=`mcp-${pn(n)}-${pn(t)}-${c}`,u=AVe(a),d=typeof a==`string`?a:u??W(a,null,2),p=await ix(d,l);if(cx(p))return`Error: result (${d.length.toLocaleString()} characters) exceeds maximum allowed tokens. Failed to save output to file: ${p.error}. If this MCP server provides pagination or filtering tools, use them to retrieve specific portions of the data.`;p.originalSize;let m=u===void 0?Ize(o,s):Ize(`toolResult`);return Lze(p.filepath,p.originalSize,m)}function kVe(){let e=process.env.MCP_TRUNCATION_PROMPT_OVERRIDE;return e?e!==`legacy`:!1}function AVe(e){if(!kVe()||!Array.isArray(e)||e.length!==1)return;let t=e[0];if(t?.type===`text`&&!(`annotations`in t||`_meta`in t))return t.text}async function jVe({client:e,clientConnection:t,tool:n,args:r,meta:i,signal:a,setAppState:o,onProgress:s,imageLimits:c,hasResultSizeAnnotation:l=!1,callToolFn:u=MVe,handleElicitation:d}){for(let f=0;;f++)try{return await u({client:e,tool:n,args:r,meta:i,signal:a,onProgress:s,imageLimits:c,hasResultSizeAnnotation:l})}catch(e){if(!(e instanceof FK)||e.code!==lW.UrlElicitationRequired||f>=3)throw e;let r=e.data,i=(typeof r==`object`&&r&&`elicitations`in r&&Array.isArray(r.elicitations)?r.elicitations:[]).filter(e=>{if(typeof e!=`object`||!e)return!1;let t=e;return t.mode===`url`&&typeof t.url==`string`&&typeof t.elicitationId==`string`&&typeof t.message==`string`}),s=t.type===`connected`?t.name:`unknown`;if(i.length===0)throw ba(s,`Tool '${n}' returned -32042 but no valid elicitations in error data`),e;ba(s,`Tool '${n}' requires URL elicitation (error -32042, attempt ${f+1}), processing ${i.length} elicitation(s)`);for(let e of i){let{elicitationId:t}=e,r=await BJ(s,e,a);if(r){if(ba(s,`URL elicitation ${t} resolved by hook: ${W(r)}`),r.action!==`accept`)return{content:`URL elicitation was ${r.action===`decline`?`declined`:`${r.action}ed`} by a hook. The tool "${n}" could not complete because it requires the user to open a URL.`};continue}let i;if(d)i=await d(s,e,a);else{let n={actionLabel:`Retry now`,showCancel:!0};i=await new Promise(r=>{let i=()=>{r({action:`cancel`})};if(a.aborted){i();return}a.addEventListener(`abort`,i,{once:!0}),o(o=>({...o,elicitation:{queue:[...o.elicitation.queue,{serverName:s,requestId:`error-elicit-${t}`,params:e,signal:a,waitingState:n,respond:e=>{e.action!==`accept`&&(a.removeEventListener(`abort`,i),r(e))},onWaitingDismiss:e=>{a.removeEventListener(`abort`,i),r(e===`retry`?{action:`accept`}:{action:`cancel`})}}]}}))})}let c=await VJ(s,i,a,`url`,t);if(c.action!==`accept`)return ba(s,`User ${c.action===`decline`?`declined`:`${c.action}ed`} URL elicitation ${t}`),{content:`URL elicitation was ${c.action===`decline`?`declined`:`${c.action}ed`} by the user. The tool "${n}" could not complete because it requires the user to open a URL.`};ba(s,`Elicitation ${t} completed, retrying tool call`)}}}async function MVe({client:{client:e,name:t,config:n},tool:r,args:i,meta:a,signal:o,onProgress:s,imageLimits:c,hasResultSizeAnnotation:l=!1}){let u=Date.now(),d;try{ba(t,`Calling MCP tool: ${r}`),d=setInterval((e,t,n)=>{let r=Date.now()-e;ba(t,`Tool '${n}' still running (${`${Math.floor(r/1e3)}s`} elapsed)`)},3e4,u,t,r);let n=uVe(),f,p=new Promise((e,i)=>{f=setTimeout((e,t,n,r)=>{e(new ji(`MCP server "${t}" tool "${n}" timed out after ${Math.floor(r/1e3)}s`,`MCP tool timeout`))},n,i,t,r,n)}),m=await Promise.race([e.callTool({name:r,arguments:i,_meta:a},BG,{signal:o,timeout:n,onprogress:s?e=>{s({type:`mcp_progress`,status:`progress`,serverName:t,toolName:r,progress:e.progress,total:e.total,progressMessage:e.message})}:void 0}),p]).finally(()=>{f&&clearTimeout(f)});if(`isError`in m&&m.isError){let e=`Unknown error`;if(`content`in m&&Array.isArray(m.content)&&m.content.length>0){let t=m.content[0];t&&typeof t==`object`&&`text`in t&&(e=t.text)}else`error`in m&&(e=String(m.error));throw Sa(t,e),new gY(e,`MCP tool returned error`,`_meta`in m&&m._meta?{_meta:m._meta}:void 0)}let h=Date.now()-u;return ba(t,`Tool '${r}' completed successfully in ${h<1e3?`${h}ms`:h<6e4?`${Math.floor(h/1e3)}s`:`${Math.floor(h/6e4)}m ${Math.floor(h%6e4/1e3)}s`}`),MEe(t),{content:await OVe(m,r,t,c,l),_meta:m._meta,structuredContent:m.structuredContent}}catch(e){d!==void 0&&clearInterval(d);let i=Date.now()-u;if(e instanceof Error&&e.name!==`AbortError`&&ba(t,`Tool '${r}' failed after ${Math.floor(i/1e3)}s: ${e.message}`),e instanceof Error){if((`code`in e?e.code:void 0)===401||e instanceof yJ)throw ba(t,`Tool call returned 401 Unauthorized - token may have expired`),new mY(t,`MCP server "${t}" requires re-authorization (token expired)`);let r=lVe(e),i=`code`in e&&e.code===-32e3&&e.message.includes(`Connection closed`)&&n.type===`http`;if(r||i)throw ba(t,`MCP session expired during tool call (${r?`404/-32001`:`connection closed`}), clearing connection cache for re-initialization`),await dY(t,n),new hY(t)}if(!(e instanceof Error)||e.name!==`AbortError`)throw e;return{content:void 0}}finally{d!==void 0&&clearInterval(d)}}function NVe(e){let t=e.message.content?.[0];if(!(!t||typeof t==`string`||t.type!==`tool_use`))return t.id}async function PVe(e,t){let n=[],r=[],i=await Promise.allSettled(Object.entries(e).map(async([e,n])=>{let r=new sVe(e,t),i=new eq({name:`workmate`,title:`Work Mate`,version:`0.0.32`,description:`Agentic coding tool`,websiteUrl:nF},{capabilities:{}});try{await i.connect(r);let t=i.getServerCapabilities(),a={type:`connected`,name:e,capabilities:t||{},client:i,config:{...n,scope:`dynamic`},cleanup:async()=>{await i.close()}},o=[];if(t?.tools){let e=await xY(a);o.push(...e)}return{client:a,tools:o}}catch(t){return Sa(e,`Failed to connect SDK MCP server: ${t}`),{client:{type:`failed`,name:e,config:{...n,scope:`user`}},tools:[]}}}));for(let e of i)e.status===`fulfilled`&&(n.push(e.value.client),r.push(...e.value.tools));return{clients:n,tools:r}}var mY,hY,gY,FVe,_Y,IVe,vY,LVe,RVe,yY,bY,xY,SY,CY,wY=n((()=>{qLe(),VRe(),YRe(),eze(),Gq(),LK(),lm(),d(),Cm(),nze(),H(),rF(),Ms(),AJ(),Fze(),LJ(),tt(),di(),wM(),q(),g(),gi(),Lie(),Cy(),wa(),Vze(),Cze(),Qze(),tn(),roe(),zs(),Nb(),fx(),La(),nBe(),Bn(),jn(),oY(),lse(),SJ(),rVe(),AF(),Hs(),rY(),oVe(),cVe(),b(),Li(),mY=class extends Error{constructor(e,t){super(t),x(this,`serverName`,void 0),this.name=`McpAuthError`,this.serverName=e}},hY=class extends Error{constructor(e){super(`MCP server "${e}" session expired`),this.name=`McpSessionExpiredError`}},gY=class extends ji{constructor(e,t,n){super(e,t),x(this,`mcpMeta`,void 0),this.mcpMeta=n,this.name=`McpToolCallError`}},FVe=1e8,_Y=2048,IVe=new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]),vY=6e4,LVe=`application/json, text/event-stream`,RVe=[`mcp__ide__executeCode`,`mcp__ide__getDiagnostics`],yY=u(async(e,t,n)=>{let r=Date.now();try{let i;if(t.type===`sse`){let n=await sY(e,t),r={fetch:pVe(Wq()),requestInit:{headers:{"User-Agent":To(),...n}}};r.eventSourceInit={fetch:async(e,t)=>{let r=Bs();return fetch(e,{...t,...r,headers:{"User-Agent":To(),...t?.headers,...n,Accept:`text/event-stream`}})}},i=new CJ(new URL(t.url),r),ba(e,`SSE transport initialized, awaiting connection`)}else if(t.type===`sse-ide`){ba(e,`Setting up SSE-IDE transport to ${t.url}`);let n=Bs(),r=n.dispatcher?{eventSourceInit:{fetch:async(e,t)=>fetch(e,{...t,...n,headers:{"User-Agent":To(),...t?.headers}})}}:{};i=new CJ(new URL(t.url),Object.keys(r).length>0?r:void 0)}else if(t.type===`ws-ide`){let e=aoe(),n={"User-Agent":To(),...t.authToken&&{"X-Work Mate-Code-Ide-Authorization":t.authToken}},r;r=typeof Bun<`u`?new globalThis.WebSocket(t.url,{protocols:[`mcp`],headers:n,proxy:ooe(t.url),tls:e||void 0}):await fVe(t.url,{headers:n,agent:ioe(t.url),...e||{}}),i=new zJ(r)}else if(t.type===`ws`){ba(e,`Initializing WebSocket transport to ${t.url}`);let n=await sY(e,t),r=aoe(),a={"User-Agent":To(),...n},o=cm(a,(e,t)=>t.toLowerCase()===`authorization`?`[REDACTED]`:e);ba(e,`WebSocket transport options: ${W({url:t.url,headers:o})}`);let s;s=typeof Bun<`u`?new globalThis.WebSocket(t.url,{protocols:[`mcp`],headers:a,proxy:ooe(t.url),tls:r||void 0}):await fVe(t.url,{headers:a,agent:ioe(t.url),...r||{}}),i=new zJ(s)}else if(t.type===`http`){ba(e,`Initializing HTTP transport to ${t.url}`),ba(e,`Node version: ${process.version}, Platform: ${process.platform}`),ba(e,`Environment: ${W({NODE_OPTIONS:process.env.NODE_OPTIONS||`not set`,UV_THREADPOOL_SIZE:process.env.UV_THREADPOOL_SIZE||`default`,HTTP_PROXY:process.env.HTTP_PROXY||`not set`,HTTPS_PROXY:process.env.HTTPS_PROXY||`not set`,NO_PROXY:process.env.NO_PROXY||`not set`})}`);let n=await sY(e,t),r=Bs();ba(e,`Proxy options: ${r.dispatcher?`custom dispatcher`:`default`}`);let a={fetch:pVe(Wq()),requestInit:{...r,headers:{"User-Agent":To(),...n}}},o=a.requestInit?.headers?cm(a.requestInit.headers,(e,t)=>t.toLowerCase()===`authorization`?`[REDACTED]`:e):void 0;ba(e,`HTTP transport options: ${W({url:t.url,headers:o,timeoutMs:vY})}`),i=new $Re(new URL(t.url),a),ba(e,`HTTP transport created successfully`)}else if(t.type===`sdk`)throw Error(`SDK servers should be handled in print.ts`);else if(t.type===`stdio`||!t.type){let e=t;i=new JRe({command:process.env.WORKMATE_SHELL_PREFIX||e.command,args:process.env.WORKMATE_SHELL_PREFIX?[[e.command,...e.args].join(` `)]:e.args,env:{...Mb(),...e.env},stderr:`pipe`})}else throw Error(`Unsupported server type: ${t.type}`);let a,o=``;if(t.type===`stdio`||!t.type){let e=i;e.stderr&&(a=e=>{if(o.length<64*1024*1024)try{o+=e.toString()}catch{}},e.stderr.on(`data`,a))}let s=new eq({name:`workmate`,title:`Work Mate`,version:`0.0.32`,description:`Agentic coding tool`,websiteUrl:nF},{capabilities:{roots:{},elicitation:{}}});if(t.type===`http`&&ba(e,`Client created, setting up request handler`),s.setRequestHandler(MK,async()=>(ba(e,`Received ListRoots request from server`),{roots:[{uri:`file://${ti()}`}]})),ba(e,`Starting connection with timeout of ${lY()}ms`),t.type===`http`){ba(e,`Testing basic HTTP connectivity to ${t.url}`);try{let n=new URL(t.url);ba(e,`Parsed URL: host=${n.hostname}, port=${n.port||`default`}, protocol=${n.protocol}`),(n.hostname===`127.0.0.1`||n.hostname===`localhost`)&&ba(e,`Using loopback address: ${n.hostname}`)}catch(t){ba(e,`Failed to parse URL: ${t}`)}}let c=s.connect(i),l=new Promise((t,n)=>{let a=setTimeout(()=>{ba(e,`Connection timeout triggered after ${Date.now()-r}ms (limit: ${lY()}ms)`),i.close().catch(()=>{}),n(new ji(`MCP server "${e}" connection timed out after ${lY()}ms`,`MCP connection timeout`))},lY());c.then(()=>{clearTimeout(a)},e=>{clearTimeout(a)})});try{await Promise.race([c,l]),o&&(Sa(e,`Server stderr: ${o}`),o=``);let n=Date.now()-r;ba(e,`Successfully connected (transport: ${t.type||`stdio`}) in ${n}ms`)}catch(n){let a=Date.now()-r;if(t.type===`sse`&&n instanceof Error){if(ba(e,`SSE Connection failed after ${a}ms: ${W({url:t.url,error:n.message,errorType:n.constructor.name,stack:n.stack})}`),Sa(e,n),n instanceof yJ)return dVe(e,t,`sse`)}else if(t.type===`http`&&n instanceof Error){let r=n;if(ba(e,`HTTP Connection failed after ${a}ms: ${n.message} (code: ${r.code||`none`}, errno: ${r.errno||`none`})`),Sa(e,n),n instanceof yJ)return dVe(e,t,`http`)}else t.type===`sse-ide`||t.type;throw i.close().catch(()=>{}),o&&Sa(e,`Server stderr: ${o}`),n}let u=s.getServerCapabilities(),d=s.getServerVersion(),f=s.getInstructions(),p=f;f&&f.length>_Y&&(p=`${f.slice(0,_Y)}… [truncated]`,ba(e,`Server instructions truncated from ${f.length} to ${_Y} chars`)),ba(e,`Connection established with capabilities: ${W({hasTools:!!u?.tools,hasPrompts:!!u?.prompts,hasResources:!!u?.resources,hasResourceSubscribe:!!u?.resources?.subscribe,serverVersion:d||`unknown`})}`),K(`[MCP] Server "${e}" connected with subscribe=${!!u?.resources?.subscribe}`),s.setRequestHandler(SK,async t=>(ba(e,`Elicitation request received during initialization: ${W(t)}`),{action:`cancel`}));let m=Date.now(),h=!1,g=s.onerror,_=s.onclose,v=0,y=!1,b=t=>{y||(y=!0,ba(e,`Closing transport (${t})`),s.close().catch(t=>{ba(e,`Error during close: ${G(t)}`)}))},x=e=>e.includes(`ECONNRESET`)||e.includes(`ETIMEDOUT`)||e.includes(`EPIPE`)||e.includes(`EHOSTUNREACH`)||e.includes(`ECONNREFUSED`)||e.includes(`Body Timeout Error`)||e.includes(`terminated`)||e.includes(`SSE stream disconnected`)||e.includes(`Failed to reconnect SSE stream`);s.onerror=n=>{let r=Date.now()-m;h=!0;let i=t.type||`stdio`;if(ba(e,`${i.toUpperCase()} connection dropped after ${Math.floor(r/1e3)}s uptime`),n.message&&(n.message.includes(`ECONNRESET`)?ba(e,`Connection reset - server may have crashed or restarted`):n.message.includes(`ETIMEDOUT`)?ba(e,`Connection timeout - network issue or server unresponsive`):n.message.includes(`ECONNREFUSED`)?ba(e,`Connection refused - server may be down`):n.message.includes(`EPIPE`)?ba(e,`Broken pipe - server closed connection unexpectedly`):n.message.includes(`EHOSTUNREACH`)?ba(e,`Host unreachable - network connectivity issue`):n.message.includes(`ESRCH`)?ba(e,`Process not found - stdio server process terminated`):n.message.includes(`spawn`)?ba(e,`Failed to spawn process - check command and permissions`):ba(e,`Connection error: ${n.message}`)),i===`http`&&lVe(n)){ba(e,`MCP session expired (server returned 404 with session-not-found), triggering reconnection`),b(`session expired`),g&&g(n);return}if(i===`sse`||i===`http`){if(n.message.includes(`Maximum reconnection attempts`)){b(`SSE reconnection exhausted`),g&&g(n);return}x(n.message)?(v++,ba(e,`Terminal connection error ${v}/3`),v>=3&&(v=0,b(`max consecutive terminal errors`))):v=0}g&&g(n)},s.onclose=()=>{let n=Date.now()-m;ba(e,`${(t.type??`unknown`).toUpperCase()} connection closed after ${Math.floor(n/1e3)}s (${h?`with errors`:`cleanly`})`);let r=uY(e,t);xY.cache.delete(e),SY.cache.delete(e),CY.cache.delete(e),yY.cache.delete(r),ba(e,`Cleared connection cache for reconnection`),_&&_()};let S=async()=>{if(a&&(t.type===`stdio`||!t.type)&&i.stderr?.off(`data`,a),t.type===`stdio`)try{let t=i.pid;if(t){ba(e,`Sending SIGINT to MCP server process`);try{process.kill(t,`SIGINT`)}catch(t){ba(e,`Error sending SIGINT: ${t}`);return}await new Promise(async n=>{let r=!1,i=setInterval(()=>{try{process.kill(t,0)}catch{r||(r=!0,clearInterval(i),clearTimeout(a),ba(e,`MCP server process exited cleanly`),n())}},50),a=setTimeout(()=>{r||(r=!0,clearInterval(i),ba(e,`Cleanup timeout reached, stopping process monitoring`),n())},600);try{if(await Vs(100),!r){try{process.kill(t,0),ba(e,`SIGINT failed, sending SIGTERM to MCP server process`);try{process.kill(t,`SIGTERM`)}catch(t){ba(e,`Error sending SIGTERM: ${t}`),r=!0,clearInterval(i),clearTimeout(a),n();return}}catch{r=!0,clearInterval(i),clearTimeout(a),n();return}if(await Vs(400),!r)try{process.kill(t,0),ba(e,`SIGTERM failed, sending SIGKILL to MCP server process`);try{process.kill(t,`SIGKILL`)}catch(t){ba(e,`Error sending SIGKILL: ${t}`)}}catch{r=!0,clearInterval(i),clearTimeout(a),n()}}r||(r=!0,clearInterval(i),clearTimeout(a),n())}catch{r||(r=!0,clearInterval(i),clearTimeout(a),n())}})}}catch(t){ba(e,`Error terminating process: ${t}`)}try{await s.close()}catch(t){ba(e,`Error closing client: ${t}`)}},C=Oi(S),w=async()=>{C?.(),await S()};return Date.now()-r,t.type,n?.totalServers,n?.stdioCount,n?.sseCount,n?.httpCount,n?.sseIdeCount,n?.wsIdeCount,{...cY(t)},{name:e,client:s,type:`connected`,capabilities:u??{},serverInfo:d,instructions:p,config:t,cleanup:w}}catch(i){let a=Date.now()-r;return n?.totalServers,n?.stdioCount||+(t.type===`stdio`),n?.sseCount||+(t.type===`sse`),n?.httpCount||+(t.type===`http`),n?.sseIdeCount||+(t.type===`sse-ide`),n?.wsIdeCount||+(t.type===`ws-ide`),t.type,{...cY(t)},ba(e,`Connection failed after ${a}ms: ${G(i)}`),Sa(e,`Connection failed: ${G(i)}`),{name:e,type:`failed`,config:t,error:G(i)}}},uY),bY=20,xY=ln(async e=>{if(e.type!==`connected`)return[];try{if(!e.capabilities?.tools)return[];let t=cse((await e.client.request({method:`tools/list`},zG)).tools),n=e.config.type===`sdk`&&h(process.env.CLAUDE_AGENT_SDK_MCP_NO_PREFIX);return t.map(t=>{let r=Jee(e.name,t.name);return{...Pze,name:n?t.name:r,mcpInfo:{serverName:e.name,toolName:t.name},isMcp:!0,searchHint:typeof t._meta?.[`anthropic/searchHint`]==`string`&&t._meta[`anthropic/searchHint`].replace(/\s+/g,` `).trim()||void 0,alwaysLoad:t._meta?.[`anthropic/alwaysLoad`]===!0,async description(){return t.description??``},async prompt(){let e=t.description??``;return e.length>_Y?`${e.slice(0,_Y)}… [truncated]`:e},isConcurrencySafe(){return t.annotations?.readOnlyHint??!1},isReadOnly(){return t.annotations?.readOnlyHint??!1},toAutoClassifierInput(e){return yVe(e,t.name)},isDestructive(){return t.annotations?.destructiveHint??!1},isOpenWorld(){return t.annotations?.openWorldHint??!1},isSearchOrReadCommand(){return eVe(e.name,t.name)},inputJSONSchema:t.inputSchema,async checkPermissions(){return{behavior:`passthrough`,message:`MCPTool requires permission.`,suggestions:[{type:`addRules`,rules:[{toolName:r,ruleContent:void 0}],behavior:`allow`,destination:`localSettings`}]}},async call(n,r,i,a,o){let s=NVe(a),c=s?{"claudecode/toolUseId":s}:{};o&&s&&o({toolUseID:s,data:{type:`mcp_progress`,status:`started`,serverName:e.name,toolName:t.name}});let l=Date.now();for(let i=0;;i++)try{let i=await jVe({client:await fY(e),clientConnection:e,tool:t.name,args:n,meta:c,signal:r.abortController.signal,setAppState:r.setAppState,onProgress:o&&s?e=>{o({toolUseID:s,data:e})}:void 0,handleElicitation:r.handleElicitation});return o&&s&&o({toolUseID:s,data:{type:`mcp_progress`,status:`completed`,serverName:e.name,toolName:t.name,elapsedTimeMs:Date.now()-l}}),{data:i.content,...(i._meta||i.structuredContent)&&{mcpMeta:{...i._meta&&{_meta:i._meta},...i.structuredContent&&{structuredContent:i.structuredContent}}}}}catch(n){if(n instanceof hY&&i<1){ba(e.name,`Retrying tool '${t.name}' after session recovery`);continue}if(o&&s&&o({toolUseID:s,data:{type:`mcp_progress`,status:`failed`,serverName:e.name,toolName:t.name,elapsedTimeMs:Date.now()-l}}),n instanceof Error&&!(n instanceof ji)){let e=n.constructor.name;if(e===`Error`)throw new ji(n.message,n.message.slice(0,200));if(e===`McpError`&&`code`in n&&typeof n.code==`number`)throw new ji(n.message,`McpError ${n.code}`)}throw n}},userFacingName(){let n=t.annotations?.title||t.name;return`${e.name} - ${n} (MCP)`}}}).filter(_Ve)}catch(t){return Sa(e.name,`Failed to fetch tools: ${G(t)}`),[]}},e=>e.name,bY),SY=ln(async e=>{if(e.type!==`connected`)return[];try{if(!e.capabilities?.resources)return[];let t=await e.client.request({method:`resources/list`},aG);return t.resources?t.resources.map(t=>({...t,server:e.name})):[]}catch(t){return Sa(e.name,`Failed to fetch resources: ${G(t)}`),[]}},e=>e.name,bY),CY=ln(async e=>{if(e.type!==`connected`)return[];try{if(!e.capabilities?.prompts)return[];let t=await e.client.request({method:`prompts/list`},SG);return t.prompts?cse(t.prompts).map(t=>{let n=Object.values(t.arguments??{}).map(e=>e.name);return{type:`prompt`,name:`mcp__${pn(e.name)}__${t.name}`,description:t.description??``,hasUserSpecifiedDescription:!!t.description,contentLength:0,isEnabled:()=>!0,isHidden:!1,isMcp:!0,progressMessage:`running`,userFacingName(){return`${e.name}:${t.name} (MCP)`},argNames:n,source:`mcp`,async getPromptForCommand(r){let i=r.split(` `);try{let r=await fY(e),a=await r.client.getPrompt({name:t.name,arguments:ufe(n,i)});return(await Promise.all(a.messages.map(e=>wVe(e.content,r.name)))).flat()}catch(n){throw Sa(e.name,`Error running command '${t.name}': ${G(n)}`),n}}}}):[]}catch(t){return Sa(e.name,`Failed to fetch commands: ${G(t)}`),[]}},e=>e.name,bY)}));function zVe(e,t){if(e.type!==t.type)return!1;let n=(e,t)=>(e.if??``)===(t.if??``);switch(e.type){case`command`:return t.type===`command`&&e.command===t.command&&(e.shell??`bash`)===(t.shell??`bash`)&&n(e,t);case`prompt`:return t.type===`prompt`&&e.prompt===t.prompt&&n(e,t);case`agent`:return t.type===`agent`&&e.prompt===t.prompt&&n(e,t);case`http`:return t.type===`http`&&e.url===t.url&&n(e,t);case`function`:return!1}}function TY(e){if(`statusMessage`in e&&e.statusMessage)return e.statusMessage;switch(e.type){case`command`:return e.command;case`prompt`:return e.prompt;case`agent`:return e.prompt;case`http`:return e.url;case`callback`:return`callback`;case`function`:return`function`}}function BVe(e){let t=[];if($n(`policySettings`)?.allowManagedHooksOnly!==!0){let e=[`userSettings`,`projectSettings`,`localSettings`],n=new Set;for(let r of e){let e=Vn(r);if(e){let t=yc(e);if(n.has(t))continue;n.add(t)}let i=$n(r);if(i?.hooks)for(let[e,n]of Object.entries(i.hooks))for(let i of n)for(let n of i.hooks)t.push({event:e,config:n,matcher:i.matcher,source:r})}}let n=XVe(e,Wr());for(let[e,r]of n.entries())for(let n of r)for(let r of n.hooks)t.push({event:e,config:r,matcher:n.matcher,source:`sessionHook`});return t}function VVe(e){switch(e){case`userSettings`:return`User settings (~/.workmate/settings.json)`;case`projectSettings`:return`Project settings (.workmate/settings.json)`;case`localSettings`:return`Local settings (.workmate/settings.local.json)`;case`pluginHook`:return`Plugin hooks (~/.workmate/plugins/*/hooks/hooks.json)`;case`sessionHook`:return`Session hooks (in-memory, temporary)`;case`builtinHook`:return`Built-in hooks (registered internally by Work Mate)`;default:return e}}function HVe(e){switch(e){case`userSettings`:return`User Settings`;case`projectSettings`:return`Project Settings`;case`localSettings`:return`Local Settings`;case`pluginHook`:return`Plugin Hooks`;case`sessionHook`:return`Session Hooks`;case`builtinHook`:return`Built-in Hooks`;default:return e}}function UVe(e){switch(e){case`userSettings`:return`User`;case`projectSettings`:return`Project`;case`localSettings`:return`Local`;case`pluginHook`:return`Plugin`;case`sessionHook`:return`Session`;case`builtinHook`:return`Built-in`;default:return e}}function WVe(e,t,n){let r=rte.reduce((e,t,n)=>(e[t]=n,e),{});return[...e].sort((e,i)=>{let a=t[n]?.[e]||[],o=t[n]?.[i]||[],s=Array.from(new Set(a.map(e=>e.source))),c=Array.from(new Set(o.map(e=>e.source))),l=e=>e===`pluginHook`||e===`builtinHook`?999:r[e],u=Math.min(...s.map(l)),d=Math.min(...c.map(l));return u===d?e.localeCompare(i):u-d})}var EY=n((()=>{H(),Rn(),Ln(),Fee(),OY()}));function GVe(e,t,n,r,i,a,o){qVe(e,t,n,r,i,a,o)}function KVe(e,t,n,r,i,a,o){let s=o?.id||`function-hook-${Date.now()}-${Math.random()}`;return qVe(e,t,n,r,{type:`function`,id:s,timeout:o?.timeout||5e3,callback:i,errorMessage:a}),s}function qVe(e,t,n,r,i,a,o){e(e=>{let s=e.sessionHooks.get(t)??{hooks:{}},c=s.hooks[n]||[],l=c.findIndex(e=>e.matcher===r&&e.skillRoot===o),u;if(l>=0){u=[...c];let e=u[l];u[l]={matcher:e.matcher,skillRoot:e.skillRoot,hooks:[...e.hooks,{hook:i,onHookSuccess:a}]}}else u=[...c,{matcher:r,skillRoot:o,hooks:[{hook:i,onHookSuccess:a}]}];let d={...s.hooks,[n]:u};return e.sessionHooks.set(t,{hooks:d}),e}),K(`Added session hook for event ${n} in session ${t}`)}function JVe(e,t,n,r){e(e=>{let i=e.sessionHooks.get(t);if(!i)return e;let a=(i.hooks[n]||[]).map(e=>{let t=e.hooks.filter(e=>!zVe(e.hook,r));return t.length>0?{...e,hooks:t}:null}).filter(e=>e!==null),o=a.length>0?{...i.hooks,[n]:a}:{...i.hooks};return a.length===0&&delete o[n],e.sessionHooks.set(t,{...i,hooks:o}),e}),K(`Removed session hook for event ${n} in session ${t}`)}function YVe(e){return e.map(e=>({matcher:e.matcher,skillRoot:e.skillRoot,hooks:e.hooks.map(e=>e.hook).filter(e=>e.type!==`function`)}))}function XVe(e,t,n){let r=e.sessionHooks.get(t);if(!r)return new Map;let i=new Map;if(n){let e=r.hooks[n];return e&&i.set(n,YVe(e)),i}for(let e of ot){let t=r.hooks[e];t&&i.set(e,YVe(t))}return i}function ZVe(e,t,n){let r=e.sessionHooks.get(t);if(!r)return new Map;let i=new Map,a=e=>e.map(e=>({matcher:e.matcher,hooks:e.hooks.map(e=>e.hook).filter(e=>e.type===`function`)})).filter(e=>e.hooks.length>0);if(n){let e=r.hooks[n];if(e){let t=a(e);t.length>0&&i.set(n,t)}return i}for(let e of ot){let t=r.hooks[e];if(t){let n=a(t);n.length>0&&i.set(e,n)}}return i}function QVe(e,t,n,r,i){let a=e.sessionHooks.get(t);if(!a)return;let o=a.hooks[n];if(o){for(let e of o)if(e.matcher===r||r===``){let t=e.hooks.find(e=>zVe(e.hook,i));if(t)return t}}}function DY(e,t){e(e=>(e.sessionHooks.delete(t),e)),K(`Cleared all session hooks for session ${t}`)}var OY=n((()=>{Pn(),q(),EY()}));function $Ve(e,t,n,r,i=!1){if(!n||Object.keys(n).length===0)return;let a=0;for(let o of ot){let s=n[o];if(!s||s.length===0)continue;let c=o;i&&o===`Stop`&&(c=`SubagentStop`,K(`Converting Stop hook to SubagentStop for ${r} (subagents trigger SubagentStop)`));for(let n of s){let r=n.matcher??``,i=n.hooks;if(!(!i||i.length===0))for(let n of i)GVe(e,t,c,r,n),a++}}a>0&&K(`Registered ${a} frontmatter hook(s) from ${r} for session ${t}`)}var eHe=n((()=>{Pn(),q(),OY()}));async function tHe(e,t){if(!e.mcpServers?.length)return{clients:t,tools:[],cleanup:async()=>{}};let n=ob(e.source);if(ab(`mcp`)&&!n)return K(`[Agent: ${e.agentType}] Skipping MCP servers: strictPluginOnlyCustomization locks MCP to plugin-only (agent source: ${e.source})`),{clients:t,tools:[],cleanup:async()=>{}};let r=[],i=[],a=[];for(let t of e.mcpServers){let n=null,o,s=!1;if(typeof t==`string`){if(o=t,n=XJ(t),!n){K(`[Agent: ${e.agentType}] MCP server not found: ${t}`,{level:`warn`});continue}}else{let r=Object.entries(t);if(r.length!==1){K(`[Agent: ${e.agentType}] Invalid MCP server spec: expected exactly one key`,{level:`warn`});continue}let[i,a]=r[0];o=i,n={...a,scope:`dynamic`},s=!0}let c=await yY(o,n);if(r.push(c),s&&i.push(c),c.type===`connected`){let t=await xY(c);a.push(...t),K(`[Agent: ${e.agentType}] Connected to MCP server '${o}' with ${t.length} tools`)}else K(`[Agent: ${e.agentType}] Failed to connect to MCP server '${o}': ${c.type}`,{level:`warn`})}let o=async()=>{for(let t of i)if(t.type===`connected`)try{await t.cleanup()}catch(n){K(`[Agent: ${e.agentType}] Error cleaning up MCP server '${t.name}': ${n}`,{level:`warn`})}};return{clients:[...t,...r],tools:a,cleanup:o}}function nHe(e){return e.type===`assistant`||e.type===`user`||e.type===`progress`||e.type===`system`&&`subtype`in e&&e.subtype===`compact_boundary`}async function*kY({agentDefinition:e,promptMessages:t,toolUseContext:n,canUseTool:r,isAsync:i,canShowPermissionPrompts:a,forkContextMessages:o,querySource:s,override:c,model:l,maxTurns:u,preserveToolUseResults:d,availableTools:f,allowedTools:p,onCacheSafeParams:m,contentReplacementState:h,useExactTools:g,worktreePath:_,description:v,transcriptSubdir:y,onQueryProgress:b}){let x=n.getAppState(),S=x.toolPermissionContext.mode,C=n.setAppStateForTasks??n.setAppState,w=WH(e.model,n.options.mainLoopModel,l,S),T=c?.agentId?c.agentId:JH();y&&h6(T,y),ese()&&(n.agentId??Wr(),e.agentType);let E=[...o?PH(o):[],...t],D=o===void 0?PT(100):LT(n.readFileState),[O,k]=await Promise.all([c?.userContext??pO(),c?.systemContext??fO()]),A=e.omitAgentsMd&&!c?.userContext&&!0,{agentsMd:ee,...te}=O,ne=A?te:O,{gitStatus:re,...ie}=k,ae=e.agentType===`Explore`||e.agentType===`Plan`?ie:k,j=e.permissionMode,oe=()=>{let e=n.getAppState(),t=e.toolPermissionContext;j&&e.toolPermissionContext.mode!==`bypassPermissions`&&e.toolPermissionContext.mode!==`acceptEdits`&&e.toolPermissionContext.mode!==`auto`&&(t={...t,mode:j});let r=a===void 0?j!==`bubble`&&i:!a;return r&&(t={...t,shouldAvoidPermissionPrompts:!0}),i&&!r&&(t={...t,awaitAutomatedChecksBeforeDialog:!0}),p!==void 0&&(t={...t,alwaysAllowRules:{cliArg:e.toolPermissionContext.alwaysAllowRules.cliArg,session:[...p]}}),t===e.toolPermissionContext?e:{...e,toolPermissionContext:t}},se=g?f:fU(e,f,i).resolvedTools,ce=Array.from(x.toolPermissionContext.additionalWorkingDirectories.keys()),M=c?.systemPrompt?c.systemPrompt:t_(await rHe(e,n,w,ce,se)),N=c?.abortController?c.abortController:i?new AbortController:n.abortController,le=[];for await(let t of Eat(T,e.agentType,N.signal))t.additionalContexts&&t.additionalContexts.length>0&&le.push(...t.additionalContexts);if(le.length>0){let e=a2({type:`hook_additional_context`,content:le,hookName:`SubagentStart`,toolUseID:Lc(),hookEvent:`SubagentStart`});E.push(e)}let ue=!ab(`hooks`)||ob(e.source);e.hooks&&ue&&$Ve(C,T,e.hooks,`agent '${e.agentType}'`,!0);let de=e.skills??[];if(de.length>0){let t=await $3(Hr()),r=[];for(let n of de){let i=iHe(n,t,e);if(!i){K(`[Agent: ${e.agentType}] Warning: Skill '${n}' specified in frontmatter was not found`,{level:`warn`});continue}let a=Xtt(i,t);if(a.type!==`prompt`){K(`[Agent: ${e.agentType}] Warning: Skill '${n}' is not a prompt-based skill`,{level:`warn`});continue}r.push({skillName:n,skill:a})}let{formatSkillLoadingMetadata:i}=await import(`./processSlashCommand-BcMLjAEQ.js`),a=await Promise.all(r.map(async({skillName:e,skill:t})=>({skillName:e,skill:t,content:await t.getPromptForCommand(``,n)})));for(let{skillName:t,skill:n,content:r}of a){K(`[Agent: ${e.agentType}] Preloaded skill '${t}'`);let a=i(t,n.progressMessage);E.push(Q({content:[{type:`text`,text:a},...r],isMeta:!0}))}}let{clients:fe,tools:pe,cleanup:me}=await tHe(e,n.options.mcpClients),he=pe.length>0?bm([...se,...pe],`name`):se,ge=o0(n,{options:{isNonInteractiveSession:g?n.options.isNonInteractiveSession:i?!0:n.options.isNonInteractiveSession??!1,appendSystemPrompt:n.options.appendSystemPrompt,tools:he,commands:[],debug:n.options.debug,verbose:n.options.verbose,mainLoopModel:w,thinkingConfig:g?n.options.thinkingConfig:{type:`disabled`},mcpClients:fe,mcpResources:n.options.mcpResources,agentDefinitions:n.options.agentDefinitions,...g&&{querySource:s}},agentId:T,agentType:e.agentType,messages:E,readFileState:D,abortController:N,getAppState:oe,shareSetAppState:!i,shareSetResponseLength:!0,criticalSystemReminder_EXPERIMENTAL:e.criticalSystemReminder_EXPERIMENTAL,contentReplacementState:h});d&&(ge.preserveToolUseResults=!0),m&&m({systemPrompt:M,userContext:ne,systemContext:ae,toolUseContext:ge,forkContextMessages:E}),w6(E,T).catch(e=>K(`Failed to record sidechain transcript: ${e}`)),v6(T,{agentType:e.agentType,..._&&{worktreePath:_},...v&&{description:v}}).catch(e=>K(`Failed to write agent metadata: ${e}`));let _e=E.at(-1)?.uuid??null;try{for await(let t of t0({messages:E,systemPrompt:M,userContext:ne,systemContext:ae,canUseTool:r,toolUseContext:ge,querySource:s,maxTurns:u??e.maxTurns})){if(b?.(),t.type===`stream_event`&&t.event.type===`message_start`&&t.ttftMs!=null){n.pushApiMetricsEntry?.(t.ttftMs);continue}if(t.type===`attachment`){if(t.attachment.type===`max_turns_reached`){K(`[Agent
1594
+ `}));function Gze(e){return!e.uri||!e.server?null:`Read resource "${e.uri}" from server "${e.server}"`}function Kze(){return`readMcpResource`}function qze(e,t,{verbose:n}){return!e?.contents||e.contents.length===0?(0,FJ.jsx)(P,{justifyContent:`space-between`,overflowX:`hidden`,width:`100%`,children:(0,FJ.jsx)($,{height:1,children:(0,FJ.jsx)(F,{dimColor:!0,children:`(No content)`})})}):(0,FJ.jsx)(pS,{content:W(e,null,2),verbose:n})}var FJ,Jze=n((()=>{dS(),hS(),Ze(),Li(),FJ=$e()})),Yze,Xze,IJ,LJ=n((()=>{Ms(),LK(),It(),wY(),rt(),Vze(),Li(),cS(),Wze(),Jze(),Yze=R(()=>z({server:B().describe(`The MCP server name`),uri:B().describe(`The resource URI to read`)})),Xze=R(()=>z({contents:I(z({uri:B().describe(`Resource URI`),mimeType:B().optional().describe(`MIME type of the content`),text:B().optional().describe(`Text content of the resource`),blobSavedTo:B().optional().describe(`Path where binary blob content was saved`)}))})),IJ=Cs({isConcurrencySafe(){return!0},isReadOnly(){return!0},toAutoClassifierInput(e){return`${e.server} ${e.uri}`},shouldDefer:!0,name:`ReadMcpResourceTool`,searchHint:`read a specific MCP resource by URI`,maxResultSizeChars:1e5,async description(){return Hze},async prompt(){return Uze},get inputSchema(){return Yze()},get outputSchema(){return Xze()},async call(e,{options:{mcpClients:t}}){let{server:n,uri:r}=e,i=t.find(e=>e.name===n);if(!i)throw Error(`Server "${n}" not found. Available servers: ${t.map(e=>e.name).join(`, `)}`);if(i.type!==`connected`)throw Error(`Server "${n}" is not connected`);if(!i.capabilities?.resources)throw Error(`Server "${n}" does not support resources`);let a=await(await fY(i)).client.request({method:`resources/read`,params:{uri:r}},dG);return{data:{contents:await Promise.all(a.contents.map(async(e,t)=>{if(`text`in e)return{uri:e.uri,mimeType:e.mimeType,text:e.text};if(!(`blob`in e)||typeof e.blob!=`string`)return{uri:e.uri,mimeType:e.mimeType};let r=`mcp-resource-${Date.now()}-${t}-${Math.random().toString(36).slice(2,8)}`,i=await zze(Buffer.from(e.blob,`base64`),e.mimeType,r);return`error`in i?{uri:e.uri,mimeType:e.mimeType,text:`Binary content could not be saved to disk: ${i.error}`}:{uri:e.uri,mimeType:e.mimeType,blobSavedTo:i.filepath,text:Bze(i.filepath,e.mimeType,i.size,`[Resource from ${n} at ${e.uri}] `)}}))}}},renderToolUseMessage:Gze,userFacingName:Kze,renderToolResultMessage:qze,isResultTruncated(e){return oS(W(e))},mapToolResultToToolResultBlockParam(e,t){return Fs(t,W(e))}})})),Zze,RJ,zJ,Qze=n((()=>{LK(),bn(),gi(),Li(),b(),Zze=0,RJ=1,zJ=class{constructor(e){if(x(this,`ws`,void 0),x(this,`started`,!1),x(this,`opened`,void 0),x(this,`isBun`,typeof Bun<`u`),x(this,`onclose`,void 0),x(this,`onerror`,void 0),x(this,`onmessage`,void 0),x(this,`onBunMessage`,e=>{try{let t=Si(typeof e.data==`string`?e.data:String(e.data)),n=fW.parse(t);this.onmessage?.(n)}catch(e){this.handleError(e)}}),x(this,`onBunError`,()=>{this.handleError(Error(`WebSocket error`))}),x(this,`onBunClose`,()=>{this.handleCloseCleanup()}),x(this,`onNodeMessage`,e=>{try{let t=Si(e.toString(`utf-8`)),n=fW.parse(t);this.onmessage?.(n)}catch(e){this.handleError(e)}}),x(this,`onNodeError`,e=>{this.handleError(e)}),x(this,`onNodeClose`,()=>{this.handleCloseCleanup()}),this.ws=e,this.opened=new Promise((e,t)=>{if(this.ws.readyState===RJ)e();else if(this.isBun){let n=this.ws,r=()=>{n.removeEventListener(`open`,r),n.removeEventListener(`error`,i),e()},i=e=>{n.removeEventListener(`open`,r),n.removeEventListener(`error`,i),Cn(`error`,`mcp_websocket_connect_fail`),t(e)};n.addEventListener(`open`,r),n.addEventListener(`error`,i)}else{let n=this.ws;n.on(`open`,()=>{e()}),n.on(`error`,e=>{Cn(`error`,`mcp_websocket_connect_fail`),t(e)})}}),this.isBun){let e=this.ws;e.addEventListener(`message`,this.onBunMessage),e.addEventListener(`error`,this.onBunError),e.addEventListener(`close`,this.onBunClose)}else{let e=this.ws;e.on(`message`,this.onNodeMessage),e.on(`error`,this.onNodeError),e.on(`close`,this.onNodeClose)}}handleError(e){Cn(`error`,`mcp_websocket_message_fail`),this.onerror?.(wi(e))}handleCloseCleanup(){if(this.onclose?.(),this.isBun){let e=this.ws;e.removeEventListener(`message`,this.onBunMessage),e.removeEventListener(`error`,this.onBunError),e.removeEventListener(`close`,this.onBunClose)}else{let e=this.ws;e.off(`message`,this.onNodeMessage),e.off(`error`,this.onNodeError),e.off(`close`,this.onNodeClose)}}async start(){if(this.started)throw Error(`Start can only be called once per transport.`);if(await this.opened,this.ws.readyState!==RJ)throw Cn(`error`,`mcp_websocket_start_not_opened`),Error(`WebSocket is not open. Cannot start transport.`);this.started=!0}async close(){(this.ws.readyState===RJ||this.ws.readyState===Zze)&&this.ws.close(),this.handleCloseCleanup()}async send(e){if(this.ws.readyState!==RJ)throw Cn(`error`,`mcp_websocket_send_not_opened`),Error(`WebSocket is not open. Cannot send message.`);let t=W(e);try{this.isBun?this.ws.send(t):await new Promise((e,n)=>{this.ws.send(t,t=>{t?n(t):e()})})}catch(e){throw this.handleError(e),e}}}}));function $ze(e){return e.mode===`url`?`url`:`form`}function eBe(e,t,n){return e.findIndex(e=>e.serverName===t&&e.params.mode===`url`&&`elicitationId`in e.params&&e.params.elicitationId===n)}function tBe(e,t,n){try{e.setRequestHandler(SK,async(e,r)=>{ba(t,`Received elicitation request: ${W(e)}`);let i=$ze(e.params);try{let a=await BJ(t,e.params,r.signal);if(a)return ba(t,`Elicitation resolved by hook: ${W(a)}`),a.action,a;let o=i===`url`&&`elicitationId`in e.params?e.params.elicitationId:void 0,s=await new Promise(i=>{let a=()=>{i({action:`cancel`})};if(r.signal.aborted){a();return}let s=o?{actionLabel:`Skip confirmation`}:void 0;n(n=>({...n,elicitation:{queue:[...n.elicitation.queue,{serverName:t,requestId:r.requestId,params:e.params,signal:r.signal,waitingState:s,respond:e=>{r.signal.removeEventListener(`abort`,a),e.action,i(e)}}]}})),r.signal.addEventListener(`abort`,a,{once:!0})});return ba(t,`Elicitation response: ${W(s)}`),await VJ(t,s,r.signal,i,o)}catch(e){return Sa(t,`Elicitation error: ${e}`),{action:`cancel`}}}),e.setNotificationHandler(wK,e=>{let{elicitationId:r}=e.params;ba(t,`Received elicitation completion notification: ${r}`),o7({message:`MCP server "${t}" confirmed elicitation ${r} complete`,notificationType:`elicitation_complete`});let i=!1;n(e=>{let n=eBe(e.elicitation.queue,t,r);if(n===-1)return e;i=!0;let a=[...e.elicitation.queue];return a[n]={...a[n],completed:!0},{...e,elicitation:{queue:a}}}),i||ba(t,`Ignoring completion notification for unknown elicitation: ${r}`)})}catch{return}}async function BJ(e,t,n){try{let r=t.mode===`url`?`url`:`form`,i=`url`in t?t.url:void 0,a=`elicitationId`in t?t.elicitationId:void 0,{elicitationResponse:o,blockingError:s}=await Nat({serverName:e,message:t.message,requestedSchema:`requestedSchema`in t?t.requestedSchema:void 0,signal:n,mode:r,url:i,elicitationId:a});return s?{action:`decline`}:o?{action:o.action,content:o.content}:void 0}catch(t){Sa(e,`Elicitation hook error: ${t}`);return}}async function VJ(e,t,n,r,i){try{let{elicitationResultResponse:a,blockingError:o}=await Pat({serverName:e,action:t.action,content:t.content,signal:n,mode:r,elicitationId:i});if(o)return o7({message:`Elicitation response for server "${e}": decline`,notificationType:`elicitation_response`}),{action:`decline`};let s=a?{action:a.action,content:a.content??t.content}:t;return o7({message:`Elicitation response for server "${e}": ${s.action}`,notificationType:`elicitation_response`}),s}catch(n){return Sa(e,`ElicitationResult hook error: ${n}`),o7({message:`Elicitation response for server "${e}": ${t.action}`,notificationType:`elicitation_response`}),t}}var nBe=n((()=>{LK(),_7(),wa(),Li(),La()}));async function rBe(e,t,n){try{K(`Loading MCP servers from MCPB: ${t}`);let n=e.repository,r=await tI(t,e.path,n,t=>{K(`MCPB [${e.name}]: ${t}`)});if(`status`in r&&r.status===`needs-config`)return K(`MCPB ${t} requires user configuration. User can configure via: /plugin → Manage plugins → ${e.name} → Configure`),null;let i=r,a=i.manifest.name;return K(`Loaded MCP server "${a}" from MCPB (extracted to ${i.extractedPath})`),{[a]:i.mcpConfig}}catch(r){let i=G(r);K(`Failed to load MCPB ${t}: ${i}`,{level:`error`});let a=`${e.name}@${e.repository}`;return t.startsWith(`http`)&&(i.includes(`download`)||i.includes(`network`))?n.push({type:`mcpb-download-failed`,source:a,plugin:e.name,url:t,reason:i}):i.includes(`manifest`)||i.includes(`user configuration`)?n.push({type:`mcpb-invalid-manifest`,source:a,plugin:e.name,mcpbPath:t,validationError:i}):n.push({type:`mcpb-extract-failed`,source:a,plugin:e.name,mcpbPath:t,reason:i}),null}}async function iBe(e,t=[]){let n={},r=await HJ(e.path,`.mcp.json`);if(r&&(n={...n,...r}),e.manifest.mcpServers){let r=e.manifest.mcpServers;if(typeof r==`string`)if(WF(r)){let i=await rBe(e,r,t);i&&(n={...n,...i})}else{let t=await HJ(e.path,r);t&&(n={...n,...t})}else if(Array.isArray(r)){let i=await Promise.all(r.map(async n=>{try{return typeof n==`string`?WF(n)?await rBe(e,n,t):await HJ(e.path,n):n}catch(t){return K(`Failed to load MCP servers from spec for plugin ${e.name}: ${t}`,{level:`error`}),null}}));for(let e of i)e&&(n={...n,...e})}else n={...n,...r}}return Object.keys(n).length>0?n:void 0}async function HJ(e,t){let n=J(),r=X(e,t),i;try{i=await n.readFile(r,{encoding:`utf-8`})}catch(e){return xi(e)||K(`Failed to load MCP servers from ${r}: ${e}`,{level:`error`}),null}try{let e=Si(i),t=e.mcpServers||e,n={};for(let[e,i]of Object.entries(t)){let t=ut().safeParse(i);t.success?n[e]=t.data:K(`Invalid MCP server config for ${e} in ${r}: ${t.error.message}`,{level:`error`})}return n}catch(e){return K(`Failed to load MCP servers from ${r}: ${e}`,{level:`error`}),null}}function aBe(e){let t=e.manifest.channels;if(!t||t.length===0)return[];let n=e.repository,r=[];for(let e of t)!e.userConfig||Object.keys(e.userConfig).length===0||ZF(YF(n,e.server)??{},e.userConfig).valid||r.push({server:e.server,displayName:e.displayName??e.server,configSchema:e.userConfig});return r}function oBe(e,t){if(e.manifest.channels?.find(e=>e.server===t)?.userConfig)return YF(e.repository,t)??void 0}function sBe(e,t,n){let r={};for(let[i,a]of Object.entries(e)){let e=`plugin:${t}:${i}`;r[e]={...a,scope:`dynamic`,pluginSource:n}}return r}function cBe(e,t){let n=e.manifest.userConfig?lI(rI(e)):void 0,r=oBe(e,t);if(!(!n&&!r))return{...n,...r}}function lBe(e,t,n,r,i,a){let o=[],s=e=>{let r=oI(e,t);n&&(r=sI(r,n));let{expanded:i,missingVars:a}=CF(r);return o.push(...a),i},c;switch(e.type){case void 0:case`stdio`:{let n={...e};n.command&&(n.command=s(n.command)),n.args&&(n.args=n.args.map(e=>s(e)));let r={CLAUDE_PLUGIN_ROOT:t.path,CLAUDE_PLUGIN_DATA:ny(t.source),...n.env||{}};for(let[e,t]of Object.entries(r))e!==`CLAUDE_PLUGIN_ROOT`&&e!==`CLAUDE_PLUGIN_DATA`&&(r[e]=s(t));n.env=r,c=n;break}case`sse`:case`http`:case`ws`:{let t={...e};if(t.url&&(t.url=s(t.url)),t.headers){let e={};for(let[n,r]of Object.entries(t.headers))e[n]=s(r);t.headers=e}c=t;break}case`sse-ide`:case`ws-ide`:case`sdk`:case`claudeai-proxy`:c=e;break}if(r&&o.length>0){let e=[...new Set(o)].join(`, `);K(`Missing environment variables in plugin MCP config: ${e}`,{level:`warn`}),i&&a&&r.push({type:`mcp-config-invalid`,source:`plugin:${i}`,plugin:i,serverName:a,validationError:`Missing environment variables: ${e}`})}return c}async function uBe(e,t=[]){if(!e.enabled)return;let n=e.mcpServers||await iBe(e,t);if(!n)return;let r={};for(let[i,a]of Object.entries(n)){let n=cBe(e,i);try{r[i]=lBe(a,e,n,t,e.name,i)}catch(n){t?.push({type:`generic-error`,source:i,plugin:e.name,error:G(n)})}}return sBe(r,e.name,e.source)}var dBe=n((()=>{wF(),pr(),q(),gi(),ki(),Li(),nI(),ry(),uI()}));function UJ(){return X(ir(),`managed-mcp.json`)}function WJ(e,t){if(!e)return{};let n={};for(let[r,i]of Object.entries(e))n[r]={...i,scope:t};return n}async function fBe(e){let t=X(U(),`.mcp.json`),n;try{n=(await Yc(t)).mode}catch(e){if(yi(e)!==`ENOENT`)throw e}let r=`${t}.tmp.${process.pid}.${Date.now()}`,i=await Uc(r,`w`,n??420);try{await i.writeFile(W(e,null,2),{encoding:`utf8`}),await i.datasync()}finally{await i.close()}try{n!==void 0&&await zc(r,n),await qc(r,t)}catch(e){try{await Zc(r)}catch{}throw e}}function GJ(e){if(e.type!==void 0&&e.type!==`stdio`)return null;let t=e;return[t.command,...t.args??[]]}function pBe(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function KJ(e){return`url`in e?e.url:null}function mBe(e){if(!jBe.some(t=>e.includes(t)))return e;try{return new URL(e).searchParams.get(`mcp_url`)||e}catch{return e}}function hBe(e){let t=GJ(e);if(t)return`stdio:${W(t)}`;let n=KJ(e);return n?`url:${mBe(n)}`:null}function gBe(e,t){let n=new Map;for(let[e,r]of Object.entries(t)){let t=hBe(r);t&&!n.has(t)&&n.set(t,e)}let r={},i=[],a=new Map;for(let[t,o]of Object.entries(e)){let e=hBe(o);if(e===null){r[t]=o;continue}let s=n.get(e);if(s!==void 0){K(`Suppressing plugin MCP server "${t}": duplicates manually-configured "${s}"`),i.push({name:t,duplicateOf:s});continue}let c=a.get(e);if(c!==void 0){K(`Suppressing plugin MCP server "${t}": duplicates earlier plugin server "${c}"`),i.push({name:t,duplicateOf:c});continue}a.set(e,t),r[t]=o}return{servers:r,suppressed:i}}function _Be(e){let t=e.replace(/[.+?^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`.*`);return RegExp(`^${t}$`)}function vBe(e,t){return _Be(t).test(e)}function yBe(){return DBe()?$n(`policySettings`)??{}:rr()}function bBe(){return rr()}function xBe(e,t){let n=bBe();if(!n.deniedMcpServers)return!1;for(let t of n.deniedMcpServers)if(Ft(t)&&t.serverName===e)return!0;if(t){let e=GJ(t);if(e){for(let t of n.deniedMcpServers)if(jt(t)&&pBe(t.serverCommand,e))return!0}let r=KJ(t);if(r){for(let e of n.deniedMcpServers)if(ft(e)&&vBe(r,e.serverUrl))return!0}}return!1}function qJ(e,t){if(xBe(e,t))return!1;let n=yBe();if(!n.allowedMcpServers)return!0;if(n.allowedMcpServers.length===0)return!1;let r=n.allowedMcpServers.some(jt),i=n.allowedMcpServers.some(ft);if(t){let a=GJ(t),o=KJ(t);if(a)if(r){for(let e of n.allowedMcpServers)if(jt(e)&&pBe(e.serverCommand,a))return!0;return!1}else{for(let t of n.allowedMcpServers)if(Ft(t)&&t.serverName===e)return!0;return!1}else if(o)if(i){for(let e of n.allowedMcpServers)if(ft(e)&&vBe(o,e.serverUrl))return!0;return!1}else{for(let t of n.allowedMcpServers)if(Ft(t)&&t.serverName===e)return!0;return!1}else{for(let t of n.allowedMcpServers)if(Ft(t)&&t.serverName===e)return!0;return!1}}for(let t of n.allowedMcpServers)if(Ft(t)&&t.serverName===e)return!0;return!1}function SBe(e){let t={},n=[];for(let[r,i]of Object.entries(e)){let e=i;e.type===`sdk`||qJ(r,e)?t[r]=i:n.push(r)}return{allowed:t,blocked:n}}function CBe(e){let t=[];function n(e){let{expanded:n,missingVars:r}=CF(e);return t.push(...r),n}let r;switch(e.type){case void 0:case`stdio`:{let t=e;r={...t,command:n(t.command),args:t.args.map(n),env:t.env?cm(t.env,n):void 0};break}case`sse`:case`http`:case`ws`:{let t=e;r={...t,url:n(t.url),headers:t.headers?cm(t.headers,n):void 0};break}case`sse-ide`:case`ws-ide`:r=e;break;case`sdk`:r=e;break;case`claudeai-proxy`:r=e;break}return{expanded:r,missingVars:[...new Set(t)]}}async function wBe(e,t,n){if(e.match(/[^a-zA-Z0-9_-]/))throw Error(`Invalid name ${e}. Names can only contain letters, numbers, hyphens, and underscores.`);if(nY())throw Error(`Cannot add MCP server: enterprise MCP configuration is active and has exclusive control over MCP servers`);let r=ut().safeParse(t);if(!r.success){let e=r.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`, `);throw Error(`Invalid configuration: ${e}`)}let i=r.data;if(xBe(e,i))throw Error(`Cannot add MCP server "${e}": server is explicitly blocked by enterprise policy`);if(!qJ(e,i))throw Error(`Cannot add MCP server "${e}": not allowed by enterprise policy`);switch(n){case`project`:{let{servers:t}=JJ();if(t[e])throw Error(`MCP server ${e} already exists in .mcp.json`);break}case`user`:if(qi().mcpServers?.[e])throw Error(`MCP server ${e} already exists in user config`);break;case`local`:if(Vi().mcpServers?.[e])throw Error(`MCP server ${e} already exists in local config`);break;case`dynamic`:throw Error(`Cannot add MCP server to scope: dynamic`);case`enterprise`:throw Error(`Cannot add MCP server to scope: enterprise`);case`claudeai`:throw Error(`Cannot add MCP server to scope: claudeai`)}switch(n){case`project`:{let{servers:t}=JJ(),n={};for(let[e,r]of Object.entries(t)){let{scope:t,...i}=r;n[e]=i}n[e]=i;let r={mcpServers:n};try{await fBe(r)}catch(e){throw Error(`Failed to write to .mcp.json: ${e}`)}break}case`user`:Gi(t=>({...t,mcpServers:{...t.mcpServers,[e]:i}}));break;case`local`:Ki(t=>({...t,mcpServers:{...t.mcpServers,[e]:i}}));break;default:throw Error(`Cannot add MCP server to scope: ${n}`)}}async function TBe(e,t){switch(t){case`project`:{let{servers:t}=JJ();if(!t[e])throw Error(`No MCP server found with name: ${e} in .mcp.json`);let n={};for(let[r,i]of Object.entries(t))if(r!==e){let{scope:e,...t}=i;n[r]=t}let r={mcpServers:n};try{await fBe(r)}catch(e){throw Error(`Failed to remove from .mcp.json: ${e}`)}break}case`user`:if(!qi().mcpServers?.[e])throw Error(`No user-scoped MCP server found with name: ${e}`);Gi(t=>{let{[e]:n,...r}=t.mcpServers??{};return{...t,mcpServers:r}});break;case`local`:if(!Vi().mcpServers?.[e])throw Error(`No project-local MCP server found with name: ${e}`);Ki(t=>{let{[e]:n,...r}=t.mcpServers??{};return{...t,mcpServers:r}});break;default:throw Error(`Cannot remove MCP server from scope: ${t}`)}}function JJ(){if(!Dn(`projectSettings`))return{servers:{},errors:[]};let e=X(U(),`.mcp.json`),{config:t,errors:n}=$J({filePath:e,expandVars:!0,scope:`project`});if(!t){let t=n.filter(e=>!e.message.startsWith(`MCP config file not found`));return t.length>0?(K(`MCP config errors for ${e}: ${W(t.map(e=>e.message))}`,{level:`error`}),{servers:{},errors:t}):{servers:{},errors:[]}}return{servers:t.mcpServers?WJ(t.mcpServers,`project`):{},errors:n||[]}}function YJ(e){let t={project:`projectSettings`,user:`userSettings`,local:`localSettings`};if(e in t&&!Dn(t[e]))return{servers:{},errors:[]};switch(e){case`project`:{let t={},n=[],r=[],i=U();for(;i!==gc(i).root;)r.push(i),i=fc(i);for(let i of r.reverse()){let r=X(i,`.mcp.json`),{config:a,errors:o}=$J({filePath:r,expandVars:!0,scope:`project`});if(!a){let e=o.filter(e=>!e.message.startsWith(`MCP config file not found`));e.length>0&&(K(`MCP config errors for ${r}: ${W(e.map(e=>e.message))}`,{level:`error`}),n.push(...e));continue}a.mcpServers&&Object.assign(t,WJ(a.mcpServers,e)),o.length>0&&n.push(...o)}return{servers:t,errors:n}}case`user`:{let t=qi().mcpServers;if(!t)return{servers:{},errors:[]};let{config:n,errors:r}=QJ({configObject:{mcpServers:t},expandVars:!0,scope:`user`});return{servers:WJ(n?.mcpServers,e),errors:r}}case`local`:{let t=Vi().mcpServers;if(!t)return{servers:{},errors:[]};let{config:n,errors:r}=QJ({configObject:{mcpServers:t},expandVars:!0,scope:`local`});return{servers:WJ(n?.mcpServers,e),errors:r}}case`enterprise`:{let t=UJ(),{config:n,errors:r}=$J({filePath:t,expandVars:!0,scope:`enterprise`});if(!n){let e=r.filter(e=>!e.message.startsWith(`MCP config file not found`));return e.length>0?(K(`Enterprise MCP config errors for ${t}: ${W(e.map(e=>e.message))}`,{level:`error`}),{servers:{},errors:e}):{servers:{},errors:[]}}return{servers:WJ(n.mcpServers,e),errors:r}}}}function XJ(e){let{servers:t}=YJ(`enterprise`);if(ab(`mcp`))return t[e]??null;let{servers:n}=YJ(`user`),{servers:r}=YJ(`project`),{servers:i}=YJ(`local`);return t[e]?t[e]:i[e]?i[e]:r[e]?r[e]:n[e]?n[e]:null}async function ZJ(e={},t=Promise.resolve({})){let{servers:n}=YJ(`enterprise`);if(nY()){let e={};for(let[t,r]of Object.entries(n))qJ(t,r)&&(e[t]=r);return{servers:e,errors:[]}}let r=ab(`mcp`),i={servers:{}},{servers:a}=r?i:YJ(`user`),{servers:o}=r?i:YJ(`project`),{servers:s}=r?i:YJ(`local`),c={},l=await R4(),u=[];if(l.errors.length>0)for(let e of l.errors)if(e.type===`mcp-config-invalid`||e.type===`mcpb-download-failed`||e.type===`mcpb-extract-failed`||e.type===`mcpb-invalid-manifest`){let t=`Plugin MCP loading error - ${e.type}: ${uv(e)}`;Y(Error(t))}else{let t=e.type;K(`Plugin not available for MCP: ${e.source} - error type: ${t}`)}let d=await Promise.all(l.enabled.map(e=>uBe(e,u)));for(let e of d)e&&Object.assign(c,e);if(u.length>0)for(let e of u){let t=`Plugin MCP server error - ${e.type}: ${uv(e)}`;Y(Error(t))}let f={};for(let[e,t]of Object.entries(o))GBe(e)===`approved`&&(f[e]=t);let p=await t,m={};for(let[t,n]of Object.entries({...a,...f,...s,...e,...p}))!tY(t)&&qJ(t,n)&&(m[t]=n);let h={},g={};for(let[e,t]of Object.entries(c))tY(e)||!qJ(e,t)?g[e]=t:h[e]=t;let{servers:_,suppressed:v}=gBe(h,m);Object.assign(_,g);for(let{name:e,duplicateOf:t}of v){let n=e.split(`:`);n[0]!==`plugin`||n.length<3||u.push({type:`mcp-server-suppressed-duplicate`,source:e,plugin:n[1],serverName:n.slice(2).join(`:`),duplicateOf:t})}let y=Object.assign({},_,a,f,s),b={};for(let[e,t]of Object.entries(y))qJ(e,t)&&(b[e]=t);return{servers:b,errors:u}}async function EBe(){if(nY())return ZJ();let{servers:e,errors:t}=await ZJ();return{servers:e,errors:t}}function QJ(e){let{configObject:t,expandVars:n,scope:r,filePath:i}=e,a=Bee().safeParse(t);if(!a.success)return{config:null,errors:a.error.issues.map(e=>({...i&&{file:i},path:e.path.join(`.`),message:`Does not adhere to MCP server configuration schema`,mcpErrorMetadata:{scope:r,severity:`fatal`}}))};let o=[],s={};for(let[e,t]of Object.entries(a.data.mcpServers)){let a=t;if(n){let{expanded:n,missingVars:s}=CBe(t);s.length>0&&o.push({...i&&{file:i},path:`mcpServers.${e}`,message:`Missing environment variables: ${s.join(`, `)}`,suggestion:`Set the following environment variables: ${s.join(`, `)}`,mcpErrorMetadata:{scope:r,serverName:e,severity:`warning`}}),a=n}Ma()===`windows`&&(!a.type||a.type===`stdio`)&&`command`in a&&(a.command===`npx`||a.command.endsWith(`\\npx`)||a.command.endsWith(`/npx`))&&o.push({...i&&{file:i},path:`mcpServers.${e}`,message:`Windows requires 'cmd /c' wrapper to execute npx`,suggestion:`Change command to "cmd" with args ["/c", "npx", ...]. See: https://code.workmate.com/docs/en/mcp#configure-mcp-servers`,mcpErrorMetadata:{scope:r,serverName:e,severity:`warning`}}),s[e]=a}return{config:{mcpServers:s},errors:o}}function $J(e){let{filePath:t,expandVars:n,scope:r}=e,i=J(),a;try{a=i.readFileSync(t,{encoding:`utf8`})}catch(e){return yi(e)===`ENOENT`?{config:null,errors:[{file:t,path:``,message:`MCP config file not found: ${t}`,suggestion:`Check that the file path is correct`,mcpErrorMetadata:{scope:r,severity:`fatal`}}]}:(K(`MCP config read error for ${t} (scope=${r}): ${e}`,{level:`error`}),{config:null,errors:[{file:t,path:``,message:`Failed to read file: ${e}`,suggestion:`Check file permissions and ensure the file exists`,mcpErrorMetadata:{scope:r,severity:`fatal`}}]})}let o=mn(a);return o?QJ({configObject:o,expandVars:n,scope:r,filePath:t}):(K(`MCP config is not valid JSON: ${t} (scope=${r}, length=${a.length}, first100=${W(a.slice(0,100))})`,{level:`error`}),{config:null,errors:[{file:t,path:``,message:`MCP config is not a valid JSON`,suggestion:`Fix the JSON syntax errors in the file`,mcpErrorMetadata:{scope:r,severity:`fatal`}}]})}function DBe(){return $n(`policySettings`)?.allowManagedMcpServersOnly===!0}function OBe(e){return Object.values(e).every(e=>e.type===`sdk`&&e.name===`claude-vscode`)}function eY(e){return MBe.has(e)}function tY(e){let t=Vi();return eY(e)?!(t.enabledMcpServers||[]).includes(e):(t.disabledMcpServers||[]).includes(e)}function kBe(e,t,n){return e.includes(t)===n?e:n?[...e,t]:e.filter(e=>e!==t)}function ABe(e,t){eY(e)&&tY(e),Ki(n=>{if(eY(e)){let r=n.enabledMcpServers||[],i=kBe(r,e,t);return i===r?n:{...n,enabledMcpServers:i}}let r=n.disabledMcpServers||[],i=kBe(r,e,!t);return i===r?n:{...n,disabledMcpServers:i}})}var jBe,nY,MBe,rY=n((()=>{lm(),d(),Pa(),dv(),Wi(),ui(),q(),gi(),ki(),ur(),wa(),dBe(),z4(),Rn(),Zn(),sb(),Ln(),At(),Li(),La(),wF(),pr(),oY(),jBe=[`/v2/session_ingress/shttp/mcp/`,`/v2/ccr-sessions/`],nY=u(()=>{let{config:e}=$J({filePath:UJ(),expandVars:!0,scope:`enterprise`});return e!==null}),MBe=new Set([])}));function NBe(e,t){let n=`mcp__${pn(t)}__`;return e.filter(e=>e.name?.startsWith(n))}function iY(e,t){let n=pn(t),r=e.name;return r?r.startsWith(`mcp__${n}__`)||r.startsWith(`${n}:`):!1}function PBe(e,t){return e.filter(e=>iY(e,t)&&!(e.type===`prompt`&&e.loadedFrom===`mcp`))}function FBe(e,t){let n=`mcp__${pn(t)}__`;return e.filter(e=>!e.name?.startsWith(n))}function IBe(e,t){return e.filter(e=>!iY(e,t))}function LBe(e,t){let n={...e};return delete n[t],n}function RBe(e){let{scope:t,...n}=e,r=W(n,(e,t)=>{if(t&&typeof t==`object`&&!Array.isArray(t)){let e=t,n={};for(let t of Object.keys(e).sort())n[t]=e[t];return n}return t});return Fc(`sha256`).update(r).digest(`hex`).slice(0,16)}function zBe(e,t){let n=e.clients.filter(e=>{let n=t[e.name];return n?RBe(e.config)!==RBe(n):e.config.scope===`dynamic`});if(n.length===0)return{...e,stale:[]};let{tools:r,commands:i,resources:a}=e;for(let e of n)r=FBe(r,e.name),i=IBe(i,e.name),a=LBe(a,e.name);let o=new Set(n.map(e=>e.name));return{clients:e.clients.filter(e=>!o.has(e.name)),tools:r,commands:i,resources:a,stale:n}}function aY(e){return e.name?.startsWith(`mcp__`)||e.isMcp===!0}function BBe(e){switch(e){case`user`:return sn();case`project`:return X(U(),`.mcp.json`);case`local`:return`${sn()} [project: ${U()}]`;case`dynamic`:return`Dynamically configured`;case`enterprise`:return UJ();case`claudeai`:return`claude.ai`;default:return e}}function VBe(e){switch(e){case`local`:return`Local config (private to you in this project)`;case`project`:return`Project config (shared via .mcp.json)`;case`user`:return`User config (available in all your projects)`;case`dynamic`:return`Dynamic config (from command line)`;case`enterprise`:return`Enterprise config (managed by your organization)`;case`claudeai`:return`claude.ai config`;default:return e}}function HBe(e){if(!e)return`local`;if(!hr().options.includes(e))throw Error(`Invalid scope: ${e}. Must be one of: ${hr().options.join(`, `)}`);return e}function UBe(e){if(!e)return`stdio`;if(e!==`stdio`&&e!==`sse`&&e!==`http`)throw Error(`Invalid transport type: ${e}. Must be one of: stdio, sse, http`);return e}function WBe(e){let t={};for(let n of e){let e=n.indexOf(`:`);if(e===-1)throw Error(`Invalid header format: "${n}". Expected format: "Header-Name: value"`);let r=n.substring(0,e).trim(),i=n.substring(e+1).trim();if(!r)throw Error(`Invalid header: "${n}". Header name cannot be empty.`);t[r]=i}return t}function GBe(e){let t=yn(),n=pn(e);return t?.disabledMcpjsonServers?.some(e=>pn(e)===n)?`rejected`:t?.enabledMcpjsonServers?.some(e=>pn(e)===n)||t?.enableAllProjectMcpServers||Nte()&&Dn(`projectSettings`)||kr()&&Dn(`projectSettings`)?`approved`:`pending`}function KBe(e){if(!aY({name:e}))return null;let t=Qn(e);if(!t)return null;let n=XJ(t.serverName);return!n&&t.serverName.startsWith(`claude_ai_`)?`claudeai`:n?.scope??null}function qBe(e){return e.type===`stdio`||e.type===void 0}function JBe(e){return e.type===`sse`}function YBe(e){return e.type===`http`}function XBe(e){return e.type===`ws`}function ZBe(e){let t=new Map;for(let n of e)if(n.mcpServers?.length)for(let e of n.mcpServers){if(typeof e==`string`)continue;let r=Object.entries(e);if(r.length!==1)continue;let[i,a]=r[0],o=t.get(i);o?o.sourceAgents.includes(n.agentType)||o.sourceAgents.push(n.agentType):t.set(i,{config:{...a,name:i},sourceAgents:[n.agentType]})}let n=[];for(let[e,{config:r,sourceAgents:i}]of t)qBe(r)?n.push({name:e,sourceAgents:i,transport:`stdio`,command:r.command,needsAuth:!1}):JBe(r)?n.push({name:e,sourceAgents:i,transport:`sse`,url:r.url,needsAuth:!0}):YBe(r)?n.push({name:e,sourceAgents:i,transport:`http`,url:r.url,needsAuth:!0}):XBe(r)&&n.push({name:e,sourceAgents:i,transport:`ws`,url:r.url,needsAuth:!1});return n.sort((e,t)=>e.name.localeCompare(t.name))}function QBe(e){if(!(!(`url`in e)||typeof e.url!=`string`))try{let t=new URL(e.url);return t.search=``,t.toString().replace(/\/$/,``)}catch{return}}var oY=n((()=>{H(),ui(),nn(),Rn(),Ln(),Li(),rY(),Bn(),jn(),pr()}));function $Be(e){return e.replace(/([a-z])([A-Z])/g,`$1_$2`).replace(/-/g,`_`).toLowerCase()}function eVe(e,t){let n=$Be(t);return{isSearch:tVe.has(n),isRead:nVe.has(n)}}var tVe,nVe,rVe=n((()=>{tVe=new Set(`slack_search_public.slack_search_public_and_private.slack_search_channels.slack_search_users.search_code.search_repositories.search_issues.search_pull_requests.search_orgs.search_users.search_documentation.search_logs.search_spans.search_rum_events.search_audit_logs.search_monitors.search_monitor_groups.find_slow_spans.find_monitors_matching_pattern.search_docs.search_events.search_issue_events.find_organizations.find_teams.find_projects.find_releases.find_dsns.search.gmail_search_messages.google_drive_search.gcal_find_my_free_time.gcal_find_meeting_times.gcal_find_user_emails.search_jira_issues_using_jql.search_confluence_using_cql.lookup_jira_account_id.confluence_search.jira_search.jira_search_fields.asana_search_tasks.asana_typeahead_search.search_files.search_nodes.brave_web_search.brave_local_search.search_dashboards.search_folders.search_docs.search_stripe_resources.search_stripe_documentation.search_articles.find_related_articles.lookup_article_by_citation.search_papers.search_pubmed.search_pubmed_key_words.search_pubmed_advanced.pubmed_search.pubmed_mesh_lookup.firecrawl_search.web_search_exa.web_search_advanced_exa.people_search_exa.linkedin_search_exa.deep_search_exa.perplexity_search.perplexity_search_web.tavily_search.obsidian_simple_search.obsidian_complex_search.find.search_knowledge.search_memories.find_memories_by_name.search_records.find_tasks.find_tasks_by_date.find_completed_tasks.find_projects.find_sections.find_comments.find_project_collaborators.find_activity.find_labels.find_filters.search_documentation.search_catalog.search_modules.search_providers.search_policies`.split(`.`)),nVe=new Set(`slack_read_channel.slack_read_thread.slack_read_canvas.slack_read_user_profile.slack_list_channels.slack_get_channel_history.slack_get_thread_replies.slack_get_users.slack_get_user_profile.get_me.get_team_members.get_teams.get_commit.get_file_contents.get_repository_tree.list_branches.list_commits.list_releases.list_tags.get_latest_release.get_release_by_tag.get_tag.list_issues.issue_read.list_issue_types.get_label.list_label.pull_request_read.get_gist.list_gists.list_notifications.get_notification_details.projects_list.projects_get.actions_get.actions_list.get_job_logs.get_code_scanning_alert.list_code_scanning_alerts.get_dependabot_alert.list_dependabot_alerts.get_secret_scanning_alert.list_secret_scanning_alerts.get_global_security_advisory.list_global_security_advisories.list_org_repository_security_advisories.list_repository_security_advisories.get_discussion.get_discussion_comments.list_discussion_categories.list_discussions.list_starred_repositories.get_issue.get_pull_request.list_pull_requests.get_pull_request_files.get_pull_request_status.get_pull_request_comments.get_pull_request_reviews.list_comments.list_cycles.get_document.list_documents.list_issue_statuses.get_issue_status.list_my_issues.list_issue_labels.list_projects.get_project.list_project_labels.list_teams.get_team.list_users.get_user.aggregate_logs.list_spans.aggregate_spans.analyze_trace.trace_critical_path.query_metrics.aggregate_rum_events.list_rum_metrics.get_rum_metric.list_monitors.get_monitor.check_can_delete_monitor.validate_monitor.validate_existing_monitor.list_dashboards.get_dashboard.query_dashboard_widget.list_notebooks.get_notebook.query_notebook_cell.get_profiling_metrics.compare_profiling_metrics.whoami.get_issue_details.get_issue_tag_values.get_trace_details.get_event_attachment.get_doc.get_sentry_resource.list_events.list_issue_events.get_sentry_issue.fetch.get_comments.get_users.get_self.gmail_get_profile.gmail_read_message.gmail_read_thread.gmail_list_drafts.gmail_list_labels.google_drive_fetch.google_drive_export.gcal_list_calendars.gcal_list_events.gcal_get_event.atlassian_user_info.get_accessible_atlassian_resources.get_visible_jira_projects.get_jira_project_issue_types_metadata.get_jira_issue.get_transitions_for_jira_issue.get_jira_issue_remote_issue_links.get_confluence_spaces.get_confluence_page.get_pages_in_confluence_space.get_confluence_page_ancestors.get_confluence_page_descendants.get_confluence_page_footer_comments.get_confluence_page_inline_comments.confluence_get_page.confluence_get_page_children.confluence_get_comments.confluence_get_labels.jira_get_issue.jira_get_transitions.jira_get_worklog.jira_get_agile_boards.jira_get_board_issues.jira_get_sprints_from_board.jira_get_sprint_issues.jira_get_link_types.jira_download_attachments.jira_batch_get_changelogs.jira_get_user_profile.jira_get_project_issues.jira_get_project_versions.asana_get_attachment.asana_get_attachments_for_object.asana_get_goal.asana_get_goals.asana_get_parent_goals_for_goal.asana_get_portfolio.asana_get_portfolios.asana_get_items_for_portfolio.asana_get_project.asana_get_projects.asana_get_project_sections.asana_get_project_status.asana_get_project_statuses.asana_get_project_task_counts.asana_get_projects_for_team.asana_get_projects_for_workspace.asana_get_task.asana_get_tasks.asana_get_stories_for_task.asana_get_teams_for_workspace.asana_get_teams_for_user.asana_get_team_users.asana_get_time_period.asana_get_time_periods.asana_get_user.asana_get_workspace_users.asana_list_workspaces.read_file.read_text_file.read_media_file.read_multiple_files.list_directory.list_directory_with_sizes.directory_tree.get_file_info.list_allowed_directories.read_graph.open_nodes.query.read_query.list_tables.describe_table.git_status.git_diff.git_diff_unstaged.git_diff_staged.git_log.git_show.git_branch.list_teams.list_users_by_org.get_dashboard_by_uid.get_dashboard_summary.get_dashboard_property.get_dashboard_panel_queries.run_panel_query.list_datasources.get_datasource.get_query_examples.query_prometheus.query_prometheus_histogram.list_prometheus_metric_metadata.list_prometheus_metric_names.list_prometheus_label_names.list_prometheus_label_values.query_loki_logs.query_loki_stats.query_loki_patterns.list_loki_label_names.list_loki_label_values.list_incidents.get_incident.list_sift_investigations.get_sift_investigation.get_sift_analysis.list_oncall_schedules.get_oncall_shift.get_current_oncall_users.list_oncall_teams.list_oncall_users.list_alert_groups.get_alert_group.get_annotations.get_annotation_tags.get_panel_image.list_incidents.get_incident.get_outlier_incident.get_past_incidents.get_related_incidents.list_incident_notes.list_incident_workflows.get_incident_workflow.list_services.get_service.list_team_members.get_user_data.list_schedules.get_schedule.list_schedule_users.list_oncalls.list_log_entries.get_log_entry.list_escalation_policies.get_escalation_policy.list_event_orchestrations.get_event_orchestration.list_status_pages.get_status_page_post.list_alerts_from_incident.get_alert_from_incident.list_change_events.get_change_event.list_organizations.get_organization.get_cost.list_extensions.list_migrations.get_logs.get_advisors.get_project_url.get_publishable_keys.generate_typescript_types.list_edge_functions.get_edge_function.list_storage_buckets.get_storage_config.get_stripe_account_info.retrieve_balance.list_customers.list_products.list_prices.list_invoices.list_payment_intents.list_subscriptions.list_coupons.list_disputes.fetch_stripe_resources.get_article_metadata.get_full_text_article.convert_article_ids.get_copyright_status.download_paper.list_papers.read_paper.get_paper_fulltext.get_pubmed_article_metadata.download_pubmed_pdf.pubmed_fetch.pubmed_pmc_fetch.pubmed_spell.pubmed_cite.pubmed_related.bigquery_query.bigquery_schema.list_dataset_ids.list_table_ids.get_dataset_info.get_table_info.firecrawl_scrape.firecrawl_map.firecrawl_crawl.firecrawl_check_crawl_status.firecrawl_extract.get_code_context_exa.company_research_exa.crawling_exa.deep_researcher_check.perplexity_ask.perplexity_research.perplexity_reason.tavily_extract.tavily_crawl.tavily_map.tavily_research.obsidian_list_files_in_vault.obsidian_list_files_in_dir.obsidian_get_file_contents.obsidian_batch_get_file_contents.obsidian_get_periodic_note.obsidian_get_recent_periodic_notes.obsidian_get_recent_changes.get_figma_data.download_figma_images.browser_console_messages.browser_network_requests.browser_take_screenshot.browser_snapshot.browser_get_config.browser_route_list.browser_cookie_list.browser_cookie_get.browser_localstorage_list.browser_localstorage_get.browser_sessionstorage_list.browser_sessionstorage_get.browser_storage_state.puppeteer_screenshot.list_databases.list_collections.collection_indexes.collection_schema.collection_storage_size.db_stats.explain.mongodb_logs.aggregate.count.export.get_neo4j_schema.read_neo4j_cypher.list_instances.get_instance_details.get_instance_by_name.list_indices.get_mappings.esql.get_shards.list_records.list_bases.get_record.get_productivity_stats.get_overview.fetch_object.user_info.list_workspaces.view_attachment.get_available_services.read_documentation.read_sections.recommend.analyze_log_group.analyze_metric.describe_log_groups.get_active_alarms.get_alarm_history.get_metric_data.get_metric_metadata.kubectl_get.kubectl_describe.kubectl_logs.kubectl_context.explain_resource.list_api_resources.namespaces_list.nodes_log.nodes_top.pods_get.pods_list.pods_list_in_namespace.pods_log.pods_top.resources_get.resources_list`.split(`.`))}));function iVe(e){return e.scope===`project`||e.scope===`local`}async function aVe(e,t){if(!t.headersHelper)return null;if(`scope`in t&&iVe(t)&&!kr()&&!Yi())return Ii(`MCP headersHelper invoked before trust check`,Error(`Security: headersHelper for MCP server '${e}' executed before workspace trust is confirmed. If you see this message, post in .`)),null;try{ba(e,`Executing headersHelper to get dynamic headers`);let n=await Oa(t.headersHelper,[],{shell:!0,timeout:1e4,env:{...process.env,WORKMATE_MCP_SERVER_NAME:e,WORKMATE_MCP_SERVER_URL:t.url}});if(n.code!==0||!n.stdout)throw Error(`headersHelper for MCP server '${e}' did not return a valid value`);let r=Si(n.stdout.trim());if(typeof r!=`object`||!r||Array.isArray(r))throw Error(`headersHelper for MCP server '${e}' must return a JSON object with string key-value pairs`);for(let[t,n]of Object.entries(r))if(typeof n!=`string`)throw Error(`headersHelper for MCP server '${e}' returned non-string value for key "${t}": ${typeof n}`);return ba(e,`Successfully retrieved ${Object.keys(r).length} headers from headersHelper`),r}catch(t){return Sa(e,`Error getting headers from headersHelper: ${G(t)}`),Y(Error(`Error getting MCP headers from headersHelper for server '${e}': ${G(t)}`)),null}}async function sY(e,t){let n=t.headers||{},r=await aVe(e,t)||{};return{...n,...r}}var oVe=n((()=>{H(),Wi(),q(),gi(),Da(),wa(),Li(),La()})),sVe,cVe=n((()=>{b(),sVe=class{constructor(e,t){x(this,`serverName`,void 0),x(this,`sendMcpMessage`,void 0),x(this,`isClosed`,!1),x(this,`onclose`,void 0),x(this,`onerror`,void 0),x(this,`onmessage`,void 0),this.serverName=e,this.sendMcpMessage=t}async start(){}async send(e){if(this.isClosed)throw Error(`Transport is closed`);let t=await this.sendMcpMessage(this.serverName,e);this.onmessage&&this.onmessage(t)}async close(){this.isClosed||(this.isClosed=!0,this.onclose?.())}}}));function lVe(e){return(`code`in e?e.code:void 0)===404?e.message.includes(`"code":-32001`)||e.message.includes(`"code": -32001`):!1}function uVe(){return parseInt(process.env.MCP_TOOL_TIMEOUT||``,10)||FVe}function cY(e){let t=QBe(e);return t?{mcpServerBaseUrl:t}:{}}function dVe(e,t,n){return{...cY(t)},ba(e,`Authentication required for ${{sse:`SSE`,http:`HTTP`,"claudeai-proxy":`claude.ai proxy`}[n]} server`),{name:e,type:`needs-auth`,config:t}}async function fVe(e,t){let n=(await import(`./wrapper-B-Q3Illb.js`)).default;return new n(e,[`mcp`],t)}function lY(){return parseInt(process.env.MCP_TIMEOUT||``,10)||3e4}function pVe(e){return async(t,n)=>{if((n?.method??`GET`).toUpperCase()===`GET`)return e(t,n);let r=new Headers(n?.headers);r.has(`accept`)||r.set(`accept`,LVe);let i=new AbortController,a=setTimeout(e=>e.abort(new DOMException(`The operation timed out.`,`TimeoutError`)),vY,i);a.unref?.();let o=n?.signal,s=()=>i.abort(o?.reason);o?.addEventListener(`abort`,s),o?.aborted&&i.abort(o.reason);let c=()=>{clearTimeout(a),o?.removeEventListener(`abort`,s)};try{let a=await e(t,{...n,headers:r,signal:i.signal});return c(),a}catch(e){throw c(),e}}}function mVe(){return parseInt(process.env.MCP_SERVER_CONNECTION_BATCH_SIZE||``,10)||3}function hVe(){return parseInt(process.env.MCP_REMOTE_SERVER_CONNECTION_BATCH_SIZE||``,10)||20}function gVe(e){return!e.type||e.type===`stdio`||e.type===`sdk`}function _Ve(e){return!e.name.startsWith(`mcp__ide__`)||RVe.includes(e.name)}function uY(e,t){return`${e}-${W(t)}`}async function dY(e,t){let n=uY(e,t);try{let n=await yY(e,t);n.type===`connected`&&await n.cleanup()}catch{}yY.cache.delete(n),xY.cache.delete(e),SY.cache.delete(e),CY.cache.delete(e)}async function fY(e){if(e.config.type===`sdk`)return e;let t=await yY(e.name,e.config);if(t.type!==`connected`)throw new ji(`MCP server "${e.name}" is not connected`,`MCP server not connected`);return t}function vVe(e,t){if(e.type!==t.type)return!1;let{scope:n,...r}=e,{scope:i,...a}=t;return W(r)===W(a)}function yVe(e,t){let n=Object.keys(e);return n.length>0?n.map(t=>`${t}=${String(e[t])}`).join(` `):t}async function bVe(e,t){try{DF(),await dY(e,t);let n=await yY(e,t);if(n.type!==`connected`)return{client:n,tools:[],commands:[]};let r=!!n.capabilities?.resources,[i,a,o]=await Promise.all([xY(n),CY(n),r?SY(n):Promise.resolve([])]),s=[...a],c=[];return r&&([kJ,IJ].some(e=>i.some(t=>us(t,e.name)))||c.push(kJ,IJ)),{client:n,tools:[...i,...c],commands:s,resources:o.length>0?o:void 0}}catch(n){return Sa(e,`Error during reconnection: ${G(n)}`),{client:{name:e,type:`failed`,config:t},tools:[],commands:[]}}}async function xVe(e,t,n){await tze(e,n,{concurrency:t})}async function SVe(e,t){let n=!1,r=Object.entries(t??(await EBe()).servers),i=[];for(let t of r)tY(t[0])?e({client:{name:t[0],type:`disabled`,config:t[1]},tools:[],commands:[]}):i.push(t);let a=i.length,o=zt(i,([e,t])=>t.type===`stdio`),s=zt(i,([e,t])=>t.type===`sse`),c=zt(i,([e,t])=>t.type===`http`),l=zt(i,([e,t])=>t.type===`sse-ide`),u=zt(i,([e,t])=>t.type===`ws-ide`),d=i.filter(([e,t])=>gVe(t)),f=i.filter(([e,t])=>!gVe(t)),p={totalServers:a,stdioCount:o,sseCount:s,httpCount:c,sseIdeCount:l,wsIdeCount:u},m=async([t,r])=>{try{if(tY(t)){e({client:{name:t,type:`disabled`,config:r},tools:[],commands:[]});return}let i=await yY(t,r,p);if(i.type!==`connected`){e({client:i,tools:[],commands:[]});return}let a=!!i.capabilities?.resources,[o,s,c]=await Promise.all([xY(i),CY(i),a?SY(i):Promise.resolve([])]),l=[...s],u=[];a&&!n&&(n=!0,u.push(kJ,IJ)),e({client:i,tools:[...o,...u],commands:l,resources:c.length>0?c:void 0})}catch(n){Sa(t,`Error fetching tools/commands/resources: ${G(n)}`),e({client:{name:t,type:`failed`,config:r},tools:[],commands:[]})}};await Promise.all([xVe(d,mVe(),m),xVe(f,hVe(),m)])}function CVe(e){return new Promise(t=>{let n=0,r=0;if(n=Object.keys(e).length,n===0){t({clients:[],tools:[],commands:[]});return}let i=[],a=[],o=[];SVe(e=>{i.push(e.client),a.push(...e.tools),o.push(...e.commands),r++,r>=n&&(o.reduce((e,t)=>e+(t.name.length+(t.description??``).length+(t.argumentHint??``).length),0),a.length,o.length,t({clients:i,tools:a,commands:o}))},e).catch(e=>{Sa(`prefetchAllMcpResources`,`Failed to get MCP resources: ${G(e)}`),t({clients:[],tools:[],commands:[]})})})}async function wVe(e,t,n,r=!1){switch(e.type){case`text`:{let t={type:`text`,text:e.text};if(r){let n=e._meta;n&&(t._meta=n)}return[t]}case`audio`:{let n=e;return await TVe(Buffer.from(n.data,`base64`),n.mimeType,t,`[Audio from ${t}] `)}case`image`:{let t=Buffer.from(String(e.data),`base64`),r=e.mimeType?.split(`/`)[1]||`png`,i=await _y(t,t.length,r,n);return[{type:`image`,source:{data:i.buffer.toString(`base64`),media_type:`image/${i.mediaType}`,type:`base64`}}]}case`resource`:{let r=e.resource,i=`[Resource from ${t} at ${r.uri}] `;if(`text`in r)return[{type:`text`,text:`${i}${r.text}`}];if(`blob`in r)if(IVe.has(r.mimeType??``)){let e=Buffer.from(r.blob,`base64`),t=r.mimeType?.split(`/`)[1]||`png`,a=await _y(e,e.length,t,n),o=[];return i&&o.push({type:`text`,text:i}),o.push({type:`image`,source:{data:a.buffer.toString(`base64`),media_type:`image/${a.mediaType}`,type:`base64`}}),o}else return await TVe(Buffer.from(r.blob,`base64`),r.mimeType,t,i);return[]}case`resource_link`:{let t=e,n=`[Resource link: ${t.name}] ${t.uri}`;return t.description&&(n+=` (${t.description})`),[{type:`text`,text:n}]}default:return[]}}async function TVe(e,t,n,r){let i=await zze(e,t,`mcp-${pn(n)}-blob-${Date.now()}-${Math.random().toString(36).slice(2,8)}`);return`error`in i?[{type:`text`,text:`${r}Binary content (${t||`unknown type`}, ${e.length} bytes) could not be saved to disk: ${i.error}`}]:[{type:`text`,text:Bze(i.filepath,t,i.size,r)}]}function pY(e,t=2){if(e===null)return`null`;if(Array.isArray(e))return e.length===0?`[]`:`[${pY(e[0],t-1)}]`;if(typeof e==`object`){if(t<=0)return`{...}`;let n=Object.entries(e).slice(0,10).map(([e,n])=>`${e}: ${pY(n,t-1)}`),r=Object.keys(e).length>10?`, ...`:``;return`{${n.join(`, `)}${r}}`}return typeof e}async function EVe(e,t,n,r){if(e&&typeof e==`object`){if(`toolResult`in e)return{content:String(e.toolResult),type:`toolResult`};if(`structuredContent`in e&&e.structuredContent!==void 0)return{content:W(e.structuredContent),type:`structuredContent`,schema:pY(e.structuredContent)};if(`content`in e&&Array.isArray(e.content)){let t=(await Promise.all(e.content.map(e=>wVe(e,n,r,!0)))).flat();return{content:t,type:`contentArray`,schema:pY(t)}}}let i=`MCP server "${n}" tool "${t}": unexpected response format`;throw Sa(n,i),new ji(i,`MCP tool unexpected response format`)}function DVe(e){return!e||typeof e==`string`?!1:e.some(e=>e.type===`image`)}async function OVe(e,t,n,r,i=!1){let{content:a,type:o,schema:s}=await EVe(e,t,n,r);if(i&&!DVe(a)||!await vze(a))return a;if(MJ(a),f(process.env.ENABLE_MCP_LARGE_OUTPUT_FILES))return await bze(a);if(!a)return a;if(DVe(a))return await bze(a);let c=Date.now(),l=`mcp-${pn(n)}-${pn(t)}-${c}`,u=AVe(a),d=typeof a==`string`?a:u??W(a,null,2),p=await ix(d,l);if(cx(p))return`Error: result (${d.length.toLocaleString()} characters) exceeds maximum allowed tokens. Failed to save output to file: ${p.error}. If this MCP server provides pagination or filtering tools, use them to retrieve specific portions of the data.`;p.originalSize;let m=u===void 0?Ize(o,s):Ize(`toolResult`);return Lze(p.filepath,p.originalSize,m)}function kVe(){let e=process.env.MCP_TRUNCATION_PROMPT_OVERRIDE;return e?e!==`legacy`:!1}function AVe(e){if(!kVe()||!Array.isArray(e)||e.length!==1)return;let t=e[0];if(t?.type===`text`&&!(`annotations`in t||`_meta`in t))return t.text}async function jVe({client:e,clientConnection:t,tool:n,args:r,meta:i,signal:a,setAppState:o,onProgress:s,imageLimits:c,hasResultSizeAnnotation:l=!1,callToolFn:u=MVe,handleElicitation:d}){for(let f=0;;f++)try{return await u({client:e,tool:n,args:r,meta:i,signal:a,onProgress:s,imageLimits:c,hasResultSizeAnnotation:l})}catch(e){if(!(e instanceof FK)||e.code!==lW.UrlElicitationRequired||f>=3)throw e;let r=e.data,i=(typeof r==`object`&&r&&`elicitations`in r&&Array.isArray(r.elicitations)?r.elicitations:[]).filter(e=>{if(typeof e!=`object`||!e)return!1;let t=e;return t.mode===`url`&&typeof t.url==`string`&&typeof t.elicitationId==`string`&&typeof t.message==`string`}),s=t.type===`connected`?t.name:`unknown`;if(i.length===0)throw ba(s,`Tool '${n}' returned -32042 but no valid elicitations in error data`),e;ba(s,`Tool '${n}' requires URL elicitation (error -32042, attempt ${f+1}), processing ${i.length} elicitation(s)`);for(let e of i){let{elicitationId:t}=e,r=await BJ(s,e,a);if(r){if(ba(s,`URL elicitation ${t} resolved by hook: ${W(r)}`),r.action!==`accept`)return{content:`URL elicitation was ${r.action===`decline`?`declined`:`${r.action}ed`} by a hook. The tool "${n}" could not complete because it requires the user to open a URL.`};continue}let i;if(d)i=await d(s,e,a);else{let n={actionLabel:`Retry now`,showCancel:!0};i=await new Promise(r=>{let i=()=>{r({action:`cancel`})};if(a.aborted){i();return}a.addEventListener(`abort`,i,{once:!0}),o(o=>({...o,elicitation:{queue:[...o.elicitation.queue,{serverName:s,requestId:`error-elicit-${t}`,params:e,signal:a,waitingState:n,respond:e=>{e.action!==`accept`&&(a.removeEventListener(`abort`,i),r(e))},onWaitingDismiss:e=>{a.removeEventListener(`abort`,i),r(e===`retry`?{action:`accept`}:{action:`cancel`})}}]}}))})}let c=await VJ(s,i,a,`url`,t);if(c.action!==`accept`)return ba(s,`User ${c.action===`decline`?`declined`:`${c.action}ed`} URL elicitation ${t}`),{content:`URL elicitation was ${c.action===`decline`?`declined`:`${c.action}ed`} by the user. The tool "${n}" could not complete because it requires the user to open a URL.`};ba(s,`Elicitation ${t} completed, retrying tool call`)}}}async function MVe({client:{client:e,name:t,config:n},tool:r,args:i,meta:a,signal:o,onProgress:s,imageLimits:c,hasResultSizeAnnotation:l=!1}){let u=Date.now(),d;try{ba(t,`Calling MCP tool: ${r}`),d=setInterval((e,t,n)=>{let r=Date.now()-e;ba(t,`Tool '${n}' still running (${`${Math.floor(r/1e3)}s`} elapsed)`)},3e4,u,t,r);let n=uVe(),f,p=new Promise((e,i)=>{f=setTimeout((e,t,n,r)=>{e(new ji(`MCP server "${t}" tool "${n}" timed out after ${Math.floor(r/1e3)}s`,`MCP tool timeout`))},n,i,t,r,n)}),m=await Promise.race([e.callTool({name:r,arguments:i,_meta:a},BG,{signal:o,timeout:n,onprogress:s?e=>{s({type:`mcp_progress`,status:`progress`,serverName:t,toolName:r,progress:e.progress,total:e.total,progressMessage:e.message})}:void 0}),p]).finally(()=>{f&&clearTimeout(f)});if(`isError`in m&&m.isError){let e=`Unknown error`;if(`content`in m&&Array.isArray(m.content)&&m.content.length>0){let t=m.content[0];t&&typeof t==`object`&&`text`in t&&(e=t.text)}else`error`in m&&(e=String(m.error));throw Sa(t,e),new gY(e,`MCP tool returned error`,`_meta`in m&&m._meta?{_meta:m._meta}:void 0)}let h=Date.now()-u;return ba(t,`Tool '${r}' completed successfully in ${h<1e3?`${h}ms`:h<6e4?`${Math.floor(h/1e3)}s`:`${Math.floor(h/6e4)}m ${Math.floor(h%6e4/1e3)}s`}`),MEe(t),{content:await OVe(m,r,t,c,l),_meta:m._meta,structuredContent:m.structuredContent}}catch(e){d!==void 0&&clearInterval(d);let i=Date.now()-u;if(e instanceof Error&&e.name!==`AbortError`&&ba(t,`Tool '${r}' failed after ${Math.floor(i/1e3)}s: ${e.message}`),e instanceof Error){if((`code`in e?e.code:void 0)===401||e instanceof yJ)throw ba(t,`Tool call returned 401 Unauthorized - token may have expired`),new mY(t,`MCP server "${t}" requires re-authorization (token expired)`);let r=lVe(e),i=`code`in e&&e.code===-32e3&&e.message.includes(`Connection closed`)&&n.type===`http`;if(r||i)throw ba(t,`MCP session expired during tool call (${r?`404/-32001`:`connection closed`}), clearing connection cache for re-initialization`),await dY(t,n),new hY(t)}if(!(e instanceof Error)||e.name!==`AbortError`)throw e;return{content:void 0}}finally{d!==void 0&&clearInterval(d)}}function NVe(e){let t=e.message.content?.[0];if(!(!t||typeof t==`string`||t.type!==`tool_use`))return t.id}async function PVe(e,t){let n=[],r=[],i=await Promise.allSettled(Object.entries(e).map(async([e,n])=>{let r=new sVe(e,t),i=new eq({name:`workmate`,title:`Work Mate`,version:`0.0.33`,description:`Agentic coding tool`,websiteUrl:nF},{capabilities:{}});try{await i.connect(r);let t=i.getServerCapabilities(),a={type:`connected`,name:e,capabilities:t||{},client:i,config:{...n,scope:`dynamic`},cleanup:async()=>{await i.close()}},o=[];if(t?.tools){let e=await xY(a);o.push(...e)}return{client:a,tools:o}}catch(t){return Sa(e,`Failed to connect SDK MCP server: ${t}`),{client:{type:`failed`,name:e,config:{...n,scope:`user`}},tools:[]}}}));for(let e of i)e.status===`fulfilled`&&(n.push(e.value.client),r.push(...e.value.tools));return{clients:n,tools:r}}var mY,hY,gY,FVe,_Y,IVe,vY,LVe,RVe,yY,bY,xY,SY,CY,wY=n((()=>{qLe(),VRe(),YRe(),eze(),Gq(),LK(),lm(),d(),Cm(),nze(),H(),rF(),Ms(),AJ(),Fze(),LJ(),tt(),di(),wM(),q(),g(),gi(),Lie(),Cy(),wa(),Vze(),Cze(),Qze(),tn(),roe(),zs(),Nb(),fx(),La(),nBe(),Bn(),jn(),oY(),lse(),SJ(),rVe(),AF(),Hs(),rY(),oVe(),cVe(),b(),Li(),mY=class extends Error{constructor(e,t){super(t),x(this,`serverName`,void 0),this.name=`McpAuthError`,this.serverName=e}},hY=class extends Error{constructor(e){super(`MCP server "${e}" session expired`),this.name=`McpSessionExpiredError`}},gY=class extends ji{constructor(e,t,n){super(e,t),x(this,`mcpMeta`,void 0),this.mcpMeta=n,this.name=`McpToolCallError`}},FVe=1e8,_Y=2048,IVe=new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]),vY=6e4,LVe=`application/json, text/event-stream`,RVe=[`mcp__ide__executeCode`,`mcp__ide__getDiagnostics`],yY=u(async(e,t,n)=>{let r=Date.now();try{let i;if(t.type===`sse`){let n=await sY(e,t),r={fetch:pVe(Wq()),requestInit:{headers:{"User-Agent":To(),...n}}};r.eventSourceInit={fetch:async(e,t)=>{let r=Bs();return fetch(e,{...t,...r,headers:{"User-Agent":To(),...t?.headers,...n,Accept:`text/event-stream`}})}},i=new CJ(new URL(t.url),r),ba(e,`SSE transport initialized, awaiting connection`)}else if(t.type===`sse-ide`){ba(e,`Setting up SSE-IDE transport to ${t.url}`);let n=Bs(),r=n.dispatcher?{eventSourceInit:{fetch:async(e,t)=>fetch(e,{...t,...n,headers:{"User-Agent":To(),...t?.headers}})}}:{};i=new CJ(new URL(t.url),Object.keys(r).length>0?r:void 0)}else if(t.type===`ws-ide`){let e=aoe(),n={"User-Agent":To(),...t.authToken&&{"X-Work Mate-Code-Ide-Authorization":t.authToken}},r;r=typeof Bun<`u`?new globalThis.WebSocket(t.url,{protocols:[`mcp`],headers:n,proxy:ooe(t.url),tls:e||void 0}):await fVe(t.url,{headers:n,agent:ioe(t.url),...e||{}}),i=new zJ(r)}else if(t.type===`ws`){ba(e,`Initializing WebSocket transport to ${t.url}`);let n=await sY(e,t),r=aoe(),a={"User-Agent":To(),...n},o=cm(a,(e,t)=>t.toLowerCase()===`authorization`?`[REDACTED]`:e);ba(e,`WebSocket transport options: ${W({url:t.url,headers:o})}`);let s;s=typeof Bun<`u`?new globalThis.WebSocket(t.url,{protocols:[`mcp`],headers:a,proxy:ooe(t.url),tls:r||void 0}):await fVe(t.url,{headers:a,agent:ioe(t.url),...r||{}}),i=new zJ(s)}else if(t.type===`http`){ba(e,`Initializing HTTP transport to ${t.url}`),ba(e,`Node version: ${process.version}, Platform: ${process.platform}`),ba(e,`Environment: ${W({NODE_OPTIONS:process.env.NODE_OPTIONS||`not set`,UV_THREADPOOL_SIZE:process.env.UV_THREADPOOL_SIZE||`default`,HTTP_PROXY:process.env.HTTP_PROXY||`not set`,HTTPS_PROXY:process.env.HTTPS_PROXY||`not set`,NO_PROXY:process.env.NO_PROXY||`not set`})}`);let n=await sY(e,t),r=Bs();ba(e,`Proxy options: ${r.dispatcher?`custom dispatcher`:`default`}`);let a={fetch:pVe(Wq()),requestInit:{...r,headers:{"User-Agent":To(),...n}}},o=a.requestInit?.headers?cm(a.requestInit.headers,(e,t)=>t.toLowerCase()===`authorization`?`[REDACTED]`:e):void 0;ba(e,`HTTP transport options: ${W({url:t.url,headers:o,timeoutMs:vY})}`),i=new $Re(new URL(t.url),a),ba(e,`HTTP transport created successfully`)}else if(t.type===`sdk`)throw Error(`SDK servers should be handled in print.ts`);else if(t.type===`stdio`||!t.type){let e=t;i=new JRe({command:process.env.WORKMATE_SHELL_PREFIX||e.command,args:process.env.WORKMATE_SHELL_PREFIX?[[e.command,...e.args].join(` `)]:e.args,env:{...Mb(),...e.env},stderr:`pipe`})}else throw Error(`Unsupported server type: ${t.type}`);let a,o=``;if(t.type===`stdio`||!t.type){let e=i;e.stderr&&(a=e=>{if(o.length<64*1024*1024)try{o+=e.toString()}catch{}},e.stderr.on(`data`,a))}let s=new eq({name:`workmate`,title:`Work Mate`,version:`0.0.33`,description:`Agentic coding tool`,websiteUrl:nF},{capabilities:{roots:{},elicitation:{}}});if(t.type===`http`&&ba(e,`Client created, setting up request handler`),s.setRequestHandler(MK,async()=>(ba(e,`Received ListRoots request from server`),{roots:[{uri:`file://${ti()}`}]})),ba(e,`Starting connection with timeout of ${lY()}ms`),t.type===`http`){ba(e,`Testing basic HTTP connectivity to ${t.url}`);try{let n=new URL(t.url);ba(e,`Parsed URL: host=${n.hostname}, port=${n.port||`default`}, protocol=${n.protocol}`),(n.hostname===`127.0.0.1`||n.hostname===`localhost`)&&ba(e,`Using loopback address: ${n.hostname}`)}catch(t){ba(e,`Failed to parse URL: ${t}`)}}let c=s.connect(i),l=new Promise((t,n)=>{let a=setTimeout(()=>{ba(e,`Connection timeout triggered after ${Date.now()-r}ms (limit: ${lY()}ms)`),i.close().catch(()=>{}),n(new ji(`MCP server "${e}" connection timed out after ${lY()}ms`,`MCP connection timeout`))},lY());c.then(()=>{clearTimeout(a)},e=>{clearTimeout(a)})});try{await Promise.race([c,l]),o&&(Sa(e,`Server stderr: ${o}`),o=``);let n=Date.now()-r;ba(e,`Successfully connected (transport: ${t.type||`stdio`}) in ${n}ms`)}catch(n){let a=Date.now()-r;if(t.type===`sse`&&n instanceof Error){if(ba(e,`SSE Connection failed after ${a}ms: ${W({url:t.url,error:n.message,errorType:n.constructor.name,stack:n.stack})}`),Sa(e,n),n instanceof yJ)return dVe(e,t,`sse`)}else if(t.type===`http`&&n instanceof Error){let r=n;if(ba(e,`HTTP Connection failed after ${a}ms: ${n.message} (code: ${r.code||`none`}, errno: ${r.errno||`none`})`),Sa(e,n),n instanceof yJ)return dVe(e,t,`http`)}else t.type===`sse-ide`||t.type;throw i.close().catch(()=>{}),o&&Sa(e,`Server stderr: ${o}`),n}let u=s.getServerCapabilities(),d=s.getServerVersion(),f=s.getInstructions(),p=f;f&&f.length>_Y&&(p=`${f.slice(0,_Y)}… [truncated]`,ba(e,`Server instructions truncated from ${f.length} to ${_Y} chars`)),ba(e,`Connection established with capabilities: ${W({hasTools:!!u?.tools,hasPrompts:!!u?.prompts,hasResources:!!u?.resources,hasResourceSubscribe:!!u?.resources?.subscribe,serverVersion:d||`unknown`})}`),K(`[MCP] Server "${e}" connected with subscribe=${!!u?.resources?.subscribe}`),s.setRequestHandler(SK,async t=>(ba(e,`Elicitation request received during initialization: ${W(t)}`),{action:`cancel`}));let m=Date.now(),h=!1,g=s.onerror,_=s.onclose,v=0,y=!1,b=t=>{y||(y=!0,ba(e,`Closing transport (${t})`),s.close().catch(t=>{ba(e,`Error during close: ${G(t)}`)}))},x=e=>e.includes(`ECONNRESET`)||e.includes(`ETIMEDOUT`)||e.includes(`EPIPE`)||e.includes(`EHOSTUNREACH`)||e.includes(`ECONNREFUSED`)||e.includes(`Body Timeout Error`)||e.includes(`terminated`)||e.includes(`SSE stream disconnected`)||e.includes(`Failed to reconnect SSE stream`);s.onerror=n=>{let r=Date.now()-m;h=!0;let i=t.type||`stdio`;if(ba(e,`${i.toUpperCase()} connection dropped after ${Math.floor(r/1e3)}s uptime`),n.message&&(n.message.includes(`ECONNRESET`)?ba(e,`Connection reset - server may have crashed or restarted`):n.message.includes(`ETIMEDOUT`)?ba(e,`Connection timeout - network issue or server unresponsive`):n.message.includes(`ECONNREFUSED`)?ba(e,`Connection refused - server may be down`):n.message.includes(`EPIPE`)?ba(e,`Broken pipe - server closed connection unexpectedly`):n.message.includes(`EHOSTUNREACH`)?ba(e,`Host unreachable - network connectivity issue`):n.message.includes(`ESRCH`)?ba(e,`Process not found - stdio server process terminated`):n.message.includes(`spawn`)?ba(e,`Failed to spawn process - check command and permissions`):ba(e,`Connection error: ${n.message}`)),i===`http`&&lVe(n)){ba(e,`MCP session expired (server returned 404 with session-not-found), triggering reconnection`),b(`session expired`),g&&g(n);return}if(i===`sse`||i===`http`){if(n.message.includes(`Maximum reconnection attempts`)){b(`SSE reconnection exhausted`),g&&g(n);return}x(n.message)?(v++,ba(e,`Terminal connection error ${v}/3`),v>=3&&(v=0,b(`max consecutive terminal errors`))):v=0}g&&g(n)},s.onclose=()=>{let n=Date.now()-m;ba(e,`${(t.type??`unknown`).toUpperCase()} connection closed after ${Math.floor(n/1e3)}s (${h?`with errors`:`cleanly`})`);let r=uY(e,t);xY.cache.delete(e),SY.cache.delete(e),CY.cache.delete(e),yY.cache.delete(r),ba(e,`Cleared connection cache for reconnection`),_&&_()};let S=async()=>{if(a&&(t.type===`stdio`||!t.type)&&i.stderr?.off(`data`,a),t.type===`stdio`)try{let t=i.pid;if(t){ba(e,`Sending SIGINT to MCP server process`);try{process.kill(t,`SIGINT`)}catch(t){ba(e,`Error sending SIGINT: ${t}`);return}await new Promise(async n=>{let r=!1,i=setInterval(()=>{try{process.kill(t,0)}catch{r||(r=!0,clearInterval(i),clearTimeout(a),ba(e,`MCP server process exited cleanly`),n())}},50),a=setTimeout(()=>{r||(r=!0,clearInterval(i),ba(e,`Cleanup timeout reached, stopping process monitoring`),n())},600);try{if(await Vs(100),!r){try{process.kill(t,0),ba(e,`SIGINT failed, sending SIGTERM to MCP server process`);try{process.kill(t,`SIGTERM`)}catch(t){ba(e,`Error sending SIGTERM: ${t}`),r=!0,clearInterval(i),clearTimeout(a),n();return}}catch{r=!0,clearInterval(i),clearTimeout(a),n();return}if(await Vs(400),!r)try{process.kill(t,0),ba(e,`SIGTERM failed, sending SIGKILL to MCP server process`);try{process.kill(t,`SIGKILL`)}catch(t){ba(e,`Error sending SIGKILL: ${t}`)}}catch{r=!0,clearInterval(i),clearTimeout(a),n()}}r||(r=!0,clearInterval(i),clearTimeout(a),n())}catch{r||(r=!0,clearInterval(i),clearTimeout(a),n())}})}}catch(t){ba(e,`Error terminating process: ${t}`)}try{await s.close()}catch(t){ba(e,`Error closing client: ${t}`)}},C=Oi(S),w=async()=>{C?.(),await S()};return Date.now()-r,t.type,n?.totalServers,n?.stdioCount,n?.sseCount,n?.httpCount,n?.sseIdeCount,n?.wsIdeCount,{...cY(t)},{name:e,client:s,type:`connected`,capabilities:u??{},serverInfo:d,instructions:p,config:t,cleanup:w}}catch(i){let a=Date.now()-r;return n?.totalServers,n?.stdioCount||+(t.type===`stdio`),n?.sseCount||+(t.type===`sse`),n?.httpCount||+(t.type===`http`),n?.sseIdeCount||+(t.type===`sse-ide`),n?.wsIdeCount||+(t.type===`ws-ide`),t.type,{...cY(t)},ba(e,`Connection failed after ${a}ms: ${G(i)}`),Sa(e,`Connection failed: ${G(i)}`),{name:e,type:`failed`,config:t,error:G(i)}}},uY),bY=20,xY=ln(async e=>{if(e.type!==`connected`)return[];try{if(!e.capabilities?.tools)return[];let t=cse((await e.client.request({method:`tools/list`},zG)).tools),n=e.config.type===`sdk`&&h(process.env.CLAUDE_AGENT_SDK_MCP_NO_PREFIX);return t.map(t=>{let r=Jee(e.name,t.name);return{...Pze,name:n?t.name:r,mcpInfo:{serverName:e.name,toolName:t.name},isMcp:!0,searchHint:typeof t._meta?.[`anthropic/searchHint`]==`string`&&t._meta[`anthropic/searchHint`].replace(/\s+/g,` `).trim()||void 0,alwaysLoad:t._meta?.[`anthropic/alwaysLoad`]===!0,async description(){return t.description??``},async prompt(){let e=t.description??``;return e.length>_Y?`${e.slice(0,_Y)}… [truncated]`:e},isConcurrencySafe(){return t.annotations?.readOnlyHint??!1},isReadOnly(){return t.annotations?.readOnlyHint??!1},toAutoClassifierInput(e){return yVe(e,t.name)},isDestructive(){return t.annotations?.destructiveHint??!1},isOpenWorld(){return t.annotations?.openWorldHint??!1},isSearchOrReadCommand(){return eVe(e.name,t.name)},inputJSONSchema:t.inputSchema,async checkPermissions(){return{behavior:`passthrough`,message:`MCPTool requires permission.`,suggestions:[{type:`addRules`,rules:[{toolName:r,ruleContent:void 0}],behavior:`allow`,destination:`localSettings`}]}},async call(n,r,i,a,o){let s=NVe(a),c=s?{"claudecode/toolUseId":s}:{};o&&s&&o({toolUseID:s,data:{type:`mcp_progress`,status:`started`,serverName:e.name,toolName:t.name}});let l=Date.now();for(let i=0;;i++)try{let i=await jVe({client:await fY(e),clientConnection:e,tool:t.name,args:n,meta:c,signal:r.abortController.signal,setAppState:r.setAppState,onProgress:o&&s?e=>{o({toolUseID:s,data:e})}:void 0,handleElicitation:r.handleElicitation});return o&&s&&o({toolUseID:s,data:{type:`mcp_progress`,status:`completed`,serverName:e.name,toolName:t.name,elapsedTimeMs:Date.now()-l}}),{data:i.content,...(i._meta||i.structuredContent)&&{mcpMeta:{...i._meta&&{_meta:i._meta},...i.structuredContent&&{structuredContent:i.structuredContent}}}}}catch(n){if(n instanceof hY&&i<1){ba(e.name,`Retrying tool '${t.name}' after session recovery`);continue}if(o&&s&&o({toolUseID:s,data:{type:`mcp_progress`,status:`failed`,serverName:e.name,toolName:t.name,elapsedTimeMs:Date.now()-l}}),n instanceof Error&&!(n instanceof ji)){let e=n.constructor.name;if(e===`Error`)throw new ji(n.message,n.message.slice(0,200));if(e===`McpError`&&`code`in n&&typeof n.code==`number`)throw new ji(n.message,`McpError ${n.code}`)}throw n}},userFacingName(){let n=t.annotations?.title||t.name;return`${e.name} - ${n} (MCP)`}}}).filter(_Ve)}catch(t){return Sa(e.name,`Failed to fetch tools: ${G(t)}`),[]}},e=>e.name,bY),SY=ln(async e=>{if(e.type!==`connected`)return[];try{if(!e.capabilities?.resources)return[];let t=await e.client.request({method:`resources/list`},aG);return t.resources?t.resources.map(t=>({...t,server:e.name})):[]}catch(t){return Sa(e.name,`Failed to fetch resources: ${G(t)}`),[]}},e=>e.name,bY),CY=ln(async e=>{if(e.type!==`connected`)return[];try{if(!e.capabilities?.prompts)return[];let t=await e.client.request({method:`prompts/list`},SG);return t.prompts?cse(t.prompts).map(t=>{let n=Object.values(t.arguments??{}).map(e=>e.name);return{type:`prompt`,name:`mcp__${pn(e.name)}__${t.name}`,description:t.description??``,hasUserSpecifiedDescription:!!t.description,contentLength:0,isEnabled:()=>!0,isHidden:!1,isMcp:!0,progressMessage:`running`,userFacingName(){return`${e.name}:${t.name} (MCP)`},argNames:n,source:`mcp`,async getPromptForCommand(r){let i=r.split(` `);try{let r=await fY(e),a=await r.client.getPrompt({name:t.name,arguments:ufe(n,i)});return(await Promise.all(a.messages.map(e=>wVe(e.content,r.name)))).flat()}catch(n){throw Sa(e.name,`Error running command '${t.name}': ${G(n)}`),n}}}}):[]}catch(t){return Sa(e.name,`Failed to fetch commands: ${G(t)}`),[]}},e=>e.name,bY)}));function zVe(e,t){if(e.type!==t.type)return!1;let n=(e,t)=>(e.if??``)===(t.if??``);switch(e.type){case`command`:return t.type===`command`&&e.command===t.command&&(e.shell??`bash`)===(t.shell??`bash`)&&n(e,t);case`prompt`:return t.type===`prompt`&&e.prompt===t.prompt&&n(e,t);case`agent`:return t.type===`agent`&&e.prompt===t.prompt&&n(e,t);case`http`:return t.type===`http`&&e.url===t.url&&n(e,t);case`function`:return!1}}function TY(e){if(`statusMessage`in e&&e.statusMessage)return e.statusMessage;switch(e.type){case`command`:return e.command;case`prompt`:return e.prompt;case`agent`:return e.prompt;case`http`:return e.url;case`callback`:return`callback`;case`function`:return`function`}}function BVe(e){let t=[];if($n(`policySettings`)?.allowManagedHooksOnly!==!0){let e=[`userSettings`,`projectSettings`,`localSettings`],n=new Set;for(let r of e){let e=Vn(r);if(e){let t=yc(e);if(n.has(t))continue;n.add(t)}let i=$n(r);if(i?.hooks)for(let[e,n]of Object.entries(i.hooks))for(let i of n)for(let n of i.hooks)t.push({event:e,config:n,matcher:i.matcher,source:r})}}let n=XVe(e,Wr());for(let[e,r]of n.entries())for(let n of r)for(let r of n.hooks)t.push({event:e,config:r,matcher:n.matcher,source:`sessionHook`});return t}function VVe(e){switch(e){case`userSettings`:return`User settings (~/.workmate/settings.json)`;case`projectSettings`:return`Project settings (.workmate/settings.json)`;case`localSettings`:return`Local settings (.workmate/settings.local.json)`;case`pluginHook`:return`Plugin hooks (~/.workmate/plugins/*/hooks/hooks.json)`;case`sessionHook`:return`Session hooks (in-memory, temporary)`;case`builtinHook`:return`Built-in hooks (registered internally by Work Mate)`;default:return e}}function HVe(e){switch(e){case`userSettings`:return`User Settings`;case`projectSettings`:return`Project Settings`;case`localSettings`:return`Local Settings`;case`pluginHook`:return`Plugin Hooks`;case`sessionHook`:return`Session Hooks`;case`builtinHook`:return`Built-in Hooks`;default:return e}}function UVe(e){switch(e){case`userSettings`:return`User`;case`projectSettings`:return`Project`;case`localSettings`:return`Local`;case`pluginHook`:return`Plugin`;case`sessionHook`:return`Session`;case`builtinHook`:return`Built-in`;default:return e}}function WVe(e,t,n){let r=rte.reduce((e,t,n)=>(e[t]=n,e),{});return[...e].sort((e,i)=>{let a=t[n]?.[e]||[],o=t[n]?.[i]||[],s=Array.from(new Set(a.map(e=>e.source))),c=Array.from(new Set(o.map(e=>e.source))),l=e=>e===`pluginHook`||e===`builtinHook`?999:r[e],u=Math.min(...s.map(l)),d=Math.min(...c.map(l));return u===d?e.localeCompare(i):u-d})}var EY=n((()=>{H(),Rn(),Ln(),Fee(),OY()}));function GVe(e,t,n,r,i,a,o){qVe(e,t,n,r,i,a,o)}function KVe(e,t,n,r,i,a,o){let s=o?.id||`function-hook-${Date.now()}-${Math.random()}`;return qVe(e,t,n,r,{type:`function`,id:s,timeout:o?.timeout||5e3,callback:i,errorMessage:a}),s}function qVe(e,t,n,r,i,a,o){e(e=>{let s=e.sessionHooks.get(t)??{hooks:{}},c=s.hooks[n]||[],l=c.findIndex(e=>e.matcher===r&&e.skillRoot===o),u;if(l>=0){u=[...c];let e=u[l];u[l]={matcher:e.matcher,skillRoot:e.skillRoot,hooks:[...e.hooks,{hook:i,onHookSuccess:a}]}}else u=[...c,{matcher:r,skillRoot:o,hooks:[{hook:i,onHookSuccess:a}]}];let d={...s.hooks,[n]:u};return e.sessionHooks.set(t,{hooks:d}),e}),K(`Added session hook for event ${n} in session ${t}`)}function JVe(e,t,n,r){e(e=>{let i=e.sessionHooks.get(t);if(!i)return e;let a=(i.hooks[n]||[]).map(e=>{let t=e.hooks.filter(e=>!zVe(e.hook,r));return t.length>0?{...e,hooks:t}:null}).filter(e=>e!==null),o=a.length>0?{...i.hooks,[n]:a}:{...i.hooks};return a.length===0&&delete o[n],e.sessionHooks.set(t,{...i,hooks:o}),e}),K(`Removed session hook for event ${n} in session ${t}`)}function YVe(e){return e.map(e=>({matcher:e.matcher,skillRoot:e.skillRoot,hooks:e.hooks.map(e=>e.hook).filter(e=>e.type!==`function`)}))}function XVe(e,t,n){let r=e.sessionHooks.get(t);if(!r)return new Map;let i=new Map;if(n){let e=r.hooks[n];return e&&i.set(n,YVe(e)),i}for(let e of ot){let t=r.hooks[e];t&&i.set(e,YVe(t))}return i}function ZVe(e,t,n){let r=e.sessionHooks.get(t);if(!r)return new Map;let i=new Map,a=e=>e.map(e=>({matcher:e.matcher,hooks:e.hooks.map(e=>e.hook).filter(e=>e.type===`function`)})).filter(e=>e.hooks.length>0);if(n){let e=r.hooks[n];if(e){let t=a(e);t.length>0&&i.set(n,t)}return i}for(let e of ot){let t=r.hooks[e];if(t){let n=a(t);n.length>0&&i.set(e,n)}}return i}function QVe(e,t,n,r,i){let a=e.sessionHooks.get(t);if(!a)return;let o=a.hooks[n];if(o){for(let e of o)if(e.matcher===r||r===``){let t=e.hooks.find(e=>zVe(e.hook,i));if(t)return t}}}function DY(e,t){e(e=>(e.sessionHooks.delete(t),e)),K(`Cleared all session hooks for session ${t}`)}var OY=n((()=>{Pn(),q(),EY()}));function $Ve(e,t,n,r,i=!1){if(!n||Object.keys(n).length===0)return;let a=0;for(let o of ot){let s=n[o];if(!s||s.length===0)continue;let c=o;i&&o===`Stop`&&(c=`SubagentStop`,K(`Converting Stop hook to SubagentStop for ${r} (subagents trigger SubagentStop)`));for(let n of s){let r=n.matcher??``,i=n.hooks;if(!(!i||i.length===0))for(let n of i)GVe(e,t,c,r,n),a++}}a>0&&K(`Registered ${a} frontmatter hook(s) from ${r} for session ${t}`)}var eHe=n((()=>{Pn(),q(),OY()}));async function tHe(e,t){if(!e.mcpServers?.length)return{clients:t,tools:[],cleanup:async()=>{}};let n=ob(e.source);if(ab(`mcp`)&&!n)return K(`[Agent: ${e.agentType}] Skipping MCP servers: strictPluginOnlyCustomization locks MCP to plugin-only (agent source: ${e.source})`),{clients:t,tools:[],cleanup:async()=>{}};let r=[],i=[],a=[];for(let t of e.mcpServers){let n=null,o,s=!1;if(typeof t==`string`){if(o=t,n=XJ(t),!n){K(`[Agent: ${e.agentType}] MCP server not found: ${t}`,{level:`warn`});continue}}else{let r=Object.entries(t);if(r.length!==1){K(`[Agent: ${e.agentType}] Invalid MCP server spec: expected exactly one key`,{level:`warn`});continue}let[i,a]=r[0];o=i,n={...a,scope:`dynamic`},s=!0}let c=await yY(o,n);if(r.push(c),s&&i.push(c),c.type===`connected`){let t=await xY(c);a.push(...t),K(`[Agent: ${e.agentType}] Connected to MCP server '${o}' with ${t.length} tools`)}else K(`[Agent: ${e.agentType}] Failed to connect to MCP server '${o}': ${c.type}`,{level:`warn`})}let o=async()=>{for(let t of i)if(t.type===`connected`)try{await t.cleanup()}catch(n){K(`[Agent: ${e.agentType}] Error cleaning up MCP server '${t.name}': ${n}`,{level:`warn`})}};return{clients:[...t,...r],tools:a,cleanup:o}}function nHe(e){return e.type===`assistant`||e.type===`user`||e.type===`progress`||e.type===`system`&&`subtype`in e&&e.subtype===`compact_boundary`}async function*kY({agentDefinition:e,promptMessages:t,toolUseContext:n,canUseTool:r,isAsync:i,canShowPermissionPrompts:a,forkContextMessages:o,querySource:s,override:c,model:l,maxTurns:u,preserveToolUseResults:d,availableTools:f,allowedTools:p,onCacheSafeParams:m,contentReplacementState:h,useExactTools:g,worktreePath:_,description:v,transcriptSubdir:y,onQueryProgress:b}){let x=n.getAppState(),S=x.toolPermissionContext.mode,C=n.setAppStateForTasks??n.setAppState,w=WH(e.model,n.options.mainLoopModel,l,S),T=c?.agentId?c.agentId:JH();y&&h6(T,y),ese()&&(n.agentId??Wr(),e.agentType);let E=[...o?PH(o):[],...t],D=o===void 0?PT(100):LT(n.readFileState),[O,k]=await Promise.all([c?.userContext??pO(),c?.systemContext??fO()]),A=e.omitAgentsMd&&!c?.userContext&&!0,{agentsMd:ee,...te}=O,ne=A?te:O,{gitStatus:re,...ie}=k,ae=e.agentType===`Explore`||e.agentType===`Plan`?ie:k,j=e.permissionMode,oe=()=>{let e=n.getAppState(),t=e.toolPermissionContext;j&&e.toolPermissionContext.mode!==`bypassPermissions`&&e.toolPermissionContext.mode!==`acceptEdits`&&e.toolPermissionContext.mode!==`auto`&&(t={...t,mode:j});let r=a===void 0?j!==`bubble`&&i:!a;return r&&(t={...t,shouldAvoidPermissionPrompts:!0}),i&&!r&&(t={...t,awaitAutomatedChecksBeforeDialog:!0}),p!==void 0&&(t={...t,alwaysAllowRules:{cliArg:e.toolPermissionContext.alwaysAllowRules.cliArg,session:[...p]}}),t===e.toolPermissionContext?e:{...e,toolPermissionContext:t}},se=g?f:fU(e,f,i).resolvedTools,ce=Array.from(x.toolPermissionContext.additionalWorkingDirectories.keys()),M=c?.systemPrompt?c.systemPrompt:t_(await rHe(e,n,w,ce,se)),N=c?.abortController?c.abortController:i?new AbortController:n.abortController,le=[];for await(let t of Eat(T,e.agentType,N.signal))t.additionalContexts&&t.additionalContexts.length>0&&le.push(...t.additionalContexts);if(le.length>0){let e=a2({type:`hook_additional_context`,content:le,hookName:`SubagentStart`,toolUseID:Lc(),hookEvent:`SubagentStart`});E.push(e)}let ue=!ab(`hooks`)||ob(e.source);e.hooks&&ue&&$Ve(C,T,e.hooks,`agent '${e.agentType}'`,!0);let de=e.skills??[];if(de.length>0){let t=await $3(Hr()),r=[];for(let n of de){let i=iHe(n,t,e);if(!i){K(`[Agent: ${e.agentType}] Warning: Skill '${n}' specified in frontmatter was not found`,{level:`warn`});continue}let a=Xtt(i,t);if(a.type!==`prompt`){K(`[Agent: ${e.agentType}] Warning: Skill '${n}' is not a prompt-based skill`,{level:`warn`});continue}r.push({skillName:n,skill:a})}let{formatSkillLoadingMetadata:i}=await import(`./processSlashCommand-BsL1c7gz.js`),a=await Promise.all(r.map(async({skillName:e,skill:t})=>({skillName:e,skill:t,content:await t.getPromptForCommand(``,n)})));for(let{skillName:t,skill:n,content:r}of a){K(`[Agent: ${e.agentType}] Preloaded skill '${t}'`);let a=i(t,n.progressMessage);E.push(Q({content:[{type:`text`,text:a},...r],isMeta:!0}))}}let{clients:fe,tools:pe,cleanup:me}=await tHe(e,n.options.mcpClients),he=pe.length>0?bm([...se,...pe],`name`):se,ge=o0(n,{options:{isNonInteractiveSession:g?n.options.isNonInteractiveSession:i?!0:n.options.isNonInteractiveSession??!1,appendSystemPrompt:n.options.appendSystemPrompt,tools:he,commands:[],debug:n.options.debug,verbose:n.options.verbose,mainLoopModel:w,thinkingConfig:g?n.options.thinkingConfig:{type:`disabled`},mcpClients:fe,mcpResources:n.options.mcpResources,agentDefinitions:n.options.agentDefinitions,...g&&{querySource:s}},agentId:T,agentType:e.agentType,messages:E,readFileState:D,abortController:N,getAppState:oe,shareSetAppState:!i,shareSetResponseLength:!0,criticalSystemReminder_EXPERIMENTAL:e.criticalSystemReminder_EXPERIMENTAL,contentReplacementState:h});d&&(ge.preserveToolUseResults=!0),m&&m({systemPrompt:M,userContext:ne,systemContext:ae,toolUseContext:ge,forkContextMessages:E}),w6(E,T).catch(e=>K(`Failed to record sidechain transcript: ${e}`)),v6(T,{agentType:e.agentType,..._&&{worktreePath:_},...v&&{description:v}}).catch(e=>K(`Failed to write agent metadata: ${e}`));let _e=E.at(-1)?.uuid??null;try{for await(let t of t0({messages:E,systemPrompt:M,userContext:ne,systemContext:ae,canUseTool:r,toolUseContext:ge,querySource:s,maxTurns:u??e.maxTurns})){if(b?.(),t.type===`stream_event`&&t.event.type===`message_start`&&t.ttftMs!=null){n.pushApiMetricsEntry?.(t.ttftMs);continue}if(t.type===`attachment`){if(t.attachment.type===`max_turns_reached`){K(`[Agent
1595
1595
  : $
1596
1596
  {
1597
1597
  agentDefinition.agentType
@@ -1633,7 +1633,7 @@ Rejected plan:
1633
1633
  `);{let e=s.getAppState(),t=await gU({agentMessages:i,tools:s.options.tools,toolPermissionContext:e.toolPermissionContext,abortSignal:a.abortController.signal,subagentType:v.agentType,totalToolUseCount:c.totalToolUseCount});t&&(l=`${t}\n\n${l}`)}let u=await re();I0({taskId:o,description:n,status:`completed`,setAppState:h,finalMessage:l,usage:{totalTokens:j0(t),toolUses:c.totalToolUseCount,durationMs:c.totalDurationMs},toolUseId:s.toolUseId,...u})}catch(e){if(e instanceof pi){L0(o,h),T.agentType,T.resolvedAgentModel,Date.now()-T.startTime,T.isBuiltInAgent;let e=await re(),t=_U(i);I0({taskId:o,description:n,status:`killed`,setAppState:h,toolUseId:s.toolUseId,finalMessage:t,...e});return}let t=G(e);i6e(o,t,h);let r=await re();I0({taskId:o,description:n,status:`failed`,error:t,setAppState:h,toolUseId:s.toolUseId,...r})}finally{e?.(),ii(t)}});let c=s.options.tools.some(e=>us(e,`Read`)||us(e,`Bash`));return{data:{isAsync:!0,status:`async_launched`,agentId:o,description:n,prompt:e,outputFile:U8(o),canReadOutputFile:c}}}}if(S.type!==`message`)continue;let{result:C}=S;if(C.done)break;let w=C.value;if(i.push(w),M0(o,w,c,s.options.tools),f){let e=mU(w);e&&(hU(o,f,s.toolUseId,n,a,e),$r()&&R0(f,N0(o),h))}if(w.type===`progress`&&(w.data?.type===`bash_progress`||w.data?.type===`powershell_progress`)&&u&&u({toolUseID:w.toolUseID,data:w.data}),w.type!==`assistant`&&w.type!==`user`)continue;if(w.type===`assistant`){let e=MD(w);e>0&&s.setResponseLength(t=>t+e)}let E=u3([w]);for(let e of E)for(let n of e.message?.content??[])n.type!==`tool_use`&&n.type!==`tool_result`||u&&u({toolUseID:`agent_${l.message.id}`,data:{message:e,type:`agent_progress`,prompt:``,agentId:t}})}}catch(e){if(e instanceof pi)throw C=!0,T.agentType,T.resolvedAgentModel,Date.now()-T.startTime,T.isBuiltInAgent,e;K(`Sync agent error: ${G(e)}`,{level:`error`}),S=wi(e)}finally{if(s.setToolJSX&&s.setToolJSX(null),y?.(),f&&(c6e(f,h),!_)){let e=N0(o);EE({type:`system`,subtype:`task_notification`,task_id:f,tool_use_id:s.toolUseId,status:S?`failed`:C?`stopped`:`completed`,output_file:``,summary:n,usage:{total_tokens:e.tokenCount,tool_uses:e.toolUseCount,duration_ms:Date.now()-a}})}ii(t),m?.(),_||(E=await re())}let D=i.findLast(e=>e.type!==`system`&&e.type!==`progress`);if(D&&Zme(D))throw T.agentType,T.resolvedAgentModel,Date.now()-T.startTime,T.isBuiltInAgent,new pi;if(S){if(!i.some(e=>e.type===`assistant`))throw S;K(`Sync agent recovering from error with ${i.length} messages`)}let O=pU(i,t,T);{let e=s.getAppState(),t=await gU({agentMessages:i,tools:s.options.tools,toolPermissionContext:e.toolPermissionContext,abortSignal:s.abortController.signal,subagentType:v.agentType,totalToolUseCount:O.totalToolUseCount});t&&(O.content=[{type:`text`,text:t},...O.content])}return{data:{status:`completed`,prompt:e,...O,...E}}}))}},isReadOnly(){return!0},toAutoClassifierInput(e){let t=e,n=[t.subagent_type].filter(e=>e!==void 0);return`${n.length>0?`(${n.join(`, `)}): `:`: `}${t.prompt}`},isConcurrencySafe(){return!0},userFacingName:TKe,userFacingNameBackgroundColor:EKe,getActivityDescription(e){return e?.description??`Running task`},async checkPermissions(e,t){return{behavior:`allow`,updatedInput:e}},mapToolResultToToolResultBlockParam(e,t){let n=e;if(`status`in n&&n.status===`remote_launched`){let e=n;return{tool_use_id:t,type:`tool_result`,content:[{type:`text`,text:`Remote agent launched in CCR.\ntaskId: ${e.taskId}\nsession_url: ${e.sessionUrl}\noutput_file: ${e.outputFile}\nThe agent is running remotely. You will be notified automatically when it completes.\nBriefly tell the user what you launched and end your response.`}]}}if(e.status===`async_launched`)return{tool_use_id:t,type:`tool_result`,content:[{type:`text`,text:`${`Async agent launched successfully.\nagentId: ${e.agentId} (internal ID - do not mention to user. Use SendMessage with to: '${e.agentId}' to continue this agent.)\nThe agent is working in the background. You will be notified automatically when it completes.`}\n${e.canReadOutputFile?`Do not duplicate this agent's work — avoid working with the same files or topics it is using. Work on non-overlapping tasks, or briefly tell the user what you launched and end your response.\noutput_file: ${e.outputFile}\nIf asked, you can check progress before completion by using ${os} or ${ks} tail on the output file.`:`Briefly tell the user what you launched and end your response. Do not generate any other text — agent results will arrive in a subsequent message.`}`}]};if(e.status===`completed`){let n=e,r=n.worktreePath?`\nworktreePath: ${n.worktreePath}\nworktreeBranch: ${n.worktreeBranch}`:``,i=e.content.length>0?e.content:[{type:`text`,text:`(Subagent completed but returned no output.)`}];return e.agentType&&Cee.has(e.agentType)&&!r?Fs(t,i):{tool_use_id:t,type:`tool_result`,content:[...i,{type:`text`,text:`agentId: ${e.agentId} (use SendMessage with to: '${e.agentId}' to continue this agent)${r}
1634
1634
  <usage>total_tokens: ${e.totalTokens}
1635
1635
  tool_uses: ${e.totalToolUseCount}
1636
- duration_ms: ${e.totalDurationMs}</usage>`}]}}throw Error(`Unexpected agent tool result status: ${e.status}`)},renderToolResultMessage:vKe,renderToolUseMessage:yKe,renderToolUseTag:bKe,renderToolUseProgressMessage:xZ,renderToolUseRejectedMessage:xKe,renderToolUseErrorMessage:SKe,renderGroupedToolUse:wKe})}));function RKe(e,t){let n=t?`${e}@${t.toLowerCase()}`:e;return Fc(`sha256`).update(n+GKe).digest(`hex`).slice(0,16)}function zKe(e,t,n){return t===WKe?`default-bundle`:yv(t)?`official`:n?.has(e)?`org`:`user-local`}function BKe(e,t,n){return e.isBuiltin?`default-enable`:t?.has(e.name)?`org-policy`:n.some(t=>e.path.startsWith(t.endsWith(bc)?t:t+bc))?`seed-mount`:`user-install`}function kZ(e,t,n=null){let r=zKe(e,t,n),i=r===`official`||r===`default-bundle`;return{plugin_id_hash:RKe(e,t),plugin_scope:r,plugin_name_redacted:i?e:`third-party`,marketplace_name_redacted:i&&t?t:`third-party`,is_official_plugin:i}}function AZ(e,t=null){let{marketplace:n}=vv(e.repository);return kZ(e.pluginManifest.name,n,t)}function VKe(e,t,n){for(let r of e){let{marketplace:e}=vv(r.repository);r.name,{...e&&{_PROTO_marketplace_name:e},...kZ(r.name,e,t)},BKe(r,t,n),+!!r.skillsPath+(r.skillsPaths?.length??0),+!!r.commandsPath+(r.commandsPaths?.length??0),r.manifest.mcpServers,r.hooksConfig,{...r.manifest.version&&{version:r.manifest.version}}}}function HKe(e){let t=String(e?.message??e);return/ENOTFOUND|ECONNREFUSED|EAI_AGAIN|ETIMEDOUT|ECONNRESET|network|Could not resolve|Connection refused|timed out/i.test(t)?`network`:/\b404\b|not found|does not exist|no such plugin/i.test(t)?`not-found`:/\b40[13]\b|EACCES|EPERM|permission denied|unauthorized/i.test(t)?`permission`:/invalid|malformed|schema|validation|parse error/i.test(t)?`validation`:`unknown`}function UKe(e,t){for(let n of e){let{name:e,marketplace:r}=vv(n.source),i=`plugin`in n&&n.plugin?n.plugin:e;n.type,{...r&&{_PROTO_marketplace_name:r},...kZ(i,r,t)}}}var WKe,GKe,jZ=n((()=>{La(),bv(),WKe=`builtin`,GKe=`claude-plugin-telemetry-v1`}));function KKe(e){let t=Date.now(),n=MZ.get(e);n!==void 0&&t-n<JKe||(MZ.set(e,t),Gi(n=>{let r=n.skillUsage?.[e];return{...n,skillUsage:{...n.skillUsage,[e]:{usageCount:(r?.usageCount??0)+1,lastUsedAt:t}}}}))}function qKe(e){let t=qi().skillUsage?.[e];if(!t)return 0;let n=.5**((Date.now()-t.lastUsedAt)/(1e3*60*60*24)/7);return t.usageCount*Math.max(n,.1)}var JKe,MZ,YKe=n((()=>{Wi(),JKe=6e4,MZ=new Map}));function XKe(e,t){return t?e.map(e=>e.type===`user`?{...e,sourceToolUseID:t}:e):e}function ZKe(e,t){let n=Array.isArray(e.message.content)?e.message.content.find(e=>e.type===`tool_use`&&e.name===t):void 0;return n&&n.type===`tool_use`?n.id:void 0}var QKe=n((()=>{}));function $Ke(e){if(`status`in e&&e.status===`forked`)return(0,PZ.jsx)($,{height:1,children:(0,PZ.jsx)(F,{children:(0,PZ.jsx)(ke,{children:[`Done`]})})});let t=[`Successfully loaded skill`];if(`allowedTools`in e&&e.allowedTools&&e.allowedTools.length>0){let n=e.allowedTools.length;t.push(`${n} ${Xa(n,`tool`)} allowed`)}return`model`in e&&e.model&&t.push(e.model),(0,PZ.jsx)($,{height:1,children:(0,PZ.jsx)(F,{children:(0,PZ.jsx)(ke,{children:t})})})}function eqe({skill:e},{commands:t}){return e?t?.find(t=>t.name===e)?.loadedFrom===`commands_DEPRECATED`?`/${e}`:e:null}function NZ(e,{tools:t,verbose:n}){if(!e.length)return(0,PZ.jsx)($,{height:1,children:(0,PZ.jsx)(F,{dimColor:!0,children:rqe})});let r=n?e:e.slice(-3),i=e.length-r.length,{inProgressToolUseIDs:a}=g3(e.map(e=>e.data));return(0,PZ.jsx)($,{children:(0,PZ.jsxs)(P,{flexDirection:`column`,children:[(0,PZ.jsx)(Qx,{children:r.map(e=>(0,PZ.jsx)(P,{height:1,overflow:`hidden`,children:(0,PZ.jsx)(_Z,{message:e.data.message,lookups:_3,addMargin:!1,tools:t,commands:[],verbose:n,inProgressToolUseIDs:a,progressMessagesForMessage:[],shouldAnimate:!1,shouldShowDot:!1,style:`condensed`,isTranscriptMode:!1,isStatic:!0})},e.uuid))}),i>0&&(0,PZ.jsxs)(F,{dimColor:!0,children:[`+`,i,` more tool `,Xa(i,`use`)]})]})})}function tqe(e,{progressMessagesForMessage:t,tools:n,verbose:r}){return(0,PZ.jsxs)(PZ.Fragment,{children:[NZ(t,{tools:n,verbose:r}),(0,PZ.jsx)(LY,{})]})}function nqe(e,{progressMessagesForMessage:t,tools:n,verbose:r}){return(0,PZ.jsxs)(PZ.Fragment,{children:[NZ(t,{tools:n,verbose:r}),(0,PZ.jsx)(gS,{result:e,verbose:r})]})}var PZ,rqe,iqe=n((()=>{rS(),yS(),zY(),Ze(),vZ(),dS(),v3(),Za(),PZ=$e(),rqe=`Initializing…`})),aqe=i({}),oqe=n((()=>{})),sqe=i({}),cqe=n((()=>{})),lqe=i({}),uqe=n((()=>{}));async function FZ(e){let t=e.getAppState().mcp.commands.filter(e=>e.type===`prompt`&&e.loadedFrom===`mcp`);return t.length===0?q3(Hr()):bm([...await q3(Hr()),...t],`name`)}async function dqe(e,t,n,r,i,a,o){let s=Date.now(),c=JH();Z3().has(t);let l=pqe(e);e.source;let u=IZ.isSkillSearchEnabled()?{was_discovered:r.discoveredSkillNames?.has(t)??!1}:{},d=e.pluginInfo?vv(e.pluginInfo.repository).marketplace:void 0;r.queryTracking?.depth;let f=Ij()?.agentId;({...f&&{parent_agent_id:f},...u,...e.pluginInfo&&{_PROTO_plugin_name:e.pluginInfo.pluginManifest.name,...d&&{_PROTO_marketplace_name:d},plugin_name:l?e.pluginInfo.pluginManifest.name:`third-party`,plugin_repository:l?e.pluginInfo.repository:`third-party`,...AZ(e.pluginInfo)}});let{modifiedGetAppState:p,baseAgent:m,promptMessages:h,skillContent:g}=await r3e(e,n||``,r),_=[];K(`SkillTool executing forked skill ${t} with agent ${m.agentType}`);try{for await(let t of kY({agentDefinition:m,promptMessages:h,toolUseContext:{...r,getAppState:p},canUseTool:i,isAsync:!1,querySource:`agent:custom`,model:e.model,availableTools:r.options.tools,override:{agentId:c}}))if(_.push(t),(t.type===`assistant`||t.type===`user`)&&o){let e=u3([t]);for(let t of e){let e=t.message?.content;Array.isArray(e)&&e.some(e=>e.type===`tool_use`||e.type===`tool_result`)&&o({toolUseID:`skill_${a.message.id}`,data:{message:t,type:`skill_progress`,prompt:g,agentId:c}})}}let n=i3e(_,`Skill execution completed`);return _.length=0,K(`SkillTool forked skill ${t} completed in ${Date.now()-s}ms`),{data:{success:!0,commandName:t,status:`forked`,agentId:c,result:n}}}finally{ii(c)}}function fqe(e){for(let t of Object.keys(e)){if(gqe.has(t))continue;let n=e[t];if(n!=null&&!(Array.isArray(n)&&n.length===0)&&!(typeof n==`object`&&!Array.isArray(n)&&Object.keys(n).length===0))return!1}return!0}function pqe(e){return e.source!==`plugin`||!e.pluginInfo?.repository?!1:yv(vv(e.pluginInfo.repository).marketplace)}var IZ,mqe,hqe,LZ,gqe,_qe=n((()=>{xm(),H(),t6(),Ms(),q(),j9(),bv(),jZ(),It(),Ta(),La(),Bj(),l0(),rt(),v3(),wo(),YKe(),XH(),AY(),QKe(),Ls(),cy(),iqe(),oqe(),cqe(),uqe(),Ep(),IZ={...aqe,...sqe,...lqe,...Cp},mqe=R(()=>z({skill:B().describe(`The skill name. E.g., "commit", "review-pr", or "pdf"`),args:B().optional().describe(`Optional arguments for the skill`)})),hqe=R(()=>_n([z({success:Ot().describe(`Whether the skill is valid`),commandName:B().describe(`The name of the skill`),allowedTools:I(B()).optional().describe(`Tools allowed by this skill`),model:B().optional().describe(`Model override if specified`),status:L(`inline`).optional().describe(`Execution status`)}),z({success:Ot().describe(`Whether the skill completed successfully`),commandName:B().describe(`The name of the skill`),status:L(`forked`).describe(`Execution status`),agentId:B().describe(`The ID of the sub-agent that executed the skill`),result:B().describe(`The result from the forked skill execution`)})])),LZ=Cs({name:ns,searchHint:`invoke a slash-command skill`,maxResultSizeChars:1e5,get inputSchema(){return mqe()},get outputSchema(){return hqe()},description:async({skill:e})=>`Execute skill: ${e}`,prompt:async()=>sy(Hr()),toAutoClassifierInput:({skill:e})=>e??``,async validateInput({skill:e},t){let n=e.trim();if(!n)return{result:!1,message:`Invalid skill format: ${e}`,errorCode:1};let r=n.startsWith(`/`)?n.substring(1):n,i=J3(r,await FZ(t));return i?i.disableModelInvocation?{result:!1,message:`Skill ${r} cannot be used with ${ns} tool due to disable-model-invocation`,errorCode:4}:i.type===`prompt`?{result:!0}:{result:!1,message:`Skill ${r} is not a prompt-based skill`,errorCode:5}:{result:!1,message:`Unknown skill: ${r}`,errorCode:2}},async checkPermissions({skill:e,args:t},n){let r=e.trim(),i=r.startsWith(`/`)?r.substring(1):r,a=n.getAppState().toolPermissionContext,o=J3(i,await FZ(n)),s=e=>{let t=e.startsWith(`/`)?e.substring(1):e;if(t===i)return!0;if(t.endsWith(`:*`)){let e=t.slice(0,-2);return i.startsWith(e)}return!1},c=E9(a,LZ,`deny`);for(let[e,t]of c.entries())if(s(e))return{behavior:`deny`,message:`Skill execution blocked by permission rules`,decisionReason:{type:`rule`,rule:t}};let l=E9(a,LZ,`allow`);for(let[n,r]of l.entries())if(s(n))return{behavior:`allow`,updatedInput:{skill:e,args:t},decisionReason:{type:`rule`,rule:r}};if(o?.type===`prompt`&&fqe(o))return{behavior:`allow`,updatedInput:{skill:e,args:t},decisionReason:void 0};let u=[{type:`addRules`,rules:[{toolName:ns,ruleContent:i}],behavior:`allow`,destination:`localSettings`},{type:`addRules`,rules:[{toolName:ns,ruleContent:`${i}:*`}],behavior:`allow`,destination:`localSettings`}];return{behavior:`ask`,message:`Execute skill: ${i}`,decisionReason:void 0,suggestions:u,updatedInput:{skill:e,args:t},metadata:o?{command:o}:void 0}},async call({skill:e,args:t},n,r,i,a){let o=e.trim(),s=o.startsWith(`/`)?o.substring(1):o,c=await FZ(n),l=J3(s,c);if(KKe(s),l?.type===`prompt`&&l.context===`fork`)return dqe(l,s,t,n,r,i,a);let{processPromptSlashCommand:u}=await import(`./processSlashCommand-BcMLjAEQ.js`),d=await u(s,t||``,c,n);if(!d.shouldQuery)throw Error(`Command processing failed`);let f=d.allowedTools||[],p=d.model;Z3().has(s),l?.type===`prompt`&&l.source;let m=l?.type===`prompt`&&pqe(l),h=IZ.isSkillSearchEnabled()?{was_discovered:n.discoveredSkillNames?.has(s)??!1}:{},g=l?.type===`prompt`&&l.pluginInfo?vv(l.pluginInfo.repository).marketplace:void 0;n.queryTracking?.depth;let _=Ij()?.agentId;({..._&&{parent_agent_id:_},...h,...l?.type===`prompt`&&l.pluginInfo&&{_PROTO_plugin_name:l.pluginInfo.pluginManifest.name,...g&&{_PROTO_marketplace_name:g},plugin_name:m?l.pluginInfo.pluginManifest.name:`third-party`,plugin_repository:m?l.pluginInfo.repository:`third-party`,...AZ(l.pluginInfo)}});let v=ZKe(i,ns),y=XKe(d.messages.filter(e=>{if(e.type===`progress`)return!1;if(e.type===`user`&&`message`in e){let t=e.message.content;if(typeof t==`string`&&t.includes(`<command-message>`))return!1}return!0}),v);return K(`SkillTool returning ${y.length} newMessages for skill ${s}`),{data:{success:!0,commandName:s,allowedTools:f.length>0?f:void 0,model:p},newMessages:y,contextModifier(e){let t=e;if(f.length>0){let e=t.getAppState;t={...t,getAppState(){let t=e();return{...t,toolPermissionContext:{...t.toolPermissionContext,alwaysAllowRules:{...t.toolPermissionContext.alwaysAllowRules,command:[...new Set([...t.toolPermissionContext.alwaysAllowRules.command||[],...f])]}}}}}}return p&&(t={...t,options:{...t.options,mainLoopModel:Sie(p,e.options.mainLoopModel)}}),t}}},mapToolResultToToolResultBlockParam(e,t){return`status`in e&&e.status===`forked`?{type:`tool_result`,tool_use_id:t,content:`Skill "${e.commandName}" completed (forked execution).\n\nResult:\n${e.result}`}:{type:`tool_result`,tool_use_id:t,content:`Launching skill: ${e.commandName}`}},renderToolResultMessage:$Ke,renderToolUseMessage:eqe,renderToolUseProgressMessage:NZ,renderToolUseRejectedMessage:tqe,renderToolUseErrorMessage:nqe}),gqe=new Set(`type.progressMessage.contentLength.argNames.model.source.pluginInfo.disableNonInteractive.skillRoot.context.agent.getPromptForCommand.frontmatterKeys.name.description.hasUserSpecifiedDescription.isEnabled.isHidden.aliases.isMcp.argumentHint.whenToUse.paths.version.disableModelInvocation.userInvocable.loadedFrom.immediate.userFacingName`.split(`.`))}));function vqe(e,t,n){let{head:r,tail:i,mtime:a,size:o}=t,s=r.indexOf(`
1636
+ duration_ms: ${e.totalDurationMs}</usage>`}]}}throw Error(`Unexpected agent tool result status: ${e.status}`)},renderToolResultMessage:vKe,renderToolUseMessage:yKe,renderToolUseTag:bKe,renderToolUseProgressMessage:xZ,renderToolUseRejectedMessage:xKe,renderToolUseErrorMessage:SKe,renderGroupedToolUse:wKe})}));function RKe(e,t){let n=t?`${e}@${t.toLowerCase()}`:e;return Fc(`sha256`).update(n+GKe).digest(`hex`).slice(0,16)}function zKe(e,t,n){return t===WKe?`default-bundle`:yv(t)?`official`:n?.has(e)?`org`:`user-local`}function BKe(e,t,n){return e.isBuiltin?`default-enable`:t?.has(e.name)?`org-policy`:n.some(t=>e.path.startsWith(t.endsWith(bc)?t:t+bc))?`seed-mount`:`user-install`}function kZ(e,t,n=null){let r=zKe(e,t,n),i=r===`official`||r===`default-bundle`;return{plugin_id_hash:RKe(e,t),plugin_scope:r,plugin_name_redacted:i?e:`third-party`,marketplace_name_redacted:i&&t?t:`third-party`,is_official_plugin:i}}function AZ(e,t=null){let{marketplace:n}=vv(e.repository);return kZ(e.pluginManifest.name,n,t)}function VKe(e,t,n){for(let r of e){let{marketplace:e}=vv(r.repository);r.name,{...e&&{_PROTO_marketplace_name:e},...kZ(r.name,e,t)},BKe(r,t,n),+!!r.skillsPath+(r.skillsPaths?.length??0),+!!r.commandsPath+(r.commandsPaths?.length??0),r.manifest.mcpServers,r.hooksConfig,{...r.manifest.version&&{version:r.manifest.version}}}}function HKe(e){let t=String(e?.message??e);return/ENOTFOUND|ECONNREFUSED|EAI_AGAIN|ETIMEDOUT|ECONNRESET|network|Could not resolve|Connection refused|timed out/i.test(t)?`network`:/\b404\b|not found|does not exist|no such plugin/i.test(t)?`not-found`:/\b40[13]\b|EACCES|EPERM|permission denied|unauthorized/i.test(t)?`permission`:/invalid|malformed|schema|validation|parse error/i.test(t)?`validation`:`unknown`}function UKe(e,t){for(let n of e){let{name:e,marketplace:r}=vv(n.source),i=`plugin`in n&&n.plugin?n.plugin:e;n.type,{...r&&{_PROTO_marketplace_name:r},...kZ(i,r,t)}}}var WKe,GKe,jZ=n((()=>{La(),bv(),WKe=`builtin`,GKe=`claude-plugin-telemetry-v1`}));function KKe(e){let t=Date.now(),n=MZ.get(e);n!==void 0&&t-n<JKe||(MZ.set(e,t),Gi(n=>{let r=n.skillUsage?.[e];return{...n,skillUsage:{...n.skillUsage,[e]:{usageCount:(r?.usageCount??0)+1,lastUsedAt:t}}}}))}function qKe(e){let t=qi().skillUsage?.[e];if(!t)return 0;let n=.5**((Date.now()-t.lastUsedAt)/(1e3*60*60*24)/7);return t.usageCount*Math.max(n,.1)}var JKe,MZ,YKe=n((()=>{Wi(),JKe=6e4,MZ=new Map}));function XKe(e,t){return t?e.map(e=>e.type===`user`?{...e,sourceToolUseID:t}:e):e}function ZKe(e,t){let n=Array.isArray(e.message.content)?e.message.content.find(e=>e.type===`tool_use`&&e.name===t):void 0;return n&&n.type===`tool_use`?n.id:void 0}var QKe=n((()=>{}));function $Ke(e){if(`status`in e&&e.status===`forked`)return(0,PZ.jsx)($,{height:1,children:(0,PZ.jsx)(F,{children:(0,PZ.jsx)(ke,{children:[`Done`]})})});let t=[`Successfully loaded skill`];if(`allowedTools`in e&&e.allowedTools&&e.allowedTools.length>0){let n=e.allowedTools.length;t.push(`${n} ${Xa(n,`tool`)} allowed`)}return`model`in e&&e.model&&t.push(e.model),(0,PZ.jsx)($,{height:1,children:(0,PZ.jsx)(F,{children:(0,PZ.jsx)(ke,{children:t})})})}function eqe({skill:e},{commands:t}){return e?t?.find(t=>t.name===e)?.loadedFrom===`commands_DEPRECATED`?`/${e}`:e:null}function NZ(e,{tools:t,verbose:n}){if(!e.length)return(0,PZ.jsx)($,{height:1,children:(0,PZ.jsx)(F,{dimColor:!0,children:rqe})});let r=n?e:e.slice(-3),i=e.length-r.length,{inProgressToolUseIDs:a}=g3(e.map(e=>e.data));return(0,PZ.jsx)($,{children:(0,PZ.jsxs)(P,{flexDirection:`column`,children:[(0,PZ.jsx)(Qx,{children:r.map(e=>(0,PZ.jsx)(P,{height:1,overflow:`hidden`,children:(0,PZ.jsx)(_Z,{message:e.data.message,lookups:_3,addMargin:!1,tools:t,commands:[],verbose:n,inProgressToolUseIDs:a,progressMessagesForMessage:[],shouldAnimate:!1,shouldShowDot:!1,style:`condensed`,isTranscriptMode:!1,isStatic:!0})},e.uuid))}),i>0&&(0,PZ.jsxs)(F,{dimColor:!0,children:[`+`,i,` more tool `,Xa(i,`use`)]})]})})}function tqe(e,{progressMessagesForMessage:t,tools:n,verbose:r}){return(0,PZ.jsxs)(PZ.Fragment,{children:[NZ(t,{tools:n,verbose:r}),(0,PZ.jsx)(LY,{})]})}function nqe(e,{progressMessagesForMessage:t,tools:n,verbose:r}){return(0,PZ.jsxs)(PZ.Fragment,{children:[NZ(t,{tools:n,verbose:r}),(0,PZ.jsx)(gS,{result:e,verbose:r})]})}var PZ,rqe,iqe=n((()=>{rS(),yS(),zY(),Ze(),vZ(),dS(),v3(),Za(),PZ=$e(),rqe=`Initializing…`})),aqe=i({}),oqe=n((()=>{})),sqe=i({}),cqe=n((()=>{})),lqe=i({}),uqe=n((()=>{}));async function FZ(e){let t=e.getAppState().mcp.commands.filter(e=>e.type===`prompt`&&e.loadedFrom===`mcp`);return t.length===0?q3(Hr()):bm([...await q3(Hr()),...t],`name`)}async function dqe(e,t,n,r,i,a,o){let s=Date.now(),c=JH();Z3().has(t);let l=pqe(e);e.source;let u=IZ.isSkillSearchEnabled()?{was_discovered:r.discoveredSkillNames?.has(t)??!1}:{},d=e.pluginInfo?vv(e.pluginInfo.repository).marketplace:void 0;r.queryTracking?.depth;let f=Ij()?.agentId;({...f&&{parent_agent_id:f},...u,...e.pluginInfo&&{_PROTO_plugin_name:e.pluginInfo.pluginManifest.name,...d&&{_PROTO_marketplace_name:d},plugin_name:l?e.pluginInfo.pluginManifest.name:`third-party`,plugin_repository:l?e.pluginInfo.repository:`third-party`,...AZ(e.pluginInfo)}});let{modifiedGetAppState:p,baseAgent:m,promptMessages:h,skillContent:g}=await r3e(e,n||``,r),_=[];K(`SkillTool executing forked skill ${t} with agent ${m.agentType}`);try{for await(let t of kY({agentDefinition:m,promptMessages:h,toolUseContext:{...r,getAppState:p},canUseTool:i,isAsync:!1,querySource:`agent:custom`,model:e.model,availableTools:r.options.tools,override:{agentId:c}}))if(_.push(t),(t.type===`assistant`||t.type===`user`)&&o){let e=u3([t]);for(let t of e){let e=t.message?.content;Array.isArray(e)&&e.some(e=>e.type===`tool_use`||e.type===`tool_result`)&&o({toolUseID:`skill_${a.message.id}`,data:{message:t,type:`skill_progress`,prompt:g,agentId:c}})}}let n=i3e(_,`Skill execution completed`);return _.length=0,K(`SkillTool forked skill ${t} completed in ${Date.now()-s}ms`),{data:{success:!0,commandName:t,status:`forked`,agentId:c,result:n}}}finally{ii(c)}}function fqe(e){for(let t of Object.keys(e)){if(gqe.has(t))continue;let n=e[t];if(n!=null&&!(Array.isArray(n)&&n.length===0)&&!(typeof n==`object`&&!Array.isArray(n)&&Object.keys(n).length===0))return!1}return!0}function pqe(e){return e.source!==`plugin`||!e.pluginInfo?.repository?!1:yv(vv(e.pluginInfo.repository).marketplace)}var IZ,mqe,hqe,LZ,gqe,_qe=n((()=>{xm(),H(),t6(),Ms(),q(),j9(),bv(),jZ(),It(),Ta(),La(),Bj(),l0(),rt(),v3(),wo(),YKe(),XH(),AY(),QKe(),Ls(),cy(),iqe(),oqe(),cqe(),uqe(),Ep(),IZ={...aqe,...sqe,...lqe,...Cp},mqe=R(()=>z({skill:B().describe(`The skill name. E.g., "commit", "review-pr", or "pdf"`),args:B().optional().describe(`Optional arguments for the skill`)})),hqe=R(()=>_n([z({success:Ot().describe(`Whether the skill is valid`),commandName:B().describe(`The name of the skill`),allowedTools:I(B()).optional().describe(`Tools allowed by this skill`),model:B().optional().describe(`Model override if specified`),status:L(`inline`).optional().describe(`Execution status`)}),z({success:Ot().describe(`Whether the skill completed successfully`),commandName:B().describe(`The name of the skill`),status:L(`forked`).describe(`Execution status`),agentId:B().describe(`The ID of the sub-agent that executed the skill`),result:B().describe(`The result from the forked skill execution`)})])),LZ=Cs({name:ns,searchHint:`invoke a slash-command skill`,maxResultSizeChars:1e5,get inputSchema(){return mqe()},get outputSchema(){return hqe()},description:async({skill:e})=>`Execute skill: ${e}`,prompt:async()=>sy(Hr()),toAutoClassifierInput:({skill:e})=>e??``,async validateInput({skill:e},t){let n=e.trim();if(!n)return{result:!1,message:`Invalid skill format: ${e}`,errorCode:1};let r=n.startsWith(`/`)?n.substring(1):n,i=J3(r,await FZ(t));return i?i.disableModelInvocation?{result:!1,message:`Skill ${r} cannot be used with ${ns} tool due to disable-model-invocation`,errorCode:4}:i.type===`prompt`?{result:!0}:{result:!1,message:`Skill ${r} is not a prompt-based skill`,errorCode:5}:{result:!1,message:`Unknown skill: ${r}`,errorCode:2}},async checkPermissions({skill:e,args:t},n){let r=e.trim(),i=r.startsWith(`/`)?r.substring(1):r,a=n.getAppState().toolPermissionContext,o=J3(i,await FZ(n)),s=e=>{let t=e.startsWith(`/`)?e.substring(1):e;if(t===i)return!0;if(t.endsWith(`:*`)){let e=t.slice(0,-2);return i.startsWith(e)}return!1},c=E9(a,LZ,`deny`);for(let[e,t]of c.entries())if(s(e))return{behavior:`deny`,message:`Skill execution blocked by permission rules`,decisionReason:{type:`rule`,rule:t}};let l=E9(a,LZ,`allow`);for(let[n,r]of l.entries())if(s(n))return{behavior:`allow`,updatedInput:{skill:e,args:t},decisionReason:{type:`rule`,rule:r}};if(o?.type===`prompt`&&fqe(o))return{behavior:`allow`,updatedInput:{skill:e,args:t},decisionReason:void 0};let u=[{type:`addRules`,rules:[{toolName:ns,ruleContent:i}],behavior:`allow`,destination:`localSettings`},{type:`addRules`,rules:[{toolName:ns,ruleContent:`${i}:*`}],behavior:`allow`,destination:`localSettings`}];return{behavior:`ask`,message:`Execute skill: ${i}`,decisionReason:void 0,suggestions:u,updatedInput:{skill:e,args:t},metadata:o?{command:o}:void 0}},async call({skill:e,args:t},n,r,i,a){let o=e.trim(),s=o.startsWith(`/`)?o.substring(1):o,c=await FZ(n),l=J3(s,c);if(KKe(s),l?.type===`prompt`&&l.context===`fork`)return dqe(l,s,t,n,r,i,a);let{processPromptSlashCommand:u}=await import(`./processSlashCommand-BsL1c7gz.js`),d=await u(s,t||``,c,n);if(!d.shouldQuery)throw Error(`Command processing failed`);let f=d.allowedTools||[],p=d.model;Z3().has(s),l?.type===`prompt`&&l.source;let m=l?.type===`prompt`&&pqe(l),h=IZ.isSkillSearchEnabled()?{was_discovered:n.discoveredSkillNames?.has(s)??!1}:{},g=l?.type===`prompt`&&l.pluginInfo?vv(l.pluginInfo.repository).marketplace:void 0;n.queryTracking?.depth;let _=Ij()?.agentId;({..._&&{parent_agent_id:_},...h,...l?.type===`prompt`&&l.pluginInfo&&{_PROTO_plugin_name:l.pluginInfo.pluginManifest.name,...g&&{_PROTO_marketplace_name:g},plugin_name:m?l.pluginInfo.pluginManifest.name:`third-party`,plugin_repository:m?l.pluginInfo.repository:`third-party`,...AZ(l.pluginInfo)}});let v=ZKe(i,ns),y=XKe(d.messages.filter(e=>{if(e.type===`progress`)return!1;if(e.type===`user`&&`message`in e){let t=e.message.content;if(typeof t==`string`&&t.includes(`<command-message>`))return!1}return!0}),v);return K(`SkillTool returning ${y.length} newMessages for skill ${s}`),{data:{success:!0,commandName:s,allowedTools:f.length>0?f:void 0,model:p},newMessages:y,contextModifier(e){let t=e;if(f.length>0){let e=t.getAppState;t={...t,getAppState(){let t=e();return{...t,toolPermissionContext:{...t.toolPermissionContext,alwaysAllowRules:{...t.toolPermissionContext.alwaysAllowRules,command:[...new Set([...t.toolPermissionContext.alwaysAllowRules.command||[],...f])]}}}}}}return p&&(t={...t,options:{...t.options,mainLoopModel:Sie(p,e.options.mainLoopModel)}}),t}}},mapToolResultToToolResultBlockParam(e,t){return`status`in e&&e.status===`forked`?{type:`tool_result`,tool_use_id:t,content:`Skill "${e.commandName}" completed (forked execution).\n\nResult:\n${e.result}`}:{type:`tool_result`,tool_use_id:t,content:`Launching skill: ${e.commandName}`}},renderToolResultMessage:$Ke,renderToolUseMessage:eqe,renderToolUseProgressMessage:NZ,renderToolUseRejectedMessage:tqe,renderToolUseErrorMessage:nqe}),gqe=new Set(`type.progressMessage.contentLength.argNames.model.source.pluginInfo.disableNonInteractive.skillRoot.context.agent.getPromptForCommand.frontmatterKeys.name.description.hasUserSpecifiedDescription.isEnabled.isHidden.aliases.isMcp.argumentHint.whenToUse.paths.version.disableModelInvocation.userInvocable.loadedFrom.immediate.userFacingName`.split(`.`))}));function vqe(e,t,n){let{head:r,tail:i,mtime:a,size:o}=t,s=r.indexOf(`
1637
1637
  `),c=s>=0?r.slice(0,s):r;if(c.includes(`"isSidechain":true`)||c.includes(`"isSidechain": true`))return null;let l=mr(i,`customTitle`)||mr(r,`customTitle`)||mr(i,`aiTitle`)||mr(r,`aiTitle`)||void 0,u=qte(r)||void 0,d=hn(r,`timestamp`),f;if(d){let e=Date.parse(d);Number.isNaN(e)||(f=e)}let p=l||mr(i,`lastPrompt`)||mr(i,`summary`)||u;if(!p)return null;let m=mr(i,`gitBranch`)||hn(r,`gitBranch`)||void 0,h=hn(r,`cwd`)||n||void 0,g=i.split(`
1638
1638
  `).findLast(e=>e.startsWith(`{"type":"tag"`));return{sessionId:e,summary:p,lastModified:a,fileSize:o,customTitle:l,firstPrompt:u,gitBranch:m,cwd:h,tag:g&&mr(g,`tag`)||void 0,createdAt:f}}async function RZ(e,t,n){let r;try{r=await Gc(e)}catch{return[]}return(await Promise.all(r.map(async r=>{if(!r.endsWith(`.jsonl`))return null;let i=bte(r.slice(0,-6));if(!i)return null;let a=X(e,r);if(!t)return{sessionId:i,filePath:a,mtime:0,projectPath:n};try{return{sessionId:i,filePath:a,mtime:(await Yc(a)).mtime.getTime(),projectPath:n}}catch{return null}}))).filter(e=>e!==null)}async function yqe(e){let t=await yee(e.filePath);if(!t)return null;let n=vqe(e.sessionId,t,e.projectPath);return n?(e.mtime&&(n.lastModified=e.mtime),n):null}function bqe(e,t){return t.mtime===e.mtime?t.sessionId<e.sessionId?-1:+(t.sessionId>e.sessionId):t.mtime-e.mtime}async function xqe(e,t,n){e.sort(bqe);let r=[],i=t&&t>0?t:1/0,a=0,o=new Set;for(let t=0;t<e.length&&r.length<i;){let s=Math.min(t+Eqe,e.length),c=e.slice(t,s),l=await Promise.all(c.map(yqe));for(let e=0;e<l.length&&r.length<i;e++){t++;let i=l[e];if(i&&!o.has(i.sessionId)){if(o.add(i.sessionId),a<n){a++;continue}r.push(i)}}}return r}async function Sqe(e){let t=await Promise.all(e.map(yqe)),n=new Map;for(let e of t){if(!e)continue;let t=n.get(e.sessionId);(!t||e.lastModified>t.lastModified)&&n.set(e.sessionId,e)}let r=[...n.values()];return r.sort((e,t)=>t.lastModified===e.lastModified?t.sessionId<e.sessionId?-1:+(t.sessionId>e.sessionId):t.lastModified-e.lastModified),r}async function Cqe(e,t,n){let r=await Vte(e),i;if(t)try{i=await Oee(r)}catch{i=[]}else i=[];if(i.length<=1){let e=await Ht(r);return e?RZ(e,n,r):[]}let a=fr(),o=process.platform===`win32`,s=i.map(e=>{let t=at(e);return{path:e,prefix:o?t.toLowerCase():t}});s.sort((e,t)=>t.prefix.length-e.prefix.length);let c;try{c=await Gc(a,{withFileTypes:!0})}catch{let e=await Ht(r);return e?RZ(e,n,r):[]}let l=[],u=new Set,d=await Ht(r);if(d){let e=dc(d);u.add(o?e.toLowerCase():e),l.push(...await RZ(d,n,r))}for(let e of c){if(!e.isDirectory())continue;let t=o?e.name.toLowerCase():e.name;if(!u.has(t)){for(let{path:r,prefix:i}of s)if(t===i||i.length>=200&&t.startsWith(`${i}-`)){u.add(t),l.push(...await RZ(X(a,e.name),n,r));break}}}return l}async function wqe(e){let t=fr(),n;try{n=await Gc(t,{withFileTypes:!0})}catch{return[]}return(await Promise.all(n.filter(e=>e.isDirectory()).map(n=>RZ(X(t,n.name),e)))).flat()}async function Tqe(e){let{dir:t,limit:n,offset:r,includeWorktrees:i}=e??{},a=r??0,o=n!==void 0&&n>0||a>0,s=t?await Cqe(t,i??!0,o):await wqe(o);return o?xqe(s,n,a):Sqe(s)}var Eqe,Dqe=n((()=>{jee(),Ut(),Eqe=32}));function zZ(){return X(Hi(),Nqe)}async function Oqe(){try{return(await Yc(zZ())).mtimeMs}catch{return 0}}async function kqe(){let e=zZ(),t,n;try{let[r,i]=await Promise.all([Yc(e),Wc(e,`utf8`)]);t=r.mtimeMs;let a=parseInt(i.trim(),10);n=Number.isFinite(a)?a:void 0}catch{}if(t!==void 0&&Date.now()-t<Pqe&&n!==void 0&&ac(n))return K(`[autoDream] lock held by live PID ${n} (mtime ${Math.round((Date.now()-t)/1e3)}s ago)`),null;await Hc(Hi(),{recursive:!0}),await Qc(e,String(process.pid));let r;try{r=await Wc(e,`utf8`)}catch{return null}return parseInt(r.trim(),10)===process.pid?t??0:null}async function Aqe(e){let t=zZ();try{if(e===0){await Zc(t);return}await Qc(t,``);let n=e/1e3;await uce(t,n,n)}catch(e){K(`[autoDream] rollback failed: ${e.message} — next trigger delayed to minHours`)}}async function jqe(e){return(await RZ(u8(ti()),!0)).filter(t=>t.mtime>e).map(e=>e.sessionId)}async function Mqe(){try{await Hc(Hi(),{recursive:!0}),await Qc(zZ(),String(process.pid))}catch(e){K(`[autoDream] recordConsolidation write failed: ${e.message}`)}}var Nqe,Pqe,BZ=n((()=>{H(),zi(),q(),oc(),Dqe(),_8(),Nqe=`.consolidate-lock`,Pqe=3600*1e3}));function Fqe(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`dream`}function Iqe(e,t){let n=c5(`dream`);return ME({...l5(n,`dream`,`dreaming`),type:`dream`,status:`running`,phase:`starting`,sessionsReviewing:t.sessionsReviewing,filesTouched:[],turns:[],abortController:t.abortController,priorMtime:t.priorMtime},e),n}function Lqe(e,t,n,r){jE(e,r,e=>{let r=new Set(e.filesTouched),i=n.filter(e=>!r.has(e)&&r.add(e));return t.text===``&&t.toolUseCount===0&&i.length===0?e:{...e,phase:i.length>0?`updating`:e.phase,filesTouched:i.length>0?[...e.filesTouched,...i]:e.filesTouched,turns:e.turns.slice(-29).concat(t)}})}function Rqe(e,t){jE(e,t,e=>({...e,status:`completed`,endTime:Date.now(),notified:!0,abortController:void 0}))}function zqe(e,t){jE(e,t,e=>({...e,status:`failed`,endTime:Date.now(),notified:!0,abortController:void 0}))}var VZ,HZ=n((()=>{BZ(),u5(),PE(),VZ={name:`DreamTask`,type:`dream`,async kill(e,t){let n;jE(e,t,e=>e.status===`running`?(e.abortController?.abort(),n=e.priorMtime,{...e,status:`killed`,endTime:Date.now(),notified:!0,abortController:void 0}):e),n!==void 0&&await Aqe(n)}}}));function Bqe(e,t){let n=c5(`local_workflow`);return ME({...l5(n,`local_workflow`,t.description,t.toolUseId),type:`local_workflow`,status:`running`,workflowName:t.workflowName,workflowFile:t.workflowFile,summary:t.summary,agentId:t.agentId,abortController:t.abortController},e),n}function Vqe(e,t){jE(e,t,e=>({...e,status:`completed`,endTime:Date.now(),notified:!0,abortController:void 0}))}function Hqe(e,t,n){jE(e,t,e=>({...e,status:`failed`,endTime:Date.now(),notified:!0,abortController:void 0,...n===void 0?{}:{error:n}}))}function UZ(e,t){jE(e,t,e=>e.status===`running`?(e.abortController?.abort(),{...e,status:`killed`,endTime:Date.now(),notified:!0,abortController:void 0}):e)}var Uqe,WZ=n((()=>{u5(),q(),PE(),Uqe={name:`LocalWorkflowTask`,type:`local_workflow`,async kill(e,t){UZ(e,t)}}}));function Wqe(){return[uM,z0,VZ,Uqe]}function Gqe(e){return Wqe().find(t=>t.type===e)}var Kqe=n((()=>{HZ(),V0(),dM(),WZ()}));async function qqe(e,t){let{getAppState:n,setAppState:r}=t,i=n().tasks?.[e];if(!i)throw new GZ(`No task found with ID: ${e}`,`not_found`);if(i.status!==`running`)throw new GZ(`Task ${e} is not running (status: ${i.status})`,`not_running`);let a=Gqe(i.type);if(!a)throw new GZ(`Unsupported task type: ${i.type}`,`unsupported_type`);if(await a.kill(e,r),Kj(i)){let t=!1;r(n=>{let r=n.tasks[e];return!r||r.notified?n:(t=!0,{...n,tasks:{...n.tasks,[e]:{...r,notified:!0}}})}),t&&DE(e,`stopped`,{toolUseId:i.toolUseId,summary:i.description})}let o=Kj(i)?i.command:i.description;return{taskId:e,taskType:i.type,command:o}}var GZ,Jqe=n((()=>{Kqe(),AE(),qj(),b(),GZ=class extends Error{constructor(e,t){super(e),x(this,`code`,void 0),this.code=t,this.name=`StopTaskError`}}}));function Yqe(){return``}function Xqe(e){let t=e.split(`
1639
1639
  `),n=e;return t.length>qZ&&(n=t.slice(0,qZ).join(`
@@ -2046,7 +2046,7 @@ Use this when:
2046
2046
 
2047
2047
  The search uses TF-IDF keyword matching against all registered skills (bundled, user-defined, and MCP-provided). Results include skill name, description, and relevance score.`})),lQe,uQe,dQe=n((()=>{It(),Ms(),rt(),cQe(),lQe=R(()=>Hn({description:B().describe(`Description of what you want to do. Be specific — e.g. "deploy a Next.js app to Cloudflare Workers" rather than just "deploy".`),limit:V().optional().describe(`Maximum number of results to return (default: 5)`)})),uQe=Cs({name:n$,searchHint:`find search discover skills commands tools capabilities`,maxResultSizeChars:1e4,strict:!0,get inputSchema(){return lQe()},async description(){return oQe},async prompt(){return sQe},isConcurrencySafe(){return!0},isReadOnly(){return!0},userFacingName(){return`Discover Skills`},renderToolUseMessage(e){return`Searching skills: ${e.description?.slice(0,80)??`...`}`},mapToolResultToToolResultBlockParam(e,t){if(e.count===0)return Fs(t,`No matching skills found for that description.`);let n=e.results.map((e,t)=>`${t+1}. **${e.name}** (score: ${e.score.toFixed(2)})\n ${e.description}`);return Fs(t,`Found ${e.count} relevant skill(s):\n\n${n.join(`
2048
2048
 
2049
- `)}`)},async call(e,t){let{getSkillIndex:n,searchSkills:r}=await import(`./localSearch-BObbNIdd.js`),{getCwd:i}=await import(`./cwd-BH2f3u0o.js`),a=await n(i()),o=r(e.description,a,e.limit??5);return{data:{results:o.map(e=>({name:e.name,description:e.description,score:e.score})),count:o.length}}}})}));function fQe(e,t,n){return{toolUseContext:e,canUseTool:t,...n===void 0?{}:{parentMessage:n},agentId:e.agentId}}function pQe(e){return Yie(e)}function mQe(e){return cae(e)}var r$=n((()=>{ps()}));function hQe(e,t=yQe){let n=new Map,r=e.subscribe(()=>{let r=e.listRuns();for(let e of r){let r=n.get(e.runId);if(r===void 0){n.set(e.runId,e.status);continue}r!==e.status&&vQe.has(e.status)&&t(gQe(e)),n.set(e.runId,e.status)}});return()=>{r(),n.clear()}}function gQe(e){let t=e.status===`completed`?`completed successfully`:e.status===`failed`?`failed`:`was stopped`,n=e.status===`failed`&&e.error?`: ${e.error}`:``,r=`Workflow "${e.workflowName}" ${t}${n}`;return`<${ra}>
2049
+ `)}`)},async call(e,t){let{getSkillIndex:n,searchSkills:r}=await import(`./localSearch-D671mYHo.js`),{getCwd:i}=await import(`./cwd-BH2f3u0o.js`),a=await n(i()),o=r(e.description,a,e.limit??5);return{data:{results:o.map(e=>({name:e.name,description:e.description,score:e.score})),count:o.length}}}})}));function fQe(e,t,n){return{toolUseContext:e,canUseTool:t,...n===void 0?{}:{parentMessage:n},agentId:e.agentId}}function pQe(e){return Yie(e)}function mQe(e){return cae(e)}var r$=n((()=>{ps()}));function hQe(e,t=yQe){let n=new Map,r=e.subscribe(()=>{let r=e.listRuns();for(let e of r){let r=n.get(e.runId);if(r===void 0){n.set(e.runId,e.status);continue}r!==e.status&&vQe.has(e.status)&&t(gQe(e)),n.set(e.runId,e.status)}});return()=>{r(),n.clear()}}function gQe(e){let t=e.status===`completed`?`completed successfully`:e.status===`failed`?`failed`:`was stopped`,n=e.status===`failed`&&e.error?`: ${e.error}`:``,r=`Workflow "${e.workflowName}" ${t}${n}`;return`<${ra}>
2050
2050
  <${Ea}>${e.runId}</${Ea}>
2051
2051
  <${va}>${_Qe}</${va}>
2052
2052
  <${da}>${e.status}</${da}>
@@ -2392,7 +2392,7 @@ ${t?`${t}\n`:``}\
2392
2392
  `,U0e=new Set([`select-string`,`get-childitem`,`findstr`,`where.exe`]),W0e=new Set([`get-content`,`get-item`,`test-path`,`resolve-path`,`get-process`,`get-service`,`get-childitem`,`get-location`,`get-filehash`,`get-acl`,`format-hex`]),G0e=new Set([`write-output`,`write-host`]),_1=2e3,K0e=1e3,q0e=15e3,J0e=[`start-sleep`,`sleep`],v1=`Enterprise policy requires sandboxing, but sandboxing is not available on native Windows. Shell command execution is blocked on this platform by policy.`,y1=h(process.env.WORKMATE_DISABLE_BACKGROUND_TASKS),b1=R(()=>Hn({command:B().describe(`The PowerShell command to execute`),timeout:wx(V().optional()).describe(`Optional timeout in milliseconds (max ${u1()})`),description:B().optional().describe(`Clear, concise description of what this command does in active voice.`),run_in_background:LM(Ot().optional()).describe(`Set to true to run this command in the background. Use Read to read the output later.`),dangerouslyDisableSandbox:LM(Ot().optional()).describe(`Set this to true to dangerously override sandbox mode and run commands without sandboxing.`)})),Y0e=R(()=>y1?b1().omit({run_in_background:!0}):b1()),X0e=R(()=>z({stdout:B().describe(`The standard output of the command`),stderr:B().describe(`The standard error output of the command`),interrupted:Ot().describe(`Whether the command was interrupted`),returnCodeInterpretation:B().optional().describe(`Semantic interpretation for non-error exit codes with special meaning`),isImage:Ot().optional().describe(`Flag to indicate if stdout contains image data`),persistedOutputPath:B().optional().describe(`Path to persisted full output when too large for inline`),persistedOutputSize:V().optional().describe(`Total output size in bytes when persisted`),backgroundTaskId:B().optional().describe(`ID of the background task if command is running in background`),backgroundedByUser:Ot().optional().describe(`True if the user manually backgrounded the command with Ctrl+B`),assistantAutoBackgrounded:Ot().optional().describe(`True if the command was auto-backgrounded by the assistant-mode blocking budget`)})),Z0e=[`npm`,`yarn`,`pnpm`,`node`,`python`,`python3`,`go`,`cargo`,`make`,`docker`,`terraform`,`webpack`,`vite`,`jest`,`pytest`,`curl`,`Invoke-WebRequest`,`build`,`test`,`serve`,`watch`,`dev`],x1=Cs({name:qo,searchHint:`execute Windows PowerShell commands`,maxResultSizeChars:3e4,strict:!0,async description({description:e}){return e||`Run PowerShell command`},async prompt(){return A0e()},isConcurrencySafe(e){return this.isReadOnly?.(e)??!1},isSearchOrReadCommand(e){return e?.command?R0e(e.command):{isSearch:!1,isRead:!1}},isReadOnly(e){return!X$e(e.command)&&Z$e(e.command)},toAutoClassifierInput(e){return e.command},get inputSchema(){return Y0e()},get outputSchema(){return X0e()},userFacingName(){return`PowerShell`},getToolUseSummary(e){if(!e?.command)return null;let{command:t,description:n}=e;return n||qa(t,50)},getActivityDescription(e){return e?.command?`Running ${e.description??qa(e.command,50)}`:`Running command`},isEnabled(){return!0},async validateInput(e){return B0e()?{result:!1,message:v1,errorCode:11}:{result:!0}},async checkPermissions(e,t){return await C0e(e,t)},renderToolUseMessage:M0e,renderToolUseProgressMessage:N0e,renderToolUseQueuedMessage:P0e,renderToolResultMessage:F0e,renderToolUseErrorMessage:I0e,mapToolResultToToolResultBlockParam({interrupted:e,stdout:t,stderr:n,isImage:r,persistedOutputPath:i,persistedOutputSize:a,backgroundTaskId:o,backgroundedByUser:s,assistantAutoBackgrounded:c},l){if(r){let e=vve(t,l);if(e)return e}let u=t;if(i){let e=sx(t?t.replace(/^(\s*\n)+/,``).trimEnd():``,dx);u=ax({filepath:i,originalSize:a??0,isJson:!1,preview:e.preview,hasMore:e.hasMore})}else t&&(u=t.replace(/^(\s*\n)+/,``),u=u.trimEnd());let d=n.trim();e&&(n&&(d+=g1),d+=`<error>Command was aborted before completion</error>`);let f=``;if(o){let e=U8(o);f=c?`Command exceeded the assistant-mode blocking budget (${q0e/1e3}s) and was moved to the background with ID: ${o}. It is still running — you will be notified when it completes. Output is being written to: ${e}. In assistant mode, delegate long-running work to a subagent or use run_in_background to keep this conversation responsive.`:s?`Command was manually backgrounded by user with ID: ${o}. Output is being written to: ${e}`:`Command running in background with ID: ${o}. Output is being written to: ${e}`}return{tool_use_id:l,type:`tool_result`,content:[u,d,f].filter(Boolean).join(`
2393
2393
  `),is_error:e}},async call(e,t,n,r,i){if(B0e())throw Error(v1);let{abortController:a,setAppState:o,setToolJSX:s}=t,c=!t.agentId,l=0;try{let n=V0e({input:e,abortController:a,setAppState:t.setAppStateForTasks??o,setToolJSX:s,preventCwdChanges:!c,isMainThread:c,toolUseId:t.toolUseId,agentId:t.agentId}),r;do if(r=await n.next(),!r.done&&i){let e=r.value;i({toolUseID:`ps-progress-${l++}`,data:{type:`powershell_progress`,output:e.output,fullOutput:e.fullOutput,elapsedTimeSeconds:e.elapsedTimeSeconds,totalLines:e.totalLines,totalBytes:e.totalBytes,timeoutMs:e.timeoutMs,taskId:e.taskId}})}while(!r.done);let u=r.value;u.code===0&&!u.stdout&&u.stderr&&!u.backgroundTaskId||KP(e.command,u.code,u.stdout);let d=u.interrupted&&a.signal.reason===`interrupt`,f=``;if(c&&xve(t.getAppState().toolPermissionContext)&&(f=Yb(``)),u.backgroundTaskId){let t=fM(u.stdout||``,e.command);if(c&&t.hints.length>0)for(let e of t.hints);return{data:{stdout:t.stripped,stderr:[u.stderr||``,f].filter(Boolean).join(`
2394
2394
  `),interrupted:!1,backgroundTaskId:u.backgroundTaskId,backgroundedByUser:u.backgroundedByUser,assistantAutoBackgrounded:u.assistantAutoBackgrounded}}}let p=new $a,m=(u.stdout||``).trimEnd();p.append(m+g1);let h=l$e(e.command,u.code,m,u.stderr||``),g=gve(p.toString()),_=fM(g,e.command);if(g=_.stripped,c&&_.hints.length>0)for(let e of _.hints);if(u.preSpawnError)throw Error(u.preSpawnError);if(h.isError&&!d)throw new fi(g,u.stderr||``,u.code,u.interrupted);let v=64*1024*1024,y,b;if(u.outputFilePath&&u.outputTaskId)try{let e=await Yc(u.outputFilePath);b=e.size,await rx();let t=nx(u.outputTaskId,!1);e.size>v&&await lce(u.outputFilePath,v);try{await Vc(u.outputFilePath,t)}catch{await Bc(u.outputFilePath,t)}y=t}catch{}let x=Jb(g),S=g;if(x){let e=await yve(g,u.outputFilePath,b);e?S=e:x=!1}let C=[u.stderr||``,f].filter(Boolean).join(`
2395
- `);return h1(e.command),S.length,C.length,u.code,u.interrupted,{data:{stdout:S,stderr:C,interrupted:u.interrupted,returnCodeInterpretation:h.message,isImage:x,persistedOutputPath:y,persistedOutputSize:b}}}finally{s&&s(null)}},isResultTruncated(e){return oS(e.stdout)||oS(e.stderr)}})}));function Q0e(e){let t=e.toLowerCase();return t2e.includes(t)?t:null}function $0e(){let e=C1(),t=e.map(e=>e.isEnabled());return e.filter((e,n)=>t[n]).map(e=>e.name)}function C1(){return[DZ,cQ,dB,...Ab()?[]:[yL,dL],fQ,DS,RX,HI,HX,FL,YZ,yQ,LZ,NQ,AZe,GXe,...MS()?[LZe,WZe,ZZe,iQe]:[],...h(process.env.ENABLE_LSP_TOOL)?[DQ]:[],...use()?[aXe,gXe]:[],...E1?[E1]:[],e2e,_Je,...D1()?[D1()]:[],uQe,kJ,IJ,...VO()?[ck]:[],IYe]}function w1(e,t){return e.filter(e=>!w9(t,e))}function T1(e,t){let n=O1(e),r=w1(t,e),i=(e,t)=>e.name.localeCompare(t.name);return bm([...n].sort(i).concat(r.sort(i)),`name`)}var E1,e2e,D1,t2e,O1,k1=n((()=>{Ms(),OZ(),_qe(),fB(),zX(),kS(),UI(),bL(),UX(),tJe(),vJe(),TJe(),IL(),pQ(),FJe(),fL(),HJe(),DYe(),AJ(),LJ(),lk(),LYe(),ZYe(),oXe(),_Xe(),KXe(),jZe(),RZe(),GZe(),QZe(),aQe(),xm(),$O(),HS(),ls(),ds(),dQe(),n$e(),j9(),jb(),g(),Ps(),dse(),WX(),E1=process.env.WORKMATE_VERIFY_PLAN===`true`?(o$e(),e(r$e)).VerifyPlanExecutionTool:null,e2e=t$e(),D1=()=>uae()?(S1(),e(m1)).PowerShellTool:null,t2e=[`default`],O1=e=>{if(h(process.env.WORKMATE_SIMPLE))return w1([dB,DS,RX],e);let t=new Set([kJ.name,IJ.name,ws]),n=w1(C1().filter(e=>!t.has(e.name)),e);WWe()&&n.some(e=>us(e,`REPL`))&&(n=n.filter(e=>!GWe.has(e.name)));let r=n.map(e=>e.isEnabled());return n.filter((e,t)=>r[t])}})),n2e,A1,r2e=n((()=>{b(),n2e=Symbol.asyncIterator,A1=class{constructor(e){x(this,`returned`,void 0),x(this,`queue`,[]),x(this,`readResolve`,void 0),x(this,`readReject`,void 0),x(this,`isDone`,!1),x(this,`hasError`,void 0),x(this,`started`,!1),this.returned=e}[n2e](){if(this.started)throw Error(`Stream can only be iterated once`);return this.started=!0,this}next(){return this.queue.length>0?Promise.resolve({done:!1,value:this.queue.shift()}):this.isDone?Promise.resolve({done:!0,value:void 0}):this.hasError?Promise.reject(this.hasError):new Promise((e,t)=>{this.readResolve=e,this.readReject=t})}enqueue(e){if(this.readResolve){let t=this.readResolve;this.readResolve=void 0,this.readReject=void 0,t({done:!1,value:e})}else this.queue.push(e)}done(){if(this.isDone=!0,this.readResolve){let e=this.readResolve;this.readResolve=void 0,this.readReject=void 0,e({done:!0,value:void 0})}}error(e){if(this.hasError=e,this.readReject){let t=this.readReject;this.readResolve=void 0,this.readReject=void 0,t(e)}}return(){return this.isDone=!0,this.returned&&this.returned(),Promise.resolve({done:!0,value:void 0})}}}));function i2e(e){switch(e){case`allow`:return`allowed`;case`deny`:return`denied`;default:return`asked for confirmation for`}}var a2e=n((()=>{}));async function*o2e(e,t,n,r,i,a,o,s,c){let l=Date.now();try{let r=e.getAppState().toolPermissionContext.mode,c=a;for await(let a of _at(t.name,n,i,c,e,r,e.abortController.signal))try{if(a.message?.type===`attachment`&&a.message.attachment.type===`hook_cancelled`){Ys(t.name),e.queryTracking?.chainId,e.queryTracking?.depth,yield{message:a2({type:`hook_cancelled`,hookName:`PostToolUse:${t.name}`,toolUseID:n,hookEvent:`PostToolUse`})};continue}if(a.message&&!(a.message.type===`attachment`&&a.message.attachment.type===`hook_blocking_error`)&&(yield{message:a.message}),a.blockingError&&(yield{message:a2({type:`hook_blocking_error`,hookName:`PostToolUse:${t.name}`,toolUseID:n,hookEvent:`PostToolUse`,blockingError:a.blockingError})}),a.preventContinuation){yield{message:a2({type:`hook_stopped_continuation`,message:a.stopReason||`Execution stopped by PostToolUse hook`,hookName:`PostToolUse:${t.name}`,toolUseID:n,hookEvent:`PostToolUse`})};return}a.additionalContexts&&a.additionalContexts.length>0&&(yield{message:a2({type:`hook_additional_context`,content:a.additionalContexts,hookName:`PostToolUse:${t.name}`,toolUseID:n,hookEvent:`PostToolUse`})}),a.updatedMCPToolOutput&&aY(t)&&(c=a.updatedMCPToolOutput,yield{updatedMCPToolOutput:c})}catch(r){Date.now()-l,Ys(t.name),t.isMcp,e.queryTracking?.chainId,e.queryTracking?.depth,{...s?{mcpServerType:s}:{},...o?{requestId:o}:{}},yield{message:a2({type:`hook_error_during_execution`,content:OQ(r),hookName:`PostToolUse:${t.name}`,toolUseID:n,hookEvent:`PostToolUse`})}}}catch(e){Y(e)}}async function*s2e(e,t,n,r,i,a,o,s,c,l){let u=Date.now();try{let r=e.getAppState().toolPermissionContext.mode;for await(let l of vat(t.name,n,i,a,e,o,r,e.abortController.signal))try{if(l.message?.type===`attachment`&&l.message.attachment.type===`hook_cancelled`){Ys(t.name),e.queryTracking?.chainId,e.queryTracking?.depth,yield{message:a2({type:`hook_cancelled`,hookName:`PostToolUseFailure:${t.name}`,toolUseID:n,hookEvent:`PostToolUseFailure`})};continue}l.message&&!(l.message.type===`attachment`&&l.message.attachment.type===`hook_blocking_error`)&&(yield{message:l.message}),l.blockingError&&(yield{message:a2({type:`hook_blocking_error`,hookName:`PostToolUseFailure:${t.name}`,toolUseID:n,hookEvent:`PostToolUseFailure`,blockingError:l.blockingError})}),l.additionalContexts&&l.additionalContexts.length>0&&(yield{message:a2({type:`hook_additional_context`,content:l.additionalContexts,hookName:`PostToolUseFailure:${t.name}`,toolUseID:n,hookEvent:`PostToolUseFailure`})})}catch(r){Date.now()-u,Ys(t.name),t.isMcp,e.queryTracking?.chainId,e.queryTracking?.depth,{...c?{mcpServerType:c}:{},...s?{requestId:s}:{}},yield{message:a2({type:`hook_error_during_execution`,content:OQ(r),hookName:`PostToolUseFailure:${t.name}`,toolUseID:n,hookEvent:`PostToolUseFailure`})}}}catch(e){Y(e)}}async function c2e(e,t,n,r,i,a,o){let s=t.requiresUserInteraction?.(),c=r.requireCanUseTool;if(e?.behavior===`allow`){let l=e.updatedInput??n,u=s&&e.updatedInput!==void 0;if(s&&!u||c)return K(`Hook approved tool use for ${t.name}, but canUseTool is required`),{decision:await i(t,l,r,a,o),input:l};let d=await vct(t,l,r);return d===null?(K(u?`Hook satisfied user interaction for ${t.name} via updatedInput`:`Hook approved tool use for ${t.name}, bypassing permission prompt`),{decision:e,input:l}):d.behavior===`deny`?(K(`Hook approved tool use for ${t.name}, but deny rule overrides: ${d.message}`),{decision:d,input:l}):(K(`Hook approved tool use for ${t.name}, but ask rule requires prompt`),{decision:await i(t,l,r,a,o),input:l})}if(e?.behavior===`deny`)return K(`Hook denied tool use for ${t.name}`),{decision:e,input:n};let l=e?.behavior===`ask`?e:void 0,u=e?.behavior===`ask`&&e.updatedInput?e.updatedInput:n;return{decision:await i(t,u,r,a,o,l),input:u}}async function*l2e(e,t,n,r,i,a,o,s){let c=Date.now();try{let i=e.getAppState();for await(let s of gat(t.name,r,n,e,i.toolPermissionContext.mode,e.abortController.signal,void 0,e.requestPrompt,t.getToolUseSummary?.(n)))try{if(s.message&&(yield{type:`message`,message:{message:s.message}}),s.blockingError){let e=dat(`PreToolUse:${t.name}`,s.blockingError);yield{type:`hookPermissionResult`,hookPermissionResult:{behavior:`deny`,message:e,decisionReason:{type:`hook`,hookName:`PreToolUse:${t.name}`,reason:e}}}}if(s.preventContinuation&&(yield{type:`preventContinuation`,shouldPreventContinuation:!0},s.stopReason&&(yield{type:`stopReason`,stopReason:s.stopReason})),s.permissionBehavior!==void 0){K(`Hook result has permissionBehavior=${s.permissionBehavior}`);let e={type:`hook`,hookName:`PreToolUse:${t.name}`,hookSource:s.hookSource,reason:s.hookPermissionDecisionReason};s.permissionBehavior===`allow`?yield{type:`hookPermissionResult`,hookPermissionResult:{behavior:`allow`,updatedInput:s.updatedInput,decisionReason:e}}:s.permissionBehavior===`ask`?yield{type:`hookPermissionResult`,hookPermissionResult:{behavior:`ask`,updatedInput:s.updatedInput,message:s.hookPermissionDecisionReason||`Hook PreToolUse:${t.name} ${i2e(s.permissionBehavior)} this tool`,decisionReason:e}}:yield{type:`hookPermissionResult`,hookPermissionResult:{behavior:s.permissionBehavior,message:s.hookPermissionDecisionReason||`Hook PreToolUse:${t.name} ${i2e(s.permissionBehavior)} this tool`,decisionReason:e}}}if(s.updatedInput&&s.permissionBehavior===void 0&&(yield{type:`hookUpdatedInput`,updatedInput:s.updatedInput}),s.additionalContexts&&s.additionalContexts.length>0&&(yield{type:`additionalContext`,message:{message:a2({type:`hook_additional_context`,content:s.additionalContexts,hookName:`PreToolUse:${t.name}`,toolUseID:r,hookEvent:`PreToolUse`})}}),e.abortController.signal.aborted){Ys(t.name),e.queryTracking?.chainId,e.queryTracking?.depth,yield{type:`message`,message:{message:a2({type:`hook_cancelled`,hookName:`PreToolUse:${t.name}`,toolUseID:r,hookEvent:`PreToolUse`})}},yield{type:`stop`};return}}catch(n){Y(n),Date.now()-c,Ys(t.name),t.isMcp,e.queryTracking?.chainId,e.queryTracking?.depth,{...o?{mcpServerType:o}:{},...a?{requestId:a}:{}},yield{type:`message`,message:{message:a2({type:`hook_error_during_execution`,content:OQ(n),hookName:`PreToolUse:${t.name}`,toolUseID:r,hookEvent:`PreToolUse`})}},yield{type:`stop`}}}catch(e){Y(e),yield{type:`stop`};return}}var u2e=n((()=>{La(),Qs(),g2(),q(),_7(),wa(),a2e(),j9(),kQ(),oY()}));function d2e(){return M1||(M1=import(`./toolEventObserver-CNXN4TOt.js`).catch(e=>{throw M1=void 0,e})),M1}function f2e(e){if(e instanceof ji)return e.telemetryMessage.slice(0,200);if(e instanceof Error){let t=yi(e);return typeof t==`string`?`Error:${t}`:e.name&&e.name!==`Error`&&e.name.length>3?e.name.slice(0,60):`Error`}return`UnknownError`}function p2e(e,t){switch(e){case`session`:return t===`allow`?`user_temporary`:`user_reject`;case`localSettings`:case`userSettings`:return t===`allow`?`user_permanent`:`user_reject`;default:return`config`}}function m2e(e,t){if(!e)return`config`;switch(e.type){case`permissionPromptTool`:{let n=e.toolResult?.decisionClassification;return n===`user_temporary`||n===`user_permanent`||n===`user_reject`?n:t===`allow`?`user_temporary`:`user_reject`}case`rule`:return p2e(e.rule.source,t);case`hook`:return`hook`;case`mode`:case`classifier`:case`subcommandResults`:case`asyncAgent`:case`sandboxOverride`:case`workingDir`:case`safetyCheck`:case`other`:return`config`;default:return`config`}}function h2e(e){let t=0;for(let n of e)if(n.type===`user`&&n.imagePasteIds)for(let e of n.imagePasteIds)e>t&&(t=e);return t+1}function g2e(e,t){if(!e.startsWith(`mcp__`))return;let n=Qn(e);if(n)return t.find(e=>pn(e.name)===n.serverName)}function _2e(e,t){let n=g2e(e,t);if(n?.type===`connected`)return n.config.type??`stdio`}function v2e(e,t){let n=g2e(e,t);if(n?.type===`connected`)return QBe(n.config)}async function*j1(e,t,n,r){let i=e.name,a=ms(r.options.tools,i);if(!a){let e=ms(C1(),i);e?.aliases?.includes(i)&&(a=e)}let o=t.message.id,s=t.requestId,c=_2e(i,r.options.mcpClients),l=v2e(i,r.options.mcpClients);if(!a){let n=Ys(i);K(`Unknown tool ${i}: ${e.id}`),`${n}`,e.id,i.startsWith(`mcp__`),r.queryTracking?.chainId,r.queryTracking?.depth,{...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...rc(i,c,l)},yield{message:Q({content:[{type:`tool_result`,content:`<tool_use_error>Error: No such tool available: ${i}</tool_use_error>`,is_error:!0,tool_use_id:e.id}],toolUseResult:`Error: No such tool available: ${i}`,sourceToolAssistantUUID:t.uuid})};return}let u=e.input;try{if(r.abortController.signal.aborted){Ys(a.name),e.id,a.isMcp,r.queryTracking?.chainId,r.queryTracking?.depth,{...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...rc(a.name,c,l)};let n=dhe(e.id);n.content=o3(F_),yield{message:Q({content:[n],toolUseResult:F_,sourceToolAssistantUUID:t.uuid})};return}for await(let i of y2e(a,e.id,u,r,n,t,o,s,c,l))yield i}catch(n){Y(n);let r=n instanceof Error?n.message:String(n),i=`Error calling tool${a?` (${a.name})`:``}: ${r}`;yield{message:Q({content:[{type:`tool_result`,content:`<tool_use_error>${i}</tool_use_error>`,is_error:!0,tool_use_id:e.id}],toolUseResult:i,sourceToolAssistantUUID:t.uuid})}}}function y2e(e,t,n,r,i,a,o,s,c,l){let u=new A1;return x2e(e,t,n,r,i,a,o,s,c,l,n=>{Ys(e.name),e.isMcp,r.queryTracking?.chainId,r.queryTracking?.depth,{...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...rc(e.name,c,l)},u.enqueue({message:uhe({toolUseID:n.toolUseID,parentToolUseID:t,data:n.data})})}).then(e=>{for(let t of e)u.enqueue(t)}).catch(e=>{u.error(e)}).finally(()=>{u.done()}),u}function b2e(e,t,n){if(!VO()||!HO(n)||!vs(e)||GO(t).has(e.name))return null;let r=e.userFacingName?e.userFacingName(void 0):e.name;return`\n\nTool "${r}" is deferred-loading and needs to be discovered before use.\nWhen using OpenAI-compatible models (DeepSeek, Ollama, etc.), follow these steps:\n1. First discover the tool with SearchExtraTools: ${Ss}("select:${e.name}")\n2. Then call ${r} tool\n\nExample:\n${Ss}("select:${e.name}") → ${r}({ ... })\n\nImportant notes:\n• Use camelCase parameter names (e.g., taskId), not snake_case (task_id)\n• All task tools (TaskGet, TaskCreate, TaskUpdate, TaskList) need to be discovered first\n• You can discover them all at once: ${Ss}("select:TaskGet,TaskCreate,TaskUpdate,TaskList")\n\nSee docs/openai-task-tools.md for detailed guide.`}async function x2e(e,t,n,r,i,a,o,s,c,l,u){let d=e.inputSchema.safeParse(n);if(!d.success){let n=AYe(e.name,d.error),i=b2e(e,r.messages,r.options.tools);return i&&(Ys(e.name),e.isMcp,n+=i),K(`${e.name} tool input error: ${n.slice(0,200)}`),n.slice(0,2e3),Ys(e.name),e.isMcp,r.queryTracking?.chainId,r.queryTracking?.depth,{...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...rc(e.name,c,l)},[{message:Q({content:[{type:`tool_result`,content:`<tool_use_error>InputValidationError: ${n}</tool_use_error>`,is_error:!0,tool_use_id:t}],toolUseResult:`InputValidationError: ${d.error.message}`,sourceToolAssistantUUID:a.uuid})}]}let f=await e.validateInput?.(d.data,r);if(f?.result===!1)return K(`${e.name} tool validation error: ${f.message?.slice(0,200)}`),Ys(e.name),f.message,f.errorCode,e.isMcp,r.queryTracking?.chainId,r.queryTracking?.depth,{...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...rc(e.name,c,l)},[{message:Q({content:[{type:`tool_result`,content:`<tool_use_error>${f.message}</tool_use_error>`,is_error:!0,tool_use_id:t}],toolUseResult:`Error: ${f.message}`,sourceToolAssistantUUID:a.uuid})}];if(e.name===`Bash`&&d.data&&`command`in d.data){let e=r.getAppState();zPe(d.data.command,e.toolPermissionContext,r.abortController.signal,r.options.isNonInteractiveSession)}let p=[],m=d.data;if(e.name===`Bash`&&m&&typeof m==`object`&&`_simulatedSedEdit`in m){let{_simulatedSedEdit:e,...t}=m;m=t}let h=m,g=e.backfillObservableInput&&typeof m==`object`&&m?{...m}:null;g&&(e.backfillObservableInput(g),m=g);let _=!1,v,y,b=[],x=Date.now();for await(let n of l2e(r,e,m,t,a.message.id,s,c,l))switch(n.type){case`message`:if(n.message.message.type===`progress`)u(n.message.message);else{p.push(n.message);let e=n.message.message.attachment;e&&`command`in e&&e.command!==void 0&&`durationMs`in e&&e.durationMs!==void 0&&b.push({command:e.command,durationMs:e.durationMs})}break;case`hookPermissionResult`:y=n.hookPermissionResult;break;case`hookUpdatedInput`:m=n.updatedInput;break;case`preventContinuation`:_=n.shouldPreventContinuation;break;case`stopReason`:v=n.stopReason;break;case`additionalContext`:p.push(n.message);break;case`stop`:return qr()?.observe(`pre_tool_hook_duration_ms`,Date.now()-x),p.push({message:Q({content:[dhe(t)],toolUseResult:`Error: ${v}`,sourceToolAssistantUUID:a.uuid})}),p}let S=Date.now()-x;qr()?.observe(`pre_tool_hook_duration_ms`,S),S>=N1&&K(`Slow PreToolUse hooks: ${S}ms for ${e.name} (${b.length} hooks)`,{level:`info`});let C={};m&&typeof m==`object`&&(e.name===`Read`&&`file_path`in m||(e.name===`Edit`||e.name===`Write`)&&`file_path`in m?C.file_path=String(m.file_path):e.name===`Bash`&&`command`in m&&(C.full_command=m.command)),Koe(e.name,C,Xs()?W(m):void 0),Zoe();let w=r.getAppState().toolPermissionContext.mode,T=Date.now(),E=await c2e(y,e,m,r,i,a,t),D=E.decision;m=E.input;let O=Date.now()-T;if(O>=N1&&w===`auto`&&K(`Slow permission decision: ${O}ms for ${e.name} (mode=${w}, behavior=${D.behavior})`,{level:`info`}),D.behavior!==`ask`&&!r.toolDecisions?.has(t)){let t=D.behavior===`allow`?`accept`:`reject`,n=m2e(D.decisionReason,D.behavior);$s(`tool_decision`,{decision:t,source:n,tool_name:Ys(e.name)}),OH(e.name)&&kH(e,m,t,n).then(e=>Are()?.add(1,e))}if(D.decisionReason?.type===`hook`&&D.decisionReason.hookName===`PermissionRequest`&&D.behavior!==`ask`&&p.push({message:a2({type:`hook_permission_decision`,decision:D.behavior,toolUseID:t,hookEvent:`PermissionRequest`})}),D.behavior!==`allow`){K(`${e.name} tool permission denied`);let n=r.toolDecisions?.get(t);Uoe(`reject`,n?.source||`unknown`),tc(),Ys(e.name),r.queryTracking?.chainId,r.queryTracking?.depth,{...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...rc(e.name,c,l)};let i=D.message;_&&!i&&(i=`Execution stopped by PreToolUse hook${v?`: ${v}`:``}`);let o=[{type:`tool_result`,content:i,is_error:!0,tool_use_id:t}],u=D.behavior===`ask`?D.contentBlocks:void 0;u?.length&&o.push(...u);let d;if(u?.length){let e=zt(u,e=>e.type===`image`);if(e>0){let t=h2e(r.messages);d=Array.from({length:e},(e,n)=>t+n)}}return p.push({message:Q({content:o,imagePasteIds:d,toolUseResult:`Error: ${i}`,sourceToolAssistantUUID:a.uuid})}),p}Ys(e.name),r.queryTracking?.chainId,r.queryTracking?.depth,{...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...rc(e.name,c,l)},D.updatedInput!==void 0&&(m=D.updatedInput);let k=Boe(m),A={};if(Voe()){if(e.name===`Bash`&&`command`in m){let e=m;A={bash_command:e.command.trim().split(/\s+/)[0]||``,full_command:e.command,...e.timeout!==void 0&&{timeout:e.timeout},...e.description!==void 0&&{description:e.description},...`dangerouslyDisableSandbox`in e&&{dangerouslyDisableSandbox:e.dangerouslyDisableSandbox}}}let t=Roe(e.name);t&&(A.mcp_server_name=t.serverName,A.mcp_tool_name=t.mcpToolName);let n=zoe(e.name,m);n&&(A.skill_name=n)}let ee=r.toolDecisions?.get(t);Uoe(ee?.decision||`unknown`,ee?.source||`unknown`),Joe();let te=Date.now();fk(`tool_exec`),g&&m!==h&&typeof m==`object`&&m&&`file_path`in m&&`file_path`in h&&m.file_path===g.file_path?h={...m,file_path:h.file_path}:m!==g&&(h=m);try{let n=()=>e.call(h,{...r,toolUseId:t,userModified:D.userModified??!1},i,a,e=>{u({toolUseID:e.toolUseID,data:e.data})}),o=fse()?await(async()=>{let{runToolCallWithSkillLearningHooks:t}=await d2e();return t(e.name,h,{sessionId:r.sessionId},n)})():await n(),d=Date.now()-te;if(dre(d),o.data&&typeof o.data==`object`){let t={};e.name===`Read`&&`content`in o.data&&(`file_path`in m&&(t.file_path=String(m.file_path)),t.content=String(o.data.content)),(e.name===`Edit`||e.name===`Write`)&&`file_path`in m&&(t.file_path=String(m.file_path),e.name===`Edit`&&`diff`in o.data&&(t.diff=String(o.data.diff)),e.name===`Write`&&`content`in m&&(t.content=String(m.content))),e.name===`Bash`&&`command`in m&&(t.bash_command=m.command,`output`in o.data&&(t.output=String(o.data.output))),Object.keys(t).length>0&&Qoe(`tool.output`,t)}typeof o==`object`&&`structured_output`in o&&p.push({message:a2({type:`structured_output`,data:o.structured_output})}),Xoe({success:!0}),tc(o.data&&typeof o.data==`object`?W(o.data):String(o.data??``));let f=e.mapToolResultToToolResultBlockParam(o.data,t),g=f.content,y=g?typeof g==`string`?g.length:W(g).length:0,b;if(m&&typeof m==`object`){if((e.name===`Read`||e.name===`Edit`||e.name===`Write`)&&`file_path`in m)b=Zs(String(m.file_path));else if(e.name===`NotebookEdit`&&`notebook_path`in m)b=Zs(String(m.notebook_path));else if(e.name===`Bash`&&`command`in m){let e=m;b=Loe(e.command,e._simulatedSedEdit?.filePath)}}if(Ys(e.name),e.isMcp,{...b!==void 0&&{fileExtension:b}},r.queryTracking?.chainId,r.queryTracking?.depth,{...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...rc(e.name,c,l)},Voe()&&(e.name===`Bash`||e.name===`PowerShell`)&&`command`in m&&typeof m.command==`string`&&m.command.match(/\bgit\s+commit\b/)&&o.data&&typeof o.data==`object`&&`stdout`in o.data){let e=WP(String(o.data.stdout));e&&(A.git_commit_id=e)}let x=aY(e)?KBe(e.name):null;$s(`tool_result`,{tool_name:Ys(e.name),success:`true`,duration_ms:String(d),...Object.keys(A).length>0&&{tool_parameters:W(A)},...k&&{tool_input:k},tool_result_size_bytes:String(y),...ee&&{decision_source:ee.source,decision_type:ee.decision},...x&&{mcp_server_scope:x}});let S=o.data,C=[],w=o.contextModifier,T=o.mcpMeta;async function E(n,i){let o=[i?await zve(i,e.name,e.maxResultSizeChars):await ox(e,n,t)];`acceptFeedback`in D&&D.acceptFeedback&&o.push({type:`text`,text:D.acceptFeedback});let s=`contentBlocks`in D?D.contentBlocks:void 0;s?.length&&o.push(...s);let c;if(s?.length){let e=zt(s,e=>e.type===`image`);if(e>0){let t=h2e(r.messages);c=Array.from({length:e},(e,n)=>t+n)}}p.push({message:Q({content:o,imagePasteIds:c,toolUseResult:r.agentId&&!r.preserveToolUseResults?void 0:n,mcpMeta:r.agentId?void 0:T,sourceToolAssistantUUID:a.uuid}),contextModifier:w?{toolUseID:t,modifyContext:w}:void 0})}aY(e)||await E(S,f);let O=[],ne=Date.now();for await(let n of o2e(r,e,t,a.message.id,m,S,s,c,l))if(`updatedMCPToolOutput`in n)aY(e)&&(S=n.updatedMCPToolOutput);else if(aY(e)){if(C.push(n),n.message.type===`attachment`){let e=n.message.attachment;`command`in e&&e.command!==void 0&&`durationMs`in e&&e.durationMs!==void 0&&O.push({command:e.command,durationMs:e.durationMs})}}else if(p.push(n),n.message.type===`attachment`){let e=n.message.attachment;`command`in e&&e.command!==void 0&&`durationMs`in e&&e.durationMs!==void 0&&O.push({command:e.command,durationMs:e.durationMs})}let re=Date.now()-ne;if(re>=N1&&K(`Slow PostToolUse hooks: ${re}ms for ${e.name} (${O.length} hooks)`,{level:`info`}),aY(e)&&await E(S),o.newMessages&&o.newMessages.length>0)for(let e of o.newMessages)p.push({message:e});_&&p.push({message:a2({type:`hook_stopped_continuation`,message:v||`Execution stopped by hook`,hookName:`PreToolUse:${e.name}`,toolUseID:t,hookEvent:`PreToolUse`})});for(let e of C)p.push(e);return p}catch(n){let i=Date.now()-te;if(dre(i),Xoe({success:!1,error:G(n)}),tc(),n instanceof mY&&r.setAppState(e=>{let t=n.serverName,r=e.mcp.clients.findIndex(e=>e.name===t);if(r===-1)return e;let i=e.mcp.clients[r];if(i?.type!==`connected`)return e;let a=[...e.mcp.clients];return a[r]={name:t,type:`needs-auth`,config:i.config},{...e,mcp:{...e.mcp,clients:a}}}),!(n instanceof pi)){let a=G(n);K(`${e.name} tool error (${i}ms): ${a.slice(0,200)}`),n instanceof fi||Y(n),Ys(e.name),f2e(n),e.isMcp,r.queryTracking?.chainId,r.queryTracking?.depth,{...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...rc(e.name,c,l)};let o=aY(e)?KBe(e.name):null;$s(`tool_result`,{tool_name:Ys(e.name),use_id:t,success:`false`,duration_ms:String(i),error:G(n),...Object.keys(A).length>0&&{tool_parameters:W(A)},...k&&{tool_input:k},...ee&&{decision_source:ee.source,decision_type:ee.decision},...o&&{mcp_server_scope:o}})}let u=OQ(n),d=n instanceof pi,f=[];for await(let n of s2e(r,e,t,o,m,u,d,s,c,l))f.push(n);return[{message:Q({content:[{type:`tool_result`,content:u,is_error:!0,tool_use_id:t}],toolUseResult:`Error: ${u}`,mcpMeta:r.agentId?void 0:n instanceof gY?n.mcpMeta:void 0,sourceToolAssistantUUID:a.uuid})},...f]}finally{pk(`tool_exec`),ee&&r.toolDecisions?.delete(t)}}var M1,N1,S2e=n((()=>{La(),Qs(),H(),MH(),Ms(),VB(),ys(),Es(),As(),Is(),hs(),Ns(),$P(),Os(),k1(),tt(),g2(),q(),gi(),wa(),v3(),Sk(),Li(),r2e(),nc(),ec(),kQ(),fx(),$O(),wY(),Bn(),jn(),oY(),u2e(),pse(),N1=2e3}));function C2e(e,t){e.setInProgressToolUseIDs(e=>{let n=new Set(e);return n.delete(t),n})}var P1,w2e=n((()=>{v3(),Ms(),ys(),GT(),S2e(),b(),P1=class{constructor(e,t,n){x(this,`toolDefinitions`,void 0),x(this,`canUseTool`,void 0),x(this,`tools`,[]),x(this,`toolUseContext`,void 0),x(this,`hasErrored`,!1),x(this,`erroredToolDescription`,``),x(this,`siblingAbortController`,void 0),x(this,`discarded`,!1),x(this,`progressAvailableResolve`,void 0),this.toolDefinitions=e,this.canUseTool=t,this.toolUseContext=n,this.siblingAbortController=UT(n.abortController)}discard(){this.discarded=!0,this.siblingAbortController.abort(`streaming_fallback`),this.tools.length=0,this.progressAvailableResolve=void 0}addTool(e,t){let n=ms(this.toolDefinitions,e.name);if(!n){this.tools.push({id:e.id,block:e,assistantMessage:t,status:`completed`,isConcurrencySafe:!0,pendingProgress:[],results:[Q({content:[{type:`tool_result`,content:`<tool_use_error>Error: No such tool available: ${e.name}</tool_use_error>`,is_error:!0,tool_use_id:e.id}],toolUseResult:`Error: No such tool available: ${e.name}`,sourceToolAssistantUUID:t.uuid})]});return}let r=n.inputSchema.safeParse(e.input),i=r?.success?(()=>{try{return!!n.isConcurrencySafe(r.data)}catch{return!1}})():!1;this.tools.push({id:e.id,block:e,assistantMessage:t,status:`queued`,isConcurrencySafe:i,pendingProgress:[]}),this.processQueue()}canExecuteTool(e){let t=this.tools.filter(e=>e.status===`executing`);return t.length===0||e&&t.every(e=>e.isConcurrencySafe)}async processQueue(){for(let e of this.tools)if(e.status===`queued`){if(this.canExecuteTool(e.isConcurrencySafe))await this.executeTool(e);else if(!e.isConcurrencySafe)break}}createSyntheticErrorMessage(e,t,n){if(t===`user_interrupted`)return Q({content:[{type:`tool_result`,content:o3(I_),is_error:!0,tool_use_id:e}],toolUseResult:`User rejected tool use`,sourceToolAssistantUUID:n.uuid});if(t===`streaming_fallback`)return Q({content:[{type:`tool_result`,content:`<tool_use_error>Error: Streaming fallback - tool execution discarded</tool_use_error>`,is_error:!0,tool_use_id:e}],toolUseResult:`Streaming fallback - tool execution discarded`,sourceToolAssistantUUID:n.uuid});let r=this.erroredToolDescription,i=r?`Cancelled: parallel tool call ${r} errored`:`Cancelled: parallel tool call errored`;return Q({content:[{type:`tool_result`,content:`<tool_use_error>${i}</tool_use_error>`,is_error:!0,tool_use_id:e}],toolUseResult:i,sourceToolAssistantUUID:n.uuid})}getAbortReason(e){return this.discarded?`streaming_fallback`:this.hasErrored?`sibling_error`:this.toolUseContext.abortController.signal.aborted?this.toolUseContext.abortController.signal.reason===`interrupt`?this.getToolInterruptBehavior(e)===`cancel`?`user_interrupted`:null:`user_interrupted`:null}getToolInterruptBehavior(e){let t=ms(this.toolDefinitions,e.block.name);if(!t?.interruptBehavior)return`block`;try{return t.interruptBehavior()}catch{return`block`}}getToolDescription(e){let t=e.block.input,n=t?.command??t?.file_path??t?.pattern??``;if(typeof n==`string`&&n.length>0){let t=n.length>40?`${n.slice(0,40)}\u2026`:n;return`${e.block.name}(${t})`}return e.block.name}updateInterruptibleState(){let e=this.tools.filter(e=>e.status===`executing`);this.toolUseContext.setHasInterruptibleToolInProgress?.(e.length>0&&e.every(e=>this.getToolInterruptBehavior(e)===`cancel`))}async executeTool(e){e.status=`executing`,this.toolUseContext.setInProgressToolUseIDs(t=>new Set(t).add(e.id)),this.updateInterruptibleState();let t=[],n=[],r=(async()=>{let r=this.getAbortReason(e);if(r){t.push(this.createSyntheticErrorMessage(e.id,r,e.assistantMessage)),e.results=t,e.contextModifiers=n,e.status=`completed`,this.updateInterruptibleState();return}let i=UT(this.siblingAbortController);i.signal.addEventListener(`abort`,()=>{i.signal.reason!==`sibling_error`&&!this.toolUseContext.abortController.signal.aborted&&!this.discarded&&this.toolUseContext.abortController.abort(i.signal.reason)},{once:!0});let a=j1(e.block,e.assistantMessage,this.canUseTool,{...this.toolUseContext,abortController:i}),o=!1;for await(let r of a){let i=this.getAbortReason(e);if(i&&!o){t.push(this.createSyntheticErrorMessage(e.id,i,e.assistantMessage));break}r.message.type===`user`&&Array.isArray(r.message.message.content)&&r.message.message.content.some(e=>e.type===`tool_result`&&e.is_error===!0)&&(o=!0,e.block.name===`Bash`&&(this.hasErrored=!0,this.erroredToolDescription=this.getToolDescription(e),this.siblingAbortController.abort(`sibling_error`))),r.message&&(r.message.type===`progress`?(e.pendingProgress.push(r.message),this.progressAvailableResolve&&(this.progressAvailableResolve(),this.progressAvailableResolve=void 0)):t.push(r.message)),r.contextModifier&&n.push(r.contextModifier.modifyContext)}if(e.results=t,e.contextModifiers=n,e.status=`completed`,this.updateInterruptibleState(),!e.isConcurrencySafe&&n.length>0)for(let e of n)this.toolUseContext=e(this.toolUseContext)})();e.promise=r,r.finally(()=>{this.processQueue()})}*getCompletedResults(){if(!this.discarded)for(let e of this.tools){for(;e.pendingProgress.length>0;)yield{message:e.pendingProgress.shift(),newContext:this.toolUseContext};if(e.status!==`yielded`){if(e.status===`completed`&&e.results){e.status=`yielded`;for(let t of e.results)yield{message:t,newContext:this.toolUseContext};C2e(this.toolUseContext,e.id)}else if(e.status===`executing`&&!e.isConcurrencySafe)break}}}hasPendingProgress(){return this.tools.some(e=>e.pendingProgress.length>0)}async*getRemainingResults(){if(!this.discarded){for(;this.hasUnfinishedTools();){await this.processQueue();for(let e of this.getCompletedResults())yield e;if(this.hasExecutingTools()&&!this.hasCompletedResults()&&!this.hasPendingProgress()){let e=this.tools.filter(e=>e.status===`executing`&&e.promise).map(e=>e.promise),t=new Promise(e=>{this.progressAvailableResolve=e});e.length>0&&await Promise.race([...e,t])}}for(let e of this.getCompletedResults())yield e}}hasCompletedResults(){return this.tools.some(e=>e.status===`completed`)}hasExecutingTools(){return this.tools.some(e=>e.status===`executing`)}hasUnfinishedTools(){return this.tools.some(e=>e.status!==`yielded`)}getUpdatedContext(){return this.toolUseContext}}}));function T2e(){I1&&(Ga().clearMarks(),L1.clear(),z1=null,R1++,F1(`query_user_input_received`))}function F1(e){if(!I1)return;let t=Ga();if(t.mark(e),L1.set(e,process.memoryUsage()),e===`query_first_chunk_received`&&z1===null){let e=t.getEntriesByType(`mark`);e.length>0&&(z1=e[e.length-1]?.startTime??0)}}function E2e(){I1&&F1(`query_profile_end`)}function D2e(e,t){return t===`query_user_input_received`?``:e>1e3?` ⚠️ VERY SLOW`:e>100?` ⚠️ SLOW`:t.includes(`git_status`)&&e>50?` ⚠️ git status`:t.includes(`tool_schema`)&&e>50?` ⚠️ tool schemas`:t.includes(`client_creation`)&&e>50?` ⚠️ client creation`:``}function O2e(){if(!I1)return`Query profiling not enabled (set WORKMATE_PROFILE_QUERY=1)`;let e=Ga().getEntriesByType(`mark`);if(e.length===0)return`No query profiling checkpoints recorded`;let t=[];t.push(`=`.repeat(80)),t.push(`QUERY PROFILING REPORT - Query #${R1}`),t.push(`=`.repeat(80)),t.push(``);let n=e[0]?.startTime??0,r=n,i=0,a=0;for(let o of e){let e=o.startTime-n,s=o.startTime-r;t.push(sie(e,s,o.name,L1.get(o.name),10,9,D2e(s,o.name))),o.name===`query_api_request_sent`&&(i=e),o.name===`query_first_chunk_received`&&(a=e),r=o.startTime}let o=e[e.length-1],s=o?o.startTime-n:0;if(t.push(``),t.push(`-`.repeat(80)),a>0){let e=i,n=a-i,r=(e/a*100).toFixed(1),o=(n/a*100).toFixed(1);t.push(`Total TTFT: ${za(a)}ms`),t.push(` - Pre-request overhead: ${za(e)}ms (${r}%)`),t.push(` - Network latency: ${za(n)}ms (${o}%)`)}else t.push(`Total time: ${za(s)}ms`);return t.push(k2e(e,n)),t.push(`=`.repeat(80)),t.join(`
2395
+ `);return h1(e.command),S.length,C.length,u.code,u.interrupted,{data:{stdout:S,stderr:C,interrupted:u.interrupted,returnCodeInterpretation:h.message,isImage:x,persistedOutputPath:y,persistedOutputSize:b}}}finally{s&&s(null)}},isResultTruncated(e){return oS(e.stdout)||oS(e.stderr)}})}));function Q0e(e){let t=e.toLowerCase();return t2e.includes(t)?t:null}function $0e(){let e=C1(),t=e.map(e=>e.isEnabled());return e.filter((e,n)=>t[n]).map(e=>e.name)}function C1(){return[DZ,cQ,dB,...Ab()?[]:[yL,dL],fQ,DS,RX,HI,HX,FL,YZ,yQ,LZ,NQ,AZe,GXe,...MS()?[LZe,WZe,ZZe,iQe]:[],...h(process.env.ENABLE_LSP_TOOL)?[DQ]:[],...use()?[aXe,gXe]:[],...E1?[E1]:[],e2e,_Je,...D1()?[D1()]:[],uQe,kJ,IJ,...VO()?[ck]:[],IYe]}function w1(e,t){return e.filter(e=>!w9(t,e))}function T1(e,t){let n=O1(e),r=w1(t,e),i=(e,t)=>e.name.localeCompare(t.name);return bm([...n].sort(i).concat(r.sort(i)),`name`)}var E1,e2e,D1,t2e,O1,k1=n((()=>{Ms(),OZ(),_qe(),fB(),zX(),kS(),UI(),bL(),UX(),tJe(),vJe(),TJe(),IL(),pQ(),FJe(),fL(),HJe(),DYe(),AJ(),LJ(),lk(),LYe(),ZYe(),oXe(),_Xe(),KXe(),jZe(),RZe(),GZe(),QZe(),aQe(),xm(),$O(),HS(),ls(),ds(),dQe(),n$e(),j9(),jb(),g(),Ps(),dse(),WX(),E1=process.env.WORKMATE_VERIFY_PLAN===`true`?(o$e(),e(r$e)).VerifyPlanExecutionTool:null,e2e=t$e(),D1=()=>uae()?(S1(),e(m1)).PowerShellTool:null,t2e=[`default`],O1=e=>{if(h(process.env.WORKMATE_SIMPLE))return w1([dB,DS,RX],e);let t=new Set([kJ.name,IJ.name,ws]),n=w1(C1().filter(e=>!t.has(e.name)),e);WWe()&&n.some(e=>us(e,`REPL`))&&(n=n.filter(e=>!GWe.has(e.name)));let r=n.map(e=>e.isEnabled());return n.filter((e,t)=>r[t])}})),n2e,A1,r2e=n((()=>{b(),n2e=Symbol.asyncIterator,A1=class{constructor(e){x(this,`returned`,void 0),x(this,`queue`,[]),x(this,`readResolve`,void 0),x(this,`readReject`,void 0),x(this,`isDone`,!1),x(this,`hasError`,void 0),x(this,`started`,!1),this.returned=e}[n2e](){if(this.started)throw Error(`Stream can only be iterated once`);return this.started=!0,this}next(){return this.queue.length>0?Promise.resolve({done:!1,value:this.queue.shift()}):this.isDone?Promise.resolve({done:!0,value:void 0}):this.hasError?Promise.reject(this.hasError):new Promise((e,t)=>{this.readResolve=e,this.readReject=t})}enqueue(e){if(this.readResolve){let t=this.readResolve;this.readResolve=void 0,this.readReject=void 0,t({done:!1,value:e})}else this.queue.push(e)}done(){if(this.isDone=!0,this.readResolve){let e=this.readResolve;this.readResolve=void 0,this.readReject=void 0,e({done:!0,value:void 0})}}error(e){if(this.hasError=e,this.readReject){let t=this.readReject;this.readResolve=void 0,this.readReject=void 0,t(e)}}return(){return this.isDone=!0,this.returned&&this.returned(),Promise.resolve({done:!0,value:void 0})}}}));function i2e(e){switch(e){case`allow`:return`allowed`;case`deny`:return`denied`;default:return`asked for confirmation for`}}var a2e=n((()=>{}));async function*o2e(e,t,n,r,i,a,o,s,c){let l=Date.now();try{let r=e.getAppState().toolPermissionContext.mode,c=a;for await(let a of _at(t.name,n,i,c,e,r,e.abortController.signal))try{if(a.message?.type===`attachment`&&a.message.attachment.type===`hook_cancelled`){Ys(t.name),e.queryTracking?.chainId,e.queryTracking?.depth,yield{message:a2({type:`hook_cancelled`,hookName:`PostToolUse:${t.name}`,toolUseID:n,hookEvent:`PostToolUse`})};continue}if(a.message&&!(a.message.type===`attachment`&&a.message.attachment.type===`hook_blocking_error`)&&(yield{message:a.message}),a.blockingError&&(yield{message:a2({type:`hook_blocking_error`,hookName:`PostToolUse:${t.name}`,toolUseID:n,hookEvent:`PostToolUse`,blockingError:a.blockingError})}),a.preventContinuation){yield{message:a2({type:`hook_stopped_continuation`,message:a.stopReason||`Execution stopped by PostToolUse hook`,hookName:`PostToolUse:${t.name}`,toolUseID:n,hookEvent:`PostToolUse`})};return}a.additionalContexts&&a.additionalContexts.length>0&&(yield{message:a2({type:`hook_additional_context`,content:a.additionalContexts,hookName:`PostToolUse:${t.name}`,toolUseID:n,hookEvent:`PostToolUse`})}),a.updatedMCPToolOutput&&aY(t)&&(c=a.updatedMCPToolOutput,yield{updatedMCPToolOutput:c})}catch(r){Date.now()-l,Ys(t.name),t.isMcp,e.queryTracking?.chainId,e.queryTracking?.depth,{...s?{mcpServerType:s}:{},...o?{requestId:o}:{}},yield{message:a2({type:`hook_error_during_execution`,content:OQ(r),hookName:`PostToolUse:${t.name}`,toolUseID:n,hookEvent:`PostToolUse`})}}}catch(e){Y(e)}}async function*s2e(e,t,n,r,i,a,o,s,c,l){let u=Date.now();try{let r=e.getAppState().toolPermissionContext.mode;for await(let l of vat(t.name,n,i,a,e,o,r,e.abortController.signal))try{if(l.message?.type===`attachment`&&l.message.attachment.type===`hook_cancelled`){Ys(t.name),e.queryTracking?.chainId,e.queryTracking?.depth,yield{message:a2({type:`hook_cancelled`,hookName:`PostToolUseFailure:${t.name}`,toolUseID:n,hookEvent:`PostToolUseFailure`})};continue}l.message&&!(l.message.type===`attachment`&&l.message.attachment.type===`hook_blocking_error`)&&(yield{message:l.message}),l.blockingError&&(yield{message:a2({type:`hook_blocking_error`,hookName:`PostToolUseFailure:${t.name}`,toolUseID:n,hookEvent:`PostToolUseFailure`,blockingError:l.blockingError})}),l.additionalContexts&&l.additionalContexts.length>0&&(yield{message:a2({type:`hook_additional_context`,content:l.additionalContexts,hookName:`PostToolUseFailure:${t.name}`,toolUseID:n,hookEvent:`PostToolUseFailure`})})}catch(r){Date.now()-u,Ys(t.name),t.isMcp,e.queryTracking?.chainId,e.queryTracking?.depth,{...c?{mcpServerType:c}:{},...s?{requestId:s}:{}},yield{message:a2({type:`hook_error_during_execution`,content:OQ(r),hookName:`PostToolUseFailure:${t.name}`,toolUseID:n,hookEvent:`PostToolUseFailure`})}}}catch(e){Y(e)}}async function c2e(e,t,n,r,i,a,o){let s=t.requiresUserInteraction?.(),c=r.requireCanUseTool;if(e?.behavior===`allow`){let l=e.updatedInput??n,u=s&&e.updatedInput!==void 0;if(s&&!u||c)return K(`Hook approved tool use for ${t.name}, but canUseTool is required`),{decision:await i(t,l,r,a,o),input:l};let d=await vct(t,l,r);return d===null?(K(u?`Hook satisfied user interaction for ${t.name} via updatedInput`:`Hook approved tool use for ${t.name}, bypassing permission prompt`),{decision:e,input:l}):d.behavior===`deny`?(K(`Hook approved tool use for ${t.name}, but deny rule overrides: ${d.message}`),{decision:d,input:l}):(K(`Hook approved tool use for ${t.name}, but ask rule requires prompt`),{decision:await i(t,l,r,a,o),input:l})}if(e?.behavior===`deny`)return K(`Hook denied tool use for ${t.name}`),{decision:e,input:n};let l=e?.behavior===`ask`?e:void 0,u=e?.behavior===`ask`&&e.updatedInput?e.updatedInput:n;return{decision:await i(t,u,r,a,o,l),input:u}}async function*l2e(e,t,n,r,i,a,o,s){let c=Date.now();try{let i=e.getAppState();for await(let s of gat(t.name,r,n,e,i.toolPermissionContext.mode,e.abortController.signal,void 0,e.requestPrompt,t.getToolUseSummary?.(n)))try{if(s.message&&(yield{type:`message`,message:{message:s.message}}),s.blockingError){let e=dat(`PreToolUse:${t.name}`,s.blockingError);yield{type:`hookPermissionResult`,hookPermissionResult:{behavior:`deny`,message:e,decisionReason:{type:`hook`,hookName:`PreToolUse:${t.name}`,reason:e}}}}if(s.preventContinuation&&(yield{type:`preventContinuation`,shouldPreventContinuation:!0},s.stopReason&&(yield{type:`stopReason`,stopReason:s.stopReason})),s.permissionBehavior!==void 0){K(`Hook result has permissionBehavior=${s.permissionBehavior}`);let e={type:`hook`,hookName:`PreToolUse:${t.name}`,hookSource:s.hookSource,reason:s.hookPermissionDecisionReason};s.permissionBehavior===`allow`?yield{type:`hookPermissionResult`,hookPermissionResult:{behavior:`allow`,updatedInput:s.updatedInput,decisionReason:e}}:s.permissionBehavior===`ask`?yield{type:`hookPermissionResult`,hookPermissionResult:{behavior:`ask`,updatedInput:s.updatedInput,message:s.hookPermissionDecisionReason||`Hook PreToolUse:${t.name} ${i2e(s.permissionBehavior)} this tool`,decisionReason:e}}:yield{type:`hookPermissionResult`,hookPermissionResult:{behavior:s.permissionBehavior,message:s.hookPermissionDecisionReason||`Hook PreToolUse:${t.name} ${i2e(s.permissionBehavior)} this tool`,decisionReason:e}}}if(s.updatedInput&&s.permissionBehavior===void 0&&(yield{type:`hookUpdatedInput`,updatedInput:s.updatedInput}),s.additionalContexts&&s.additionalContexts.length>0&&(yield{type:`additionalContext`,message:{message:a2({type:`hook_additional_context`,content:s.additionalContexts,hookName:`PreToolUse:${t.name}`,toolUseID:r,hookEvent:`PreToolUse`})}}),e.abortController.signal.aborted){Ys(t.name),e.queryTracking?.chainId,e.queryTracking?.depth,yield{type:`message`,message:{message:a2({type:`hook_cancelled`,hookName:`PreToolUse:${t.name}`,toolUseID:r,hookEvent:`PreToolUse`})}},yield{type:`stop`};return}}catch(n){Y(n),Date.now()-c,Ys(t.name),t.isMcp,e.queryTracking?.chainId,e.queryTracking?.depth,{...o?{mcpServerType:o}:{},...a?{requestId:a}:{}},yield{type:`message`,message:{message:a2({type:`hook_error_during_execution`,content:OQ(n),hookName:`PreToolUse:${t.name}`,toolUseID:r,hookEvent:`PreToolUse`})}},yield{type:`stop`}}}catch(e){Y(e),yield{type:`stop`};return}}var u2e=n((()=>{La(),Qs(),g2(),q(),_7(),wa(),a2e(),j9(),kQ(),oY()}));function d2e(){return M1||(M1=import(`./toolEventObserver-DWcRzEHx.js`).catch(e=>{throw M1=void 0,e})),M1}function f2e(e){if(e instanceof ji)return e.telemetryMessage.slice(0,200);if(e instanceof Error){let t=yi(e);return typeof t==`string`?`Error:${t}`:e.name&&e.name!==`Error`&&e.name.length>3?e.name.slice(0,60):`Error`}return`UnknownError`}function p2e(e,t){switch(e){case`session`:return t===`allow`?`user_temporary`:`user_reject`;case`localSettings`:case`userSettings`:return t===`allow`?`user_permanent`:`user_reject`;default:return`config`}}function m2e(e,t){if(!e)return`config`;switch(e.type){case`permissionPromptTool`:{let n=e.toolResult?.decisionClassification;return n===`user_temporary`||n===`user_permanent`||n===`user_reject`?n:t===`allow`?`user_temporary`:`user_reject`}case`rule`:return p2e(e.rule.source,t);case`hook`:return`hook`;case`mode`:case`classifier`:case`subcommandResults`:case`asyncAgent`:case`sandboxOverride`:case`workingDir`:case`safetyCheck`:case`other`:return`config`;default:return`config`}}function h2e(e){let t=0;for(let n of e)if(n.type===`user`&&n.imagePasteIds)for(let e of n.imagePasteIds)e>t&&(t=e);return t+1}function g2e(e,t){if(!e.startsWith(`mcp__`))return;let n=Qn(e);if(n)return t.find(e=>pn(e.name)===n.serverName)}function _2e(e,t){let n=g2e(e,t);if(n?.type===`connected`)return n.config.type??`stdio`}function v2e(e,t){let n=g2e(e,t);if(n?.type===`connected`)return QBe(n.config)}async function*j1(e,t,n,r){let i=e.name,a=ms(r.options.tools,i);if(!a){let e=ms(C1(),i);e?.aliases?.includes(i)&&(a=e)}let o=t.message.id,s=t.requestId,c=_2e(i,r.options.mcpClients),l=v2e(i,r.options.mcpClients);if(!a){let n=Ys(i);K(`Unknown tool ${i}: ${e.id}`),`${n}`,e.id,i.startsWith(`mcp__`),r.queryTracking?.chainId,r.queryTracking?.depth,{...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...rc(i,c,l)},yield{message:Q({content:[{type:`tool_result`,content:`<tool_use_error>Error: No such tool available: ${i}</tool_use_error>`,is_error:!0,tool_use_id:e.id}],toolUseResult:`Error: No such tool available: ${i}`,sourceToolAssistantUUID:t.uuid})};return}let u=e.input;try{if(r.abortController.signal.aborted){Ys(a.name),e.id,a.isMcp,r.queryTracking?.chainId,r.queryTracking?.depth,{...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...rc(a.name,c,l)};let n=dhe(e.id);n.content=o3(F_),yield{message:Q({content:[n],toolUseResult:F_,sourceToolAssistantUUID:t.uuid})};return}for await(let i of y2e(a,e.id,u,r,n,t,o,s,c,l))yield i}catch(n){Y(n);let r=n instanceof Error?n.message:String(n),i=`Error calling tool${a?` (${a.name})`:``}: ${r}`;yield{message:Q({content:[{type:`tool_result`,content:`<tool_use_error>${i}</tool_use_error>`,is_error:!0,tool_use_id:e.id}],toolUseResult:i,sourceToolAssistantUUID:t.uuid})}}}function y2e(e,t,n,r,i,a,o,s,c,l){let u=new A1;return x2e(e,t,n,r,i,a,o,s,c,l,n=>{Ys(e.name),e.isMcp,r.queryTracking?.chainId,r.queryTracking?.depth,{...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...rc(e.name,c,l)},u.enqueue({message:uhe({toolUseID:n.toolUseID,parentToolUseID:t,data:n.data})})}).then(e=>{for(let t of e)u.enqueue(t)}).catch(e=>{u.error(e)}).finally(()=>{u.done()}),u}function b2e(e,t,n){if(!VO()||!HO(n)||!vs(e)||GO(t).has(e.name))return null;let r=e.userFacingName?e.userFacingName(void 0):e.name;return`\n\nTool "${r}" is deferred-loading and needs to be discovered before use.\nWhen using OpenAI-compatible models (DeepSeek, Ollama, etc.), follow these steps:\n1. First discover the tool with SearchExtraTools: ${Ss}("select:${e.name}")\n2. Then call ${r} tool\n\nExample:\n${Ss}("select:${e.name}") → ${r}({ ... })\n\nImportant notes:\n• Use camelCase parameter names (e.g., taskId), not snake_case (task_id)\n• All task tools (TaskGet, TaskCreate, TaskUpdate, TaskList) need to be discovered first\n• You can discover them all at once: ${Ss}("select:TaskGet,TaskCreate,TaskUpdate,TaskList")\n\nSee docs/openai-task-tools.md for detailed guide.`}async function x2e(e,t,n,r,i,a,o,s,c,l,u){let d=e.inputSchema.safeParse(n);if(!d.success){let n=AYe(e.name,d.error),i=b2e(e,r.messages,r.options.tools);return i&&(Ys(e.name),e.isMcp,n+=i),K(`${e.name} tool input error: ${n.slice(0,200)}`),n.slice(0,2e3),Ys(e.name),e.isMcp,r.queryTracking?.chainId,r.queryTracking?.depth,{...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...rc(e.name,c,l)},[{message:Q({content:[{type:`tool_result`,content:`<tool_use_error>InputValidationError: ${n}</tool_use_error>`,is_error:!0,tool_use_id:t}],toolUseResult:`InputValidationError: ${d.error.message}`,sourceToolAssistantUUID:a.uuid})}]}let f=await e.validateInput?.(d.data,r);if(f?.result===!1)return K(`${e.name} tool validation error: ${f.message?.slice(0,200)}`),Ys(e.name),f.message,f.errorCode,e.isMcp,r.queryTracking?.chainId,r.queryTracking?.depth,{...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...rc(e.name,c,l)},[{message:Q({content:[{type:`tool_result`,content:`<tool_use_error>${f.message}</tool_use_error>`,is_error:!0,tool_use_id:t}],toolUseResult:`Error: ${f.message}`,sourceToolAssistantUUID:a.uuid})}];if(e.name===`Bash`&&d.data&&`command`in d.data){let e=r.getAppState();zPe(d.data.command,e.toolPermissionContext,r.abortController.signal,r.options.isNonInteractiveSession)}let p=[],m=d.data;if(e.name===`Bash`&&m&&typeof m==`object`&&`_simulatedSedEdit`in m){let{_simulatedSedEdit:e,...t}=m;m=t}let h=m,g=e.backfillObservableInput&&typeof m==`object`&&m?{...m}:null;g&&(e.backfillObservableInput(g),m=g);let _=!1,v,y,b=[],x=Date.now();for await(let n of l2e(r,e,m,t,a.message.id,s,c,l))switch(n.type){case`message`:if(n.message.message.type===`progress`)u(n.message.message);else{p.push(n.message);let e=n.message.message.attachment;e&&`command`in e&&e.command!==void 0&&`durationMs`in e&&e.durationMs!==void 0&&b.push({command:e.command,durationMs:e.durationMs})}break;case`hookPermissionResult`:y=n.hookPermissionResult;break;case`hookUpdatedInput`:m=n.updatedInput;break;case`preventContinuation`:_=n.shouldPreventContinuation;break;case`stopReason`:v=n.stopReason;break;case`additionalContext`:p.push(n.message);break;case`stop`:return qr()?.observe(`pre_tool_hook_duration_ms`,Date.now()-x),p.push({message:Q({content:[dhe(t)],toolUseResult:`Error: ${v}`,sourceToolAssistantUUID:a.uuid})}),p}let S=Date.now()-x;qr()?.observe(`pre_tool_hook_duration_ms`,S),S>=N1&&K(`Slow PreToolUse hooks: ${S}ms for ${e.name} (${b.length} hooks)`,{level:`info`});let C={};m&&typeof m==`object`&&(e.name===`Read`&&`file_path`in m||(e.name===`Edit`||e.name===`Write`)&&`file_path`in m?C.file_path=String(m.file_path):e.name===`Bash`&&`command`in m&&(C.full_command=m.command)),Koe(e.name,C,Xs()?W(m):void 0),Zoe();let w=r.getAppState().toolPermissionContext.mode,T=Date.now(),E=await c2e(y,e,m,r,i,a,t),D=E.decision;m=E.input;let O=Date.now()-T;if(O>=N1&&w===`auto`&&K(`Slow permission decision: ${O}ms for ${e.name} (mode=${w}, behavior=${D.behavior})`,{level:`info`}),D.behavior!==`ask`&&!r.toolDecisions?.has(t)){let t=D.behavior===`allow`?`accept`:`reject`,n=m2e(D.decisionReason,D.behavior);$s(`tool_decision`,{decision:t,source:n,tool_name:Ys(e.name)}),OH(e.name)&&kH(e,m,t,n).then(e=>Are()?.add(1,e))}if(D.decisionReason?.type===`hook`&&D.decisionReason.hookName===`PermissionRequest`&&D.behavior!==`ask`&&p.push({message:a2({type:`hook_permission_decision`,decision:D.behavior,toolUseID:t,hookEvent:`PermissionRequest`})}),D.behavior!==`allow`){K(`${e.name} tool permission denied`);let n=r.toolDecisions?.get(t);Uoe(`reject`,n?.source||`unknown`),tc(),Ys(e.name),r.queryTracking?.chainId,r.queryTracking?.depth,{...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...rc(e.name,c,l)};let i=D.message;_&&!i&&(i=`Execution stopped by PreToolUse hook${v?`: ${v}`:``}`);let o=[{type:`tool_result`,content:i,is_error:!0,tool_use_id:t}],u=D.behavior===`ask`?D.contentBlocks:void 0;u?.length&&o.push(...u);let d;if(u?.length){let e=zt(u,e=>e.type===`image`);if(e>0){let t=h2e(r.messages);d=Array.from({length:e},(e,n)=>t+n)}}return p.push({message:Q({content:o,imagePasteIds:d,toolUseResult:`Error: ${i}`,sourceToolAssistantUUID:a.uuid})}),p}Ys(e.name),r.queryTracking?.chainId,r.queryTracking?.depth,{...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...rc(e.name,c,l)},D.updatedInput!==void 0&&(m=D.updatedInput);let k=Boe(m),A={};if(Voe()){if(e.name===`Bash`&&`command`in m){let e=m;A={bash_command:e.command.trim().split(/\s+/)[0]||``,full_command:e.command,...e.timeout!==void 0&&{timeout:e.timeout},...e.description!==void 0&&{description:e.description},...`dangerouslyDisableSandbox`in e&&{dangerouslyDisableSandbox:e.dangerouslyDisableSandbox}}}let t=Roe(e.name);t&&(A.mcp_server_name=t.serverName,A.mcp_tool_name=t.mcpToolName);let n=zoe(e.name,m);n&&(A.skill_name=n)}let ee=r.toolDecisions?.get(t);Uoe(ee?.decision||`unknown`,ee?.source||`unknown`),Joe();let te=Date.now();fk(`tool_exec`),g&&m!==h&&typeof m==`object`&&m&&`file_path`in m&&`file_path`in h&&m.file_path===g.file_path?h={...m,file_path:h.file_path}:m!==g&&(h=m);try{let n=()=>e.call(h,{...r,toolUseId:t,userModified:D.userModified??!1},i,a,e=>{u({toolUseID:e.toolUseID,data:e.data})}),o=fse()?await(async()=>{let{runToolCallWithSkillLearningHooks:t}=await d2e();return t(e.name,h,{sessionId:r.sessionId},n)})():await n(),d=Date.now()-te;if(dre(d),o.data&&typeof o.data==`object`){let t={};e.name===`Read`&&`content`in o.data&&(`file_path`in m&&(t.file_path=String(m.file_path)),t.content=String(o.data.content)),(e.name===`Edit`||e.name===`Write`)&&`file_path`in m&&(t.file_path=String(m.file_path),e.name===`Edit`&&`diff`in o.data&&(t.diff=String(o.data.diff)),e.name===`Write`&&`content`in m&&(t.content=String(m.content))),e.name===`Bash`&&`command`in m&&(t.bash_command=m.command,`output`in o.data&&(t.output=String(o.data.output))),Object.keys(t).length>0&&Qoe(`tool.output`,t)}typeof o==`object`&&`structured_output`in o&&p.push({message:a2({type:`structured_output`,data:o.structured_output})}),Xoe({success:!0}),tc(o.data&&typeof o.data==`object`?W(o.data):String(o.data??``));let f=e.mapToolResultToToolResultBlockParam(o.data,t),g=f.content,y=g?typeof g==`string`?g.length:W(g).length:0,b;if(m&&typeof m==`object`){if((e.name===`Read`||e.name===`Edit`||e.name===`Write`)&&`file_path`in m)b=Zs(String(m.file_path));else if(e.name===`NotebookEdit`&&`notebook_path`in m)b=Zs(String(m.notebook_path));else if(e.name===`Bash`&&`command`in m){let e=m;b=Loe(e.command,e._simulatedSedEdit?.filePath)}}if(Ys(e.name),e.isMcp,{...b!==void 0&&{fileExtension:b}},r.queryTracking?.chainId,r.queryTracking?.depth,{...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...rc(e.name,c,l)},Voe()&&(e.name===`Bash`||e.name===`PowerShell`)&&`command`in m&&typeof m.command==`string`&&m.command.match(/\bgit\s+commit\b/)&&o.data&&typeof o.data==`object`&&`stdout`in o.data){let e=WP(String(o.data.stdout));e&&(A.git_commit_id=e)}let x=aY(e)?KBe(e.name):null;$s(`tool_result`,{tool_name:Ys(e.name),success:`true`,duration_ms:String(d),...Object.keys(A).length>0&&{tool_parameters:W(A)},...k&&{tool_input:k},tool_result_size_bytes:String(y),...ee&&{decision_source:ee.source,decision_type:ee.decision},...x&&{mcp_server_scope:x}});let S=o.data,C=[],w=o.contextModifier,T=o.mcpMeta;async function E(n,i){let o=[i?await zve(i,e.name,e.maxResultSizeChars):await ox(e,n,t)];`acceptFeedback`in D&&D.acceptFeedback&&o.push({type:`text`,text:D.acceptFeedback});let s=`contentBlocks`in D?D.contentBlocks:void 0;s?.length&&o.push(...s);let c;if(s?.length){let e=zt(s,e=>e.type===`image`);if(e>0){let t=h2e(r.messages);c=Array.from({length:e},(e,n)=>t+n)}}p.push({message:Q({content:o,imagePasteIds:c,toolUseResult:r.agentId&&!r.preserveToolUseResults?void 0:n,mcpMeta:r.agentId?void 0:T,sourceToolAssistantUUID:a.uuid}),contextModifier:w?{toolUseID:t,modifyContext:w}:void 0})}aY(e)||await E(S,f);let O=[],ne=Date.now();for await(let n of o2e(r,e,t,a.message.id,m,S,s,c,l))if(`updatedMCPToolOutput`in n)aY(e)&&(S=n.updatedMCPToolOutput);else if(aY(e)){if(C.push(n),n.message.type===`attachment`){let e=n.message.attachment;`command`in e&&e.command!==void 0&&`durationMs`in e&&e.durationMs!==void 0&&O.push({command:e.command,durationMs:e.durationMs})}}else if(p.push(n),n.message.type===`attachment`){let e=n.message.attachment;`command`in e&&e.command!==void 0&&`durationMs`in e&&e.durationMs!==void 0&&O.push({command:e.command,durationMs:e.durationMs})}let re=Date.now()-ne;if(re>=N1&&K(`Slow PostToolUse hooks: ${re}ms for ${e.name} (${O.length} hooks)`,{level:`info`}),aY(e)&&await E(S),o.newMessages&&o.newMessages.length>0)for(let e of o.newMessages)p.push({message:e});_&&p.push({message:a2({type:`hook_stopped_continuation`,message:v||`Execution stopped by hook`,hookName:`PreToolUse:${e.name}`,toolUseID:t,hookEvent:`PreToolUse`})});for(let e of C)p.push(e);return p}catch(n){let i=Date.now()-te;if(dre(i),Xoe({success:!1,error:G(n)}),tc(),n instanceof mY&&r.setAppState(e=>{let t=n.serverName,r=e.mcp.clients.findIndex(e=>e.name===t);if(r===-1)return e;let i=e.mcp.clients[r];if(i?.type!==`connected`)return e;let a=[...e.mcp.clients];return a[r]={name:t,type:`needs-auth`,config:i.config},{...e,mcp:{...e.mcp,clients:a}}}),!(n instanceof pi)){let a=G(n);K(`${e.name} tool error (${i}ms): ${a.slice(0,200)}`),n instanceof fi||Y(n),Ys(e.name),f2e(n),e.isMcp,r.queryTracking?.chainId,r.queryTracking?.depth,{...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...rc(e.name,c,l)};let o=aY(e)?KBe(e.name):null;$s(`tool_result`,{tool_name:Ys(e.name),use_id:t,success:`false`,duration_ms:String(i),error:G(n),...Object.keys(A).length>0&&{tool_parameters:W(A)},...k&&{tool_input:k},...ee&&{decision_source:ee.source,decision_type:ee.decision},...o&&{mcp_server_scope:o}})}let u=OQ(n),d=n instanceof pi,f=[];for await(let n of s2e(r,e,t,o,m,u,d,s,c,l))f.push(n);return[{message:Q({content:[{type:`tool_result`,content:u,is_error:!0,tool_use_id:t}],toolUseResult:`Error: ${u}`,mcpMeta:r.agentId?void 0:n instanceof gY?n.mcpMeta:void 0,sourceToolAssistantUUID:a.uuid})},...f]}finally{pk(`tool_exec`),ee&&r.toolDecisions?.delete(t)}}var M1,N1,S2e=n((()=>{La(),Qs(),H(),MH(),Ms(),VB(),ys(),Es(),As(),Is(),hs(),Ns(),$P(),Os(),k1(),tt(),g2(),q(),gi(),wa(),v3(),Sk(),Li(),r2e(),nc(),ec(),kQ(),fx(),$O(),wY(),Bn(),jn(),oY(),u2e(),pse(),N1=2e3}));function C2e(e,t){e.setInProgressToolUseIDs(e=>{let n=new Set(e);return n.delete(t),n})}var P1,w2e=n((()=>{v3(),Ms(),ys(),GT(),S2e(),b(),P1=class{constructor(e,t,n){x(this,`toolDefinitions`,void 0),x(this,`canUseTool`,void 0),x(this,`tools`,[]),x(this,`toolUseContext`,void 0),x(this,`hasErrored`,!1),x(this,`erroredToolDescription`,``),x(this,`siblingAbortController`,void 0),x(this,`discarded`,!1),x(this,`progressAvailableResolve`,void 0),this.toolDefinitions=e,this.canUseTool=t,this.toolUseContext=n,this.siblingAbortController=UT(n.abortController)}discard(){this.discarded=!0,this.siblingAbortController.abort(`streaming_fallback`),this.tools.length=0,this.progressAvailableResolve=void 0}addTool(e,t){let n=ms(this.toolDefinitions,e.name);if(!n){this.tools.push({id:e.id,block:e,assistantMessage:t,status:`completed`,isConcurrencySafe:!0,pendingProgress:[],results:[Q({content:[{type:`tool_result`,content:`<tool_use_error>Error: No such tool available: ${e.name}</tool_use_error>`,is_error:!0,tool_use_id:e.id}],toolUseResult:`Error: No such tool available: ${e.name}`,sourceToolAssistantUUID:t.uuid})]});return}let r=n.inputSchema.safeParse(e.input),i=r?.success?(()=>{try{return!!n.isConcurrencySafe(r.data)}catch{return!1}})():!1;this.tools.push({id:e.id,block:e,assistantMessage:t,status:`queued`,isConcurrencySafe:i,pendingProgress:[]}),this.processQueue()}canExecuteTool(e){let t=this.tools.filter(e=>e.status===`executing`);return t.length===0||e&&t.every(e=>e.isConcurrencySafe)}async processQueue(){for(let e of this.tools)if(e.status===`queued`){if(this.canExecuteTool(e.isConcurrencySafe))await this.executeTool(e);else if(!e.isConcurrencySafe)break}}createSyntheticErrorMessage(e,t,n){if(t===`user_interrupted`)return Q({content:[{type:`tool_result`,content:o3(I_),is_error:!0,tool_use_id:e}],toolUseResult:`User rejected tool use`,sourceToolAssistantUUID:n.uuid});if(t===`streaming_fallback`)return Q({content:[{type:`tool_result`,content:`<tool_use_error>Error: Streaming fallback - tool execution discarded</tool_use_error>`,is_error:!0,tool_use_id:e}],toolUseResult:`Streaming fallback - tool execution discarded`,sourceToolAssistantUUID:n.uuid});let r=this.erroredToolDescription,i=r?`Cancelled: parallel tool call ${r} errored`:`Cancelled: parallel tool call errored`;return Q({content:[{type:`tool_result`,content:`<tool_use_error>${i}</tool_use_error>`,is_error:!0,tool_use_id:e}],toolUseResult:i,sourceToolAssistantUUID:n.uuid})}getAbortReason(e){return this.discarded?`streaming_fallback`:this.hasErrored?`sibling_error`:this.toolUseContext.abortController.signal.aborted?this.toolUseContext.abortController.signal.reason===`interrupt`?this.getToolInterruptBehavior(e)===`cancel`?`user_interrupted`:null:`user_interrupted`:null}getToolInterruptBehavior(e){let t=ms(this.toolDefinitions,e.block.name);if(!t?.interruptBehavior)return`block`;try{return t.interruptBehavior()}catch{return`block`}}getToolDescription(e){let t=e.block.input,n=t?.command??t?.file_path??t?.pattern??``;if(typeof n==`string`&&n.length>0){let t=n.length>40?`${n.slice(0,40)}\u2026`:n;return`${e.block.name}(${t})`}return e.block.name}updateInterruptibleState(){let e=this.tools.filter(e=>e.status===`executing`);this.toolUseContext.setHasInterruptibleToolInProgress?.(e.length>0&&e.every(e=>this.getToolInterruptBehavior(e)===`cancel`))}async executeTool(e){e.status=`executing`,this.toolUseContext.setInProgressToolUseIDs(t=>new Set(t).add(e.id)),this.updateInterruptibleState();let t=[],n=[],r=(async()=>{let r=this.getAbortReason(e);if(r){t.push(this.createSyntheticErrorMessage(e.id,r,e.assistantMessage)),e.results=t,e.contextModifiers=n,e.status=`completed`,this.updateInterruptibleState();return}let i=UT(this.siblingAbortController);i.signal.addEventListener(`abort`,()=>{i.signal.reason!==`sibling_error`&&!this.toolUseContext.abortController.signal.aborted&&!this.discarded&&this.toolUseContext.abortController.abort(i.signal.reason)},{once:!0});let a=j1(e.block,e.assistantMessage,this.canUseTool,{...this.toolUseContext,abortController:i}),o=!1;for await(let r of a){let i=this.getAbortReason(e);if(i&&!o){t.push(this.createSyntheticErrorMessage(e.id,i,e.assistantMessage));break}r.message.type===`user`&&Array.isArray(r.message.message.content)&&r.message.message.content.some(e=>e.type===`tool_result`&&e.is_error===!0)&&(o=!0,e.block.name===`Bash`&&(this.hasErrored=!0,this.erroredToolDescription=this.getToolDescription(e),this.siblingAbortController.abort(`sibling_error`))),r.message&&(r.message.type===`progress`?(e.pendingProgress.push(r.message),this.progressAvailableResolve&&(this.progressAvailableResolve(),this.progressAvailableResolve=void 0)):t.push(r.message)),r.contextModifier&&n.push(r.contextModifier.modifyContext)}if(e.results=t,e.contextModifiers=n,e.status=`completed`,this.updateInterruptibleState(),!e.isConcurrencySafe&&n.length>0)for(let e of n)this.toolUseContext=e(this.toolUseContext)})();e.promise=r,r.finally(()=>{this.processQueue()})}*getCompletedResults(){if(!this.discarded)for(let e of this.tools){for(;e.pendingProgress.length>0;)yield{message:e.pendingProgress.shift(),newContext:this.toolUseContext};if(e.status!==`yielded`){if(e.status===`completed`&&e.results){e.status=`yielded`;for(let t of e.results)yield{message:t,newContext:this.toolUseContext};C2e(this.toolUseContext,e.id)}else if(e.status===`executing`&&!e.isConcurrencySafe)break}}}hasPendingProgress(){return this.tools.some(e=>e.pendingProgress.length>0)}async*getRemainingResults(){if(!this.discarded){for(;this.hasUnfinishedTools();){await this.processQueue();for(let e of this.getCompletedResults())yield e;if(this.hasExecutingTools()&&!this.hasCompletedResults()&&!this.hasPendingProgress()){let e=this.tools.filter(e=>e.status===`executing`&&e.promise).map(e=>e.promise),t=new Promise(e=>{this.progressAvailableResolve=e});e.length>0&&await Promise.race([...e,t])}}for(let e of this.getCompletedResults())yield e}}hasCompletedResults(){return this.tools.some(e=>e.status===`completed`)}hasExecutingTools(){return this.tools.some(e=>e.status===`executing`)}hasUnfinishedTools(){return this.tools.some(e=>e.status!==`yielded`)}getUpdatedContext(){return this.toolUseContext}}}));function T2e(){I1&&(Ga().clearMarks(),L1.clear(),z1=null,R1++,F1(`query_user_input_received`))}function F1(e){if(!I1)return;let t=Ga();if(t.mark(e),L1.set(e,process.memoryUsage()),e===`query_first_chunk_received`&&z1===null){let e=t.getEntriesByType(`mark`);e.length>0&&(z1=e[e.length-1]?.startTime??0)}}function E2e(){I1&&F1(`query_profile_end`)}function D2e(e,t){return t===`query_user_input_received`?``:e>1e3?` ⚠️ VERY SLOW`:e>100?` ⚠️ SLOW`:t.includes(`git_status`)&&e>50?` ⚠️ git status`:t.includes(`tool_schema`)&&e>50?` ⚠️ tool schemas`:t.includes(`client_creation`)&&e>50?` ⚠️ client creation`:``}function O2e(){if(!I1)return`Query profiling not enabled (set WORKMATE_PROFILE_QUERY=1)`;let e=Ga().getEntriesByType(`mark`);if(e.length===0)return`No query profiling checkpoints recorded`;let t=[];t.push(`=`.repeat(80)),t.push(`QUERY PROFILING REPORT - Query #${R1}`),t.push(`=`.repeat(80)),t.push(``);let n=e[0]?.startTime??0,r=n,i=0,a=0;for(let o of e){let e=o.startTime-n,s=o.startTime-r;t.push(sie(e,s,o.name,L1.get(o.name),10,9,D2e(s,o.name))),o.name===`query_api_request_sent`&&(i=e),o.name===`query_first_chunk_received`&&(a=e),r=o.startTime}let o=e[e.length-1],s=o?o.startTime-n:0;if(t.push(``),t.push(`-`.repeat(80)),a>0){let e=i,n=a-i,r=(e/a*100).toFixed(1),o=(n/a*100).toFixed(1);t.push(`Total TTFT: ${za(a)}ms`),t.push(` - Pre-request overhead: ${za(e)}ms (${r}%)`),t.push(` - Network latency: ${za(n)}ms (${o}%)`)}else t.push(`Total time: ${za(s)}ms`);return t.push(k2e(e,n)),t.push(`=`.repeat(80)),t.join(`
2396
2396
  `)}function k2e(e,t){let n=[{name:`Context loading`,start:`query_context_loading_start`,end:`query_context_loading_end`},{name:`Microcompact`,start:`query_microcompact_start`,end:`query_microcompact_end`},{name:`Autocompact`,start:`query_autocompact_start`,end:`query_autocompact_end`},{name:`Query setup`,start:`query_setup_start`,end:`query_setup_end`},{name:`Tool schemas`,start:`query_tool_schema_build_start`,end:`query_tool_schema_build_end`},{name:`Message normalization`,start:`query_message_normalization_start`,end:`query_message_normalization_end`},{name:`Client creation`,start:`query_client_creation_start`,end:`query_client_creation_end`},{name:`Network TTFB`,start:`query_api_request_sent`,end:`query_first_chunk_received`},{name:`Tool execution`,start:`query_tool_execution_start`,end:`query_tool_execution_end`}],r=new Map(e.map(e=>[e.name,e.startTime-t])),i=[];i.push(``),i.push(`PHASE BREAKDOWN:`);for(let e of n){let t=r.get(e.start),n=r.get(e.end);if(t!==void 0&&n!==void 0){let r=n-t,a=`█`.repeat(Math.min(Math.ceil(r/10),50));i.push(` ${e.name.padEnd(22)} ${za(r).padStart(10)}ms ${a}`)}}let a=r.get(`query_api_request_sent`);return a!==void 0&&(i.push(``),i.push(` ${`Total pre-API overhead`.padEnd(22)} ${za(a).padStart(10)}ms`)),i.join(`
2397
2397
  `)}function A2e(){I1&&K(O2e())}var I1,L1,R1,z1,B1=n((()=>{q(),g(),Ba(),I1=h(process.env.WORKMATE_PROFILE_QUERY),L1=new Map,R1=0,z1=null}));async function*j2e(e,t=1/0){let n=e=>{let t=e.next().then(({done:n,value:r})=>({done:n,value:r,generator:e,promise:t}));return t},r=[...e],i=new Set;for(;i.size<t&&r.length>0;){let e=r.shift();i.add(n(e))}for(;i.size>0;){let{done:e,value:t,generator:a,promise:o}=await Promise.race(i);if(i.delete(o),!e)i.add(n(a)),t!==void 0&&(yield t);else if(r.length>0){let e=r.shift();i.add(n(e))}}}async function M2e(e){let t=[];for await(let n of e)t.push(n);return t}async function*N2e(e){for(let t of e)yield t}var V1=n((()=>{}));function P2e(){return parseInt(process.env.WORKMATE_MAX_TOOL_USE_CONCURRENCY||``,10)||10}async function*F2e(e,t,n,r){let i=r;for(let{isConcurrencySafe:r,blocks:a}of I2e(e,i))if(r){let e={};for await(let r of R2e(a,t,n,i)){if(r.contextModifier){let{toolUseID:t,modifyContext:n}=r.contextModifier;e[t]||(e[t]=[]),e[t].push(n)}yield{message:r.message,newContext:i}}for(let t of a){let n=e[t.id];if(n)for(let e of n)i=e(i)}yield{newContext:i}}else for await(let e of L2e(a,t,n,i))e.newContext&&(i=e.newContext),yield{message:e.message,newContext:i}}function I2e(e,t){return e.reduce((e,n)=>{let r=ms(t.options.tools,n.name),i=r?.inputSchema.safeParse(n.input),a=i?.success?(()=>{try{return!!r?.isConcurrencySafe(i.data)}catch{return!1}})():!1;return a&&e[e.length-1]?.isConcurrencySafe?e[e.length-1].blocks.push(n):e.push({isConcurrencySafe:a,blocks:[n]}),e},[])}async function*L2e(e,t,n,r){let i=r;for(let a of e){r.setInProgressToolUseIDs(e=>new Set(e).add(a.id));for await(let e of j1(a,t.find(e=>Array.isArray(e.message.content)&&e.message.content.some(e=>e.type===`tool_use`&&e.id===a.id)),n,i))e.contextModifier&&(i=e.contextModifier.modifyContext(i)),yield{message:e.message,newContext:i};z2e(r,a.id)}}async function*R2e(e,t,n,r){yield*j2e(e.map(async function*(e){r.setInProgressToolUseIDs(t=>new Set(t).add(e.id)),yield*j1(e,t.find(t=>Array.isArray(t.message.content)&&t.message.content.some(t=>t.type===`tool_use`&&t.id===e.id)),n,r),z2e(r,e.id)}),P2e())}function z2e(e,t){e.setInProgressToolUseIDs(e=>{let n=new Set(e);return n.delete(t),n})}var B2e=n((()=>{Ms(),V1(),S2e()}));async function V2e(e,t){let n=X(e,`state.json`),r;try{r=JSON.parse(Oc(n,`utf-8`))}catch{return}let i=H2e(t);r.status=i,r.updatedAt=new Date().toISOString(),Vse(n,JSON.stringify(r,null,2),`utf-8`)}function H2e(e){if(e.length===0)return`running`;let t=e[e.length-1],n=t.message?.content;return Array.isArray(n)&&n.some(e=>typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_use`)?`running`:t.message?.stop_reason===`end_turn`?`completed`:`running`}var U2e=n((()=>{}));function W2e(){let e=rr().autoDreamEnabled;return e!==void 0&&e}var G2e=n((()=>{Ln()}));async function K2e(e,t){try{let n=(await Gc(e,{recursive:!0})).filter(e=>e.endsWith(`.md`)&&dc(e)!==`MEMORY.md`);return(await Promise.allSettled(n.map(async n=>{let r=X(e,n),{content:i,mtimeMs:a}=await bx(r,0,Y2e,void 0,t),{frontmatter:o}=Mu(i,r);return{filename:n,filePath:r,mtimeMs:a,description:o.description||null,type:bue(o.type)}}))).filter(e=>e.status===`fulfilled`).map(e=>e.value).sort((e,t)=>t.mtimeMs-e.mtimeMs).slice(0,J2e)}catch{return[]}}function q2e(e){return e.map(e=>{let t=e.type?`[${e.type}] `:``,n=new Date(e.mtimeMs).toISOString();return e.description?`- ${t}${e.filename} (${n}): ${e.description}`:`- ${t}${e.filename} (${n})`}).join(`
2398
2398
  `)}var J2e,Y2e,X2e=n((()=>{Hu(),Cx(),ad(),J2e=200,Y2e=30}));function Z2e(e,t){let n=t.length>0?`\n\n## Existing memory files\n\n${t}\n\nCheck this list before writing — update an existing file rather than creating a duplicate.`:``;return[`You are now acting as the memory extraction subagent. Analyze the most recent ~${e} messages above and use them to update your persistent memory systems.`,``,`Available tools: ${os}, ${ts}, ${Yo}, read-only ${ks} (ls/find/cat/stat/wc/head/tail and similar), and ${xs}/${ss} for paths inside the memory directory only. ${ks} rm is not permitted. All other tools — MCP, Agent, write-capable ${ks}, etc — will be denied.`,``,`You have a limited turn budget. ${xs} requires a prior ${os} of the same file, so the efficient strategy is: turn 1 — issue all ${os} calls in parallel for every file you might update; turn 2 — issue all ${ss}/${xs} calls in parallel. Do not interleave reads and writes across multiple turns.`,``,`You MUST only use content from the last ~${e} messages to update your persistent memories. Do not waste any turns attempting to investigate or verify that content further — no grepping source files, no reading code to confirm a pattern exists, no git commands.`+n].join(`
@@ -2452,7 +2452,7 @@ Return a brief summary of what you consolidated, updated, or pruned. If nothing
2452
2452
 
2453
2453
  Sessions since last consolidation (${c.length}):
2454
2454
  ${c.map(e=>`- ${e}`).join(`
2455
- `)}`)})],cacheSafeParams:a0(t),canUseTool:U1(e),querySource:`auto_dream`,forkLabel:`auto_dream`,maxTurns:20,skipTranscript:!0,overrides:{abortController:f},onMessage:h4e(p,d)});Rqe(p,d);let i=t.toolUseContext.getAppState().tasks?.[p];n&&Fqe(i)&&i.filesTouched.length>0&&n({...hhe(i.filesTouched),verb:`Improved`}),K(`[autoDream] completed — cache: read=${r.totalUsage.cache_read_input_tokens} created=${r.totalUsage.cache_creation_input_tokens}`),r.totalUsage.cache_read_input_tokens,r.totalUsage.cache_creation_input_tokens,r.totalUsage.output_tokens,c.length}catch(e){if(f.signal.aborted){K(`[autoDream] aborted by user`);return}K(`[autoDream] fork failed: ${e.message}`),zqe(p,d),await Aqe(u)}}}function h4e(e,t){return n=>{if(n.type!==`assistant`)return;let r=``,i=0,a=[],o=n.message.content;for(let e of o)if(e.type===`text`)r+=e.text;else if(e.type===`tool_use`&&(i++,e.name===`Edit`||e.name===`Write`)){let t=e.input;typeof t.file_path==`string`&&a.push(t.file_path)}Lqe(e,{text:r.trim(),toolUseCount:i},a,t)}}async function g4e(e,t){await K1?.(e,t)}var _4e,v4e,K1,y4e=n((()=>{l0(),v3(),q(),La(),zi(),G2e(),_8(),H(),c4e(),u4e(),BZ(),HZ(),Es(),Is(),_4e=600*1e3,v4e={minHours:24,minSessions:5},K1=null}));async function*b4e(e,t,n,r,i,a,o,s){let c=Date.now(),l={messages:[...e,...t],systemPrompt:n,userContext:r,systemContext:i,toolUseContext:a,querySource:o};if((o===`repl_main_thread`||o===`sdk`)&&e3e(a0(l)),process.env.WORKMATE_JOB_DIR&&o.startsWith(`repl_main_thread`)&&!a.agentId){let e=l.messages.filter(e=>e.type===`assistant`),t=V2e(process.env.WORKMATE_JOB_DIR,e).catch(e=>{K(`[job] classifier error: ${G(e)}`,{level:`error`})});await Promise.race([t,new Promise(e=>setTimeout(e,6e4).unref())])}let u=(await import(`./poorMode-CP6359Sz.js`)).isPoorModeActive();v()||(!f(process.env.WORKMATE_ENABLE_PROMPT_SUGGESTION)&&!u&&v3e(l),!a.agentId&&Gre()&&!u&&import(`./extractMemories-DOfFiInm.js`).then(({executeExtractMemories:e})=>e(l,a.appendSystemMessage)).catch(()=>{}),!a.agentId&&!u&&g4e(l,a.appendSystemMessage));try{let n=[],r=a.getAppState().toolPermissionContext.mode,i=bat(r,a.abortController.signal,void 0,s??!1,a.agentId,a,[...e,...t],a.agentType),o=``,c=0,l=!1,u=``,d=!1,f=[],p=[];for await(let e of i){if(e.message){if(yield e.message,e.message.type===`progress`&&e.message.toolUseID){o=e.message.toolUseID,c++;let t=e.message.data;t.command&&p.push({command:t.command,promptText:t.promptText})}if(e.message.type===`attachment`){let t=e.message.attachment;if(`hookEvent`in t&&(t.hookEvent===`Stop`||t.hookEvent===`SubagentStop`)&&(t.type===`hook_non_blocking_error`?(f.push(t.stderr||`Exit code ${t.exitCode}`),d=!0):t.type===`hook_error_during_execution`?(f.push(t.content),d=!0):t.type===`hook_success`&&(t.stdout&&t.stdout.trim()||t.stderr&&t.stderr.trim())&&(d=!0),`durationMs`in t&&`command`in t)){let e=p.find(e=>e.command===t.command&&e.durationMs===void 0);e&&(e.durationMs=t.durationMs)}}}if(e.blockingError){let t=Q({content:fat(e.blockingError),isMeta:!0});n.push(t),yield t,d=!0,f.push(e.blockingError.blockingError)}if(e.preventContinuation&&(l=!0,u=e.stopReason||`Stop hook prevented continuation`,yield a2({type:`hook_stopped_continuation`,message:u,hookName:`Stop`,toolUseID:o,hookEvent:`Stop`})),a.abortController.signal.aborted)return a.queryTracking?.chainId,a.queryTracking?.depth,yield q_({toolUse:!1}),{blockingErrors:[],preventContinuation:!0}}if(c>0&&(yield phe(c,p,f,l,u,d,`suggestion`,o),f.length>0)){let e=jx(`app:toggleTranscript`,`Global`,`ctrl+o`);a.addNotification?.({key:`stop-hook-error`,text:`Stop hook error occurred \u00b7 ${e} to see`,priority:`immediate`})}return l?{blockingErrors:[],preventContinuation:!0}:n.length>0?{blockingErrors:n,preventContinuation:!1}:{blockingErrors:[],preventContinuation:!1}}catch(e){return Date.now()-c,a.queryTracking?.chainId,a.queryTracking?.depth,yield X_(`Stop hook failed: ${G(e)}`,`warning`),{blockingErrors:[],preventContinuation:!1}}}var x4e=n((()=>{Nx(),zi(),La(),g2(),q(),gi(),_7(),v3(),U2e(),y4e(),_0(),g(),l0()}));function S4e(){return{sessionId:Wr(),gates:{streamingToolExecution:!1,emitToolUseSummaries:h(process.env.WORKMATE_EMIT_TOOL_USE_SUMMARIES),fastModeEnabled:!h(process.env.WORKMATE_DISABLE_FAST_MODE)}}}var C4e=n((()=>{H(),g()}));function w4e(){return{callModel:kst,microcompact:eO,autocompact:cFe,uuid:Lc}}var T4e=n((()=>{r9(),yV(),iO()}));function q1(e,t){return parseFloat(e)*A4e[t.toLowerCase()]}function E4e(e){let t=e.match(O4e);if(t)return q1(t[1],t[2]);let n=e.match(k4e);if(n)return q1(n[1],n[2]);let r=e.match(J1);return r?q1(r[1],r[2]):null}function D4e(e,t,n){let r=e=>new Intl.NumberFormat(`en-US`).format(e);return`Stopped at ${e}% of token target (${r(t)} / ${r(n)}). Keep working \u2014 do not summarize.`}var O4e,k4e,J1,A4e,j4e=n((()=>{O4e=/^\s*\+(\d+(?:\.\d+)?)\s*(k|m|b)\b/i,k4e=/\s\+(\d+(?:\.\d+)?)\s*(k|m|b)\s*[.!?]?\s*$/i,J1=/\b(?:use|spend)\s+(\d+(?:\.\d+)?)\s*(k|m|b)\s*tokens?\b/i,new RegExp(J1.source,`gi`),A4e={k:1e3,m:1e6,b:1e9}}));function M4e(){return{continuationCount:0,lastDeltaTokens:0,lastGlobalTurnTokens:0,startedAt:Date.now()}}function N4e(e,t,n,r){if(t||n===null||n<=0)return{action:`stop`,completionEvent:null};let i=r,a=Math.round(i/n*100),o=r-e.lastGlobalTurnTokens,s=e.continuationCount>=3&&o<Y1&&e.lastDeltaTokens<Y1;return!s&&i<n*P4e?(e.continuationCount++,e.lastDeltaTokens=o,e.lastGlobalTurnTokens=r,{action:`continue`,nudgeMessage:D4e(a,i,n),continuationCount:e.continuationCount,pct:a,turnTokens:i,budget:n}):s||e.continuationCount>0?{action:`stop`,completionEvent:{continuationCount:e.continuationCount,pct:a,turnTokens:i,budget:n,diminishingReturns:s,durationMs:Date.now()-e.startedAt}}:{action:`stop`,completionEvent:null}}var P4e,Y1,F4e=n((()=>{j4e(),P4e=.9,Y1=500}));function X1(){return X(m(),`sessions`)}function I4e(){let e=process.env.WORKMATE_SESSION_KIND;if(e===`bg`)return e}function L4e(){return I4e()===`bg`}async function R4e(){let e=I4e()??`interactive`,t=X1(),n=X(t,`${process.pid}.json`);Oi(async()=>{try{await Zc(n)}catch{}});try{return await Hc(t,{recursive:!0,mode:448}),await zc(t,448),await Qc(n,W({pid:process.pid,sessionId:Wr(),cwd:ti(),startedAt:Date.now(),kind:e,entrypoint:process.env.WORKMATE_ENTRYPOINT,name:process.env.WORKMATE_SESSION_NAME,logPath:process.env.WORKMATE_SESSION_LOG,agent:process.env.WORKMATE_AGENT})),jre(e=>{Z1({sessionId:e})}),!0}catch(e){return K(`[concurrentSessions] register failed: ${G(e)}`),!1}}async function Z1(e){let t=X(X1(),`${process.pid}.json`);try{await Qc(t,W({...Si(await Wc(t,`utf8`)),...e}))}catch(e){K(`[concurrentSessions] updatePidFile failed: ${G(e)}`)}}async function z4e(e){e&&await Z1({name:e})}async function B4e(e){await Z1({...e,updatedAt:Date.now()})}async function V4e(){let e=X1(),t;try{t=await Gc(e)}catch(e){return Ri(e)||K(`[concurrentSessions] readdir failed: ${G(e)}`),0}let n=0;for(let r of t){if(!/^\d+\.json$/.test(r))continue;let t=parseInt(r.slice(0,-5),10);if(t===process.pid){n++;continue}ac(t)?n++:Ma()!==`wsl`&&Zc(X(e,r)).catch(()=>{})}return n}var Q1=n((()=>{H(),di(),q(),g(),gi(),oc(),Pa(),Li()}));function H4e(){return L4e()?Date.now()-$1>=W4e:!1}function U4e(e){$1=Date.now();try{let t=e.forkContextMessages;if(!t||t.length===0)return;let n;for(let e=t.length-1;e>=0;e--)if(t[e].type===`assistant`){n=t[e];break}let r=`busy`,i;if(n?.message?.content){let e=n.message.content;if(Array.isArray(e)){let t=e[e.length-1];t?.type===`tool_use`&&(r=`busy`,i=`tool: ${t.name||`unknown`}`)}}B4e({status:r,waitingFor:i}).catch(e=>{K(`[taskSummary] updateSessionActivity failed: ${e}`)})}catch(e){K(`[taskSummary] error: ${e}`)}}var W4e,$1,G4e=n((()=>{Q1(),q(),W4e=3e4,$1=0}));function*e0(e,t){for(let n of e){let e=(Array.isArray(n.message?.content)?n.message.content:[]).filter(e=>e.type===`tool_use`);for(let r of e)yield Q({content:[{type:`tool_result`,content:t,is_error:!0,tool_use_id:r.id}],toolUseResult:t,sourceToolAssistantUUID:n.uuid})}}function K4e(e){return e?.type===`assistant`&&e.apiError===`max_output_tokens`}function q4e(e){if(e.thrownError!==void 0)return{type:`failed`,error:e.thrownError};let t=e.terminal,n=t?.reason;switch(n){case`completed`:return{type:`completed`};case void 0:case`aborted_streaming`:case`aborted_tools`:return{type:`cancelled`};case`model_error`:return{type:`failed`,error:t.error};default:return{type:`failed`,message:`query ended without successful completion: ${n}`}}}async function*t0(e){let t=[],n=[],r,i=!1,a;try{r=yield*J4e(e,t,n)}catch(e){throw i=!0,a=e,e}finally{await mH({commands:n,outcome:q4e({terminal:r,...i?{thrownError:a}:{}}),priority:`later`}).then(e=>{for(let t of e)oE(t)}).catch(Y);let e=globalThis.performance;if(e&&typeof e.clearMarks==`function`)try{e.clearMarks(),e.clearMeasures?.(),e.clearResourceTimings?.()}catch{}}for(let e of t)gH(e,`completed`);return r}async function*J4e(e,t,n){try{var r=Vre();let{systemPrompt:i,userContext:a,systemContext:o,canUseTool:s,fallbackModel:c,querySource:l,maxTurns:u,skipCacheWrite:d}=e,f=e.deps??w4e(),p={messages:e.messages,toolUseContext:e.toolUseContext,maxOutputTokensOverride:e.maxOutputTokensOverride,autoCompactTracking:void 0,stopHookActive:void 0,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,turnCount:1,pendingToolUseSummary:void 0,transition:void 0},m=M4e(),h,g=S4e(),_=r.u(t8e(p.messages,p.toolUseContext));for(;;){let{toolUseContext:r}=p,{messages:v,autoCompactTracking:y,maxOutputTokensRecoveryCount:b,hasAttemptedReactiveCompact:x,maxOutputTokensOverride:S,pendingToolUseSummary:C,stopHookActive:w,turnCount:T}=p,E=Yw(null,v,r),D=bT(r.options.tools??[],v);yield{type:`stream_request_start`},F1(`query_fn_entry`),r.agentId||yH(`query_started`);let O=r.queryTracking?{chainId:r.queryTracking.chainId,depth:r.queryTracking.depth+1}:{chainId:f.uuid(),depth:0};O.chainId,r={...r,queryTracking:O};let k=cv(v);k=k.map(e=>{if(e.type!==`user`||!(`toolUseResult`in e)||e.toolUseResult===void 0)return e;let t={...e};return delete t.toolUseResult,t});let A=y,ee=l.startsWith(`agent:`)||l.startsWith(`repl_main_thread`);k=await rye(k,r.contentReplacementState,ee?e=>void D6(e,r.agentId).catch(Y):void 0,new Set(r.options.tools.filter(e=>!Number.isFinite(e.maxResultSizeChars)).map(e=>e.name)));let te=0;F1(`query_microcompact_start`);let ne=await f.microcompact(k,r,l);if(k=ne.messages,ne.clearedToolUseIds?.length){let e=r?.contentReplacementState?.replacements;if(e)for(let t of ne.clearedToolUseIds)e.delete(t)}F1(`query_microcompact_end`);let re=t_($ot(i,o));F1(`query_autocompact_start`);let{compactionResult:ie,consecutiveFailures:ae}=await f.autocompact(k,r,{systemPrompt:i,userContext:a,systemContext:o,toolUseContext:r,forkContextMessages:k},l,A,te);if(F1(`query_autocompact_end`),ie){let{preCompactTokenCount:t,postCompactTokenCount:n,truePostCompactTokenCount:r,compactionUsage:i}=ie;if(v.length,ie.summaryMessages.length+ie.attachments.length+ie.hookResults.length,i?.input_tokens,i?.output_tokens,i?.cache_read_input_tokens,i?.cache_creation_input_tokens,i&&i.input_tokens+(i.cache_creation_input_tokens??0)+(i.cache_read_input_tokens??0)+i.output_tokens,O.depth,e.taskBudget){let t=xwe(k);h=Math.max(0,(h??e.taskBudget.total)-t)}A={compacted:!0,turnId:f.uuid(),turnCounter:0,consecutiveFailures:0};let a=Wk(ie);for(let e of a)yield e;k=a}else ae!==void 0&&(A={...A??{compacted:!1,turnId:``,turnCounter:0},consecutiveFailures:ae});r={...r,messages:k};let j=[],oe=[],se=[],ce=!1;F1(`query_setup_start`);let M=g.gates.streamingToolExecution?new P1(r.options.tools,s,r):null,N=r.getAppState(),le=N.toolPermissionContext.mode,ue=ko({permissionMode:le,mainLoopModel:r.options.mainLoopModel,exceeds200kTokens:le===`plan`&&jD(k)});if(F1(`query_setup_end`),!ie&&l!==`compact`&&l!==`session_memory`){let{isAtBlockingLimit:e}=uV(ND(k)-te,r.options.mainLoopModel);if(e)return yield K_({content:YE,error:`invalid_request`}),{reason:`blocking_limit`}}if(!ie&&dV()){let e=r.options.mainLoopModel,t=ND(k)-te,n=oFe(e);if(t>cV(e)-n){let e=await f.autocompact(k,r,{systemPrompt:i,userContext:a,systemContext:o,toolUseContext:r,forkContextMessages:k},l,A,te);e.compactionResult&&(k=Wk(e.compactionResult),te=0,A=A&&{...A,compacted:!0,consecutiveFailures:e.consecutiveFailures??0})}}let de=!0;F1(`query_api_loop_start`);try{for(;de;){de=!1;try{let t=!1;F1(`query_api_streaming_start`);for await(let n of f.callModel({messages:est(k,a),systemPrompt:re,thinkingConfig:r.options.thinkingConfig,tools:r.options.tools,signal:r.abortController.signal,options:{async getToolPermissionContext(){return r.getAppState().toolPermissionContext},model:ue,...g.gates.fastModeEnabled&&{fastMode:N.fastMode},toolChoice:void 0,isNonInteractiveSession:r.options.isNonInteractiveSession,fallbackModel:c,onStreamingFallback:()=>{t=!0},querySource:l,agents:r.options.agentDefinitions.activeAgents,allowedAgentTypes:r.options.agentDefinitions.allowedAgentTypes,hasAppendSystemPrompt:!!r.options.appendSystemPrompt,maxOutputTokensOverride:S,mcpTools:N.mcp.tools,hasPendingMcpServers:N.mcp.clients.some(e=>e.type===`pending`),queryTracking:O,advisorModel:N.advisorModel,skipCacheWrite:d,agentId:r.agentId,addNotification:r.addNotification,...e.taskBudget&&{taskBudget:{total:e.taskBudget.total,...h!==void 0&&{remaining:h}}}}})){if(t){for(let e of j)yield{type:`tombstone`,message:e};j.length,O.depth,j.length=0,oe.length=0,se.length=0,ce=!1,M&&(M.discard(),M=new P1(r.options.tools,s,r))}let e=n;if(n.type===`assistant`){let t=n,i=Array.isArray(t.message?.content)?t.message.content:[],a;for(let e=0;e<i.length;e++){let t=i[e];if(t.type===`tool_use`&&typeof t.input==`object`&&t.input!==null){let n=ms(r.options.tools,t.name);if(n?.backfillObservableInput){let r=t.input,o={...r};n.backfillObservableInput(o),Object.keys(o).some(e=>!(e in r))&&(a??(a=[...i]),a[e]={...t,input:o})}}}a&&(e={...n,message:{...t.message??{},content:a}})}let i=!1;if(K4e(n)&&(i=!0),i||(yield e),n.type===`assistant`){let e=n;j.push(e);let t=(Array.isArray(e.message?.content)?e.message.content:[]).filter(e=>e.type===`tool_use`);if(t.length>0&&(se.push(...t),ce=!0),M&&!r.abortController.signal.aborted)for(let n of t)M.addTool(n,e)}if(M&&!r.abortController.signal.aborted)for(let e of M.getCompletedResults())e.message&&(yield e.message,oe.push(...d3([e.message],r.options.tools).filter(e=>e.type===`user`)))}F1(`query_api_streaming_end`)}catch(e){if(e instanceof xD&&c){ue=c,de=!0,yield*e0(j,`Model fallback triggered`),j.length=0,oe.length=0,se.length=0,ce=!1,M&&(M.discard(),M=new P1(r.options.tools,s,r)),r.options.mainLoopModel=c,e.originalModel,O.depth,yield X_(`Switched to ${bo(e.fallbackModel)} due to high demand for ${bo(e.originalModel)}`,`warning`);continue}throw e}}}catch(e){Y(e);let t=e instanceof Error?e.message:String(e);return j.length,j.flatMap(e=>(Array.isArray(e.message?.content)?e.message.content:[]).filter(e=>e.type===`tool_use`)).length,O.depth,e instanceof FE||e instanceof Sy?(yield K_({content:e.message}),{reason:`image_error`}):(yield*e0(j,t),yield K_({content:t}),Ii(`Query error`,e),{reason:`model_error`,error:e})}if(j.length>0&&!r.options.isNonInteractiveSession){let e=j.at(-1)?.message?.usage;if(e&&vO()){let t=bO(e,l,_O());t&&(yield xO(t))}}if(j.length>0&&iIe(k.concat(j),i,a,o,r,l),r.abortController.signal.aborted){if(M)for await(let e of M.getRemainingResults())e.message&&(yield e.message);else yield*e0(j,`Interrupted by user`);return r.abortController.signal.reason!==`interrupt`&&(yield q_({toolUse:!1})),{reason:`aborted_streaming`}}if(C){let e=await C;e&&(yield e)}if(!ce){let e=j.at(-1);if(e?.type===`assistant`&&e.isApiErrorMessage&&zE(e),K4e(e)){if(b<Y4e){let e=Q({content:`Output token limit hit. Resume directly — no apology, no recap of what you were doing. Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces.`,isMeta:!0});p={messages:[...k,...j,e],toolUseContext:r,autoCompactTracking:A,maxOutputTokensRecoveryCount:b+1,hasAttemptedReactiveCompact:x,maxOutputTokensOverride:void 0,pendingToolUseSummary:void 0,stopHookActive:void 0,turnCount:T,transition:{reason:`max_output_tokens_recovery`,attempt:b+1}};continue}yield e}if(e?.isApiErrorMessage)return yat(e,r),{reason:`model_error`,error:e.error??e.apiError??`api_error`};let t=yield*b4e(k,j,i,a,o,r,l,w);if(t.preventContinuation)return{reason:`stop_hook_prevented`};if(t.blockingErrors.length>0){p={messages:[...k,...j,...t.blockingErrors],toolUseContext:r,autoCompactTracking:A,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:x,maxOutputTokensOverride:void 0,pendingToolUseSummary:void 0,stopHookActive:!0,turnCount:T,transition:{reason:`stop_hook_blocking`}};continue}{let e=N4e(m,r.agentId,Ore(),One());if(e.action===`continue`){mne(),K(`Token budget continuation #${e.continuationCount}: ${e.pct}% (${e.turnTokens.toLocaleString()} / ${e.budget.toLocaleString()})`),p={messages:[...k,...j,Q({content:e.nudgeMessage,isMeta:!0})],toolUseContext:r,autoCompactTracking:A,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,pendingToolUseSummary:void 0,stopHookActive:void 0,turnCount:T,transition:{reason:`token_budget_continuation`}};continue}e.completionEvent&&(e.completionEvent.diminishingReturns&&K(`Token budget early stop: diminishing returns at ${e.completionEvent.pct}%`),{...e.completionEvent},O.depth)}return{reason:`completed`}}let fe=!1,pe=r;F1(`query_tool_execution_start`),se.length,O.depth;let me=M?M.getRemainingResults():F2e(se,j,s,r);for await(let e of me)e.message&&(yield e.message,e.message.type===`attachment`&&e.message.attachment.type===`hook_stopped_continuation`&&(fe=!0),oe.push(...d3([e.message],r.options.tools).filter(e=>e.type===`user`))),e.newContext&&(pe={...e.newContext,queryTracking:O});F1(`query_tool_execution_end`);let he;if(g.gates.emitToolUseSummaries&&se.length>0&&!r.abortController.signal.aborted&&!r.agentId){let e=j.at(-1),t;if(e){let n=(Array.isArray(e.message?.content)?e.message.content:[]).filter(e=>e.type===`text`);if(n.length>0){let e=n.at(-1);e&&`text`in e&&(t=e.text)}}let n=se.map(e=>e.id);he=uFe({tools:se.map(e=>{let t=oe.find(t=>t.type===`user`&&Array.isArray(t.message.content)&&t.message.content.some(t=>t.type===`tool_result`&&t.tool_use_id===e.id)),n=t?.type===`user`&&Array.isArray(t.message.content)?t.message.content.find(t=>t.type===`tool_result`&&t.tool_use_id===e.id):void 0;return{name:e.name,input:e.input,output:n&&`content`in n?n.content:null}}),signal:r.abortController.signal,isNonInteractiveSession:r.options.isNonInteractiveSession,lastAssistantText:t}).then(e=>e?yhe(e,n):null).catch(()=>null)}if(r.abortController.signal.aborted){r.abortController.signal.reason!==`interrupt`&&(yield q_({toolUse:!0}));let e=T+1;return u&&e>u&&(yield a2({type:`max_turns_reached`,maxTurns:u,turnCount:e})),{reason:`aborted_tools`}}if(fe)return{reason:`hook_stopped`};A?.compacted&&(A.turnCounter++,A.turnId,A.turnCounter,O.depth),k.length,j.length,oe.length,O.depth;let ge=se.some(e=>e.name===Wo),_e=l.startsWith(`repl_main_thread`)||l===`sdk`,ve=r.agentId,ye=await pH(_E(ge?`later`:`next`).filter(e=>vE(e)?!1:_e?e.agentId===void 0:e.mode===`task-notification`&&e.agentId===ve));ye.staleCommands.length>0&&dE(ye.staleCommands);let be=ye.claimedCommands.filter(e=>e.mode===`prompt`||e.mode===`task-notification`);if(be.length>0){n.push(...be);for(let e of be)e.uuid&&(t.push(e.uuid),gH(e.uuid,`started`));dE(be)}for await(let e of v8e(null,pe,ye.attachmentCommands,k.concat(j,oe),l))yield e,oe.push(e);if(_&&_.settledAt!==null&&_.consumedOnIteration===-1){let e=a8e(await _.promise,r.readFileState);for(let t of e){let e=a2(t);yield e,oe.push(e)}_.consumedOnIteration=T-1}if(Ww&&E){let e=await ECe(E);for(let t of e){let e=a2(t);yield e,oe.push(e)}}if(mT&&D){let e=await xT(D);for(let t of e){let e=a2(t);yield e,oe.push(e)}}let P=new Set(be),xe=ye.attachmentCommands.filter(e=>(e.mode===`prompt`||e.mode===`task-notification`)&&!P.has(e));if(xe.length>0){for(let e of xe)e.uuid&&(t.push(e.uuid),gH(e.uuid,`started`));dE(xe)}if(zt(oe,e=>e.type===`attachment`&&e.attachment.type===`edited_text_file`),oe.length,O.depth,pe.options.refreshTools){let e=pe.options.refreshTools();e!==pe.options.tools&&(pe={...pe,options:{...pe.options,tools:e}})}let Se={...pe,queryTracking:O},Ce=T+1;if(!r.agentId&&H4e()&&U4e({systemPrompt:i,userContext:a,systemContext:o,toolUseContext:r,forkContextMessages:k.concat(j,oe)}),u&&Ce>u)return yield a2({type:`max_turns_reached`,maxTurns:u,turnCount:Ce}),{reason:`max_turns`,turnCount:Ce};F1(`query_recursive_call`),p={messages:k.concat(j,oe),toolUseContext:Se,autoCompactTracking:A,turnCount:Ce,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,pendingToolUseSummary:he,maxOutputTokensOverride:void 0,stopHookActive:w,transition:{reason:`next_turn`}}}}catch(e){r.e=e}finally{r.d()}}var Y4e,n0=n((()=>{TD(),yV(),fA(),Hre(),La(),IE(),Cy(),Ms(),Iw(),wa(),iD(),q(),v3(),dFe(),W7(),g2(),rT(),DT(),TE(),hH(),vH(),TH(),wo(),PD(),yo(),js(),DH(),_7(),w2e(),B1(),B2e(),fx(),_8(),x4e(),C4e(),T4e(),H(),F4e(),tt(),TO(),G4e(),Y4e=3}));function X4e(){return{consecutiveDenials:0,totalDenials:0}}function Z4e(e){return{...e,consecutiveDenials:e.consecutiveDenials+1,totalDenials:e.totalDenials+1}}function r0(e){return e.consecutiveDenials===0?e:{...e,consecutiveDenials:0}}function Q4e(e){return e.consecutiveDenials>=i0.maxConsecutive||e.totalDenials>=i0.maxTotal}var i0,$4e=n((()=>{i0={maxConsecutive:3,maxTotal:20}}));function e3e(e){c0=e}function t3e(){return c0}function a0(e){return{systemPrompt:e.systemPrompt,userContext:e.userContext,systemContext:e.systemContext,toolUseContext:e.toolUseContext,forkContextMessages:e.messages}}function n3e(e,t){return t.length===0?e:()=>{let n=e();return{...n,toolPermissionContext:{...n.toolPermissionContext,alwaysAllowRules:{...n.toolPermissionContext.alwaysAllowRules,command:[...new Set([...n.toolPermissionContext.alwaysAllowRules.command||[],...t])]}}}}}async function r3e(e,t,n){let r=(await e.getPromptForCommand(t,n)).map(e=>e.type===`text`?e.text:``).join(`
2455
+ `)}`)})],cacheSafeParams:a0(t),canUseTool:U1(e),querySource:`auto_dream`,forkLabel:`auto_dream`,maxTurns:20,skipTranscript:!0,overrides:{abortController:f},onMessage:h4e(p,d)});Rqe(p,d);let i=t.toolUseContext.getAppState().tasks?.[p];n&&Fqe(i)&&i.filesTouched.length>0&&n({...hhe(i.filesTouched),verb:`Improved`}),K(`[autoDream] completed — cache: read=${r.totalUsage.cache_read_input_tokens} created=${r.totalUsage.cache_creation_input_tokens}`),r.totalUsage.cache_read_input_tokens,r.totalUsage.cache_creation_input_tokens,r.totalUsage.output_tokens,c.length}catch(e){if(f.signal.aborted){K(`[autoDream] aborted by user`);return}K(`[autoDream] fork failed: ${e.message}`),zqe(p,d),await Aqe(u)}}}function h4e(e,t){return n=>{if(n.type!==`assistant`)return;let r=``,i=0,a=[],o=n.message.content;for(let e of o)if(e.type===`text`)r+=e.text;else if(e.type===`tool_use`&&(i++,e.name===`Edit`||e.name===`Write`)){let t=e.input;typeof t.file_path==`string`&&a.push(t.file_path)}Lqe(e,{text:r.trim(),toolUseCount:i},a,t)}}async function g4e(e,t){await K1?.(e,t)}var _4e,v4e,K1,y4e=n((()=>{l0(),v3(),q(),La(),zi(),G2e(),_8(),H(),c4e(),u4e(),BZ(),HZ(),Es(),Is(),_4e=600*1e3,v4e={minHours:24,minSessions:5},K1=null}));async function*b4e(e,t,n,r,i,a,o,s){let c=Date.now(),l={messages:[...e,...t],systemPrompt:n,userContext:r,systemContext:i,toolUseContext:a,querySource:o};if((o===`repl_main_thread`||o===`sdk`)&&e3e(a0(l)),process.env.WORKMATE_JOB_DIR&&o.startsWith(`repl_main_thread`)&&!a.agentId){let e=l.messages.filter(e=>e.type===`assistant`),t=V2e(process.env.WORKMATE_JOB_DIR,e).catch(e=>{K(`[job] classifier error: ${G(e)}`,{level:`error`})});await Promise.race([t,new Promise(e=>setTimeout(e,6e4).unref())])}let u=(await import(`./poorMode-CP6359Sz.js`)).isPoorModeActive();v()||(!f(process.env.WORKMATE_ENABLE_PROMPT_SUGGESTION)&&!u&&v3e(l),!a.agentId&&Gre()&&!u&&import(`./extractMemories-COnBUALO.js`).then(({executeExtractMemories:e})=>e(l,a.appendSystemMessage)).catch(()=>{}),!a.agentId&&!u&&g4e(l,a.appendSystemMessage));try{let n=[],r=a.getAppState().toolPermissionContext.mode,i=bat(r,a.abortController.signal,void 0,s??!1,a.agentId,a,[...e,...t],a.agentType),o=``,c=0,l=!1,u=``,d=!1,f=[],p=[];for await(let e of i){if(e.message){if(yield e.message,e.message.type===`progress`&&e.message.toolUseID){o=e.message.toolUseID,c++;let t=e.message.data;t.command&&p.push({command:t.command,promptText:t.promptText})}if(e.message.type===`attachment`){let t=e.message.attachment;if(`hookEvent`in t&&(t.hookEvent===`Stop`||t.hookEvent===`SubagentStop`)&&(t.type===`hook_non_blocking_error`?(f.push(t.stderr||`Exit code ${t.exitCode}`),d=!0):t.type===`hook_error_during_execution`?(f.push(t.content),d=!0):t.type===`hook_success`&&(t.stdout&&t.stdout.trim()||t.stderr&&t.stderr.trim())&&(d=!0),`durationMs`in t&&`command`in t)){let e=p.find(e=>e.command===t.command&&e.durationMs===void 0);e&&(e.durationMs=t.durationMs)}}}if(e.blockingError){let t=Q({content:fat(e.blockingError),isMeta:!0});n.push(t),yield t,d=!0,f.push(e.blockingError.blockingError)}if(e.preventContinuation&&(l=!0,u=e.stopReason||`Stop hook prevented continuation`,yield a2({type:`hook_stopped_continuation`,message:u,hookName:`Stop`,toolUseID:o,hookEvent:`Stop`})),a.abortController.signal.aborted)return a.queryTracking?.chainId,a.queryTracking?.depth,yield q_({toolUse:!1}),{blockingErrors:[],preventContinuation:!0}}if(c>0&&(yield phe(c,p,f,l,u,d,`suggestion`,o),f.length>0)){let e=jx(`app:toggleTranscript`,`Global`,`ctrl+o`);a.addNotification?.({key:`stop-hook-error`,text:`Stop hook error occurred \u00b7 ${e} to see`,priority:`immediate`})}return l?{blockingErrors:[],preventContinuation:!0}:n.length>0?{blockingErrors:n,preventContinuation:!1}:{blockingErrors:[],preventContinuation:!1}}catch(e){return Date.now()-c,a.queryTracking?.chainId,a.queryTracking?.depth,yield X_(`Stop hook failed: ${G(e)}`,`warning`),{blockingErrors:[],preventContinuation:!1}}}var x4e=n((()=>{Nx(),zi(),La(),g2(),q(),gi(),_7(),v3(),U2e(),y4e(),_0(),g(),l0()}));function S4e(){return{sessionId:Wr(),gates:{streamingToolExecution:!1,emitToolUseSummaries:h(process.env.WORKMATE_EMIT_TOOL_USE_SUMMARIES),fastModeEnabled:!h(process.env.WORKMATE_DISABLE_FAST_MODE)}}}var C4e=n((()=>{H(),g()}));function w4e(){return{callModel:kst,microcompact:eO,autocompact:cFe,uuid:Lc}}var T4e=n((()=>{r9(),yV(),iO()}));function q1(e,t){return parseFloat(e)*A4e[t.toLowerCase()]}function E4e(e){let t=e.match(O4e);if(t)return q1(t[1],t[2]);let n=e.match(k4e);if(n)return q1(n[1],n[2]);let r=e.match(J1);return r?q1(r[1],r[2]):null}function D4e(e,t,n){let r=e=>new Intl.NumberFormat(`en-US`).format(e);return`Stopped at ${e}% of token target (${r(t)} / ${r(n)}). Keep working \u2014 do not summarize.`}var O4e,k4e,J1,A4e,j4e=n((()=>{O4e=/^\s*\+(\d+(?:\.\d+)?)\s*(k|m|b)\b/i,k4e=/\s\+(\d+(?:\.\d+)?)\s*(k|m|b)\s*[.!?]?\s*$/i,J1=/\b(?:use|spend)\s+(\d+(?:\.\d+)?)\s*(k|m|b)\s*tokens?\b/i,new RegExp(J1.source,`gi`),A4e={k:1e3,m:1e6,b:1e9}}));function M4e(){return{continuationCount:0,lastDeltaTokens:0,lastGlobalTurnTokens:0,startedAt:Date.now()}}function N4e(e,t,n,r){if(t||n===null||n<=0)return{action:`stop`,completionEvent:null};let i=r,a=Math.round(i/n*100),o=r-e.lastGlobalTurnTokens,s=e.continuationCount>=3&&o<Y1&&e.lastDeltaTokens<Y1;return!s&&i<n*P4e?(e.continuationCount++,e.lastDeltaTokens=o,e.lastGlobalTurnTokens=r,{action:`continue`,nudgeMessage:D4e(a,i,n),continuationCount:e.continuationCount,pct:a,turnTokens:i,budget:n}):s||e.continuationCount>0?{action:`stop`,completionEvent:{continuationCount:e.continuationCount,pct:a,turnTokens:i,budget:n,diminishingReturns:s,durationMs:Date.now()-e.startedAt}}:{action:`stop`,completionEvent:null}}var P4e,Y1,F4e=n((()=>{j4e(),P4e=.9,Y1=500}));function X1(){return X(m(),`sessions`)}function I4e(){let e=process.env.WORKMATE_SESSION_KIND;if(e===`bg`)return e}function L4e(){return I4e()===`bg`}async function R4e(){let e=I4e()??`interactive`,t=X1(),n=X(t,`${process.pid}.json`);Oi(async()=>{try{await Zc(n)}catch{}});try{return await Hc(t,{recursive:!0,mode:448}),await zc(t,448),await Qc(n,W({pid:process.pid,sessionId:Wr(),cwd:ti(),startedAt:Date.now(),kind:e,entrypoint:process.env.WORKMATE_ENTRYPOINT,name:process.env.WORKMATE_SESSION_NAME,logPath:process.env.WORKMATE_SESSION_LOG,agent:process.env.WORKMATE_AGENT})),jre(e=>{Z1({sessionId:e})}),!0}catch(e){return K(`[concurrentSessions] register failed: ${G(e)}`),!1}}async function Z1(e){let t=X(X1(),`${process.pid}.json`);try{await Qc(t,W({...Si(await Wc(t,`utf8`)),...e}))}catch(e){K(`[concurrentSessions] updatePidFile failed: ${G(e)}`)}}async function z4e(e){e&&await Z1({name:e})}async function B4e(e){await Z1({...e,updatedAt:Date.now()})}async function V4e(){let e=X1(),t;try{t=await Gc(e)}catch(e){return Ri(e)||K(`[concurrentSessions] readdir failed: ${G(e)}`),0}let n=0;for(let r of t){if(!/^\d+\.json$/.test(r))continue;let t=parseInt(r.slice(0,-5),10);if(t===process.pid){n++;continue}ac(t)?n++:Ma()!==`wsl`&&Zc(X(e,r)).catch(()=>{})}return n}var Q1=n((()=>{H(),di(),q(),g(),gi(),oc(),Pa(),Li()}));function H4e(){return L4e()?Date.now()-$1>=W4e:!1}function U4e(e){$1=Date.now();try{let t=e.forkContextMessages;if(!t||t.length===0)return;let n;for(let e=t.length-1;e>=0;e--)if(t[e].type===`assistant`){n=t[e];break}let r=`busy`,i;if(n?.message?.content){let e=n.message.content;if(Array.isArray(e)){let t=e[e.length-1];t?.type===`tool_use`&&(r=`busy`,i=`tool: ${t.name||`unknown`}`)}}B4e({status:r,waitingFor:i}).catch(e=>{K(`[taskSummary] updateSessionActivity failed: ${e}`)})}catch(e){K(`[taskSummary] error: ${e}`)}}var W4e,$1,G4e=n((()=>{Q1(),q(),W4e=3e4,$1=0}));function*e0(e,t){for(let n of e){let e=(Array.isArray(n.message?.content)?n.message.content:[]).filter(e=>e.type===`tool_use`);for(let r of e)yield Q({content:[{type:`tool_result`,content:t,is_error:!0,tool_use_id:r.id}],toolUseResult:t,sourceToolAssistantUUID:n.uuid})}}function K4e(e){return e?.type===`assistant`&&e.apiError===`max_output_tokens`}function q4e(e){if(e.thrownError!==void 0)return{type:`failed`,error:e.thrownError};let t=e.terminal,n=t?.reason;switch(n){case`completed`:return{type:`completed`};case void 0:case`aborted_streaming`:case`aborted_tools`:return{type:`cancelled`};case`model_error`:return{type:`failed`,error:t.error};default:return{type:`failed`,message:`query ended without successful completion: ${n}`}}}async function*t0(e){let t=[],n=[],r,i=!1,a;try{r=yield*J4e(e,t,n)}catch(e){throw i=!0,a=e,e}finally{await mH({commands:n,outcome:q4e({terminal:r,...i?{thrownError:a}:{}}),priority:`later`}).then(e=>{for(let t of e)oE(t)}).catch(Y);let e=globalThis.performance;if(e&&typeof e.clearMarks==`function`)try{e.clearMarks(),e.clearMeasures?.(),e.clearResourceTimings?.()}catch{}}for(let e of t)gH(e,`completed`);return r}async function*J4e(e,t,n){try{var r=Vre();let{systemPrompt:i,userContext:a,systemContext:o,canUseTool:s,fallbackModel:c,querySource:l,maxTurns:u,skipCacheWrite:d}=e,f=e.deps??w4e(),p={messages:e.messages,toolUseContext:e.toolUseContext,maxOutputTokensOverride:e.maxOutputTokensOverride,autoCompactTracking:void 0,stopHookActive:void 0,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,turnCount:1,pendingToolUseSummary:void 0,transition:void 0},m=M4e(),h,g=S4e(),_=r.u(t8e(p.messages,p.toolUseContext));for(;;){let{toolUseContext:r}=p,{messages:v,autoCompactTracking:y,maxOutputTokensRecoveryCount:b,hasAttemptedReactiveCompact:x,maxOutputTokensOverride:S,pendingToolUseSummary:C,stopHookActive:w,turnCount:T}=p,E=Yw(null,v,r),D=bT(r.options.tools??[],v);yield{type:`stream_request_start`},F1(`query_fn_entry`),r.agentId||yH(`query_started`);let O=r.queryTracking?{chainId:r.queryTracking.chainId,depth:r.queryTracking.depth+1}:{chainId:f.uuid(),depth:0};O.chainId,r={...r,queryTracking:O};let k=cv(v);k=k.map(e=>{if(e.type!==`user`||!(`toolUseResult`in e)||e.toolUseResult===void 0)return e;let t={...e};return delete t.toolUseResult,t});let A=y,ee=l.startsWith(`agent:`)||l.startsWith(`repl_main_thread`);k=await rye(k,r.contentReplacementState,ee?e=>void D6(e,r.agentId).catch(Y):void 0,new Set(r.options.tools.filter(e=>!Number.isFinite(e.maxResultSizeChars)).map(e=>e.name)));let te=0;F1(`query_microcompact_start`);let ne=await f.microcompact(k,r,l);if(k=ne.messages,ne.clearedToolUseIds?.length){let e=r?.contentReplacementState?.replacements;if(e)for(let t of ne.clearedToolUseIds)e.delete(t)}F1(`query_microcompact_end`);let re=t_($ot(i,o));F1(`query_autocompact_start`);let{compactionResult:ie,consecutiveFailures:ae}=await f.autocompact(k,r,{systemPrompt:i,userContext:a,systemContext:o,toolUseContext:r,forkContextMessages:k},l,A,te);if(F1(`query_autocompact_end`),ie){let{preCompactTokenCount:t,postCompactTokenCount:n,truePostCompactTokenCount:r,compactionUsage:i}=ie;if(v.length,ie.summaryMessages.length+ie.attachments.length+ie.hookResults.length,i?.input_tokens,i?.output_tokens,i?.cache_read_input_tokens,i?.cache_creation_input_tokens,i&&i.input_tokens+(i.cache_creation_input_tokens??0)+(i.cache_read_input_tokens??0)+i.output_tokens,O.depth,e.taskBudget){let t=xwe(k);h=Math.max(0,(h??e.taskBudget.total)-t)}A={compacted:!0,turnId:f.uuid(),turnCounter:0,consecutiveFailures:0};let a=Wk(ie);for(let e of a)yield e;k=a}else ae!==void 0&&(A={...A??{compacted:!1,turnId:``,turnCounter:0},consecutiveFailures:ae});r={...r,messages:k};let j=[],oe=[],se=[],ce=!1;F1(`query_setup_start`);let M=g.gates.streamingToolExecution?new P1(r.options.tools,s,r):null,N=r.getAppState(),le=N.toolPermissionContext.mode,ue=ko({permissionMode:le,mainLoopModel:r.options.mainLoopModel,exceeds200kTokens:le===`plan`&&jD(k)});if(F1(`query_setup_end`),!ie&&l!==`compact`&&l!==`session_memory`){let{isAtBlockingLimit:e}=uV(ND(k)-te,r.options.mainLoopModel);if(e)return yield K_({content:YE,error:`invalid_request`}),{reason:`blocking_limit`}}if(!ie&&dV()){let e=r.options.mainLoopModel,t=ND(k)-te,n=oFe(e);if(t>cV(e)-n){let e=await f.autocompact(k,r,{systemPrompt:i,userContext:a,systemContext:o,toolUseContext:r,forkContextMessages:k},l,A,te);e.compactionResult&&(k=Wk(e.compactionResult),te=0,A=A&&{...A,compacted:!0,consecutiveFailures:e.consecutiveFailures??0})}}let de=!0;F1(`query_api_loop_start`);try{for(;de;){de=!1;try{let t=!1;F1(`query_api_streaming_start`);for await(let n of f.callModel({messages:est(k,a),systemPrompt:re,thinkingConfig:r.options.thinkingConfig,tools:r.options.tools,signal:r.abortController.signal,options:{async getToolPermissionContext(){return r.getAppState().toolPermissionContext},model:ue,...g.gates.fastModeEnabled&&{fastMode:N.fastMode},toolChoice:void 0,isNonInteractiveSession:r.options.isNonInteractiveSession,fallbackModel:c,onStreamingFallback:()=>{t=!0},querySource:l,agents:r.options.agentDefinitions.activeAgents,allowedAgentTypes:r.options.agentDefinitions.allowedAgentTypes,hasAppendSystemPrompt:!!r.options.appendSystemPrompt,maxOutputTokensOverride:S,mcpTools:N.mcp.tools,hasPendingMcpServers:N.mcp.clients.some(e=>e.type===`pending`),queryTracking:O,advisorModel:N.advisorModel,skipCacheWrite:d,agentId:r.agentId,addNotification:r.addNotification,...e.taskBudget&&{taskBudget:{total:e.taskBudget.total,...h!==void 0&&{remaining:h}}}}})){if(t){for(let e of j)yield{type:`tombstone`,message:e};j.length,O.depth,j.length=0,oe.length=0,se.length=0,ce=!1,M&&(M.discard(),M=new P1(r.options.tools,s,r))}let e=n;if(n.type===`assistant`){let t=n,i=Array.isArray(t.message?.content)?t.message.content:[],a;for(let e=0;e<i.length;e++){let t=i[e];if(t.type===`tool_use`&&typeof t.input==`object`&&t.input!==null){let n=ms(r.options.tools,t.name);if(n?.backfillObservableInput){let r=t.input,o={...r};n.backfillObservableInput(o),Object.keys(o).some(e=>!(e in r))&&(a??(a=[...i]),a[e]={...t,input:o})}}}a&&(e={...n,message:{...t.message??{},content:a}})}let i=!1;if(K4e(n)&&(i=!0),i||(yield e),n.type===`assistant`){let e=n;j.push(e);let t=(Array.isArray(e.message?.content)?e.message.content:[]).filter(e=>e.type===`tool_use`);if(t.length>0&&(se.push(...t),ce=!0),M&&!r.abortController.signal.aborted)for(let n of t)M.addTool(n,e)}if(M&&!r.abortController.signal.aborted)for(let e of M.getCompletedResults())e.message&&(yield e.message,oe.push(...d3([e.message],r.options.tools).filter(e=>e.type===`user`)))}F1(`query_api_streaming_end`)}catch(e){if(e instanceof xD&&c){ue=c,de=!0,yield*e0(j,`Model fallback triggered`),j.length=0,oe.length=0,se.length=0,ce=!1,M&&(M.discard(),M=new P1(r.options.tools,s,r)),r.options.mainLoopModel=c,e.originalModel,O.depth,yield X_(`Switched to ${bo(e.fallbackModel)} due to high demand for ${bo(e.originalModel)}`,`warning`);continue}throw e}}}catch(e){Y(e);let t=e instanceof Error?e.message:String(e);return j.length,j.flatMap(e=>(Array.isArray(e.message?.content)?e.message.content:[]).filter(e=>e.type===`tool_use`)).length,O.depth,e instanceof FE||e instanceof Sy?(yield K_({content:e.message}),{reason:`image_error`}):(yield*e0(j,t),yield K_({content:t}),Ii(`Query error`,e),{reason:`model_error`,error:e})}if(j.length>0&&!r.options.isNonInteractiveSession){let e=j.at(-1)?.message?.usage;if(e&&vO()){let t=bO(e,l,_O());t&&(yield xO(t))}}if(j.length>0&&iIe(k.concat(j),i,a,o,r,l),r.abortController.signal.aborted){if(M)for await(let e of M.getRemainingResults())e.message&&(yield e.message);else yield*e0(j,`Interrupted by user`);return r.abortController.signal.reason!==`interrupt`&&(yield q_({toolUse:!1})),{reason:`aborted_streaming`}}if(C){let e=await C;e&&(yield e)}if(!ce){let e=j.at(-1);if(e?.type===`assistant`&&e.isApiErrorMessage&&zE(e),K4e(e)){if(b<Y4e){let e=Q({content:`Output token limit hit. Resume directly — no apology, no recap of what you were doing. Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces.`,isMeta:!0});p={messages:[...k,...j,e],toolUseContext:r,autoCompactTracking:A,maxOutputTokensRecoveryCount:b+1,hasAttemptedReactiveCompact:x,maxOutputTokensOverride:void 0,pendingToolUseSummary:void 0,stopHookActive:void 0,turnCount:T,transition:{reason:`max_output_tokens_recovery`,attempt:b+1}};continue}yield e}if(e?.isApiErrorMessage)return yat(e,r),{reason:`model_error`,error:e.error??e.apiError??`api_error`};let t=yield*b4e(k,j,i,a,o,r,l,w);if(t.preventContinuation)return{reason:`stop_hook_prevented`};if(t.blockingErrors.length>0){p={messages:[...k,...j,...t.blockingErrors],toolUseContext:r,autoCompactTracking:A,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:x,maxOutputTokensOverride:void 0,pendingToolUseSummary:void 0,stopHookActive:!0,turnCount:T,transition:{reason:`stop_hook_blocking`}};continue}{let e=N4e(m,r.agentId,Ore(),One());if(e.action===`continue`){mne(),K(`Token budget continuation #${e.continuationCount}: ${e.pct}% (${e.turnTokens.toLocaleString()} / ${e.budget.toLocaleString()})`),p={messages:[...k,...j,Q({content:e.nudgeMessage,isMeta:!0})],toolUseContext:r,autoCompactTracking:A,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,pendingToolUseSummary:void 0,stopHookActive:void 0,turnCount:T,transition:{reason:`token_budget_continuation`}};continue}e.completionEvent&&(e.completionEvent.diminishingReturns&&K(`Token budget early stop: diminishing returns at ${e.completionEvent.pct}%`),{...e.completionEvent},O.depth)}return{reason:`completed`}}let fe=!1,pe=r;F1(`query_tool_execution_start`),se.length,O.depth;let me=M?M.getRemainingResults():F2e(se,j,s,r);for await(let e of me)e.message&&(yield e.message,e.message.type===`attachment`&&e.message.attachment.type===`hook_stopped_continuation`&&(fe=!0),oe.push(...d3([e.message],r.options.tools).filter(e=>e.type===`user`))),e.newContext&&(pe={...e.newContext,queryTracking:O});F1(`query_tool_execution_end`);let he;if(g.gates.emitToolUseSummaries&&se.length>0&&!r.abortController.signal.aborted&&!r.agentId){let e=j.at(-1),t;if(e){let n=(Array.isArray(e.message?.content)?e.message.content:[]).filter(e=>e.type===`text`);if(n.length>0){let e=n.at(-1);e&&`text`in e&&(t=e.text)}}let n=se.map(e=>e.id);he=uFe({tools:se.map(e=>{let t=oe.find(t=>t.type===`user`&&Array.isArray(t.message.content)&&t.message.content.some(t=>t.type===`tool_result`&&t.tool_use_id===e.id)),n=t?.type===`user`&&Array.isArray(t.message.content)?t.message.content.find(t=>t.type===`tool_result`&&t.tool_use_id===e.id):void 0;return{name:e.name,input:e.input,output:n&&`content`in n?n.content:null}}),signal:r.abortController.signal,isNonInteractiveSession:r.options.isNonInteractiveSession,lastAssistantText:t}).then(e=>e?yhe(e,n):null).catch(()=>null)}if(r.abortController.signal.aborted){r.abortController.signal.reason!==`interrupt`&&(yield q_({toolUse:!0}));let e=T+1;return u&&e>u&&(yield a2({type:`max_turns_reached`,maxTurns:u,turnCount:e})),{reason:`aborted_tools`}}if(fe)return{reason:`hook_stopped`};A?.compacted&&(A.turnCounter++,A.turnId,A.turnCounter,O.depth),k.length,j.length,oe.length,O.depth;let ge=se.some(e=>e.name===Wo),_e=l.startsWith(`repl_main_thread`)||l===`sdk`,ve=r.agentId,ye=await pH(_E(ge?`later`:`next`).filter(e=>vE(e)?!1:_e?e.agentId===void 0:e.mode===`task-notification`&&e.agentId===ve));ye.staleCommands.length>0&&dE(ye.staleCommands);let be=ye.claimedCommands.filter(e=>e.mode===`prompt`||e.mode===`task-notification`);if(be.length>0){n.push(...be);for(let e of be)e.uuid&&(t.push(e.uuid),gH(e.uuid,`started`));dE(be)}for await(let e of v8e(null,pe,ye.attachmentCommands,k.concat(j,oe),l))yield e,oe.push(e);if(_&&_.settledAt!==null&&_.consumedOnIteration===-1){let e=a8e(await _.promise,r.readFileState);for(let t of e){let e=a2(t);yield e,oe.push(e)}_.consumedOnIteration=T-1}if(Ww&&E){let e=await ECe(E);for(let t of e){let e=a2(t);yield e,oe.push(e)}}if(mT&&D){let e=await xT(D);for(let t of e){let e=a2(t);yield e,oe.push(e)}}let P=new Set(be),xe=ye.attachmentCommands.filter(e=>(e.mode===`prompt`||e.mode===`task-notification`)&&!P.has(e));if(xe.length>0){for(let e of xe)e.uuid&&(t.push(e.uuid),gH(e.uuid,`started`));dE(xe)}if(zt(oe,e=>e.type===`attachment`&&e.attachment.type===`edited_text_file`),oe.length,O.depth,pe.options.refreshTools){let e=pe.options.refreshTools();e!==pe.options.tools&&(pe={...pe,options:{...pe.options,tools:e}})}let Se={...pe,queryTracking:O},Ce=T+1;if(!r.agentId&&H4e()&&U4e({systemPrompt:i,userContext:a,systemContext:o,toolUseContext:r,forkContextMessages:k.concat(j,oe)}),u&&Ce>u)return yield a2({type:`max_turns_reached`,maxTurns:u,turnCount:Ce}),{reason:`max_turns`,turnCount:Ce};F1(`query_recursive_call`),p={messages:k.concat(j,oe),toolUseContext:Se,autoCompactTracking:A,turnCount:Ce,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,pendingToolUseSummary:he,maxOutputTokensOverride:void 0,stopHookActive:w,transition:{reason:`next_turn`}}}}catch(e){r.e=e}finally{r.d()}}var Y4e,n0=n((()=>{TD(),yV(),fA(),Hre(),La(),IE(),Cy(),Ms(),Iw(),wa(),iD(),q(),v3(),dFe(),W7(),g2(),rT(),DT(),TE(),hH(),vH(),TH(),wo(),PD(),yo(),js(),DH(),_7(),w2e(),B1(),B2e(),fx(),_8(),x4e(),C4e(),T4e(),H(),F4e(),tt(),TO(),G4e(),Y4e=3}));function X4e(){return{consecutiveDenials:0,totalDenials:0}}function Z4e(e){return{...e,consecutiveDenials:e.consecutiveDenials+1,totalDenials:e.totalDenials+1}}function r0(e){return e.consecutiveDenials===0?e:{...e,consecutiveDenials:0}}function Q4e(e){return e.consecutiveDenials>=i0.maxConsecutive||e.totalDenials>=i0.maxTotal}var i0,$4e=n((()=>{i0={maxConsecutive:3,maxTotal:20}}));function e3e(e){c0=e}function t3e(){return c0}function a0(e){return{systemPrompt:e.systemPrompt,userContext:e.userContext,systemContext:e.systemContext,toolUseContext:e.toolUseContext,forkContextMessages:e.messages}}function n3e(e,t){return t.length===0?e:()=>{let n=e();return{...n,toolPermissionContext:{...n.toolPermissionContext,alwaysAllowRules:{...n.toolPermissionContext.alwaysAllowRules,command:[...new Set([...n.toolPermissionContext.alwaysAllowRules.command||[],...t])]}}}}}async function r3e(e,t,n){let r=(await e.getPromptForCommand(t,n)).map(e=>e.type===`text`?e.text:``).join(`
2456
2456
  `),i=P9(e.allowedTools??[]),a=n3e(n.getAppState,i),o=e.agent??`general-purpose`,s=n.options.agentDefinitions.activeAgents,c=s.find(e=>e.agentType===o)??s.find(e=>e.agentType===`general-purpose`)??s[0];if(!c)throw Error(`No agent available for forked execution`);return{skillContent:r,modifiedGetAppState:a,baseAgent:c,promptMessages:[Q({content:r})]}}function i3e(e,t=`Execution completed`){let n=$_(e);return n&&av(Array.isArray(n.message.content)?n.message.content:[],`
2457
2457
  `)||t}function o0(e,t){let n=t?.abortController??(t?.shareAbortController?e.abortController:UT(e.abortController)),r=t?.getAppState?t.getAppState:t?.shareAbortController?e.getAppState:()=>{let t=e.getAppState();return t.toolPermissionContext.shouldAvoidPermissionPrompts?t:{...t,toolPermissionContext:{...t.toolPermissionContext,shouldAvoidPermissionPrompts:!0}}};return{readFileState:LT(t?.readFileState??e.readFileState),nestedMemoryAttachmentTriggers:new Set,loadedNestedMemoryPaths:new Set,dynamicSkillDirTriggers:new Set,discoveredSkillNames:new Set,toolDecisions:void 0,contentReplacementState:t?.contentReplacementState??(e.contentReplacementState?Uve(e.contentReplacementState):void 0),abortController:n,getAppState:r,setAppState:t?.shareSetAppState?e.setAppState:()=>{},setAppStateForTasks:e.setAppStateForTasks??e.setAppState,localDenialTracking:t?.shareSetAppState?e.localDenialTracking:X4e(),setInProgressToolUseIDs:()=>{},setResponseLength:t?.shareSetResponseLength?e.setResponseLength:()=>{},pushApiMetricsEntry:t?.shareSetResponseLength?e.pushApiMetricsEntry:void 0,updateFileHistoryState:()=>{},updateAttributionState:e.updateAttributionState,addNotification:void 0,setToolJSX:void 0,setStreamMode:void 0,setSDKStatus:void 0,openMessageSelector:void 0,options:t?.options??e.options,messages:t?.messages??e.messages,agentId:t?.agentId??JH(),agentType:t?.agentType,queryTracking:{chainId:Lc(),depth:(e.queryTracking?.depth??-1)+1},fileReadingLimits:e.fileReadingLimits,userModified:e.userModified,criticalSystemReminder_EXPERIMENTAL:t?.criticalSystemReminder_EXPERIMENTAL,requireCanUseTool:t?.requireCanUseTool}}function a3e(e){return e.type===`stream_event`&&typeof e.event==`object`&&e.event!==null&&`type`in e.event&&e.event.type===`message_delta`}async function s0({promptMessages:e,cacheSafeParams:t,canUseTool:n,querySource:r,forkLabel:i,overrides:a,maxOutputTokens:o,maxTurns:s,onMessage:c,skipTranscript:l,skipCacheWrite:u}){let d=Date.now(),f=[],p={...$g},{systemPrompt:m,userContext:h,systemContext:g,toolUseContext:_,forkContextMessages:v}=t,y=o0(_,a),b=[...v,...e],x=l?void 0:JH(i),S=null;x&&(await w6(b,x).catch(e=>K(`Forked agent [${i}] failed to record initial transcript: ${e}`)),S=b.length>0?b[b.length-1].uuid:null);try{for await(let e of t0({messages:b,systemPrompt:m,userContext:h,systemContext:g,canUseTool:n,toolUseContext:y,querySource:r,maxOutputTokensOverride:o,maxTurns:s,skipCacheWrite:u})){if(e.type===`stream_event`){if(a3e(e)){let t=$7({...$g},e.event.usage);p=Lst(p,t)}continue}if(e.type===`stream_request_start`)continue;K(`Forked agent [${i}] received message: type=${e.type}`),f.push(e),c?.(e);let t=e;x&&(t.type===`assistant`||t.type===`user`||t.type===`progress`)&&(await w6([t],x,S).catch(e=>K(`Forked agent [${i}] failed to record transcript: ${e}`)),t.type!==`progress`&&(S=t.uuid))}}finally{y.readFileState.clear(),b.length=0}return K(`Forked agent [${i}] finished: ${f.length} messages, types=[${f.map(e=>e.type).join(`, `)}], totalUsage: input=${p.input_tokens} output=${p.output_tokens} cacheRead=${p.cache_read_input_tokens} cacheCreate=${p.cache_creation_input_tokens}`),o3e({forkLabel:i,querySource:r,durationMs:Date.now()-d,messageCount:f.length,totalUsage:p,queryTracking:_.queryTracking}),{messages:f,totalUsage:p}}function o3e({forkLabel:e,querySource:t,durationMs:n,messageCount:r,totalUsage:i,queryTracking:a}){let o=i.input_tokens+i.cache_creation_input_tokens+i.cache_read_input_tokens;o>0&&i.cache_read_input_tokens/o,i.input_tokens,i.output_tokens,i.cache_read_input_tokens,i.cache_creation_input_tokens,i.service_tier,i.cache_creation.ephemeral_1h_input_tokens,i.cache_creation.ephemeral_5m_input_tokens,{...a?{queryChainId:a.chainId,queryDepth:a.depth}:{}}}var c0,l0=n((()=>{n0(),La(),r9(),E_(),GT(),q(),VT(),v3(),$4e(),z9(),_8(),fx(),XH(),c0=null})),s3e,c3e=n((()=>{s3e={providerId:`anthropic`,parseHeaders(e){let t=[];for(let[n,r,i]of[[`5h`,`session`,`Session`],[`7d`,`weekly`,`Weekly`]]){let a=e.get(`anthropic-ratelimit-unified-${n}-utilization`),o=e.get(`anthropic-ratelimit-unified-${n}-reset`);if(a===null||o===null)continue;let s=Number(a),c=Number(o);Number.isFinite(s)&&t.push({kind:r,label:i,utilization:s,...Number.isFinite(c)&&c>0?{resetsAt:c}:{}})}return t}}}));function l3e(){return d0}function u3e(e){u0=e,f0.forEach(t=>t(e)),Math.round((e.resetsAt?e.resetsAt-Date.now()/1e3:0)/3600),e.status,e.unifiedRateLimitFallbackAvailable}async function d3e(){}function f3e(e){d0={},Ooe(`anthropic`,s3e.parseHeaders(e)),(u0.status!==`allowed`||u0.resetsAt)&&u3e({status:`allowed`,unifiedRateLimitFallbackAvailable:!1,isUsingOverage:!1})}var u0,d0,f0,p0=n((()=>{La(),c3e(),koe(),lX(),u0={status:`allowed`,unifiedRateLimitFallbackAvailable:!1,isUsingOverage:!1},d0={},f0=new Set}));function p3e(){return`user_intent`}function m3e(){let e=process.env.WORKMATE_ENABLE_PROMPT_SUGGESTION;return!f(e)&&!!h(e)}function h3e(){h0&&(h0.abort(),h0=null)}function g3e(e){return e.promptSuggestionEnabled?e.elicitation.queue.length>0?`elicitation_active`:e.toolPermissionContext.mode===`plan`?`plan_mode`:u0.status===`allowed`?null:`rate_limit`:`disabled`}async function _3e(e,t,n,r,i){if(e.signal.aborted)return m0(`aborted`,void 0,void 0,i),null;if(zt(t,e=>e.type===`assistant`)<2)return m0(`early_conversation`,void 0,void 0,i),null;let a=$_(t);if(a?.isApiErrorMessage)return m0(`last_response_error`,void 0,void 0,i),null;let o=y3e(a);if(o)return m0(o,void 0,void 0,i),null;let s=g3e(n());if(s)return m0(s,void 0,void 0,i),null;let c=p3e(),{suggestion:l,generationRequestId:u}=await b3e(e,c,r);return e.signal.aborted?(m0(`aborted`,void 0,void 0,i),null):l?x3e(l,c,i)?null:{suggestion:l,promptId:c,generationRequestId:u}:(m0(`empty`,void 0,c,i),null)}async function v3e(e){if(e.querySource!==`repl_main_thread`)return;h0=new AbortController;let t=h0,n=a0(e);try{let r=await _3e(t,e.messages,e.toolUseContext.getAppState,n,`cli`);if(!r)return;e.toolUseContext.setAppState(e=>({...e,promptSuggestion:{text:r.suggestion,promptId:r.promptId,shownAt:0,acceptedAt:0,generationRequestId:r.generationRequestId}})),W3e()&&r.suggestion&&K3e(r.suggestion,e,e.toolUseContext.setAppState,!1,n)}catch(e){if(e instanceof Error&&(e.name===`AbortError`||e.name===`APIUserAbortError`)){m0(`aborted`,void 0,void 0,`cli`);return}Y(wi(e))}finally{h0===t&&(h0=null)}}function y3e(e){if(!e)return null;let t=e.message.usage,n=t.input_tokens??0,r=t.cache_creation_input_tokens??0,i=t.output_tokens??0;return n+r+i>C3e?`cache_cold`:null}async function b3e(e,t,n){let r=w3e[t],i=await s0({promptMessages:[Q({content:r})],cacheSafeParams:n,canUseTool:async()=>({behavior:`deny`,message:`No tools needed for suggestion`,decisionReason:{type:`other`,reason:`suggestion only`}}),querySource:`prompt_suggestion`,forkLabel:`prompt_suggestion`,overrides:{abortController:e},skipTranscript:!0,skipCacheWrite:!0}),a=i.messages.find(e=>e.type===`assistant`),o=a?.type===`assistant`?a.requestId??null:null;for(let e of i.messages){if(e.type!==`assistant`)continue;let t=(Array.isArray(e.message.content)?e.message.content:[]).find(e=>e.type===`text`);if(t?.type===`text`&&typeof t.text==`string`){let e=t.text.trim();if(e)return{suggestion:e,generationRequestId:o}}}return{suggestion:null,generationRequestId:o}}function x3e(e,t,n){if(!e)return m0(`empty`,void 0,t,n),!0;let r=e.toLowerCase(),i=e.trim().split(/\s+/).length,a=[[`done`,()=>r===`done`],[`meta_text`,()=>r===`nothing found`||r===`nothing found.`||r.startsWith(`nothing to suggest`)||r.startsWith(`no suggestion`)||/\bsilence is\b|\bstay(s|ing)? silent\b/.test(r)||/^\W*silence\W*$/.test(r)],[`meta_wrapped`,()=>/^\(.*\)$|^\[.*\]$/.test(e)],[`error_message`,()=>r.startsWith(`api error:`)||r.startsWith(`prompt is too long`)||r.startsWith(`request timed out`)||r.startsWith(`invalid api key`)||r.startsWith(`image was too large`)],[`prefixed_label`,()=>/^\w+:\s/.test(e)],[`too_few_words`,()=>i>=2||e.startsWith(`/`)?!1:!new Set([`yes`,`yeah`,`yep`,`yea`,`yup`,`sure`,`ok`,`okay`,`push`,`commit`,`deploy`,`stop`,`continue`,`check`,`exit`,`quit`,`no`]).has(r)],[`too_many_words`,()=>i>12],[`too_long`,()=>e.length>=100],[`multiple_sentences`,()=>/[.!?]\s+[A-Z]/.test(e)],[`has_formatting`,()=>/[\n*]|\*\*/.test(e)],[`evaluative`,()=>/thanks|thank you|looks good|sounds good|that works|that worked|that's all|nice|great|perfect|makes sense|awesome|excellent/.test(r)],[`claude_voice`,()=>/^(let me|i'll|i've|i'm|i can|i would|i think|i notice|here's|here is|here are|that's|this is|this will|you can|you should|you could|sure,|of course|certainly)/i.test(e)]];for(let[r,i]of a)if(i())return m0(r,e,t,n),!0;return!1}function S3e(e,t,n,r,i){Math.round(t.length/(e.length||1)*100)/100;let a=t===e,o=Math.max(0,Date.now()-n);({...i&&{generationRequestId:i},...a&&{timeToAcceptMs:o},...!a&&{timeToIgnoreMs:o}})}function m0(e,t,n,r){({...r&&{source:r}})}var h0,C3e,g0,w3e,_0=n((()=>{tt(),g(),gi(),l0(),wa(),v3(),La(),p0(),k0(),h0=null,C3e=1e4,g0=`[SUGGESTION MODE: Suggest what the user might naturally type next into Work Mate.]
2458
2458
 
@@ -3055,13 +3055,13 @@ Goal: Write your final plan to the plan file (the only file you can edit).
3055
3055
  - **Hard limit: 40 lines.** If the plan is longer, delete prose — not file paths.`}));function Tet(e,t){let n=new Map,r=new Map,i=new Map;for(let e of t)if(e.type===`assistant`){let t=e,a=t.message.id,o=n.get(a);if(o||(o=new Set,n.set(a,o)),Array.isArray(t.message.content)){for(let e of t.message.content)if(typeof e!=`string`&&e.type===`tool_use`){let t=e;o.add(t.id),r.set(t.id,a),i.set(t.id,e)}}}let a=new Map;for(let[e,t]of r)a.set(e,n.get(t));let o=new Map,s=new Map,c=new Map,l=new Map,u=new Set,d=new Set;for(let t of e){if(t.type===`progress`){let e=t.parentToolUseID,n=o.get(e);n?n.push(t):o.set(e,[t]);let r=t.data;if(r.type===`hook_progress`){let t=r.hookEvent,n=s.get(e);n||(n=new Map,s.set(e,n)),n.set(t,(n.get(t)??0)+1)}}if(t.type===`user`&&Array.isArray(t.message?.content)){for(let e of t.message?.content??[])if(typeof e!=`string`&&e.type===`tool_result`){let n=e;l.set(n.tool_use_id,t),u.add(n.tool_use_id),n.is_error&&d.add(n.tool_use_id)}}if(t.type===`assistant`&&Array.isArray(t.message?.content)){for(let e of t.message?.content??[])if(typeof e!=`string`&&(`tool_use_id`in e&&typeof e.tool_use_id==`string`&&u.add(e.tool_use_id),e.type===`advisor_tool_result`)){let t=e;t.content.type===`advisor_tool_result_error`&&d.add(t.tool_use_id)}}if(tv(t)){let e=t.attachment.toolUseID,n=t.attachment.hookEvent,r=t.attachment.hookName;if(r!==void 0){let t=c.get(e);t||(t=new Map,c.set(e,t));let i=t.get(n);i||(i=new Set,t.set(n,i)),i.add(r)}}}let f=new Map;for(let[e,t]of c){let n=new Map;for(let[e,r]of t)n.set(e,r.size);f.set(e,n)}let p=t.at(-1),m=p?.type===`assistant`?p.message?.id:void 0;for(let t of e){if(t.type!==`assistant`)continue;let e=t;if(e.message.id!==m&&Array.isArray(e.message.content)){for(let t of e.message.content)if(typeof t!=`string`&&(t.type===`server_tool_use`||t.type===`mcp_tool_use`)&&!u.has(t.id)){let e=t.id;u.add(e),d.add(e)}}}return{siblingToolUseIDs:a,progressMessagesByToolUseID:o,inProgressHookCounts:s,resolvedHookCounts:f,toolResultByToolUseID:l,toolUseByToolUseID:i,normalizedMessageCount:e.length,resolvedToolUseIDs:u,erroredToolUseIDs:d}}function Eet(e,t,n,r,i){if(r.length<t||i.length<n)return null;if(r.length===t&&i.length===n){let t=r[r.length-1];return t&&t.type===`progress`?null:e}let a=n;for(let t=a;t<i.length;t++){let n=i[t];if(n.type===`assistant`){let t=n;if(t.message.id,Array.isArray(t.message.content)){let n=[];for(let r of t.message.content)if(typeof r!=`string`&&r.type===`tool_use`){let t=r;n.push(t.id),e.toolUseByToolUseID.set(t.id,r)}let r=new Set(n);for(let t of n)e.siblingToolUseIDs.set(t,r)}}}let o=t;for(let t=o;t<r.length;t++){let n=r[t];if(n.type===`progress`){let t=n.parentToolUseID,r=e.progressMessagesByToolUseID.get(t);r?r.push(n):e.progressMessagesByToolUseID.set(t,[n]);let i=n.data;if(i.type===`hook_progress`){let n=i.hookEvent,r=e.inProgressHookCounts.get(t);r||(r=new Map,e.inProgressHookCounts.set(t,r)),r.set(n,(r.get(n)??0)+1)}}if(n.type===`user`&&Array.isArray(n.message?.content)){for(let t of n.message?.content??[])if(typeof t!=`string`&&t.type===`tool_result`){let r=t;e.toolResultByToolUseID.set(r.tool_use_id,n),e.resolvedToolUseIDs.add(r.tool_use_id),r.is_error&&e.erroredToolUseIDs.add(r.tool_use_id)}}if(n.type===`assistant`&&Array.isArray(n.message?.content)){for(let t of n.message?.content??[])if(typeof t!=`string`&&(`tool_use_id`in t&&typeof t.tool_use_id==`string`&&e.resolvedToolUseIDs.add(t.tool_use_id),t.type===`advisor_tool_result`)){let n=t;n.content.type===`advisor_tool_result_error`&&e.erroredToolUseIDs.add(n.tool_use_id)}}if(tv(n)){let t=n.attachment.toolUseID,r=n.attachment.hookEvent;if(n.attachment.hookName!==void 0){let n=e.resolvedHookCounts.get(t);n||(n=new Map,e.resolvedHookCounts.set(t,n)),n.set(r,(n.get(r)??0)+1)}}}e.normalizedMessageCount=r.length;let s=i.at(-1),c=s?.type===`assistant`?s.message?.id:void 0;for(let t=o;t<r.length;t++){let n=r[t];if(n.type!==`assistant`)continue;let i=n;if(i.message.id!==c&&Array.isArray(i.message.content)){for(let t of i.message.content)if(typeof t!=`string`&&(t.type===`server_tool_use`||t.type===`mcp_tool_use`)&&!e.resolvedToolUseIDs.has(t.id)){let n=t.id;e.resolvedToolUseIDs.add(n),e.erroredToolUseIDs.add(n)}}}return e}function Det(e,t){let n=[String(e.length),`|`,String(t.length)];for(let e of t)if(n.push(e.type[0]),e.type===`assistant`){let t=e.message?.content;if(Array.isArray(t))for(let e of t)typeof e!=`string`&&e.type===`tool_use`&&n.push(`t`,e.id)}else if(e.type===`user`){let t=e.message?.content;if(Array.isArray(t))for(let e of t)typeof e!=`string`&&e.type===`tool_result`&&n.push(`r`,e.tool_use_id)}for(let t of e)if(t.type===`progress`){let e=t;n.push(`p`,e.parentToolUseID,e.uuid)}return n.join(`,`)}function g3(e){let t=new Map,n=new Set,r=new Map;for(let{message:i}of e)if(i.type===`assistant`&&Array.isArray(i.message.content))for(let e of i.message.content)typeof e!=`string`&&e.type===`tool_use`&&t.set(e.id,e);else if(i.type===`user`&&Array.isArray(i.message.content)){for(let e of i.message.content)if(typeof e!=`string`&&e.type===`tool_result`){let t=e;n.add(t.tool_use_id),r.set(t.tool_use_id,i)}}let i=new Set;for(let e of t.keys())n.has(e)||i.add(e);return{lookups:{..._3,toolUseByToolUseID:t,resolvedToolUseIDs:n,toolResultByToolUseID:r},inProgressToolUseIDs:i}}function Oet(e,t){let n=nv(e);return n?t.siblingToolUseIDs.get(n)??B_:B_}function ket(e,t){let n=nv(e);return n?t.progressMessagesByToolUseID.get(n)??[]:[]}function Aet(e,t,n){return(n.inProgressHookCounts.get(e)?.get(t)??0)>(n.resolvedHookCounts.get(e)?.get(t)??0)}function jet(e){return new Set(e.filter(e=>e.type===`assistant`&&Array.isArray(e.message?.content)&&e.message.content[0]?.type===`tool_use`).map(e=>e.message.content[0].id))}var _3,Met=n((()=>{H_(),lv(),_3={siblingToolUseIDs:new Map,progressMessagesByToolUseID:new Map,inProgressHookCounts:new Map,resolvedHookCounts:new Map,toolResultByToolUseID:new Map,toolUseByToolUseID:new Map,normalizedMessageCount:0,resolvedToolUseIDs:new Set,erroredToolUseIDs:new Set}}));function Net(e,t,n,r,i,a,o,s,c){if(e.type!==`stream_event`&&e.type!==`stream_request_start`){if(e.type===`tombstone`){a?.(e.message);return}if(e.type===`tool_use_summary`)return;if(e.type===`assistant`){let t=e,n=(Array.isArray(t.message?.content)?t.message.content:[]).find(e=>typeof e!=`string`&&e.type===`thinking`);if(n&&typeof n!=`string`&&n.type===`thinking`){let e=n;o?.(()=>({thinking:e.thinking,isStreaming:!1,streamingEndedAt:Date.now()}))}}c?.(()=>null),t(e);return}if(e.type===`stream_request_start`){r(`requesting`);return}let l=e;if(l.event.type===`message_start`&&l.ttftMs!=null&&s?.({ttftMs:l.ttftMs}),l.event.type===`message_stop`){r(`tool-use`),i(()=>[]);return}switch(l.event.type){case`content_block_start`:switch(c?.(()=>null),l.event.content_block.type){case`thinking`:case`redacted_thinking`:r(`thinking`);return;case`text`:r(`responding`);return;case`tool_use`:{r(`tool-input`);let e=l.event.content_block,t=l.event.index;i(n=>[...n,{index:t,contentBlock:e,unparsedToolInput:``}]);return}case`server_tool_use`:case`web_search_tool_result`:case`code_execution_tool_result`:case`mcp_tool_use`:case`mcp_tool_result`:case`container_upload`:case`web_fetch_tool_result`:case`bash_code_execution_tool_result`:case`text_editor_code_execution_tool_result`:case`tool_search_tool_result`:case`compaction`:r(`tool-input`);return}return;case`content_block_delta`:switch(l.event.delta.type){case`text_delta`:{let e=l.event.delta.text;n(e),c?.(t=>(t??``)+e);return}case`input_json_delta`:{let e=l.event.delta.partial_json,t=l.event.index;n(e),i(n=>{let r=n.find(e=>e.index===t);return r?[...n.filter(e=>e!==r),{...r,unparsedToolInput:r.unparsedToolInput+e}]:n});return}case`thinking_delta`:n(l.event.delta.thinking);return;case`signature_delta`:return;default:return}case`content_block_stop`:return;case`message_delta`:r(`responding`);return;default:r(`responding`);return}}var Pet=n((()=>{})),v3=n((()=>{H_(),Q_(),lv(),wet(),Met(),Pet(),a3(),c3()}));function y3(){return!1}async function Fet(e,t,n){if(!y3())return await n();let r=Fc(`sha1`).update(W(e)).digest(`hex`).slice(0,12),i=X(process.env.WORKMATE_TEST_FIXTURES_ROOT??U(),`fixtures/${t}-${r}.json`);try{return Si(await Wc(i,{encoding:`utf8`}))}catch(e){if(yi(e)!==`ENOENT`)throw e}if((Jn.isCI||process.env.CI)&&!h(process.env.VCR_RECORD))throw Error(`Fixture missing: ${i}. Re-run tests with VCR_RECORD=1, then commit the result.`);let a=await n();return await Hc(fc(i),{recursive:!0}),await Qc(i,W(a,null,2),{encoding:`utf8`}),a}async function Iet(e,t){if(!y3())return await t();let n=Ret(d3(e.filter(e=>e.type!==`user`||!e.isMeta)).map(e=>e.message.content),x3),r=X(process.env.WORKMATE_TEST_FIXTURES_ROOT??U(),`fixtures/${n.map(e=>Fc(`sha1`).update(W(e)).digest(`hex`).slice(0,6)).join(`-`)}.json`);try{let e=Si(await Wc(r,{encoding:`utf8`}));return e.output.forEach(Let),e.output.map((e,t)=>Bet(e,Vet,t,Lc()))}catch(e){if(yi(e)!==`ENOENT`)throw e}if(Jn.isCI&&!h(process.env.VCR_RECORD))throw Error(`API fixture missing: ${r}. Re-run tests with VCR_RECORD=1, then commit the result. Input messages:\n${W(n,null,2)}`);let i=await t();return Jn.isCI&&!h(process.env.VCR_RECORD)?i:(await Hc(fc(r),{recursive:!0}),await Qc(r,W({input:n,output:i.map((e,t)=>Bet(e,x3,t))},null,2),{encoding:`utf8`}),i)}function Let(e){if(e.type===`stream_event`)return;let t=e.message.model,n=e.message.usage;bw(fw(t,n),n,t)}function Ret(e,t){return e.map(e=>typeof e==`string`?t(e):e.map(e=>{switch(e.type){case`tool_result`:return typeof e.content==`string`?{...e,content:t(e.content)}:Array.isArray(e.content)?{...e,content:e.content.map(e=>{switch(e.type){case`text`:return{...e,text:t(e.text)};case`image`:return e;default:return}})}:e;case`text`:return{...e,text:t(e.text)};case`tool_use`:return{...e,input:b3(e.input,t)};case`image`:return e;default:return}}))}function b3(e,t){return cm(e,(n,r)=>Array.isArray(n)?n.map(e=>b3(e,t)):Rte(n)?b3(n,t):t(n,r,e))}function zet(e,t,n,r){return{uuid:r??`UUID-${n}`,requestId:`REQUEST_ID`,timestamp:e.timestamp,message:{...e.message,content:e.message.content.map(e=>{switch(e.type){case`text`:return{...e,text:t(e.text),citations:e.citations||[]};case`tool_use`:return{...e,input:b3(e.input,t)};default:return e}}).filter(Boolean)},type:`assistant`}}function Bet(e,t,n,r){return e.type===`assistant`?zet(e,t,n,r):e}function x3(e){if(typeof e!=`string`)return e;let t=U(),n=m(),r=e.replace(/num_files="\d+"/g,`num_files="[NUM]"`).replace(/duration_ms="\d+"/g,`duration_ms="[DURATION]"`).replace(/cost_usd="\d+"/g,`cost_usd="[COST]"`).replaceAll(n,`[CONFIG_HOME]`).replaceAll(t,`[CWD]`).replace(/Available commands:.+/,`Available commands: [COMMANDS]`);if(process.platform===`win32`){let e=t.replaceAll(`\\`,`/`),i=n.replaceAll(`\\`,`/`),a=W(t).slice(1,-1),o=W(n).slice(1,-1);r=r.replaceAll(a,`[CWD]`).replaceAll(o,`[CONFIG_HOME]`).replaceAll(e,`[CWD]`).replaceAll(i,`[CONFIG_HOME]`)}return r=r.replace(/\[CWD\][^\s"'<>]*/g,e=>e.replaceAll(`\\\\`,`/`).replaceAll(`\\`,`/`)).replace(/\[CONFIG_HOME\][^\s"'<>]*/g,e=>e.replaceAll(`\\\\`,`/`).replaceAll(`\\`,`/`)),r.includes(`Files modified by user:`)?`Files modified by user: [FILES]`:r}function Vet(e){return typeof e==`string`?e.replaceAll(`[NUM]`,`1`).replaceAll(`[DURATION]`,`100`).replaceAll(`[CONFIG_HOME]`,m()).replaceAll(`[CWD]`,U()):e}async function*Het(e,t){if(!y3())return yield*t();let n=[],r=await Iet(e,async()=>{for await(let e of t())n.push(e);return n});if(r.length>0){yield*r;return}yield*n}async function Uet(e,t,n){let r=U().replace(/[^a-zA-Z0-9]/g,`-`);return(await Fet(x3(W({messages:e,tools:t})).replaceAll(r,`[CWD_SLUG]`).replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,`[UUID]`).replace(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z?/g,`[TIMESTAMP]`),`token-count`,async()=>({tokenCount:await n()}))).tokenCount}var Wet=n((()=>{Mte(),lm(),xw(),vw(),ui(),nn(),g(),gi(),v3(),Li()}));function Get(e){for(let t of e)if(t.role===`assistant`&&Array.isArray(t.content)){for(let e of t.content)if(typeof e==`object`&&e&&`type`in e&&(e.type===`thinking`||e.type===`redacted_thinking`))return!0}return!1}function Ket(e){return e.map(e=>{if(!Array.isArray(e.content))return e;let t=e.content.map(e=>{if(e.type===`tool_use`){let t=e;return{type:`tool_use`,id:t.id,name:t.name,input:t.input}}if(e.type===`tool_result`){let t=e;if(Array.isArray(t.content)){let e=t.content.filter(e=>!WO(e));if(e.length===0)return{...t,content:[{type:`text`,text:`[tool references]`}]};if(e.length!==t.content.length)return{...t,content:e}}}return e});return{...e,content:t}})}async function qet(e){return e?S3([{role:`user`,content:e}],[]):0}async function S3(e,t){return Uet(e,t,async()=>{try{let n=lo();if(n===`gemini`)return Qet(e,t);let r=Lo(),i=Hg(r),a=Get(e);if(n===`bedrock`)return ett({model:_o(r),messages:e,tools:t,betas:i,containsThinking:a});let o=await Bo({maxRetries:1,model:r,source:`count_tokens`}),s=lo()===`vertex`?i.filter(e=>io.has(e)):i,c=await o.beta.messages.countTokens({model:_o(r),messages:e.length>0?e:[{role:`user`,content:`foo`}],tools:t,...s.length>0&&{betas:s},...a&&{thinking:{type:`enabled`,budget_tokens:E3}}});return typeof c.input_tokens==`number`?c.input_tokens:null}catch(e){return Y(e),null}})}function C3(e,t=4){return Math.round(e.length/t)}function Jet(e){switch(e){case`json`:case`jsonl`:case`jsonc`:return 2;default:return 4}}function Yet(e,t){return C3(e,Jet(t))}async function Xet(e,t){if(lo()===`gemini`)return Qet(e,t);let n=Get(e),r=h(process.env.WORKMATE_USE_VERTEX)&&_(zo())===`global`,i=h(process.env.WORKMATE_USE_BEDROCK)&&n,a=h(process.env.WORKMATE_USE_VERTEX)&&n,o=r||i||a?Po():zo(),s=await Bo({maxRetries:1,model:o,source:`count_tokens`}),c=Ket(e),l=c.length>0?c:[{role:`user`,content:`count`}],u=Hg(o),d=lo()===`vertex`?u.filter(e=>io.has(e)):u,f=(await s.beta.messages.create({model:_o(o),max_tokens:n?D3:1,messages:l,tools:t.length>0?t:void 0,...d.length>0&&{betas:d},metadata:X7(),...J7(),...n&&{thinking:{type:`enabled`,budget_tokens:E3}}})).usage,p=f.input_tokens,m=f.cache_creation_input_tokens||0,g=f.cache_read_input_tokens||0;return p+m+g}function w3(e){let t=0;for(let n of e)t+=Zet(n);return t}function Zet(e){if((e.type===`assistant`||e.type===`user`)&&e.message?.content)return T3(e.message?.content);if(e.type===`attachment`&&e.attachment){let t=_et(e.attachment),n=0;for(let e of t)n+=T3(e.message.content);return n}return 0}function T3(e){if(!e)return 0;if(typeof e==`string`)return C3(e);let t=0;for(let n of e)t+=$et(n);return t}function Qet(e,t){let n=0;for(let t of e)n+=T3(t.content);return t.length>0&&(n+=C3(W(t))),n}function $et(e){return typeof e==`string`?C3(e):e.type===`text`?C3(e.text):e.type===`image`||e.type===`document`?2e3:e.type===`tool_result`?T3(e.content):e.type===`tool_use`?C3(e.name+W(e.input??{})):e.type===`thinking`?C3(e.thinking):e.type===`redacted_thinking`?C3(e.data):C3(W(e))}async function ett({model:e,messages:t,tools:n,betas:r,containsThinking:i}){try{let a=await wie(),o=hie(e)?e:await co(e);if(!o)return null;let s={anthropic_version:`bedrock-2023-05-31`,messages:t.length>0?t:[{role:`user`,content:`foo`}],max_tokens:i?D3:1,...n.length>0&&{tools:n},...r.length>0&&{anthropic_beta:r},...i&&{thinking:{type:`enabled`,budget_tokens:E3}}},{CountTokensCommand:c}=await import(`./dist-es-CzTYn7xo.js`),l={modelId:o,input:{invokeModel:{body:new TextEncoder().encode(W(s))}}};return(await a.send(new c(l))).inputTokens??null}catch(e){return Y(e),null}}var E3,D3,O3=n((()=>{mo(),po(),Wg(),g(),wa(),v3(),Io(),wo(),Li(),$O(),r9(),So(),Wet(),E3=1024,D3=2048}));function ttt(e){ntt=e}var ntt,rtt=n((()=>{}));function itt(e,t){switch(e){case`policySettings`:return X(ir(),`.workmate`,t);case`userSettings`:return X(m(),t);case`projectSettings`:return`.workmate/${t}`;case`plugin`:return`plugin`;default:return``}}function att(e){return C3([e.name,e.description,e.whenToUse].filter(Boolean).join(` `))}async function ott(e){try{return await Kc(e)}catch{return null}}function stt(e,t){if(!e.hooks)return;let n=Wt().safeParse(e.hooks);if(!n.success){K(`Invalid hooks in skill '${t}': ${n.error.message}`);return}return n.data}function ctt(e){if(!e.paths)return;let t=Nu(e.paths).map(e=>e.endsWith(`/**`)?e.slice(0,-3):e).filter(e=>e.length>0);if(!(t.length===0||t.every(e=>e===`**`)))return t}function k3(e,t,n,r=`Skill`){let i=Iu(e.description,n),a=i??B9(t,r),o=e[`user-invocable`]===void 0||Lu(e[`user-invocable`]),s=e.model===`inherit`?void 0:e.model?Vo(e.model):void 0;return{displayName:e.name==null?void 0:String(e.name),description:a,hasUserSpecifiedDescription:i!==null,allowedTools:H9(e[`allowed-tools`]),argumentHint:e[`argument-hint`]==null?void 0:String(e[`argument-hint`]),argumentNames:B8e(e.arguments),whenToUse:e.when_to_use,version:e.version,model:s,disableModelInvocation:Lu(e[`disable-model-invocation`]),userInvocable:o,hooks:stt(e,n),executionContext:e.context===`fork`?`fork`:void 0,agent:e.agent,shell:Ru(e.shell,n)}}function A3({skillName:e,displayName:t,description:n,hasUserSpecifiedDescription:r,markdownContent:i,allowedTools:a,argumentHint:o,argumentNames:s,whenToUse:c,version:l,model:u,disableModelInvocation:d,userInvocable:f,source:p,baseDir:m,loadedFrom:h,hooks:g,executionContext:_,agent:v,paths:y,shell:b}){return{type:`prompt`,name:e,description:n,hasUserSpecifiedDescription:r,allowedTools:a,argumentHint:o,argNames:s.length>0?s:void 0,whenToUse:c,version:l,model:u,disableModelInvocation:d,userInvocable:f,context:_,agent:v,paths:y,contentLength:i.length,isHidden:!f,progressMessage:`running`,userFacingName(){return t||e},source:p,loadedFrom:h,hooks:g,skillRoot:m,async getPromptForCommand(t,n){let r=m?`Base directory for this skill: ${m}\n\n${i}`:i;if(r=S2(r,t,!0,s),m){let e=process.platform===`win32`?m.replace(/\\/g,`/`):m;r=r.replace(/\$\{CLAUDE_SKILL_DIR\}/g,e)}return r=r.replace(/\$\{CLAUDE_SESSION_ID\}/g,Wr()),h!==`mcp`&&(r=await H8e(r,{...n,getAppState(){let e=n.getAppState();return{...e,toolPermissionContext:{...e.toolPermissionContext,alwaysAllowRules:{...e.toolPermissionContext.alwaysAllowRules,command:a}}}}},`/${e}`,b)),[{type:`text`,text:r}]}}}async function j3(e,t){let n=J(),r;try{r=await n.readdir(e)}catch(e){return Ri(e)||Y(e),[]}return(await Promise.all(r.map(async r=>{try{if(!r.isDirectory()&&!r.isSymbolicLink())return null;let i=X(e,r.name),a=X(i,`SKILL.md`),o;try{o=await n.readFile(a,{encoding:`utf-8`})}catch(e){return xi(e)||K(`[skills] failed to read ${a}: ${e}`,{level:`warn`}),null}let{frontmatter:s,content:c}=Mu(o,a),l=r.name,u=k3(s,c,l),d=ctt(s);return{skill:A3({...u,skillName:l,markdownContent:c,source:t,baseDir:i,loadedFrom:`skills`,paths:d}),filePath:a}}catch(e){return Y(e),null}}))).filter(e=>e!==null)}function M3(e){return/^skill\.md$/i.test(dc(e))}function ltt(e){let t=new Map;for(let n of e){let e=fc(n.filePath),r=t.get(e)??[];r.push(n),t.set(e,r)}let n=[];for(let[e,r]of t){let t=r.filter(e=>M3(e.filePath));if(t.length>0){let r=t[0];t.length>1&&K(`Multiple skill files found in ${e}, using ${dc(r.filePath)}`),n.push(r)}else n.push(...r)}return n}function utt(e,t){let n=t.endsWith(bc)?t.slice(0,-1):t;if(e===n)return``;let r=e.slice(n.length+1);return r?r.split(bc).join(`:`):``}function dtt(e,t){let n=fc(e),r=fc(n),i=dc(n),a=utt(r,t);return a?`${a}:${i}`:i}function ftt(e,t){let n=dc(e),r=fc(e),i=n.replace(/\.md$/,``),a=utt(r,t);return a?`${a}:${i}`:i}function ptt(e){return M3(e.filePath)?dtt(e.filePath,e.baseDir):ftt(e.filePath,e.baseDir)}async function mtt(e){try{let t=ltt(await G9(`commands`,e)),n=[];for(let{baseDir:e,filePath:r,frontmatter:i,content:a,source:o}of t)try{let t=M3(r)?fc(r):void 0,s=ptt({baseDir:e,filePath:r,frontmatter:i,content:a,source:o}),c=k3(i,a,s,`Custom command`);n.push({skill:A3({...c,skillName:s,displayName:void 0,markdownContent:a,source:o,baseDir:t,loadedFrom:`commands_DEPRECATED`,paths:void 0}),filePath:r})}catch(e){Y(e)}return n}catch(e){return Y(e),[]}}function htt(){I3.cache?.clear?.(),G9.cache?.clear?.(),z3.clear(),B3.clear()}function gtt(e){return V3.subscribe(()=>{try{e()}catch(e){Y(e)}})}async function N3(e,t){let n=J(),r=t.endsWith(bc)?t.slice(0,-1):t,i=[];for(let t of e){let e=fc(t);for(;e.startsWith(r+bc);){let t=X(e,`.workmate`,`skills`);if(!L3.has(t)){L3.add(t);try{if(await n.stat(t),await Uee(e,r)){K(`[skills] Skipped gitignored skills dir: ${t}`);continue}i.push(t)}catch{}}let a=fc(e);if(a===e)break;e=a}}return i.sort((e,t)=>t.split(bc).length-e.split(bc).length)}async function P3(e){if(!Dn(`projectSettings`)||ab(`skills`)){K(`[skills] Dynamic skill discovery skipped: projectSettings disabled or plugin-only policy`);return}if(e.length===0)return;let t=new Set(R3.keys()),n=await Promise.all(e.map(e=>j3(e,`projectSettings`)));for(let e=n.length-1;e>=0;e--)for(let{skill:t}of n[e]??[])t.type===`prompt`&&R3.set(t.name,t);let r=n.flat().length;if(r>0){let n=[...R3.keys()].filter(e=>!t.has(e));K(`[skills] Dynamically discovered ${r} skills from ${e.length} directories`),n.length>0&&(t.size,R3.size,n.length,e.length)}V3.emit()}function _tt(){return Array.from(R3.values())}function F3(e,t){if(z3.size===0)return[];let n=[];for(let[r,i]of z3){if(i.type!==`prompt`||!i.paths||i.paths.length===0)continue;let a=(0,ytt.default)().add(i.paths);for(let o of e){let e=mc(o)?vc(t,o):o;if(!(!e||e.startsWith(`..`)||mc(e))&&a.ignores(e)){R3.set(r,i),z3.delete(r),B3.add(r),n.push(r),K(`[skills] Activated conditional skill '${r}' (matched path: ${e})`);break}}}return n.length>0&&(R3.size-n.length,R3.size,n.length,V3.emit()),n}function vtt(){L3.clear(),R3.clear(),z3.clear(),B3.clear()}var ytt,I3,L3,R3,z3,B3,V3,H3=n((()=>{ytt=r(ce(),1),d(),H(),La(),O3(),C2(),q(),g(),gi(),Hu(),ki(),Wte(),wa(),K9(),wo(),J8e(),Rn(),Zn(),sb(),At(),Ir(),rtt(),I3=u(async e=>{let t=X(m(),`skills`),n=X(ir(),`.workmate`,`skills`),r=U9(`skills`,e);K(`Loading skills from: managed=${n}, user=${t}, project=[${r.join(`, `)}]`);let i=Zr(),a=ab(`skills`),o=Dn(`projectSettings`)&&!a;if(v())return i.length===0||!o?(K(`[bare] Skipping skill dir discovery (${i.length===0?`no --add-dir`:`projectSettings disabled or skillsLocked`})`),[]):(await Promise.all(i.map(e=>j3(X(e,`.workmate`,`skills`),`projectSettings`)))).flat().map(e=>e.skill);let[s,c,l,u,d]=await Promise.all([h(process.env.WORKMATE_DISABLE_POLICY_SKILLS)?Promise.resolve([]):j3(n,`policySettings`),Dn(`userSettings`)&&!a?j3(t,`userSettings`):Promise.resolve([]),o?Promise.all(r.map(e=>j3(e,`projectSettings`))):Promise.resolve([]),o?Promise.all(i.map(e=>j3(X(e,`.workmate`,`skills`),`projectSettings`))):Promise.resolve([]),a?Promise.resolve([]):mtt(e)]),f=[...s,...c,...l.flat(),...u.flat(),...d],p=await Promise.all(f.map(({skill:e,filePath:t})=>e.type===`prompt`?ott(t):Promise.resolve(null))),g=new Map,_=[];for(let e=0;e<f.length;e++){let t=f[e];if(t===void 0||t.skill.type!==`prompt`)continue;let{skill:n}=t,r=p[e];if(r==null){_.push(n);continue}let i=g.get(r);if(i!==void 0){K(`Skipping duplicate skill '${n.name}' from ${n.source} (same file already loaded from ${i})`);continue}g.set(r,n.source),_.push(n)}let y=f.length-_.length;y>0&&K(`Deduplicated ${y} skills (same file)`);let b=[],x=[];for(let e of _)e.type===`prompt`&&e.paths&&e.paths.length>0&&!B3.has(e.name)?x.push(e):b.push(e);for(let e of x)z3.set(e.name,e);return x.length>0&&K(`[skills] ${x.length} conditional skills stored (activated when matching files are touched)`),K(`Loaded ${_.length} unique skills (${b.length} unconditional, ${x.length} conditional, managed: ${s.length}, user: ${c.length}, project: ${l.flat().length}, additional: ${u.flat().length}, legacy commands: ${d.length})`),b}),L3=new Set,R3=new Map,z3=new Map,B3=new Set,V3=jr(),ttt({createSkillCommand:A3,parseSkillFrontmatterFields:k3})}));function btt(e){let{files:t}=e,n,r=e.getPromptForCommand;if(t&&Object.keys(t).length>0){n=Stt(e.name);let i,a=e.getPromptForCommand;r=async(n,r)=>{i??(i=Ctt(e.name,t));let o=await i,s=await a(n,r);return o===null?s:Dtt(s,o)}}let i={type:`prompt`,name:e.name,description:e.description,aliases:e.aliases,hasUserSpecifiedDescription:!0,allowedTools:e.allowedTools??[],argumentHint:e.argumentHint,whenToUse:e.whenToUse,model:e.model,disableModelInvocation:e.disableModelInvocation??!1,userInvocable:e.userInvocable??!0,contentLength:0,source:`bundled`,loadedFrom:`bundled`,hooks:e.hooks,skillRoot:n,context:e.context,agent:e.agent,isEnabled:e.isEnabled,isHidden:!(e.userInvocable??!0),progressMessage:`running`,getPromptForCommand:r};U3.push(i)}function xtt(){return[...U3]}function Stt(e){return X(z8(),e)}async function Ctt(e,t){let n=Stt(e);try{return await wtt(n,t),n}catch(t){return K(`Failed to extract bundled skill '${e}' to ${n}: ${t instanceof Error?t.message:String(t)}`),null}}async function wtt(e,t){let n=new Map;for(let[r,i]of Object.entries(t)){let t=Ett(e,r),a=fc(t),o=[t,i],s=n.get(a);s?s.push(o):n.set(a,[o])}await Promise.all([...n].map(async([e,t])=>{await Hc(e,{recursive:!0,mode:448}),await Promise.all(t.map(([e,t])=>Ttt(e,t)))}))}async function Ttt(e,t){let n=await Uc(e,ktt,384);try{await n.writeFile(t,`utf8`)}finally{await n.close()}}function Ett(e,t){let n=hc(t);if(mc(n)||n.split(bc).includes(`..`)||n.split(`/`).includes(`..`))throw Error(`bundled skill file path escapes skill dir: ${t}`);return X(e,n)}function Dtt(e,t){let n=`Base directory for this skill: ${t}\n\n`;return e.length>0&&e[0].type===`text`?[{type:`text`,text:n+e[0].text},...e.slice(1)]:[{type:`text`,text:n},...e]}var U3,Ott,ktt,Att=n((()=>{q(),B8(),U3=[],Ott=Dc.O_NOFOLLOW??0,ktt=process.platform===`win32`?`wx`:Dc.O_WRONLY|Dc.O_CREAT|Dc.O_EXCL|Ott}));function jtt(e){return Itt.some(t=>t.test(e))}function Mtt(e){return e.length<=8?`***`:`${e.slice(0,4)}…${e.slice(-2)} (${e.length} chars)`}function Ntt(e){return Ltt.some(t=>e.startsWith(t))}function Ptt(){let e=Object.entries(process.env).filter(([e])=>Ntt(e)).map(([e,t])=>[e,jtt(e)&&t?Mtt(t):t??``]).sort(([e],[t])=>e.localeCompare(t));return e.length===0?` (no recognized env vars set)`:e.map(([e,t])=>` ${e}=${t}`).join(`
3056
3056
  `)}function Ftt(){return[` platform: ${process.platform} ${process.arch}`,` cwd: ${process.cwd()}`,` pid: ${process.pid}`,` bun: ${typeof Bun<`u`?Bun.version:`n/a`}`,` node: ${process.version}`,` session: ${Wr()}`].join(`
3057
3057
  `)}var Itt,Ltt,Rtt,ztt=n((()=>{H(),Itt=[/token/i,/secret/i,/password/i,/api[_-]?key/i,/auth/i,/private/i,/credential/i,/jwt/i,/session[_-]?id$/i],Ltt=[`CLAUDE_`,`WORKMATE_`,`FEATURE_`,`ANTHROPIC_`,`BUN_`,`NODE_`,`GEMINI_`,`OPENAI_`,`GROK_`,`CCR_`,`BUGHUNTER_`],Rtt={type:`local`,name:`env`,description:`显示当前环境、运行时与 feature flag`,isHidden:!1,isEnabled:()=>!0,supportsNonInteractive:!0,load:async()=>({call:async()=>({type:`text`,value:[`## Runtime`,Ftt(),``,`## Environment Variables (allowlisted prefixes)`,Ptt(),``,"_Secrets matching token/password/auth/api_key are masked. Set additional `CLAUDE_*` / `FEATURE_*` env vars to see them here._"].join(`
3058
- `)})})}})),W3,Btt=n((()=>{W3={type:`local-jsx`,name:`exit`,aliases:[`quit`],description:`退出 REPL`,immediate:!0,load:()=>import(`./exit-Q-xc8GEs.js`)}})),Vtt,Htt=n((()=>{pp(),wo(),Vtt={type:`local-jsx`,name:`model`,get description(){return`Set the AI model for Work Mate (currently ${bo(Lo())})`},argumentHint:`[model]`,get immediate(){return fp()},load:()=>import(`./model-BdWlSYyq.js`)}})),Utt,Wtt=n((()=>{$t(),Utt={type:`prompt`,description:`设置 Work Mate 的状态栏 UI`,contentLength:0,aliases:[],name:`statusline`,progressMessage:`setting up statusLine`,allowedTools:[Dt,`Read(~/**)`,`Edit(~/.workmate/settings.json)`],source:`builtin`,disableNonInteractive:!0,async getPromptForCommand(e){return[{type:`text`,text:`Create an ${Dt} with subagent_type "statusline-setup" and the prompt "${e.trim()||`Configure my statusLine from my shell PS1 configuration`}"`}]}}}));function G3(e){return(e.userFacingName?.()??e.name)||``}function K3(e){return e.isEnabled?.()??!0}var Gtt=n((()=>{}));async function Ktt(e){try{let[t,n]=await Promise.all([I3(e).catch(e=>(Y(wi(e)),K(`Skill directory commands failed to load, continuing without them`),[])),D2().catch(e=>(Y(wi(e)),K(`Plugin skills failed to load, continuing without them`),[]))]),r=xtt(),i=The();return K(`getSkills returning: ${t.length} skill dir commands, ${n.length} plugin skills, ${r.length} bundled skills, ${i.length} builtin plugin skills`),{skillDirCommands:t,pluginSkills:n,bundledSkills:r,builtinPluginSkills:i}}catch(e){return Y(wi(e)),K(`Unexpected error in getSkills, returning empty`),{skillDirCommands:[],pluginSkills:[],bundledSkills:[],builtinPluginSkills:[]}}}async function q3(e){let t=await Q3(e),n=_tt(),r=t.filter(e=>K3(e));if(n.length===0)return r;let i=new Set(r.map(e=>e.name)),a=n.filter(e=>!i.has(e.name)&&K3(e));if(a.length===0)return r;let o=new Set(X3().map(e=>e.name)),s=r.findIndex(e=>o.has(e.name));return s===-1?[...r,...a]:[...r.slice(0,s),...a,...r.slice(s)]}function qtt(){Q3.cache?.clear?.(),$3.cache?.clear?.(),e6.cache?.clear?.(),woe()}function Jtt(){qtt(),$8e(),t5e(),htt()}function Ytt(e){return[]}function J3(e,t){return t.find(t=>t.name===e||G3(t)===e||t.aliases?.includes(e))}function Y3(e,t){return J3(e,t)!==void 0}function Xtt(e,t){let n=J3(e,t);if(!n)throw ReferenceError(`Command ${e} not found. Available commands: ${t.map(e=>{let t=G3(e);return e.aliases?`${t} (aliases: ${e.aliases.join(`, `)})`:t}).sort((e,t)=>e.localeCompare(t)).join(`, `)}`);return n}function Ztt(e){if(e.type!==`prompt`)return e.description;if(e.kind===`workflow`)return`${e.description} (workflow)`;if(e.source===`plugin`){let t=e.pluginInfo?.pluginManifest.name;return t?`(${t}) ${e.description}`:`${e.description} (plugin)`}return e.source===`builtin`||e.source===`mcp`?e.description:e.source===`bundled`?`${e.description} (bundled)`:`${e.description} (${lte(e.source)})`}var X3,Z3,Q3,$3,e6,t6=n((()=>{Mue(),Nue(),Pue(),Fue(),Iue(),Lue(),Rue(),zue(),Bue(),Vue(),Hue(),Uue(),ede(),tde(),nde(),_oe(),rde(),ide(),ade(),ode(),sde(),cde(),lde(),ude(),dde(),fde(),pde(),hde(),Ws(),gde(),_de(),vde(),yde(),Ade(),jde(),Mde(),Nde(),Pde(),Fde(),Ide(),Lde(),Rde(),Ape(),Rme(),Kme(),wa(),gi(),q(),H3(),Att(),mv(),O2(),d(),ztt(),Btt(),Htt(),Wtt(),Rn(),Gtt(),X3=u(()=>[Id,Lme,vf,Gme,_p,gp,Ld,zd,Bd,Vd,Rd,Hd,Ud,Wd,Gd,W3,mp,Jd,cf,uf,df,Kd,qd,Vtt,vp,yp,pf,mf,hf,gf,Utt,bf,bp,yf,xf,Gf,Uf,Kf,qf,hp,Og,_f,Wf,Dp,Sp,lf,Rtt,voe,goe,ff]),Z3=u(()=>new Set(X3().flatMap(e=>[e.name,...e.aliases??[]]))),Q3=u(async e=>{let[{skillDirCommands:t,pluginSkills:n,bundledSkills:r,builtinPluginSkills:i},a]=await Promise.all([Ktt(e),E2()]);return[...r,...i,...t,...a,...n,...X3()]}),$3=u(async e=>(await q3(e)).filter(e=>e.type===`prompt`&&!e.disableModelInvocation&&e.source!==`builtin`&&(e.loadedFrom===`bundled`||e.loadedFrom===`skills`||e.loadedFrom===`commands_DEPRECATED`||e.hasUserSpecifiedDescription||e.whenToUse))),e6=u(async e=>{try{return(await q3(e)).filter(e=>e.type===`prompt`&&e.source!==`builtin`&&(e.hasUserSpecifiedDescription||e.whenToUse)&&(e.loadedFrom===`skills`||e.loadedFrom===`plugin`||e.loadedFrom===`bundled`||e.disableModelInvocation))}catch(e){return Y(wi(e)),K(`Returning empty skills array due to load failure`),[]}})}));async function Qtt(e){let t=Date.now(),{stdout:n,code:r}=await Oa(qn(),[`worktree`,`list`,`--porcelain`],{cwd:e,preserveOutputOnError:!1});if(Date.now()-t,r!==0)return[];let i=n.split(`
3059
- `).filter(e=>e.startsWith(`worktree `)).map(e=>e.slice(9).normalize(`NFC`));i.length;let a=i.find(t=>e===t||e.startsWith(t+bc)),o=i.filter(e=>e!==a).sort((e,t)=>e.localeCompare(t));return a?[a,...o]:o}var $tt=n((()=>{La(),Da(),Et()}));async function ent(){}var tnt=n((()=>{}));function n6(){if(process.stdout.isTTY)try{kc(1,Ue);let e=Oe.get(process.stdout);if(e?.isAltScreenActive)try{e.unmount()}catch{kc(1,lee)}e?.drainStdin(),e?.detachForShutdown(),kc(1,fe),kc(1,De),kc(1,Ge),kc(1,eee),kc(1,cee),kc(1,ree),He()&&kc(1,aee(oee)),h(process.env.WORKMATE_DISABLE_TERMINAL_TITLE)||(process.platform===`win32`?process.title=``:kc(1,Re))}catch{}}function r6(){if(!o6&&process.stdout.isTTY&&_ne()&&!Ar())try{let e=Wr();if(!y6(e))return;let t=V6(e),n;n=t?`"${t.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`:e,kc(1,Be.dim(`\nResume this session with:\nclaude --resume ${n}\n`)),o6=!0}catch{}}function i6(e){c6!==void 0&&(clearTimeout(c6),c6=void 0);try{Oe.get(process.stdout)?.drainStdin()}catch{}try{process.exit(e)}catch{process.kill(process.pid,`SIGKILL`)}throw Error(`unreachable`)}function nnt(e=0,t=`other`,n){process.exitCode=e,ant=a6(e,t,n).catch(t=>{K(`Graceful shutdown failed: ${t}`,{level:`error`}),n6(),r6(),i6(e)}).catch(()=>{})}function rnt(){return s6}async function a6(e=0,t=`other`,n){if(s6)return;s6=!0;let{executeSessionEndHooks:r,getSessionEndHookTimeoutMs:i}=await import(`./hooks-ujSG0QYH.js`),a=i();c6=setTimeout(e=>{n6(),r6(),i6(e)},Math.max(5e3,a+3500),e),c6.unref(),process.exitCode=e,n6(),r6();let o;try{let e=(async()=>{try{await Bre()}catch{}})();await Promise.race([e,new Promise((e,t)=>{o=setTimeout(e=>e(new ont),2e3,t)})]),clearTimeout(o)}catch{clearTimeout(o)}try{await r(t,{...n,signal:AbortSignal.timeout(a),timeoutMs:a})}catch{}try{aie()}catch{}Zte();try{await Promise.race([Promise.all([mse(),ent()]),Vs(500)])}catch{}if(n?.finalMessage)try{kc(2,`${n.finalMessage}\n`)}catch{}i6(e)}var o6,int,s6,c6,l6,ant,ont,snt=n((()=>{Ve(),d(),re(),H(),Ze(),tnt(),hse(),La(),di(),q(),bn(),g(),_8(),Hs(),oie(),o6=!1,int=u(()=>{te(()=>{}),process.on(`SIGINT`,()=>{process.argv.includes(`-p`)||process.argv.includes(`--print`)||(Cn(`info`,`shutdown_signal`,{signal:`SIGINT`}),a6(0))}),process.on(`SIGTERM`,()=>{Cn(`info`,`shutdown_signal`,{signal:`SIGTERM`}),a6(143)}),process.platform!==`win32`&&(process.on(`SIGHUP`,()=>{Cn(`info`,`shutdown_signal`,{signal:`SIGHUP`}),a6(129)}),process.stdin.isTTY&&(l6=setInterval(()=>{cne()||(!process.stdout.writable||!process.stdin.readable)&&(clearInterval(l6),Cn(`info`,`shutdown_signal`,{signal:`orphan_detected`}),a6(129))},3e4),l6.unref())),process.on(`uncaughtException`,e=>{Cn(`error`,`uncaught_exception`,{error_name:e.name,error_message:e.message.slice(0,2e3)}),e.name}),process.on(`unhandledRejection`,e=>{e instanceof Error&&e.name,Cn(`error`,`unhandled_rejection`,e instanceof Error?{error_name:e.name,error_message:e.message.slice(0,2e3),error_stack:e.stack?.slice(0,4e3)}:{error_message:String(e).slice(0,2e3)})})}),s6=!1,ont=class extends Error{constructor(){super(`Cleanup timeout`)}}})),cnt=i({MAX_TRANSCRIPT_READ_BYTES:()=>c8,adoptResumedSessionFile:()=>Cnt,buildConversationChain:()=>M6,cacheSessionTitle:()=>qnt,checkResumeConsistency:()=>jnt,cleanMessagesForLogging:()=>n8,clearAgentTranscriptSubdir:()=>g6,clearGoalEntry:()=>B6,clearSessionMessagesCache:()=>Y6,clearSessionMetadata:()=>Wnt,doesMessageExistInSession:()=>nrt,enrichLogs:()=>o8,extractAgentIdsFromMessages:()=>crt,fetchLogs:()=>L6,findUnresolvedToolUse:()=>prt,flushSessionStorage:()=>Ent,getAgentTranscript:()=>$6,getAgentTranscriptPath:()=>_6,getCurrentSessionTag:()=>Hnt,getCurrentSessionTitle:()=>V6,getFirstMeaningfulUserMessageTextContent:()=>k6,getLastSessionLog:()=>rrt,getLogByIndex:()=>frt,getNodeEnv:()=>b6,getProjectDir:()=>u8,getProjectsDir:()=>f6,getSessionFilesLite:()=>a8,getSessionFilesWithMtime:()=>r8,getSessionIdFromLog:()=>W6,getSessionMessages:()=>q6,getSessionMessagesCache:()=>J6,getTranscriptPath:()=>p6,getTranscriptPathForSession:()=>m6,getUserType:()=>x6,hydrateFromCCRv2InternalEvents:()=>Dnt,isChainParticipant:()=>d6,isCustomTitleEnabled:()=>mnt,isEphemeralToolProgress:()=>unt,isLiteLog:()=>G6,isLoggableMessage:()=>t8,isTranscriptMessage:()=>u6,linkSessionToPR:()=>Vnt,loadAllLogsFromSessionFile:()=>i8,loadAllProjectsMessageLogs:()=>irt,loadAllProjectsMessageLogsProgressive:()=>Z6,loadAllSubagentTranscriptsFromDisk:()=>lrt,loadFullLog:()=>Ynt,loadMessageLogs:()=>X6,loadSameRepoMessageLogs:()=>ort,loadSameRepoMessageLogsProgressive:()=>Q6,loadSubagentTranscripts:()=>e8,loadTranscriptFile:()=>K6,loadTranscriptFromFile:()=>Mnt,reAppendSessionMetadata:()=>H6,readAgentMetadata:()=>fnt,recordAttributionSnapshot:()=>xnt,recordContentReplacement:()=>D6,recordContextCollapseCommit:()=>wnt,recordContextCollapseSnapshot:()=>Tnt,recordFileHistorySnapshot:()=>E6,recordQueueOperation:()=>T6,recordSidechainTranscript:()=>w6,recordTranscript:()=>C6,removeExtraFields:()=>A6,removeTranscriptMessage:()=>bnt,resetProjectFlushStateForTesting:()=>hnt,resetProjectForTesting:()=>gnt,resetSessionFilePointer:()=>Snt,restoreSessionMetadata:()=>Unt,saveAgentName:()=>Gnt,saveAgentSetting:()=>Knt,saveAiGeneratedTitle:()=>Rnt,saveCustomTitle:()=>Lnt,saveGoal:()=>z6,saveMode:()=>Jnt,saveTag:()=>Bnt,saveTaskSummary:()=>znt,saveWorktreeState:()=>U6,searchSessionsByCustomTitle:()=>Xnt,sessionIdExists:()=>y6,setAgentTranscriptSubdir:()=>h6,setInternalEventReader:()=>ynt,setInternalEventWriter:()=>vnt,setSessionFileForTesting:()=>_nt,writeAgentMetadata:()=>v6});function u6(e){return e.type===`user`||e.type===`assistant`||e.type===`attachment`||e.type===`system`}function d6(e){return e.type!==`progress`}function lnt(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`progress`&&`uuid`in e&&typeof e.uuid==`string`}function unt(e){return typeof e==`string`&&Srt.has(e)}function f6(){return X(m(),`projects`)}function p6(){return X(ei()??u8(ti()),`${Wr()}.jsonl`)}function m6(e){return e===Wr()?p6():X(u8(ti()),`${e}.jsonl`)}function h6(e,t){l8.set(e,t)}function g6(e){l8.delete(e)}function _6(e){let t=ei()??u8(ti()),n=Wr(),r=l8.get(e);return X(r?X(t,n,`subagents`,r):X(t,n,`subagents`),`agent-${e}.jsonl`)}function dnt(e){return _6(e).replace(/\.jsonl$/,`.meta.json`)}async function v6(e,t){let n=dnt(e);await Hc(fc(n),{recursive:!0}),await Qc(n,JSON.stringify(t))}async function fnt(e){let t=dnt(e);try{let e=await Wc(t,`utf-8`);return JSON.parse(e)}catch(e){if(Ri(e))return null;throw e}}function y6(e){let t=X(u8(ti()),`${e}.jsonl`),n=J();try{return n.statSync(t),!0}catch{return!1}}function b6(){return`production`}function x6(){return`external`}function pnt(){return process.env.WORKMATE_ENTRYPOINT}function mnt(){return!0}function S6(){return d8||(d8=new wrt,f8||(Oi(async()=>{await d8?.flush();try{d8?.reAppendSessionMetadata()}catch{}}),f8=!0)),d8}function hnt(){d8?._resetFlushState()}function gnt(){d8=null}function _nt(e){S6().sessionFile=e}function vnt(e){S6().setInternalEventWriter(e)}function ynt(e,t){S6().setInternalEventReader(e),S6().setInternalSubagentEventReader(t)}async function C6(e,t,n,r){let i=n8(e,r),a=await q6(Wr()),o=[],s=n,c=!1;for(let e of i)a.has(e.uuid)?!c&&d6(e)&&(s=e.uuid):(o.push(e),c=!0);return o.length>0&&await S6().insertMessageChain(o,!1,void 0,s,t),o.findLast(d6)?.uuid??s??null}async function w6(e,t,n){await S6().insertMessageChain(n8(e),!0,t,n)}async function T6(e){await S6().insertQueueOperation(e)}async function bnt(e){await S6().removeMessageByUuid(e)}async function E6(e,t,n){await S6().insertFileHistorySnapshot(e,t,n)}async function xnt(e){await S6().insertAttributionSnapshot(e)}async function D6(e,t){await S6().insertContentReplacement(e,t)}async function Snt(){S6().resetSessionFile()}function Cnt(){let e=S6();e.sessionFile=p6(),e.reAppendSessionMetadata(!0)}async function wnt(e){let t=Wr();t&&await S6().appendEntry({type:`marble-origami-commit`,sessionId:t,...e})}async function Tnt(e){let t=Wr();t&&await S6().appendEntry({type:`marble-origami-snapshot`,sessionId:t,...e})}async function Ent(){await S6().flush()}async function Dnt(e){let t=Date.now();sne(Nj(e));let n=S6(),r=n.getInternalEventReader();if(!r)return K(`No internal event reader registered for CCR v2 resume`),!1;try{let i=await r();if(!i)return K(`Failed to read internal events for resume`),Cn(`error`,`hydrate_ccr_v2_read_fail`),!1;await Hc(u8(ti()),{recursive:!0,mode:448}),await Qc(m6(e),i.map(e=>`${W(e.payload)}\n`).join(``),{encoding:`utf8`,mode:384}),K(`Hydrated ${i.length} foreground entries from CCR v2 internal events`);let a=0,o=n.getInternalSubagentEventReader();if(o){let e=await o();if(e&&e.length>0){a=e.length;let t=new Map;for(let n of e){let e=n.agent_id||``;if(!e)continue;let r=t.get(e);r||(r=[],t.set(e,r)),r.push(n.payload)}for(let[e,n]of t){let t=_6(Pj(e));await Hc(fc(t),{recursive:!0,mode:448}),await Qc(t,n.map(e=>`${W(e)}\n`).join(``),{encoding:`utf8`,mode:384})}K(`Hydrated ${e.length} subagent entries across ${t.size} agents`)}}return Cn(`info`,`hydrate_ccr_v2_completed`,{duration_ms:Date.now()-t,event_count:i.length,subagent_event_count:a}),i.length>0}catch(e){if(e instanceof Error&&e.message===`CCRClient: Epoch mismatch (409)`)throw e;return K(`Error hydrating session from CCR v2: ${e}`),Cn(`error`,`hydrate_ccr_v2_fail`),!1}}function O6(e){let t=k6(e);if(t){let e=t.replace(/\n/g,` `).trim();return e.length>200&&(e=`${e.slice(0,200).trim()}…`),e}return`No prompt`}function k6(e){for(let t of e){if(t.type!==`user`||t.isMeta||`isCompactSummary`in t&&t.isCompactSummary)continue;let e=t.message?.content;if(!e)continue;let n=[];if(typeof e==`string`)n.push(e);else if(Array.isArray(e))for(let t of e)t.type===`text`&&t.text&&n.push(t.text);for(let e of n){if(!e)continue;let t=ev(e,ma);if(t){let n=t.replace(/^\//,``);if(Z3().has(n))continue;{let n=ev(e,`command-args`)?.trim();if(!n)continue;return`${t} ${n}`}}let n=ev(e,`bash-input`);if(n)return`! ${n}`;if(!s8.test(e))return e}}}function A6(e){return e.map(e=>{let{isSidechain:t,parentUuid:n,...r}=e;return r})}function Ont(e){let t,n=-1,r=-1,i=new Map,a=0;for(let o of e.values()){if(i.set(o.uuid,a),sv(o)){r=a;let e=o.compactMetadata?.preservedSegment;e&&(t=e,n=a)}a++}if(!t)return;let o=n===r,s=new Set;if(o){let n=new Set,r=e.get(t.tailUuid),i=!1;for(;r&&!n.has(r.uuid);){if(n.add(r.uuid),s.add(r.uuid),r.uuid===t.headUuid){i=!0;break}r=r.parentUuid?e.get(r.parentUuid):void 0}if(!i){e.has(t.tailUuid),e.has(t.headUuid),e.has(t.anchorUuid),n.size,e.size;return}}if(o){let n=e.get(t.headUuid);n&&e.set(t.headUuid,{...n,parentUuid:t.anchorUuid});for(let[n,r]of e)r.parentUuid===t.anchorUuid&&n!==t.headUuid&&e.set(n,{...r,parentUuid:t.tailUuid});for(let t of s){let n=e.get(t);n?.type===`assistant`&&e.set(t,{...n,message:{...n.message,usage:{...n.message.usage,input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0}}})}}let c=[];for(let[t]of e){let e=i.get(t);e!==void 0&&e<r&&!s.has(t)&&c.push(t)}for(let t of c)e.delete(t)}function knt(e){let t=new Set;for(let n of e.values()){let e=n.snipMetadata?.removedUuids;if(e)for(let n of e)t.add(n)}if(t.size===0)return;let n=new Map,r=0;for(let i of t){let t=e.get(i);t&&(n.set(i,t.parentUuid),e.delete(i),r++)}let i=e=>{let r=[],i=e;for(;i&&t.has(i);)if(r.push(i),i=n.get(i),i===void 0){i=null;break}for(let e of r)n.set(e,i);return i},a=0;for(let[n,r]of e)!r.parentUuid||!t.has(r.parentUuid)||(e.set(n,{...r,parentUuid:i(r.parentUuid)}),a++)}function j6(e,t){let n,r=-1/0;for(let i of e){if(!t(i))continue;let e=Date.parse(i.timestamp);e>r&&(r=e,n=i)}return n}function M6(e,t){let n=[],r=new Set,i=t;for(;i;){if(r.has(i.uuid)){Y(Error(`Cycle detected in parentUuid chain at message ${i.uuid}. Returning partial transcript.`));break}r.add(i.uuid),n.push(i),i=i.parentUuid?e.get(i.parentUuid):void 0}return n.reverse(),Ant(e,n,r)}function Ant(e,t,n){let r=t.filter(e=>e.type===`assistant`);if(r.length===0)return t;let i=new Map;for(let e of r)e.message.id&&i.set(e.message.id,e);let a=new Map,o=new Map;for(let t of e.values())if(t.type===`assistant`&&t.message.id){let e=a.get(t.message.id);e?e.push(t):a.set(t.message.id,[t])}else if(t.type===`user`&&t.parentUuid&&Array.isArray(t.message.content)&&t.message.content.some(e=>e.type===`tool_result`)){let e=o.get(t.parentUuid);e?e.push(t):o.set(t.parentUuid,[t])}let s=new Set,c=new Map,l=0;for(let e of r){let t=e.message.id;if(!t||s.has(t))continue;s.add(t);let r=a.get(t)??[e],u=r.filter(e=>!n.has(e.uuid)),d=[];for(let e of r){let t=o.get(e.uuid);if(t)for(let e of t)n.has(e.uuid)||d.push(e)}if(u.length===0&&d.length===0)continue;u.sort((e,t)=>e.timestamp.localeCompare(t.timestamp)),d.sort((e,t)=>e.timestamp.localeCompare(t.timestamp));let f=i.get(t),p=[...u,...d];for(let e of p)n.add(e.uuid);l+=p.length,c.set(f.uuid,p)}if(l===0)return t;let u=[];for(let e of t){u.push(e);let t=c.get(e.uuid);t&&u.push(...t)}return u}function jnt(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.type!==`system`||n.subtype!==`turn_duration`)continue;let r=n.messageCount;if(r===void 0)return;t-r,e.length,e.length-1-t;return}}function N6(e,t){let n=[],r=new Map;for(let i of t){let t=e.get(i.uuid);if(!t)continue;let{snapshot:a,isSnapshotUpdate:o}=t,s=o?r.get(a.messageId):void 0;s===void 0?(r.set(a.messageId,n.length),n.push(a)):n[s]=a}return n}function P6(e,t){return Array.from(e.values())}async function Mnt(e){if(e.endsWith(`.jsonl`)){let{messages:t,summaries:n,customTitles:r,tags:i,fileHistorySnapshots:a,attributionSnapshots:o,contextCollapseCommits:s,contextCollapseSnapshot:c,leafUuids:l,contentReplacements:u,worktreeStates:d}=await K6(e);if(t.size===0)throw Error(`No messages found in JSONL file`);let f=j6(t.values(),e=>l.has(e.uuid));if(!f)throw Error(`No valid conversation chain found in JSONL file`);let p=M6(t,f),m=n.get(f.uuid),h=r.get(f.sessionId),g=i.get(f.sessionId),_=f.sessionId;return{...I6(p,0,m,h,N6(a,p),g,e,P6(o,p),void 0,u.get(_)??[]),contextCollapseCommits:s.filter(e=>e.sessionId===_),contextCollapseSnapshot:c?.sessionId===_?c:void 0,worktreeSession:d.has(_)?d.get(_):void 0}}let t=await Wc(e,{encoding:`utf-8`}),n;try{n=Si(t)}catch(e){throw Error(`Invalid JSON in transcript file: ${e}`)}let r;if(Array.isArray(n))r=n;else if(n&&typeof n==`object`&&`messages`in n){if(!Array.isArray(n.messages))throw Error(`Transcript messages must be an array`);r=n.messages}else throw Error(`Transcript must be an array of messages or an object with a messages array`);return I6(r,0,void 0,void 0,void 0,void 0,e)}function Nnt(e){if(e.type!==`user`||e.isMeta)return!1;let t=e.message?.content;return t?typeof t==`string`?t.trim().length>0:Array.isArray(t)?t.some(e=>e.type===`text`||e.type===`image`||e.type===`document`):!1:!1}function Pnt(e){if(e.type!==`assistant`)return!1;let t=e.message?.content;return!t||!Array.isArray(t)?!1:t.some(e=>e.type===`text`&&typeof e.text==`string`&&e.text.trim().length>0)}function F6(e){let t=0;for(let n of e)switch(n.type){case`user`:Nnt(n)&&t++;break;case`assistant`:Pnt(n)&&t++;break;case`attachment`:case`system`:case`progress`:break}return t}function I6(e,t=0,n,r,i,a,o,s,c,l){let u=e.at(-1),d=e[0],f=O6(e),p=new Date(d.timestamp),m=new Date(u.timestamp);return{date:u.timestamp,messages:A6(e),fullPath:o,value:t,created:p,modified:m,firstPrompt:f,messageCount:F6(e),isSidechain:d.isSidechain,agentName:d.agentName,agentSetting:c,leafUuid:u.uuid,summary:n,customTitle:r,tag:a,fileHistorySnapshots:i,attributionSnapshots:s,contentReplacements:l,gitBranch:u.gitBranch,projectPath:d.cwd}}async function Fnt(e){let t=new Map,n=0;for(let r of e){let e=W6(r);if(e){let r=(t.get(e)||0)+1;t.set(e,r),n=Math.max(r,n)}}if(n<=1)return;let r=Array.from(t.values()).filter(e=>e>1),i=r.length,a=r.reduce((e,t)=>e+t,0);t.size,Math.max(...r),Math.round(a/i),e.length}async function L6(e){let t=await a8(u8(ti()),e,ti());return await Fnt(t),t}function R6(e,t){let n=J(),r=`${W(t)}\n`;try{n.appendFileSync(e,r,{mode:384})}catch{n.mkdirSync(fc(e),{mode:448}),n.appendFileSync(e,r,{mode:384})}}function Int(e){let t;try{t=Pse(e,`r`);let n=Mse(t),r=Math.max(0,n.size-Tn),i=Buffer.allocUnsafe(Math.min(Tn,n.size-r)),a=Fse(t,i,0,i.length,r);return i.toString(`utf8`,0,a)}catch{return``}finally{if(t!==void 0)try{Ose(t)}catch{}}}async function Lnt(e,t,n,r=`user`){R6(n??m6(e),{type:`custom-title`,customTitle:t,sessionId:e}),e===Wr()&&(S6().currentSessionTitle=t)}function Rnt(e,t){R6(m6(e),{type:`ai-title`,aiTitle:t,sessionId:e})}function znt(e,t){R6(m6(e),{type:`task-summary`,summary:t,sessionId:e,timestamp:new Date().toISOString()})}async function Bnt(e,t,n){R6(n??m6(e),{type:`tag`,tag:t,sessionId:e}),e===Wr()&&(S6().currentSessionTag=t)}function z6(e,t,n){R6(n??m6(e),{type:`goal`,sessionId:e,state:t,timestamp:new Date().toISOString()}),e===Wr()&&(S6().currentSessionGoal=t)}function B6(e,t){R6(t??m6(e),{type:`goal-cleared`,sessionId:e,timestamp:new Date().toISOString()}),e===Wr()&&(S6().currentSessionGoal=void 0)}async function Vnt(e,t,n,r,i){if(R6(i??m6(e),{type:`pr-link`,sessionId:e,prNumber:t,prUrl:n,prRepository:r,timestamp:new Date().toISOString()}),e===Wr()){let e=S6();e.currentSessionPrNumber=t,e.currentSessionPrUrl=n,e.currentSessionPrRepository=r}}function Hnt(e){if(e===Wr())return S6().currentSessionTag}function V6(e){if(e===Wr())return S6().currentSessionTitle}function Unt(e){let t=S6();e.customTitle&&(t.currentSessionTitle??(t.currentSessionTitle=e.customTitle)),e.tag!==void 0&&(t.currentSessionTag=e.tag||void 0),e.agentName&&(t.currentSessionAgentName=e.agentName),e.agentColor&&(t.currentSessionAgentColor=e.agentColor),e.agentSetting&&(t.currentSessionAgentSetting=e.agentSetting),e.mode&&(t.currentSessionMode=e.mode),e.worktreeSession!==void 0&&(t.currentSessionWorktree=e.worktreeSession),e.prNumber!==void 0&&(t.currentSessionPrNumber=e.prNumber),e.prUrl&&(t.currentSessionPrUrl=e.prUrl),e.prRepository&&(t.currentSessionPrRepository=e.prRepository),e.goal&&(t.currentSessionGoal=e.goal)}function Wnt(){let e=S6();e.currentSessionTitle=void 0,e.currentSessionTag=void 0,e.currentSessionAgentName=void 0,e.currentSessionAgentColor=void 0,e.currentSessionLastPrompt=void 0,e.currentSessionAgentSetting=void 0,e.currentSessionMode=void 0,e.currentSessionGoal=void 0,e.currentSessionWorktree=void 0,e.currentSessionPrNumber=void 0,e.currentSessionPrUrl=void 0,e.currentSessionPrRepository=void 0}function H6(){S6().reAppendSessionMetadata()}async function Gnt(e,t,n,r=`user`){R6(n??m6(e),{type:`agent-name`,agentName:t,sessionId:e}),e===Wr()&&(S6().currentSessionAgentName=t,z4e(t))}function Knt(e){S6().currentSessionAgentSetting=e}function qnt(e){S6().currentSessionTitle=e}function Jnt(e){S6().currentSessionMode=e}function U6(e){let t=e?{originalCwd:e.originalCwd,worktreePath:e.worktreePath,worktreeName:e.worktreeName,worktreeBranch:e.worktreeBranch,originalBranch:e.originalBranch,originalHeadCommit:e.originalHeadCommit,sessionId:e.sessionId,tmuxSessionName:e.tmuxSessionName,hookBased:e.hookBased}:null,n=S6();n.currentSessionWorktree=t,n.sessionFile&&R6(n.sessionFile,{type:`worktree-state`,worktreeSession:t,sessionId:Wr()})}function W6(e){return e.sessionId?e.sessionId:e.messages[0]?.sessionId}function G6(e){return e.messages.length===0&&e.sessionId!==void 0}async function Ynt(e){if(!G6(e))return e;let t=e.fullPath;if(!t)return e;try{let{messages:n,summaries:r,customTitles:i,tags:a,agentNames:o,agentColors:s,agentSettings:c,prNumbers:l,prUrls:u,prRepositories:d,modes:f,worktreeStates:p,goals:m,fileHistorySnapshots:h,attributionSnapshots:g,contentReplacements:_,contextCollapseCommits:v,contextCollapseSnapshot:y,leafUuids:b}=await K6(t);if(n.size===0){let t=e.sessionId?m.get(e.sessionId):void 0;return t?{...e,goal:t}:e}let x=j6(n.values(),e=>b.has(e.uuid)&&(e.type===`user`||e.type===`assistant`));if(!x){let t=e.sessionId?m.get(e.sessionId):void 0;return t?{...e,goal:t}:e}let S=M6(n,x),C=x.sessionId;return{...e,messages:A6(S),firstPrompt:O6(S),messageCount:F6(S),summary:x?r.get(x.uuid):e.summary,customTitle:C?i.get(C):e.customTitle,tag:C?a.get(C):e.tag,agentName:C?o.get(C):e.agentName,agentColor:C?s.get(C):e.agentColor,agentSetting:C?c.get(C):e.agentSetting,mode:C?f.get(C):e.mode,worktreeSession:C&&p.has(C)?p.get(C):e.worktreeSession,goal:C?m.get(C):e.goal,prNumber:C?l.get(C):e.prNumber,prUrl:C?u.get(C):e.prUrl,prRepository:C?d.get(C):e.prRepository,gitBranch:x?.gitBranch??e.gitBranch,isSidechain:S[0]?.isSidechain??e.isSidechain,leafUuid:x?.uuid??e.leafUuid,fileHistorySnapshots:N6(h,S),attributionSnapshots:P6(g,S),contentReplacements:C?_.get(C)??[]:e.contentReplacements,contextCollapseCommits:C?v.filter(e=>e.sessionId===C):void 0,contextCollapseSnapshot:C&&y?.sessionId===C?y:void 0}}catch{return e}}async function Xnt(e,t){let{limit:n,exact:r}=t||{},i=await srt(await Qtt(ti())),{logs:a}=await o8(i,0,i.length),o=e.toLowerCase().trim(),s=a.filter(e=>{let t=e.customTitle?.toLowerCase().trim();return t?r?t===o:t.includes(o):!1}),c=new Map;for(let e of s){let t=W6(e);if(t){let n=c.get(t);(!n||e.modified>n.modified)&&c.set(t,e)}}let l=Array.from(c.values());return l.sort((e,t)=>t.modified.getTime()-e.modified.getTime()),n?l.slice(0,n):l}function Znt(e,t){if(e===null||e.length===0)return t;if(e.length<Trt)return Buffer.concat([e,t]);if(e[0]===123){for(let n of m8)if(e.compare(n,0,n.length,1,1+n.length)===0)return Buffer.concat([e,t])}let n=t.indexOf(10);return n===-1?null:t.subarray(n+1)}async function Qnt(e,t){let{createReadStream:n}=await import(`fs`),r=n(e,{end:t-1}),i=[],a=null;for await(let e of r){let t=Znt(a,e);if(t===null){a=null;continue}let n=!1;for(let e of m8)if(t.includes(e)){n=!0;break}if(n){let e=0,n=t.indexOf(10);for(;n!==-1;){for(let r of m8){let a=t.indexOf(r,e);if(a!==-1&&a<n){i.push(t.toString(`utf-8`,e,n));break}}e=n+1,n=t.indexOf(10,e)}a=t.subarray(e)}else{let e=t.lastIndexOf(10);a=e>=0?t.subarray(e+1):t}a.length>64*1024&&(a=null)}if(a!==null&&a.length>0){for(let e of m8)if(a.includes(e)){i.push(a.toString(`utf-8`));break}}return i}function $nt(e,t,n){let r=0,i=!1,a=!1,o=0;for(let s=t;o<n.length;s++){if(s===n[o]){if(r===1&&!i)return n[o];o++}let t=e[s];a?a=!1:i?t===92?a=!0:t===34&&(i=!1):t===34?i=!0:t===123?r++:t===125&&r--}return n.at(-1)}function ert(e){let t=Buffer.from(`{"parentUuid":`),n=Buffer.from(`"uuid":"`),r=Buffer.from(`"isSidechain":true`),i=Buffer.from(`","timestamp":"`),a=i.length,o=t.length,s=n.length,c=[],l=[],u=new Map,d=0,f=e.length;for(;d<f;){let r=e.indexOf(10,d),p=r===-1?f:r+1;if(p-d>o&&e[d]===123&&e.compare(t,0,o,d,d+o)===0){let t=e[d+o]===34?d+o+1:-1,r=-1,f=-1,m,h=d;for(;;){let t=e.indexOf(n,h);if(t<0||t>=p)break;r<0&&(r=t);let o=t+s+36;o+a<=p&&e.compare(i,0,a,o,o+a)===0&&(f<0?f=t:(m??(m=[f])).push(t)),h=t+s}let g=m?$nt(e,d,m):f>=0?f:r;if(g>=0){let n=g+s,r=e.toString(`latin1`,n,n+36);u.set(r,c.length),c.push(d,p,t)}else l.push(d,p)}else l.push(d,p);d=p}let p=-1;for(let t=c.length-3;t>=0;t-=3){let n=e.indexOf(r,c[t]);if(n===-1||n>=c[t+1]){p=t;break}}if(p<0)return e;let m=new Set,h=new Set,g=0,_=p;for(;_!==void 0&&!m.has(_);){m.add(_),h.add(c[_]),g+=c[_+1]-c[_];let t=c[_+2];if(t<0)break;let n=e.toString(`latin1`,t,t+36);_=u.get(n)}if(f-g<f>>1)return e;let v=[],y=0;for(let t=0;t<c.length;t+=3){let n=c[t];for(;y<l.length&&l[y]<n;)v.push(e.subarray(l[y],l[y+1])),y+=2;h.has(n)&&v.push(e.subarray(n,c[t+1]))}for(;y<l.length;)v.push(e.subarray(l[y],l[y+1])),y+=2;return Buffer.concat(v)}async function K6(e,t){let n=new Map,r=new Map,i=new Map,a=new Map,o=new Map,s=new Map,c=new Map,l=new Map,u=new Map,d=new Map,f=new Map,p=new Map,m=new Map,g=new Map,_=new Map,v=new Map,y=new Map,b=[],x;try{let S=null,C=null,w=!1;if(!h(process.env.WORKMATE_DISABLE_PRECOMPACT_SKIP)){let{size:t}=await Yc(e);if(t>5242880){let n=await Pee(e,t);S=n.postBoundaryBuf,w=n.hasPreservedSegment,n.boundaryStartOffset>0&&(C=await Qnt(e,n.boundaryStartOffset))}}if(S??(S=await Wc(e)),!t?.keepAllLeaves&&!w&&!h(process.env.WORKMATE_DISABLE_PRECOMPACT_SKIP)&&S.length>5242880&&(S=ert(S)),C&&C.length>0){let e=vr(Buffer.from(C.join(`
3058
+ `)})})}})),W3,Btt=n((()=>{W3={type:`local-jsx`,name:`exit`,aliases:[`quit`],description:`退出 REPL`,immediate:!0,load:()=>import(`./exit-DFWdzIc6.js`)}})),Vtt,Htt=n((()=>{pp(),wo(),Vtt={type:`local-jsx`,name:`model`,get description(){return`Set the AI model for Work Mate (currently ${bo(Lo())})`},argumentHint:`[model]`,get immediate(){return fp()},load:()=>import(`./model-CttVg7um.js`)}})),Utt,Wtt=n((()=>{$t(),Utt={type:`prompt`,description:`设置 Work Mate 的状态栏 UI`,contentLength:0,aliases:[],name:`statusline`,progressMessage:`setting up statusLine`,allowedTools:[Dt,`Read(~/**)`,`Edit(~/.workmate/settings.json)`],source:`builtin`,disableNonInteractive:!0,async getPromptForCommand(e){return[{type:`text`,text:`Create an ${Dt} with subagent_type "statusline-setup" and the prompt "${e.trim()||`Configure my statusLine from my shell PS1 configuration`}"`}]}}}));function G3(e){return(e.userFacingName?.()??e.name)||``}function K3(e){return e.isEnabled?.()??!0}var Gtt=n((()=>{}));async function Ktt(e){try{let[t,n]=await Promise.all([I3(e).catch(e=>(Y(wi(e)),K(`Skill directory commands failed to load, continuing without them`),[])),D2().catch(e=>(Y(wi(e)),K(`Plugin skills failed to load, continuing without them`),[]))]),r=xtt(),i=The();return K(`getSkills returning: ${t.length} skill dir commands, ${n.length} plugin skills, ${r.length} bundled skills, ${i.length} builtin plugin skills`),{skillDirCommands:t,pluginSkills:n,bundledSkills:r,builtinPluginSkills:i}}catch(e){return Y(wi(e)),K(`Unexpected error in getSkills, returning empty`),{skillDirCommands:[],pluginSkills:[],bundledSkills:[],builtinPluginSkills:[]}}}async function q3(e){let t=await Q3(e),n=_tt(),r=t.filter(e=>K3(e));if(n.length===0)return r;let i=new Set(r.map(e=>e.name)),a=n.filter(e=>!i.has(e.name)&&K3(e));if(a.length===0)return r;let o=new Set(X3().map(e=>e.name)),s=r.findIndex(e=>o.has(e.name));return s===-1?[...r,...a]:[...r.slice(0,s),...a,...r.slice(s)]}function qtt(){Q3.cache?.clear?.(),$3.cache?.clear?.(),e6.cache?.clear?.(),woe()}function Jtt(){qtt(),$8e(),t5e(),htt()}function Ytt(e){return[]}function J3(e,t){return t.find(t=>t.name===e||G3(t)===e||t.aliases?.includes(e))}function Y3(e,t){return J3(e,t)!==void 0}function Xtt(e,t){let n=J3(e,t);if(!n)throw ReferenceError(`Command ${e} not found. Available commands: ${t.map(e=>{let t=G3(e);return e.aliases?`${t} (aliases: ${e.aliases.join(`, `)})`:t}).sort((e,t)=>e.localeCompare(t)).join(`, `)}`);return n}function Ztt(e){if(e.type!==`prompt`)return e.description;if(e.kind===`workflow`)return`${e.description} (workflow)`;if(e.source===`plugin`){let t=e.pluginInfo?.pluginManifest.name;return t?`(${t}) ${e.description}`:`${e.description} (plugin)`}return e.source===`builtin`||e.source===`mcp`?e.description:e.source===`bundled`?`${e.description} (bundled)`:`${e.description} (${lte(e.source)})`}var X3,Z3,Q3,$3,e6,t6=n((()=>{Mue(),Nue(),Pue(),Fue(),Iue(),Lue(),Rue(),zue(),Bue(),Vue(),Hue(),Uue(),ede(),tde(),nde(),_oe(),rde(),ide(),ade(),ode(),sde(),cde(),lde(),ude(),dde(),fde(),pde(),hde(),Ws(),gde(),_de(),vde(),yde(),Ade(),jde(),Mde(),Nde(),Pde(),Fde(),Ide(),Lde(),Rde(),Ape(),Rme(),Kme(),wa(),gi(),q(),H3(),Att(),mv(),O2(),d(),ztt(),Btt(),Htt(),Wtt(),Rn(),Gtt(),X3=u(()=>[Id,Lme,vf,Gme,_p,gp,Ld,zd,Bd,Vd,Rd,Hd,Ud,Wd,Gd,W3,mp,Jd,cf,uf,df,Kd,qd,Vtt,vp,yp,pf,mf,hf,gf,Utt,bf,bp,yf,xf,Gf,Uf,Kf,qf,hp,Og,_f,Wf,Dp,Sp,lf,Rtt,voe,goe,ff]),Z3=u(()=>new Set(X3().flatMap(e=>[e.name,...e.aliases??[]]))),Q3=u(async e=>{let[{skillDirCommands:t,pluginSkills:n,bundledSkills:r,builtinPluginSkills:i},a]=await Promise.all([Ktt(e),E2()]);return[...r,...i,...t,...a,...n,...X3()]}),$3=u(async e=>(await q3(e)).filter(e=>e.type===`prompt`&&!e.disableModelInvocation&&e.source!==`builtin`&&(e.loadedFrom===`bundled`||e.loadedFrom===`skills`||e.loadedFrom===`commands_DEPRECATED`||e.hasUserSpecifiedDescription||e.whenToUse))),e6=u(async e=>{try{return(await q3(e)).filter(e=>e.type===`prompt`&&e.source!==`builtin`&&(e.hasUserSpecifiedDescription||e.whenToUse)&&(e.loadedFrom===`skills`||e.loadedFrom===`plugin`||e.loadedFrom===`bundled`||e.disableModelInvocation))}catch(e){return Y(wi(e)),K(`Returning empty skills array due to load failure`),[]}})}));async function Qtt(e){let t=Date.now(),{stdout:n,code:r}=await Oa(qn(),[`worktree`,`list`,`--porcelain`],{cwd:e,preserveOutputOnError:!1});if(Date.now()-t,r!==0)return[];let i=n.split(`
3059
+ `).filter(e=>e.startsWith(`worktree `)).map(e=>e.slice(9).normalize(`NFC`));i.length;let a=i.find(t=>e===t||e.startsWith(t+bc)),o=i.filter(e=>e!==a).sort((e,t)=>e.localeCompare(t));return a?[a,...o]:o}var $tt=n((()=>{La(),Da(),Et()}));async function ent(){}var tnt=n((()=>{}));function n6(){if(process.stdout.isTTY)try{kc(1,Ue);let e=Oe.get(process.stdout);if(e?.isAltScreenActive)try{e.unmount()}catch{kc(1,lee)}e?.drainStdin(),e?.detachForShutdown(),kc(1,fe),kc(1,De),kc(1,Ge),kc(1,eee),kc(1,cee),kc(1,ree),He()&&kc(1,aee(oee)),h(process.env.WORKMATE_DISABLE_TERMINAL_TITLE)||(process.platform===`win32`?process.title=``:kc(1,Re))}catch{}}function r6(){if(!o6&&process.stdout.isTTY&&_ne()&&!Ar())try{let e=Wr();if(!y6(e))return;let t=V6(e),n;n=t?`"${t.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`:e,kc(1,Be.dim(`\nResume this session with:\nclaude --resume ${n}\n`)),o6=!0}catch{}}function i6(e){c6!==void 0&&(clearTimeout(c6),c6=void 0);try{Oe.get(process.stdout)?.drainStdin()}catch{}try{process.exit(e)}catch{process.kill(process.pid,`SIGKILL`)}throw Error(`unreachable`)}function nnt(e=0,t=`other`,n){process.exitCode=e,ant=a6(e,t,n).catch(t=>{K(`Graceful shutdown failed: ${t}`,{level:`error`}),n6(),r6(),i6(e)}).catch(()=>{})}function rnt(){return s6}async function a6(e=0,t=`other`,n){if(s6)return;s6=!0;let{executeSessionEndHooks:r,getSessionEndHookTimeoutMs:i}=await import(`./hooks-DG0-4_wq.js`),a=i();c6=setTimeout(e=>{n6(),r6(),i6(e)},Math.max(5e3,a+3500),e),c6.unref(),process.exitCode=e,n6(),r6();let o;try{let e=(async()=>{try{await Bre()}catch{}})();await Promise.race([e,new Promise((e,t)=>{o=setTimeout(e=>e(new ont),2e3,t)})]),clearTimeout(o)}catch{clearTimeout(o)}try{await r(t,{...n,signal:AbortSignal.timeout(a),timeoutMs:a})}catch{}try{aie()}catch{}Zte();try{await Promise.race([Promise.all([mse(),ent()]),Vs(500)])}catch{}if(n?.finalMessage)try{kc(2,`${n.finalMessage}\n`)}catch{}i6(e)}var o6,int,s6,c6,l6,ant,ont,snt=n((()=>{Ve(),d(),re(),H(),Ze(),tnt(),hse(),La(),di(),q(),bn(),g(),_8(),Hs(),oie(),o6=!1,int=u(()=>{te(()=>{}),process.on(`SIGINT`,()=>{process.argv.includes(`-p`)||process.argv.includes(`--print`)||(Cn(`info`,`shutdown_signal`,{signal:`SIGINT`}),a6(0))}),process.on(`SIGTERM`,()=>{Cn(`info`,`shutdown_signal`,{signal:`SIGTERM`}),a6(143)}),process.platform!==`win32`&&(process.on(`SIGHUP`,()=>{Cn(`info`,`shutdown_signal`,{signal:`SIGHUP`}),a6(129)}),process.stdin.isTTY&&(l6=setInterval(()=>{cne()||(!process.stdout.writable||!process.stdin.readable)&&(clearInterval(l6),Cn(`info`,`shutdown_signal`,{signal:`orphan_detected`}),a6(129))},3e4),l6.unref())),process.on(`uncaughtException`,e=>{Cn(`error`,`uncaught_exception`,{error_name:e.name,error_message:e.message.slice(0,2e3)}),e.name}),process.on(`unhandledRejection`,e=>{e instanceof Error&&e.name,Cn(`error`,`unhandled_rejection`,e instanceof Error?{error_name:e.name,error_message:e.message.slice(0,2e3),error_stack:e.stack?.slice(0,4e3)}:{error_message:String(e).slice(0,2e3)})})}),s6=!1,ont=class extends Error{constructor(){super(`Cleanup timeout`)}}})),cnt=i({MAX_TRANSCRIPT_READ_BYTES:()=>c8,adoptResumedSessionFile:()=>Cnt,buildConversationChain:()=>M6,cacheSessionTitle:()=>qnt,checkResumeConsistency:()=>jnt,cleanMessagesForLogging:()=>n8,clearAgentTranscriptSubdir:()=>g6,clearGoalEntry:()=>B6,clearSessionMessagesCache:()=>Y6,clearSessionMetadata:()=>Wnt,doesMessageExistInSession:()=>nrt,enrichLogs:()=>o8,extractAgentIdsFromMessages:()=>crt,fetchLogs:()=>L6,findUnresolvedToolUse:()=>prt,flushSessionStorage:()=>Ent,getAgentTranscript:()=>$6,getAgentTranscriptPath:()=>_6,getCurrentSessionTag:()=>Hnt,getCurrentSessionTitle:()=>V6,getFirstMeaningfulUserMessageTextContent:()=>k6,getLastSessionLog:()=>rrt,getLogByIndex:()=>frt,getNodeEnv:()=>b6,getProjectDir:()=>u8,getProjectsDir:()=>f6,getSessionFilesLite:()=>a8,getSessionFilesWithMtime:()=>r8,getSessionIdFromLog:()=>W6,getSessionMessages:()=>q6,getSessionMessagesCache:()=>J6,getTranscriptPath:()=>p6,getTranscriptPathForSession:()=>m6,getUserType:()=>x6,hydrateFromCCRv2InternalEvents:()=>Dnt,isChainParticipant:()=>d6,isCustomTitleEnabled:()=>mnt,isEphemeralToolProgress:()=>unt,isLiteLog:()=>G6,isLoggableMessage:()=>t8,isTranscriptMessage:()=>u6,linkSessionToPR:()=>Vnt,loadAllLogsFromSessionFile:()=>i8,loadAllProjectsMessageLogs:()=>irt,loadAllProjectsMessageLogsProgressive:()=>Z6,loadAllSubagentTranscriptsFromDisk:()=>lrt,loadFullLog:()=>Ynt,loadMessageLogs:()=>X6,loadSameRepoMessageLogs:()=>ort,loadSameRepoMessageLogsProgressive:()=>Q6,loadSubagentTranscripts:()=>e8,loadTranscriptFile:()=>K6,loadTranscriptFromFile:()=>Mnt,reAppendSessionMetadata:()=>H6,readAgentMetadata:()=>fnt,recordAttributionSnapshot:()=>xnt,recordContentReplacement:()=>D6,recordContextCollapseCommit:()=>wnt,recordContextCollapseSnapshot:()=>Tnt,recordFileHistorySnapshot:()=>E6,recordQueueOperation:()=>T6,recordSidechainTranscript:()=>w6,recordTranscript:()=>C6,removeExtraFields:()=>A6,removeTranscriptMessage:()=>bnt,resetProjectFlushStateForTesting:()=>hnt,resetProjectForTesting:()=>gnt,resetSessionFilePointer:()=>Snt,restoreSessionMetadata:()=>Unt,saveAgentName:()=>Gnt,saveAgentSetting:()=>Knt,saveAiGeneratedTitle:()=>Rnt,saveCustomTitle:()=>Lnt,saveGoal:()=>z6,saveMode:()=>Jnt,saveTag:()=>Bnt,saveTaskSummary:()=>znt,saveWorktreeState:()=>U6,searchSessionsByCustomTitle:()=>Xnt,sessionIdExists:()=>y6,setAgentTranscriptSubdir:()=>h6,setInternalEventReader:()=>ynt,setInternalEventWriter:()=>vnt,setSessionFileForTesting:()=>_nt,writeAgentMetadata:()=>v6});function u6(e){return e.type===`user`||e.type===`assistant`||e.type===`attachment`||e.type===`system`}function d6(e){return e.type!==`progress`}function lnt(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`progress`&&`uuid`in e&&typeof e.uuid==`string`}function unt(e){return typeof e==`string`&&Srt.has(e)}function f6(){return X(m(),`projects`)}function p6(){return X(ei()??u8(ti()),`${Wr()}.jsonl`)}function m6(e){return e===Wr()?p6():X(u8(ti()),`${e}.jsonl`)}function h6(e,t){l8.set(e,t)}function g6(e){l8.delete(e)}function _6(e){let t=ei()??u8(ti()),n=Wr(),r=l8.get(e);return X(r?X(t,n,`subagents`,r):X(t,n,`subagents`),`agent-${e}.jsonl`)}function dnt(e){return _6(e).replace(/\.jsonl$/,`.meta.json`)}async function v6(e,t){let n=dnt(e);await Hc(fc(n),{recursive:!0}),await Qc(n,JSON.stringify(t))}async function fnt(e){let t=dnt(e);try{let e=await Wc(t,`utf-8`);return JSON.parse(e)}catch(e){if(Ri(e))return null;throw e}}function y6(e){let t=X(u8(ti()),`${e}.jsonl`),n=J();try{return n.statSync(t),!0}catch{return!1}}function b6(){return`production`}function x6(){return`external`}function pnt(){return process.env.WORKMATE_ENTRYPOINT}function mnt(){return!0}function S6(){return d8||(d8=new wrt,f8||(Oi(async()=>{await d8?.flush();try{d8?.reAppendSessionMetadata()}catch{}}),f8=!0)),d8}function hnt(){d8?._resetFlushState()}function gnt(){d8=null}function _nt(e){S6().sessionFile=e}function vnt(e){S6().setInternalEventWriter(e)}function ynt(e,t){S6().setInternalEventReader(e),S6().setInternalSubagentEventReader(t)}async function C6(e,t,n,r){let i=n8(e,r),a=await q6(Wr()),o=[],s=n,c=!1;for(let e of i)a.has(e.uuid)?!c&&d6(e)&&(s=e.uuid):(o.push(e),c=!0);return o.length>0&&await S6().insertMessageChain(o,!1,void 0,s,t),o.findLast(d6)?.uuid??s??null}async function w6(e,t,n){await S6().insertMessageChain(n8(e),!0,t,n)}async function T6(e){await S6().insertQueueOperation(e)}async function bnt(e){await S6().removeMessageByUuid(e)}async function E6(e,t,n){await S6().insertFileHistorySnapshot(e,t,n)}async function xnt(e){await S6().insertAttributionSnapshot(e)}async function D6(e,t){await S6().insertContentReplacement(e,t)}async function Snt(){S6().resetSessionFile()}function Cnt(){let e=S6();e.sessionFile=p6(),e.reAppendSessionMetadata(!0)}async function wnt(e){let t=Wr();t&&await S6().appendEntry({type:`marble-origami-commit`,sessionId:t,...e})}async function Tnt(e){let t=Wr();t&&await S6().appendEntry({type:`marble-origami-snapshot`,sessionId:t,...e})}async function Ent(){await S6().flush()}async function Dnt(e){let t=Date.now();sne(Nj(e));let n=S6(),r=n.getInternalEventReader();if(!r)return K(`No internal event reader registered for CCR v2 resume`),!1;try{let i=await r();if(!i)return K(`Failed to read internal events for resume`),Cn(`error`,`hydrate_ccr_v2_read_fail`),!1;await Hc(u8(ti()),{recursive:!0,mode:448}),await Qc(m6(e),i.map(e=>`${W(e.payload)}\n`).join(``),{encoding:`utf8`,mode:384}),K(`Hydrated ${i.length} foreground entries from CCR v2 internal events`);let a=0,o=n.getInternalSubagentEventReader();if(o){let e=await o();if(e&&e.length>0){a=e.length;let t=new Map;for(let n of e){let e=n.agent_id||``;if(!e)continue;let r=t.get(e);r||(r=[],t.set(e,r)),r.push(n.payload)}for(let[e,n]of t){let t=_6(Pj(e));await Hc(fc(t),{recursive:!0,mode:448}),await Qc(t,n.map(e=>`${W(e)}\n`).join(``),{encoding:`utf8`,mode:384})}K(`Hydrated ${e.length} subagent entries across ${t.size} agents`)}}return Cn(`info`,`hydrate_ccr_v2_completed`,{duration_ms:Date.now()-t,event_count:i.length,subagent_event_count:a}),i.length>0}catch(e){if(e instanceof Error&&e.message===`CCRClient: Epoch mismatch (409)`)throw e;return K(`Error hydrating session from CCR v2: ${e}`),Cn(`error`,`hydrate_ccr_v2_fail`),!1}}function O6(e){let t=k6(e);if(t){let e=t.replace(/\n/g,` `).trim();return e.length>200&&(e=`${e.slice(0,200).trim()}…`),e}return`No prompt`}function k6(e){for(let t of e){if(t.type!==`user`||t.isMeta||`isCompactSummary`in t&&t.isCompactSummary)continue;let e=t.message?.content;if(!e)continue;let n=[];if(typeof e==`string`)n.push(e);else if(Array.isArray(e))for(let t of e)t.type===`text`&&t.text&&n.push(t.text);for(let e of n){if(!e)continue;let t=ev(e,ma);if(t){let n=t.replace(/^\//,``);if(Z3().has(n))continue;{let n=ev(e,`command-args`)?.trim();if(!n)continue;return`${t} ${n}`}}let n=ev(e,`bash-input`);if(n)return`! ${n}`;if(!s8.test(e))return e}}}function A6(e){return e.map(e=>{let{isSidechain:t,parentUuid:n,...r}=e;return r})}function Ont(e){let t,n=-1,r=-1,i=new Map,a=0;for(let o of e.values()){if(i.set(o.uuid,a),sv(o)){r=a;let e=o.compactMetadata?.preservedSegment;e&&(t=e,n=a)}a++}if(!t)return;let o=n===r,s=new Set;if(o){let n=new Set,r=e.get(t.tailUuid),i=!1;for(;r&&!n.has(r.uuid);){if(n.add(r.uuid),s.add(r.uuid),r.uuid===t.headUuid){i=!0;break}r=r.parentUuid?e.get(r.parentUuid):void 0}if(!i){e.has(t.tailUuid),e.has(t.headUuid),e.has(t.anchorUuid),n.size,e.size;return}}if(o){let n=e.get(t.headUuid);n&&e.set(t.headUuid,{...n,parentUuid:t.anchorUuid});for(let[n,r]of e)r.parentUuid===t.anchorUuid&&n!==t.headUuid&&e.set(n,{...r,parentUuid:t.tailUuid});for(let t of s){let n=e.get(t);n?.type===`assistant`&&e.set(t,{...n,message:{...n.message,usage:{...n.message.usage,input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0}}})}}let c=[];for(let[t]of e){let e=i.get(t);e!==void 0&&e<r&&!s.has(t)&&c.push(t)}for(let t of c)e.delete(t)}function knt(e){let t=new Set;for(let n of e.values()){let e=n.snipMetadata?.removedUuids;if(e)for(let n of e)t.add(n)}if(t.size===0)return;let n=new Map,r=0;for(let i of t){let t=e.get(i);t&&(n.set(i,t.parentUuid),e.delete(i),r++)}let i=e=>{let r=[],i=e;for(;i&&t.has(i);)if(r.push(i),i=n.get(i),i===void 0){i=null;break}for(let e of r)n.set(e,i);return i},a=0;for(let[n,r]of e)!r.parentUuid||!t.has(r.parentUuid)||(e.set(n,{...r,parentUuid:i(r.parentUuid)}),a++)}function j6(e,t){let n,r=-1/0;for(let i of e){if(!t(i))continue;let e=Date.parse(i.timestamp);e>r&&(r=e,n=i)}return n}function M6(e,t){let n=[],r=new Set,i=t;for(;i;){if(r.has(i.uuid)){Y(Error(`Cycle detected in parentUuid chain at message ${i.uuid}. Returning partial transcript.`));break}r.add(i.uuid),n.push(i),i=i.parentUuid?e.get(i.parentUuid):void 0}return n.reverse(),Ant(e,n,r)}function Ant(e,t,n){let r=t.filter(e=>e.type===`assistant`);if(r.length===0)return t;let i=new Map;for(let e of r)e.message.id&&i.set(e.message.id,e);let a=new Map,o=new Map;for(let t of e.values())if(t.type===`assistant`&&t.message.id){let e=a.get(t.message.id);e?e.push(t):a.set(t.message.id,[t])}else if(t.type===`user`&&t.parentUuid&&Array.isArray(t.message.content)&&t.message.content.some(e=>e.type===`tool_result`)){let e=o.get(t.parentUuid);e?e.push(t):o.set(t.parentUuid,[t])}let s=new Set,c=new Map,l=0;for(let e of r){let t=e.message.id;if(!t||s.has(t))continue;s.add(t);let r=a.get(t)??[e],u=r.filter(e=>!n.has(e.uuid)),d=[];for(let e of r){let t=o.get(e.uuid);if(t)for(let e of t)n.has(e.uuid)||d.push(e)}if(u.length===0&&d.length===0)continue;u.sort((e,t)=>e.timestamp.localeCompare(t.timestamp)),d.sort((e,t)=>e.timestamp.localeCompare(t.timestamp));let f=i.get(t),p=[...u,...d];for(let e of p)n.add(e.uuid);l+=p.length,c.set(f.uuid,p)}if(l===0)return t;let u=[];for(let e of t){u.push(e);let t=c.get(e.uuid);t&&u.push(...t)}return u}function jnt(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.type!==`system`||n.subtype!==`turn_duration`)continue;let r=n.messageCount;if(r===void 0)return;t-r,e.length,e.length-1-t;return}}function N6(e,t){let n=[],r=new Map;for(let i of t){let t=e.get(i.uuid);if(!t)continue;let{snapshot:a,isSnapshotUpdate:o}=t,s=o?r.get(a.messageId):void 0;s===void 0?(r.set(a.messageId,n.length),n.push(a)):n[s]=a}return n}function P6(e,t){return Array.from(e.values())}async function Mnt(e){if(e.endsWith(`.jsonl`)){let{messages:t,summaries:n,customTitles:r,tags:i,fileHistorySnapshots:a,attributionSnapshots:o,contextCollapseCommits:s,contextCollapseSnapshot:c,leafUuids:l,contentReplacements:u,worktreeStates:d}=await K6(e);if(t.size===0)throw Error(`No messages found in JSONL file`);let f=j6(t.values(),e=>l.has(e.uuid));if(!f)throw Error(`No valid conversation chain found in JSONL file`);let p=M6(t,f),m=n.get(f.uuid),h=r.get(f.sessionId),g=i.get(f.sessionId),_=f.sessionId;return{...I6(p,0,m,h,N6(a,p),g,e,P6(o,p),void 0,u.get(_)??[]),contextCollapseCommits:s.filter(e=>e.sessionId===_),contextCollapseSnapshot:c?.sessionId===_?c:void 0,worktreeSession:d.has(_)?d.get(_):void 0}}let t=await Wc(e,{encoding:`utf-8`}),n;try{n=Si(t)}catch(e){throw Error(`Invalid JSON in transcript file: ${e}`)}let r;if(Array.isArray(n))r=n;else if(n&&typeof n==`object`&&`messages`in n){if(!Array.isArray(n.messages))throw Error(`Transcript messages must be an array`);r=n.messages}else throw Error(`Transcript must be an array of messages or an object with a messages array`);return I6(r,0,void 0,void 0,void 0,void 0,e)}function Nnt(e){if(e.type!==`user`||e.isMeta)return!1;let t=e.message?.content;return t?typeof t==`string`?t.trim().length>0:Array.isArray(t)?t.some(e=>e.type===`text`||e.type===`image`||e.type===`document`):!1:!1}function Pnt(e){if(e.type!==`assistant`)return!1;let t=e.message?.content;return!t||!Array.isArray(t)?!1:t.some(e=>e.type===`text`&&typeof e.text==`string`&&e.text.trim().length>0)}function F6(e){let t=0;for(let n of e)switch(n.type){case`user`:Nnt(n)&&t++;break;case`assistant`:Pnt(n)&&t++;break;case`attachment`:case`system`:case`progress`:break}return t}function I6(e,t=0,n,r,i,a,o,s,c,l){let u=e.at(-1),d=e[0],f=O6(e),p=new Date(d.timestamp),m=new Date(u.timestamp);return{date:u.timestamp,messages:A6(e),fullPath:o,value:t,created:p,modified:m,firstPrompt:f,messageCount:F6(e),isSidechain:d.isSidechain,agentName:d.agentName,agentSetting:c,leafUuid:u.uuid,summary:n,customTitle:r,tag:a,fileHistorySnapshots:i,attributionSnapshots:s,contentReplacements:l,gitBranch:u.gitBranch,projectPath:d.cwd}}async function Fnt(e){let t=new Map,n=0;for(let r of e){let e=W6(r);if(e){let r=(t.get(e)||0)+1;t.set(e,r),n=Math.max(r,n)}}if(n<=1)return;let r=Array.from(t.values()).filter(e=>e>1),i=r.length,a=r.reduce((e,t)=>e+t,0);t.size,Math.max(...r),Math.round(a/i),e.length}async function L6(e){let t=await a8(u8(ti()),e,ti());return await Fnt(t),t}function R6(e,t){let n=J(),r=`${W(t)}\n`;try{n.appendFileSync(e,r,{mode:384})}catch{n.mkdirSync(fc(e),{mode:448}),n.appendFileSync(e,r,{mode:384})}}function Int(e){let t;try{t=Pse(e,`r`);let n=Mse(t),r=Math.max(0,n.size-Tn),i=Buffer.allocUnsafe(Math.min(Tn,n.size-r)),a=Fse(t,i,0,i.length,r);return i.toString(`utf8`,0,a)}catch{return``}finally{if(t!==void 0)try{Ose(t)}catch{}}}async function Lnt(e,t,n,r=`user`){R6(n??m6(e),{type:`custom-title`,customTitle:t,sessionId:e}),e===Wr()&&(S6().currentSessionTitle=t)}function Rnt(e,t){R6(m6(e),{type:`ai-title`,aiTitle:t,sessionId:e})}function znt(e,t){R6(m6(e),{type:`task-summary`,summary:t,sessionId:e,timestamp:new Date().toISOString()})}async function Bnt(e,t,n){R6(n??m6(e),{type:`tag`,tag:t,sessionId:e}),e===Wr()&&(S6().currentSessionTag=t)}function z6(e,t,n){R6(n??m6(e),{type:`goal`,sessionId:e,state:t,timestamp:new Date().toISOString()}),e===Wr()&&(S6().currentSessionGoal=t)}function B6(e,t){R6(t??m6(e),{type:`goal-cleared`,sessionId:e,timestamp:new Date().toISOString()}),e===Wr()&&(S6().currentSessionGoal=void 0)}async function Vnt(e,t,n,r,i){if(R6(i??m6(e),{type:`pr-link`,sessionId:e,prNumber:t,prUrl:n,prRepository:r,timestamp:new Date().toISOString()}),e===Wr()){let e=S6();e.currentSessionPrNumber=t,e.currentSessionPrUrl=n,e.currentSessionPrRepository=r}}function Hnt(e){if(e===Wr())return S6().currentSessionTag}function V6(e){if(e===Wr())return S6().currentSessionTitle}function Unt(e){let t=S6();e.customTitle&&(t.currentSessionTitle??(t.currentSessionTitle=e.customTitle)),e.tag!==void 0&&(t.currentSessionTag=e.tag||void 0),e.agentName&&(t.currentSessionAgentName=e.agentName),e.agentColor&&(t.currentSessionAgentColor=e.agentColor),e.agentSetting&&(t.currentSessionAgentSetting=e.agentSetting),e.mode&&(t.currentSessionMode=e.mode),e.worktreeSession!==void 0&&(t.currentSessionWorktree=e.worktreeSession),e.prNumber!==void 0&&(t.currentSessionPrNumber=e.prNumber),e.prUrl&&(t.currentSessionPrUrl=e.prUrl),e.prRepository&&(t.currentSessionPrRepository=e.prRepository),e.goal&&(t.currentSessionGoal=e.goal)}function Wnt(){let e=S6();e.currentSessionTitle=void 0,e.currentSessionTag=void 0,e.currentSessionAgentName=void 0,e.currentSessionAgentColor=void 0,e.currentSessionLastPrompt=void 0,e.currentSessionAgentSetting=void 0,e.currentSessionMode=void 0,e.currentSessionGoal=void 0,e.currentSessionWorktree=void 0,e.currentSessionPrNumber=void 0,e.currentSessionPrUrl=void 0,e.currentSessionPrRepository=void 0}function H6(){S6().reAppendSessionMetadata()}async function Gnt(e,t,n,r=`user`){R6(n??m6(e),{type:`agent-name`,agentName:t,sessionId:e}),e===Wr()&&(S6().currentSessionAgentName=t,z4e(t))}function Knt(e){S6().currentSessionAgentSetting=e}function qnt(e){S6().currentSessionTitle=e}function Jnt(e){S6().currentSessionMode=e}function U6(e){let t=e?{originalCwd:e.originalCwd,worktreePath:e.worktreePath,worktreeName:e.worktreeName,worktreeBranch:e.worktreeBranch,originalBranch:e.originalBranch,originalHeadCommit:e.originalHeadCommit,sessionId:e.sessionId,tmuxSessionName:e.tmuxSessionName,hookBased:e.hookBased}:null,n=S6();n.currentSessionWorktree=t,n.sessionFile&&R6(n.sessionFile,{type:`worktree-state`,worktreeSession:t,sessionId:Wr()})}function W6(e){return e.sessionId?e.sessionId:e.messages[0]?.sessionId}function G6(e){return e.messages.length===0&&e.sessionId!==void 0}async function Ynt(e){if(!G6(e))return e;let t=e.fullPath;if(!t)return e;try{let{messages:n,summaries:r,customTitles:i,tags:a,agentNames:o,agentColors:s,agentSettings:c,prNumbers:l,prUrls:u,prRepositories:d,modes:f,worktreeStates:p,goals:m,fileHistorySnapshots:h,attributionSnapshots:g,contentReplacements:_,contextCollapseCommits:v,contextCollapseSnapshot:y,leafUuids:b}=await K6(t);if(n.size===0){let t=e.sessionId?m.get(e.sessionId):void 0;return t?{...e,goal:t}:e}let x=j6(n.values(),e=>b.has(e.uuid)&&(e.type===`user`||e.type===`assistant`));if(!x){let t=e.sessionId?m.get(e.sessionId):void 0;return t?{...e,goal:t}:e}let S=M6(n,x),C=x.sessionId;return{...e,messages:A6(S),firstPrompt:O6(S),messageCount:F6(S),summary:x?r.get(x.uuid):e.summary,customTitle:C?i.get(C):e.customTitle,tag:C?a.get(C):e.tag,agentName:C?o.get(C):e.agentName,agentColor:C?s.get(C):e.agentColor,agentSetting:C?c.get(C):e.agentSetting,mode:C?f.get(C):e.mode,worktreeSession:C&&p.has(C)?p.get(C):e.worktreeSession,goal:C?m.get(C):e.goal,prNumber:C?l.get(C):e.prNumber,prUrl:C?u.get(C):e.prUrl,prRepository:C?d.get(C):e.prRepository,gitBranch:x?.gitBranch??e.gitBranch,isSidechain:S[0]?.isSidechain??e.isSidechain,leafUuid:x?.uuid??e.leafUuid,fileHistorySnapshots:N6(h,S),attributionSnapshots:P6(g,S),contentReplacements:C?_.get(C)??[]:e.contentReplacements,contextCollapseCommits:C?v.filter(e=>e.sessionId===C):void 0,contextCollapseSnapshot:C&&y?.sessionId===C?y:void 0}}catch{return e}}async function Xnt(e,t){let{limit:n,exact:r}=t||{},i=await srt(await Qtt(ti())),{logs:a}=await o8(i,0,i.length),o=e.toLowerCase().trim(),s=a.filter(e=>{let t=e.customTitle?.toLowerCase().trim();return t?r?t===o:t.includes(o):!1}),c=new Map;for(let e of s){let t=W6(e);if(t){let n=c.get(t);(!n||e.modified>n.modified)&&c.set(t,e)}}let l=Array.from(c.values());return l.sort((e,t)=>t.modified.getTime()-e.modified.getTime()),n?l.slice(0,n):l}function Znt(e,t){if(e===null||e.length===0)return t;if(e.length<Trt)return Buffer.concat([e,t]);if(e[0]===123){for(let n of m8)if(e.compare(n,0,n.length,1,1+n.length)===0)return Buffer.concat([e,t])}let n=t.indexOf(10);return n===-1?null:t.subarray(n+1)}async function Qnt(e,t){let{createReadStream:n}=await import(`fs`),r=n(e,{end:t-1}),i=[],a=null;for await(let e of r){let t=Znt(a,e);if(t===null){a=null;continue}let n=!1;for(let e of m8)if(t.includes(e)){n=!0;break}if(n){let e=0,n=t.indexOf(10);for(;n!==-1;){for(let r of m8){let a=t.indexOf(r,e);if(a!==-1&&a<n){i.push(t.toString(`utf-8`,e,n));break}}e=n+1,n=t.indexOf(10,e)}a=t.subarray(e)}else{let e=t.lastIndexOf(10);a=e>=0?t.subarray(e+1):t}a.length>64*1024&&(a=null)}if(a!==null&&a.length>0){for(let e of m8)if(a.includes(e)){i.push(a.toString(`utf-8`));break}}return i}function $nt(e,t,n){let r=0,i=!1,a=!1,o=0;for(let s=t;o<n.length;s++){if(s===n[o]){if(r===1&&!i)return n[o];o++}let t=e[s];a?a=!1:i?t===92?a=!0:t===34&&(i=!1):t===34?i=!0:t===123?r++:t===125&&r--}return n.at(-1)}function ert(e){let t=Buffer.from(`{"parentUuid":`),n=Buffer.from(`"uuid":"`),r=Buffer.from(`"isSidechain":true`),i=Buffer.from(`","timestamp":"`),a=i.length,o=t.length,s=n.length,c=[],l=[],u=new Map,d=0,f=e.length;for(;d<f;){let r=e.indexOf(10,d),p=r===-1?f:r+1;if(p-d>o&&e[d]===123&&e.compare(t,0,o,d,d+o)===0){let t=e[d+o]===34?d+o+1:-1,r=-1,f=-1,m,h=d;for(;;){let t=e.indexOf(n,h);if(t<0||t>=p)break;r<0&&(r=t);let o=t+s+36;o+a<=p&&e.compare(i,0,a,o,o+a)===0&&(f<0?f=t:(m??(m=[f])).push(t)),h=t+s}let g=m?$nt(e,d,m):f>=0?f:r;if(g>=0){let n=g+s,r=e.toString(`latin1`,n,n+36);u.set(r,c.length),c.push(d,p,t)}else l.push(d,p)}else l.push(d,p);d=p}let p=-1;for(let t=c.length-3;t>=0;t-=3){let n=e.indexOf(r,c[t]);if(n===-1||n>=c[t+1]){p=t;break}}if(p<0)return e;let m=new Set,h=new Set,g=0,_=p;for(;_!==void 0&&!m.has(_);){m.add(_),h.add(c[_]),g+=c[_+1]-c[_];let t=c[_+2];if(t<0)break;let n=e.toString(`latin1`,t,t+36);_=u.get(n)}if(f-g<f>>1)return e;let v=[],y=0;for(let t=0;t<c.length;t+=3){let n=c[t];for(;y<l.length&&l[y]<n;)v.push(e.subarray(l[y],l[y+1])),y+=2;h.has(n)&&v.push(e.subarray(n,c[t+1]))}for(;y<l.length;)v.push(e.subarray(l[y],l[y+1])),y+=2;return Buffer.concat(v)}async function K6(e,t){let n=new Map,r=new Map,i=new Map,a=new Map,o=new Map,s=new Map,c=new Map,l=new Map,u=new Map,d=new Map,f=new Map,p=new Map,m=new Map,g=new Map,_=new Map,v=new Map,y=new Map,b=[],x;try{let S=null,C=null,w=!1;if(!h(process.env.WORKMATE_DISABLE_PRECOMPACT_SKIP)){let{size:t}=await Yc(e);if(t>5242880){let n=await Pee(e,t);S=n.postBoundaryBuf,w=n.hasPreservedSegment,n.boundaryStartOffset>0&&(C=await Qnt(e,n.boundaryStartOffset))}}if(S??(S=await Wc(e)),!t?.keepAllLeaves&&!w&&!h(process.env.WORKMATE_DISABLE_PRECOMPACT_SKIP)&&S.length>5242880&&(S=ert(S)),C&&C.length>0){let e=vr(Buffer.from(C.join(`
3060
3060
  `)));for(let t of e)t.type===`summary`&&t.leafUuid?r.set(t.leafUuid,t.summary):t.type===`custom-title`&&t.sessionId?i.set(t.sessionId,t.customTitle):t.type===`tag`&&t.sessionId?a.set(t.sessionId,t.tag):t.type===`agent-name`&&t.sessionId?o.set(t.sessionId,t.agentName):t.type===`agent-color`&&t.sessionId?s.set(t.sessionId,t.agentColor):t.type===`agent-setting`&&t.sessionId?c.set(t.sessionId,t.agentSetting):t.type===`mode`&&t.sessionId?f.set(t.sessionId,t.mode):t.type===`worktree-state`&&t.sessionId?p.set(t.sessionId,t.worktreeSession):t.type===`goal`&&t.sessionId?m.set(t.sessionId,t.state):t.type===`goal-cleared`&&t.sessionId?m.delete(t.sessionId):t.type===`pr-link`&&t.sessionId&&(l.set(t.sessionId,t.prNumber),u.set(t.sessionId,t.prUrl),d.set(t.sessionId,t.prRepository))}let T=vr(S),E=new Map;for(let e of T){if(lnt(e)){let t=e.parentUuid;E.set(e.uuid,t&&E.has(t)?E.get(t)??null:t);continue}if(u6(e))e.parentUuid&&E.has(e.parentUuid)&&(e.parentUuid=E.get(e.parentUuid)??null),n.set(e.uuid,e),sv(e)&&(b.length=0,x=void 0);else if(e.type===`summary`&&e.leafUuid)r.set(e.leafUuid,e.summary);else if(e.type===`custom-title`&&e.sessionId)i.set(e.sessionId,e.customTitle);else if(e.type===`tag`&&e.sessionId)a.set(e.sessionId,e.tag);else if(e.type===`agent-name`&&e.sessionId)o.set(e.sessionId,e.agentName);else if(e.type===`agent-color`&&e.sessionId)s.set(e.sessionId,e.agentColor);else if(e.type===`agent-setting`&&e.sessionId)c.set(e.sessionId,e.agentSetting);else if(e.type===`mode`&&e.sessionId)f.set(e.sessionId,e.mode);else if(e.type===`worktree-state`&&e.sessionId)p.set(e.sessionId,e.worktreeSession);else if(e.type===`goal`&&e.sessionId)m.set(e.sessionId,e.state);else if(e.type===`goal-cleared`&&e.sessionId)m.delete(e.sessionId);else if(e.type===`pr-link`&&e.sessionId)l.set(e.sessionId,e.prNumber),u.set(e.sessionId,e.prUrl),d.set(e.sessionId,e.prRepository);else if(e.type===`file-history-snapshot`)g.set(e.messageId,e);else if(e.type===`attribution-snapshot`)_.set(e.messageId,e);else if(e.type===`content-replacement`)if(e.agentId){let t=y.get(e.agentId)??[];y.set(e.agentId,t),t.push(...e.replacements)}else{let t=v.get(e.sessionId)??[];v.set(e.sessionId,t),t.push(...e.replacements)}else e.type===`marble-origami-commit`?b.push(e):e.type===`marble-origami-snapshot`&&(x=e)}}catch{}Ont(n),knt(n);let S=[...n.values()],C=new Set(S.map(e=>e.parentUuid).filter(e=>e!==null)),w=S.filter(e=>!C.has(e.uuid)),T=new Set;for(let e of w){let t=new Set,r=e;for(;r&&!t.has(r.uuid);){if(t.add(r.uuid),r.type===`user`||r.type===`assistant`){T.add(r.uuid);break}r=r.parentUuid?n.get(r.parentUuid):void 0}}return{messages:n,summaries:r,customTitles:i,tags:a,agentNames:o,agentColors:s,agentSettings:c,prNumbers:l,prUrls:u,prRepositories:d,modes:f,worktreeStates:p,goals:m,fileHistorySnapshots:g,attributionSnapshots:_,contentReplacements:v,agentContentReplacements:y,contextCollapseCommits:b,contextCollapseSnapshot:x,leafUuids:T}}async function trt(e){return K6(X(ei()??u8(ti()),`${e}.jsonl`))}async function q6(e){let t=h8.get(e);if(t!==void 0)return t;if(h8.size>=p8){let e=h8.keys().next().value;e!==void 0&&h8.delete(e)}let n=(async()=>{let{messages:t}=await trt(e);return new Set(t.keys())})();return h8.set(e,n),n}function J6(){return h8}function Y6(){h8.clear()}async function nrt(e,t){return(await q6(e)).has(t)}async function rrt(e){let{messages:t,summaries:n,customTitles:r,tags:i,agentSettings:a,worktreeStates:o,fileHistorySnapshots:s,attributionSnapshots:c,contentReplacements:l,goals:u,contextCollapseCommits:d,contextCollapseSnapshot:f}=await trt(e);if(t.size===0)return null;let p=J6();p.has(e)||p.set(e,Promise.resolve(new Set(t.keys())));let m=j6(t.values(),e=>!e.isSidechain);if(!m)return null;let h=M6(t,m),g=n.get(m.uuid),_=r.get(m.sessionId),v=i.get(m.sessionId),y=a.get(e);return{...I6(h,0,g,_,N6(s,h),v,m6(e),P6(c,h),y,l.get(e)??[]),worktreeSession:o.get(e),goal:u.get(e),contextCollapseCommits:d.filter(t=>t.sessionId===e),contextCollapseSnapshot:f?.sessionId===e?f:void 0}}async function X6(e){let t=await L6(e),{logs:n}=await o8(t,0,t.length),r=Nl(n);return r.forEach((e,t)=>{e.value=t}),r}async function irt(e,t){return t?.skipIndex?art(e):(await Z6(e,t?.initialEnrichCount??g8)).logs}async function art(e){let t=f6(),n;try{n=await Gc(t,{withFileTypes:!0})}catch{return[]}let r=n.filter(e=>e.isDirectory()).map(e=>X(t,e.name)),i=(await Promise.all(r.map(t=>mrt(t,e)))).flat(),a=new Map;for(let e of i){let t=`${e.sessionId??``}:${e.leafUuid??``}`,n=a.get(t);(!n||e.modified.getTime()>n.modified.getTime())&&a.set(t,e)}let o=Nl([...a.values()]);return o.forEach((e,t)=>{e.value=t}),o}async function Z6(e,t=g8){let n=f6(),r;try{r=await Gc(n,{withFileTypes:!0})}catch{return{logs:[],allStatLogs:[],nextIndex:0}}let i=r.filter(e=>e.isDirectory()).map(e=>X(n,e.name)),a=[];for(let t of i)a.push(...await a8(t,e));let o=vrt(a),{logs:s,nextIndex:c}=await o8(o,0,t);return s.forEach((e,t)=>{e.value=t}),{logs:s,allStatLogs:o,nextIndex:c}}async function ort(e,t,n=g8){return(await Q6(e,t,n)).logs}async function Q6(e,t,n=g8){K(`/resume: loading sessions for cwd=${ti()}, worktrees=[${e.join(`, `)}]`);let r=await srt(e,t);K(`/resume: found ${r.length} session files on disk`);let{logs:i,nextIndex:a}=await o8(r,0,n);return i.forEach((e,t)=>{e.value=t}),{logs:i,allStatLogs:r,nextIndex:a}}async function srt(e,t){let n=f6();if(e.length<=1){let e=ti();return a8(u8(e),void 0,e)}let r=process.platform===`win32`,i=e.map(e=>{let t=at(e);return{path:e,prefix:r?t.toLowerCase():t}});i.sort((e,t)=>t.prefix.length-e.prefix.length);let a=[],o=new Set,s;try{s=await Gc(n,{withFileTypes:!0})}catch(e){return K(`Failed to read projects dir ${n}, falling back to current project: ${e}`),a8(u8(ti()),t,ti())}for(let e of s){if(!e.isDirectory())continue;let t=r?e.name.toLowerCase():e.name;if(!o.has(t)){for(let{path:r,prefix:s}of i)if(t===s||t.startsWith(`${s}-`)){o.add(t),a.push(...await a8(X(n,e.name),void 0,r));break}}}return vrt(a)}async function $6(e){let t=_6(e);try{let{messages:n,agentContentReplacements:r}=await K6(t),i=Array.from(n.values()).filter(t=>t.agentId===e&&t.isSidechain);if(i.length===0)return null;let a=new Set(i.map(e=>e.parentUuid)),o=j6(i,e=>!a.has(e.uuid));return o?{messages:M6(n,o).filter(t=>t.agentId===e).map(({isSidechain:e,parentUuid:t,...n})=>n),contentReplacements:r.get(e)??[]}:null}catch{return null}}function crt(e){let t=[];for(let n of e)n.type===`progress`&&n.data&&typeof n.data==`object`&&`type`in n.data&&(n.data.type===`agent_progress`||n.data.type===`skill_progress`)&&`agentId`in n.data&&typeof n.data.agentId==`string`&&t.push(n.data.agentId);return ar(t)}async function e8(e){let t=await Promise.all(e.map(async e=>{try{let t=await $6(Pj(e));return t&&t.messages.length>0?{agentId:e,transcript:t.messages}:null}catch{return null}})),n={};for(let e of t)e&&(n[e.agentId]=e.transcript);return n}async function lrt(){let e=X(ei()??u8(ti()),Wr(),`subagents`),t;try{t=await Gc(e,{withFileTypes:!0})}catch{return{}}return e8(t.filter(e=>e.isFile()&&e.name.startsWith(`agent-`)&&e.name.endsWith(`.jsonl`)).map(e=>e.name.slice(6,-6)))}function t8(e){return e.type===`progress`?!1:e.type===`attachment`&&x6()!==`ant`?!!(e.attachment.type===`hook_additional_context`&&h(process.env.WORKMATE_SAVE_HOOK_ADDITIONAL_CONTEXT)):!0}function urt(e){let t=new Set;for(let n of e)if(n.type===`assistant`&&Array.isArray(n.message.content))for(let e of n.message.content)e.type===`tool_use`&&e.name===`REPL`&&t.add(e.id);return t}function drt(e,t){return e.flatMap(e=>{if(e.type===`assistant`&&Array.isArray(e.message.content)){let t=e.message.content,n=t.some(e=>e.type===`tool_use`&&e.name===`REPL`)?t.filter(e=>!(e.type===`tool_use`&&e.name===`REPL`)):t;if(n.length===0)return[];if(e.isVirtual){let{isVirtual:t,...r}=e;return[{...r,message:{...e.message,content:n}}]}return n===t?[e]:[{...e,message:{...e.message,content:n}}]}if(e.type===`user`&&Array.isArray(e.message.content)){let n=e.message.content,r=n.some(e=>e.type===`tool_result`&&t.has(e.tool_use_id))?n.filter(e=>!(e.type===`tool_result`&&t.has(e.tool_use_id))):n;if(r.length===0)return[];if(e.isVirtual){let{isVirtual:t,...n}=e;return[{...n,message:{...e.message,content:r}}]}return r===n?[e]:[{...e,message:{...e.message,content:r}}]}if(`isVirtual`in e&&e.isVirtual){let{isVirtual:t,...n}=e;return[n]}return[e]})}function n8(e,t=e){let n=e.filter(t8);return x6()===`ant`?n:drt(n,urt(t))}async function frt(e){return(await X6())[e]||null}async function prt(e){try{let{messages:t}=await K6(p6()),n=null;for(let r of t.values())if(r.type===`assistant`){let t=r.message.content;if(Array.isArray(t)){for(let i of t)if(i.type===`tool_use`&&i.id===e){n=r;break}}}else if(r.type===`user`){let t=r.message.content;if(Array.isArray(t)){for(let n of t)if(n.type===`tool_result`&&n.tool_use_id===e)return null}}return n}catch{return null}}async function r8(e){let t=new Map,n;try{n=await Gc(e,{withFileTypes:!0})}catch{return t}let r=[];for(let t of n){if(!t.isFile()||!t.name.endsWith(`.jsonl`))continue;let n=qH(dc(t.name,`.jsonl`));n&&r.push({sessionId:n,filePath:X(e,t.name)})}return await Promise.all(r.map(async({sessionId:e,filePath:n})=>{try{let r=await Yc(n);t.set(e,{path:n,mtime:r.mtime.getTime(),ctime:r.birthtime.getTime(),size:r.size})}catch{K(`Failed to stat session file: ${n}`)}})),t}async function i8(e,t){let{messages:n,summaries:r,customTitles:i,tags:a,agentNames:o,agentColors:s,agentSettings:c,prNumbers:l,prUrls:u,prRepositories:d,modes:f,fileHistorySnapshots:p,attributionSnapshots:m,contentReplacements:h,leafUuids:g}=await K6(e,{keepAllLeaves:!0});if(n.size===0)return[];let _=[],v=new Map;for(let e of n.values())if(g.has(e.uuid))_.push(e);else if(e.parentUuid){let t=v.get(e.parentUuid);t?t.push(e):v.set(e.parentUuid,[e])}let y=[];for(let g of _){let _=M6(n,g);if(_.length===0)continue;let b=v.get(g.uuid);b&&(b.sort((e,t)=>e.timestamp<t.timestamp?-1:+(e.timestamp>t.timestamp)),_.push(...b));let x=_[0],S=g.sessionId;y.push({date:g.timestamp,messages:A6(_),fullPath:e,value:0,created:new Date(x.timestamp),modified:new Date(g.timestamp),firstPrompt:O6(_),messageCount:F6(_),isSidechain:x.isSidechain??!1,sessionId:S,leafUuid:g.uuid,summary:r.get(g.uuid),customTitle:i.get(S),tag:a.get(S),agentName:o.get(S),agentColor:s.get(S),agentSetting:c.get(S),mode:f.get(S),prNumber:l.get(S),prUrl:u.get(S),prRepository:d.get(S),gitBranch:g.gitBranch,projectPath:t??x.cwd,fileHistorySnapshots:N6(p,_),attributionSnapshots:P6(m,_),contentReplacements:h.get(S)??[]})}return y}async function mrt(e,t){let n=await r8(e);if(n.size===0)return[];let r;r=t&&n.size>t?[...n.values()].sort((e,t)=>t.mtime-e.mtime).slice(0,t):[...n.values()];let i=[];for(let e of r)try{let t=await i8(e.path);i.push(...t)}catch{K(`Failed to load session file: ${e.path}`)}return i}async function hrt(e,t,n){let{head:r,tail:i}=await xee(e,t,n);if(!r)return{firstPrompt:``,isSidechain:!1};let a=r.includes(`"isSidechain":true`)||r.includes(`"isSidechain": true`),o=hn(r,`cwd`),s=hn(r,`agentSetting`),c=mr(i,`lastPrompt`)||grt(r)||_rt(r,`content`,200)||_rt(r,`text`,200)||``,l=mr(i,`customTitle`)??mr(r,`customTitle`)??mr(i,`aiTitle`)??mr(r,`aiTitle`),u=mr(i,`summary`),d=mr(i,`tag`),f=mr(i,`gitBranch`)??hn(r,`gitBranch`),p=mr(i,`prUrl`),m=mr(i,`prRepository`),h,g=mr(i,`prNumber`);if(g&&(h=parseInt(g,10)||void 0),!h){let e=i.lastIndexOf(`"prNumber":`);if(e>=0){let t=i.slice(e+11,e+25),n=parseInt(t.trim(),10);n>0&&(h=n)}}return{firstPrompt:c,gitBranch:f,isSidechain:a,projectPath:o,customTitle:l,summary:u,tag:d,agentSetting:s,prNumber:h,prUrl:p,prRepository:m}}function grt(e){let t=0,n=!1,r=``;for(;t<e.length;){let i=e.indexOf(`
3061
- `,t),a=i>=0?e.slice(t,i):e.slice(t);if(t=i>=0?i+1:e.length,!(!a.includes(`"type":"user"`)&&!a.includes(`"type": "user"`))&&!a.includes(`"tool_result"`)&&!(a.includes(`"isMeta":true`)||a.includes(`"isMeta": true`)))try{let e=Si(a);if(e.type!==`user`)continue;let t=e.message;if(!t)continue;let i=t.content,o=[];if(typeof i==`string`)o.push(i);else if(Array.isArray(i))for(let e of i){let t=e;t.type===`text`&&typeof t.text==`string`&&o.push(t.text)}for(let e of o){if(!e)continue;let t=e.replace(/\n/g,` `).trim(),i=ev(t,ma);if(i){let e=i.replace(/^\//,``),n=ev(t,`command-args`)?.trim()||``;if(Z3().has(e)||!n){r||(r=i);continue}return n?`${i} ${n}`:i}let a=ev(t,`bash-input`);if(a)return`! ${a}`;if(s8.test(t)){t.startsWith(`<tick>`)&&(n=!0);continue}return t.length>200&&(t=`${t.slice(0,200).trim()}…`),t}}catch{}}return r||(n?`Proactive session`:``)}function _rt(e,t,n){let r=[`"${t}":"`,`"${t}": "`];for(let t of r){let r=e.indexOf(t);if(r<0)continue;let i=r+t.length,a=i,o=0;for(;a<e.length&&o<n;){if(e[a]===`\\`){a+=2,o++;continue}if(e[a]===`"`)break;a++,o++}return e.slice(i,a).replace(/\\n/g,` `).replace(/\\t/g,` `).trim()}return``}function vrt(e){let t=new Map;for(let n of e){if(!n.sessionId)continue;let e=t.get(n.sessionId);(!e||n.modified.getTime()>e.modified.getTime())&&t.set(n.sessionId,n)}return Nl([...t.values()]).map((e,t)=>({...e,value:t}))}async function a8(e,t,n){let r=[...(await r8(e)).entries()].sort((e,t)=>t[1].mtime-e[1].mtime);t&&r.length>t&&(r=r.slice(0,t));let i=[];for(let[e,t]of r)i.push({date:new Date(t.mtime).toISOString(),messages:[],isLite:!0,fullPath:t.path,value:0,created:new Date(t.ctime),modified:new Date(t.mtime),firstPrompt:``,messageCount:0,fileSize:t.size,isSidechain:!1,sessionId:e,projectPath:n});let a=Nl(i);return a.forEach((e,t)=>{e.value=t}),a}async function yrt(e,t){if(!e.isLite||!e.fullPath)return e;let n=await hrt(e.fullPath,e.fileSize??0,t),r={...e,isLite:!1,firstPrompt:n.firstPrompt,gitBranch:n.gitBranch,isSidechain:n.isSidechain,customTitle:n.customTitle,summary:n.summary,tag:n.tag,agentSetting:n.agentSetting,prNumber:n.prNumber,prUrl:n.prUrl,prRepository:n.prRepository,projectPath:n.projectPath??e.projectPath};return!r.firstPrompt&&!r.customTitle&&(r.firstPrompt=`(session)`),r.isSidechain?(K(`Session ${e.sessionId} filtered from /resume: isSidechain=true`),null):r}async function o8(e,t,n){let r=[],i=Buffer.alloc(Tn),a=t;for(;a<e.length&&r.length<n;){let t=e[a];a++;let n=await yrt(t,i);n&&r.push(n)}let o=a-t,s=o-r.length;return s>0&&K(`/resume: enriched ${o} sessions, ${s} filtered out, ${r.length} visible (${e.length-a} remaining on disk)`),{logs:r,nextIndex:a}}var brt,xrt,s8,Srt,c8,l8,u8,d8,f8,Crt,p8,wrt,m8,Trt,h8,g8,_8=n((()=>{d(),La(),H(),t6(),Ta(),WX(),Fj(),qle(),tt(),di(),Q1(),ui(),q(),bn(),g(),gi(),Ra(),ki(),$tt(),Et(),snt(),ur(),wa(),v3(),Wn(),Ut(),Ln(),Li(),XH(),b(),brt=typeof MACRO<`u`?`0.0.32`:`unknown`,xrt=50*1024*1024,s8=/^(?:\s*<[a-z][\w-]*[\s>]|\[Request interrupted by user[^\]]*\])/,Srt=new Set([`bash_progress`,`powershell_progress`,`mcp_progress`,`sleep_progress`]),c8=50*1024*1024,l8=new Map,u8=u(e=>X(f6(),at(e))),d8=null,f8=!1,Crt=10,p8=200,wrt=class{constructor(){x(this,`currentSessionTag`,void 0),x(this,`currentSessionTitle`,void 0),x(this,`currentSessionAgentName`,void 0),x(this,`currentSessionAgentColor`,void 0),x(this,`currentSessionLastPrompt`,void 0),x(this,`currentSessionAgentSetting`,void 0),x(this,`currentSessionMode`,void 0),x(this,`currentSessionGoal`,void 0),x(this,`currentSessionWorktree`,void 0),x(this,`currentSessionPrNumber`,void 0),x(this,`currentSessionPrUrl`,void 0),x(this,`currentSessionPrRepository`,void 0),x(this,`sessionFile`,null),x(this,`pendingEntries`,[]),x(this,`internalEventWriter`,null),x(this,`internalEventReader`,null),x(this,`internalSubagentEventReader`,null),x(this,`pendingWriteCount`,0),x(this,`flushResolvers`,[]),x(this,`writeQueues`,new Map),x(this,`flushTimer`,null),x(this,`activeDrain`,null),x(this,`FLUSH_INTERVAL_MS`,100),x(this,`MAX_CHUNK_BYTES`,100*1024*1024),x(this,`existingSessionFiles`,new Map)}_resetFlushState(){this.pendingWriteCount=0,this.flushResolvers=[],this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=null,this.activeDrain=null,this.writeQueues=new Map,this.existingSessionFiles=new Map}incrementPendingWrites(){this.pendingWriteCount++}decrementPendingWrites(){if(this.pendingWriteCount--,this.pendingWriteCount===0){for(let e of this.flushResolvers)e();this.flushResolvers=[]}}async trackWrite(e){this.incrementPendingWrites();try{return await e()}finally{this.decrementPendingWrites()}}enqueueWrite(e,t){return new Promise(n=>{let r=this.writeQueues.get(e);if(r||(r=[],this.writeQueues.set(e,r)),r.length>=1e3){let e=r.splice(0,r.length-999);for(let t of e)t.resolve()}r.push({entry:t,resolve:n}),this.scheduleDrain()})}scheduleDrain(){this.flushTimer||(this.flushTimer=setTimeout(async()=>{this.flushTimer=null,this.activeDrain=this.drainWriteQueue(),await this.activeDrain,this.activeDrain=null,this.writeQueues.size>0&&this.scheduleDrain()},this.FLUSH_INTERVAL_MS))}async appendToFile(e,t){try{await Rc(e,t,{mode:384})}catch{await Hc(fc(e),{recursive:!0,mode:448}),await Rc(e,t,{mode:384})}}async drainWriteQueue(){for(let[e,t]of this.writeQueues){if(t.length===0)continue;let n=t.splice(0),r=``,i=[];for(let{entry:t,resolve:a}of n){let n=`${W(t)}\n`;if(r.length+n.length>=this.MAX_CHUNK_BYTES){await this.appendToFile(e,r);for(let e of i)e();i.length=0,r=``}r+=n,i.push(a)}if(r.length>0){await this.appendToFile(e,r);for(let e of i)e()}}for(let[e,t]of this.writeQueues)t.length===0&&this.writeQueues.delete(e)}resetSessionFile(){this.sessionFile=null,this.pendingEntries=[]}reAppendSessionMetadata(e=!1){if(!this.sessionFile)return;let t=Wr();if(!t)return;let n=Int(this.sessionFile).split(`
3061
+ `,t),a=i>=0?e.slice(t,i):e.slice(t);if(t=i>=0?i+1:e.length,!(!a.includes(`"type":"user"`)&&!a.includes(`"type": "user"`))&&!a.includes(`"tool_result"`)&&!(a.includes(`"isMeta":true`)||a.includes(`"isMeta": true`)))try{let e=Si(a);if(e.type!==`user`)continue;let t=e.message;if(!t)continue;let i=t.content,o=[];if(typeof i==`string`)o.push(i);else if(Array.isArray(i))for(let e of i){let t=e;t.type===`text`&&typeof t.text==`string`&&o.push(t.text)}for(let e of o){if(!e)continue;let t=e.replace(/\n/g,` `).trim(),i=ev(t,ma);if(i){let e=i.replace(/^\//,``),n=ev(t,`command-args`)?.trim()||``;if(Z3().has(e)||!n){r||(r=i);continue}return n?`${i} ${n}`:i}let a=ev(t,`bash-input`);if(a)return`! ${a}`;if(s8.test(t)){t.startsWith(`<tick>`)&&(n=!0);continue}return t.length>200&&(t=`${t.slice(0,200).trim()}…`),t}}catch{}}return r||(n?`Proactive session`:``)}function _rt(e,t,n){let r=[`"${t}":"`,`"${t}": "`];for(let t of r){let r=e.indexOf(t);if(r<0)continue;let i=r+t.length,a=i,o=0;for(;a<e.length&&o<n;){if(e[a]===`\\`){a+=2,o++;continue}if(e[a]===`"`)break;a++,o++}return e.slice(i,a).replace(/\\n/g,` `).replace(/\\t/g,` `).trim()}return``}function vrt(e){let t=new Map;for(let n of e){if(!n.sessionId)continue;let e=t.get(n.sessionId);(!e||n.modified.getTime()>e.modified.getTime())&&t.set(n.sessionId,n)}return Nl([...t.values()]).map((e,t)=>({...e,value:t}))}async function a8(e,t,n){let r=[...(await r8(e)).entries()].sort((e,t)=>t[1].mtime-e[1].mtime);t&&r.length>t&&(r=r.slice(0,t));let i=[];for(let[e,t]of r)i.push({date:new Date(t.mtime).toISOString(),messages:[],isLite:!0,fullPath:t.path,value:0,created:new Date(t.ctime),modified:new Date(t.mtime),firstPrompt:``,messageCount:0,fileSize:t.size,isSidechain:!1,sessionId:e,projectPath:n});let a=Nl(i);return a.forEach((e,t)=>{e.value=t}),a}async function yrt(e,t){if(!e.isLite||!e.fullPath)return e;let n=await hrt(e.fullPath,e.fileSize??0,t),r={...e,isLite:!1,firstPrompt:n.firstPrompt,gitBranch:n.gitBranch,isSidechain:n.isSidechain,customTitle:n.customTitle,summary:n.summary,tag:n.tag,agentSetting:n.agentSetting,prNumber:n.prNumber,prUrl:n.prUrl,prRepository:n.prRepository,projectPath:n.projectPath??e.projectPath};return!r.firstPrompt&&!r.customTitle&&(r.firstPrompt=`(session)`),r.isSidechain?(K(`Session ${e.sessionId} filtered from /resume: isSidechain=true`),null):r}async function o8(e,t,n){let r=[],i=Buffer.alloc(Tn),a=t;for(;a<e.length&&r.length<n;){let t=e[a];a++;let n=await yrt(t,i);n&&r.push(n)}let o=a-t,s=o-r.length;return s>0&&K(`/resume: enriched ${o} sessions, ${s} filtered out, ${r.length} visible (${e.length-a} remaining on disk)`),{logs:r,nextIndex:a}}var brt,xrt,s8,Srt,c8,l8,u8,d8,f8,Crt,p8,wrt,m8,Trt,h8,g8,_8=n((()=>{d(),La(),H(),t6(),Ta(),WX(),Fj(),qle(),tt(),di(),Q1(),ui(),q(),bn(),g(),gi(),Ra(),ki(),$tt(),Et(),snt(),ur(),wa(),v3(),Wn(),Ut(),Ln(),Li(),XH(),b(),brt=typeof MACRO<`u`?`0.0.33`:`unknown`,xrt=50*1024*1024,s8=/^(?:\s*<[a-z][\w-]*[\s>]|\[Request interrupted by user[^\]]*\])/,Srt=new Set([`bash_progress`,`powershell_progress`,`mcp_progress`,`sleep_progress`]),c8=50*1024*1024,l8=new Map,u8=u(e=>X(f6(),at(e))),d8=null,f8=!1,Crt=10,p8=200,wrt=class{constructor(){x(this,`currentSessionTag`,void 0),x(this,`currentSessionTitle`,void 0),x(this,`currentSessionAgentName`,void 0),x(this,`currentSessionAgentColor`,void 0),x(this,`currentSessionLastPrompt`,void 0),x(this,`currentSessionAgentSetting`,void 0),x(this,`currentSessionMode`,void 0),x(this,`currentSessionGoal`,void 0),x(this,`currentSessionWorktree`,void 0),x(this,`currentSessionPrNumber`,void 0),x(this,`currentSessionPrUrl`,void 0),x(this,`currentSessionPrRepository`,void 0),x(this,`sessionFile`,null),x(this,`pendingEntries`,[]),x(this,`internalEventWriter`,null),x(this,`internalEventReader`,null),x(this,`internalSubagentEventReader`,null),x(this,`pendingWriteCount`,0),x(this,`flushResolvers`,[]),x(this,`writeQueues`,new Map),x(this,`flushTimer`,null),x(this,`activeDrain`,null),x(this,`FLUSH_INTERVAL_MS`,100),x(this,`MAX_CHUNK_BYTES`,100*1024*1024),x(this,`existingSessionFiles`,new Map)}_resetFlushState(){this.pendingWriteCount=0,this.flushResolvers=[],this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=null,this.activeDrain=null,this.writeQueues=new Map,this.existingSessionFiles=new Map}incrementPendingWrites(){this.pendingWriteCount++}decrementPendingWrites(){if(this.pendingWriteCount--,this.pendingWriteCount===0){for(let e of this.flushResolvers)e();this.flushResolvers=[]}}async trackWrite(e){this.incrementPendingWrites();try{return await e()}finally{this.decrementPendingWrites()}}enqueueWrite(e,t){return new Promise(n=>{let r=this.writeQueues.get(e);if(r||(r=[],this.writeQueues.set(e,r)),r.length>=1e3){let e=r.splice(0,r.length-999);for(let t of e)t.resolve()}r.push({entry:t,resolve:n}),this.scheduleDrain()})}scheduleDrain(){this.flushTimer||(this.flushTimer=setTimeout(async()=>{this.flushTimer=null,this.activeDrain=this.drainWriteQueue(),await this.activeDrain,this.activeDrain=null,this.writeQueues.size>0&&this.scheduleDrain()},this.FLUSH_INTERVAL_MS))}async appendToFile(e,t){try{await Rc(e,t,{mode:384})}catch{await Hc(fc(e),{recursive:!0,mode:448}),await Rc(e,t,{mode:384})}}async drainWriteQueue(){for(let[e,t]of this.writeQueues){if(t.length===0)continue;let n=t.splice(0),r=``,i=[];for(let{entry:t,resolve:a}of n){let n=`${W(t)}\n`;if(r.length+n.length>=this.MAX_CHUNK_BYTES){await this.appendToFile(e,r);for(let e of i)e();i.length=0,r=``}r+=n,i.push(a)}if(r.length>0){await this.appendToFile(e,r);for(let e of i)e()}}for(let[e,t]of this.writeQueues)t.length===0&&this.writeQueues.delete(e)}resetSessionFile(){this.sessionFile=null,this.pendingEntries=[]}reAppendSessionMetadata(e=!1){if(!this.sessionFile)return;let t=Wr();if(!t)return;let n=Int(this.sessionFile).split(`
3062
3062
  `);if(!e){let e=n.findLast(e=>e.startsWith(`{"type":"custom-title"`));if(e){let t=mr(e,`customTitle`);t!==void 0&&(this.currentSessionTitle=t||void 0)}}let r=n.findLast(e=>e.startsWith(`{"type":"tag"`));if(r){let e=mr(r,`tag`);e!==void 0&&(this.currentSessionTag=e||void 0)}this.currentSessionLastPrompt&&R6(this.sessionFile,{type:`last-prompt`,lastPrompt:this.currentSessionLastPrompt,sessionId:t}),this.currentSessionTitle&&R6(this.sessionFile,{type:`custom-title`,customTitle:this.currentSessionTitle,sessionId:t}),this.currentSessionTag&&R6(this.sessionFile,{type:`tag`,tag:this.currentSessionTag,sessionId:t}),this.currentSessionAgentName&&R6(this.sessionFile,{type:`agent-name`,agentName:this.currentSessionAgentName,sessionId:t}),this.currentSessionAgentColor&&R6(this.sessionFile,{type:`agent-color`,agentColor:this.currentSessionAgentColor,sessionId:t}),this.currentSessionAgentSetting&&R6(this.sessionFile,{type:`agent-setting`,agentSetting:this.currentSessionAgentSetting,sessionId:t}),this.currentSessionMode&&R6(this.sessionFile,{type:`mode`,mode:this.currentSessionMode,sessionId:t}),this.currentSessionGoal&&R6(this.sessionFile,{type:`goal`,sessionId:t,state:this.currentSessionGoal,timestamp:new Date().toISOString()}),this.currentSessionWorktree!==void 0&&R6(this.sessionFile,{type:`worktree-state`,worktreeSession:this.currentSessionWorktree,sessionId:t}),this.currentSessionPrNumber!==void 0&&this.currentSessionPrUrl&&this.currentSessionPrRepository&&R6(this.sessionFile,{type:`pr-link`,sessionId:t,prNumber:this.currentSessionPrNumber,prUrl:this.currentSessionPrUrl,prRepository:this.currentSessionPrRepository,timestamp:new Date().toISOString()})}async flush(){if(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.activeDrain&&await this.activeDrain,await this.drainWriteQueue(),this.pendingWriteCount!==0)return new Promise(e=>{this.flushResolvers.push(e)})}async removeMessageByUuid(e){return this.trackWrite(async()=>{if(this.sessionFile!==null)try{let t=0,n=await Uc(this.sessionFile,`r+`);try{let{size:r}=await n.stat();if(t=r,r===0)return;let i=Math.min(r,Tn),a=r-i,o=Buffer.allocUnsafe(i),{bytesRead:s}=await n.read(o,0,i,a),c=o.subarray(0,s),l=`"uuid":"${e}"`,u=c.lastIndexOf(l);if(u>=0){let e=c.lastIndexOf(10,u);if(e>=0||a===0){let t=e+1,r=c.indexOf(10,u+l.length),i=r>=0?r+1:s,o=a+t,d=s-i;await n.truncate(o),d>0&&await n.write(c,i,d,o);return}}}finally{await n.close()}if(t>xrt){K(`Skipping tombstone removal: session file too large (${Ka(t)})`,{level:`warn`});return}let r=(await Wc(this.sessionFile,{encoding:`utf-8`})).split(`
3063
3063
  `).filter(t=>{if(!t.trim())return!0;try{return Si(t).uuid!==e}catch{return!0}});await Qc(this.sessionFile,r.join(`
3064
- `),{encoding:`utf8`})}catch{}})}shouldSkipPersistence(){let e=h(process.env.TEST_ENABLE_SESSION_PERSISTENCE);return b6()===`test`&&!e||yn()?.cleanupPeriodDays===0||Ar()||h(process.env.WORKMATE_SKIP_PROMPT_HISTORY)}async materializeSessionFile(){if(!this.shouldSkipPersistence()&&(this.ensureCurrentSessionFile(),this.reAppendSessionMetadata(),this.pendingEntries.length>0)){let e=this.pendingEntries;this.pendingEntries=[];for(let t of e)await this.appendEntry(t)}}async insertMessageChain(e,t=!1,n,r,i){return this.trackWrite(async()=>{let a=r??null;this.sessionFile===null&&e.some(e=>e.type===`user`||e.type===`assistant`)&&await this.materializeSessionFile();let o;try{o=await Jt()}catch{o=void 0}let s=Wr(),c=Pr().get(s);for(let r of e){let e=sv(r),l=a;r.type===`user`&&`sourceToolAssistantUUID`in r&&r.sourceToolAssistantUUID&&(l=r.sourceToolAssistantUUID);let u={parentUuid:e?null:l,logicalParentUuid:e?a:void 0,isSidechain:t,agentName:i?.agentName,promptId:r.type===`user`?Xte()??void 0:void 0,agentId:n,...r,userType:x6(),entrypoint:pnt(),cwd:U(),sessionId:s,timestamp:new Date().toISOString(),version:brt,gitBranch:o,slug:c};await this.appendEntry(u),d6(r)&&(a=r.uuid)}if(!t){let t=k6(e);if(t){let e=t.replace(/\n/g,` `).trim();this.currentSessionLastPrompt=e.length>200?`${e.slice(0,200).trim()}…`:e}}})}async insertFileHistorySnapshot(e,t,n){return this.trackWrite(async()=>{let r={type:`file-history-snapshot`,messageId:e,snapshot:t,isSnapshotUpdate:n};await this.appendEntry(r)})}async insertQueueOperation(e){return this.trackWrite(async()=>{await this.appendEntry(e)})}async insertAttributionSnapshot(e){return this.trackWrite(async()=>{await this.appendEntry(e)})}async insertContentReplacement(e,t){return this.trackWrite(async()=>{let n={type:`content-replacement`,sessionId:Wr(),agentId:t,replacements:e};await this.appendEntry(n)})}async appendEntry(e,t=Wr()){if(this.shouldSkipPersistence())return;let n=t===Wr(),r;if(n){if(this.sessionFile===null){this.pendingEntries.push(e);return}r=this.sessionFile}else{let e=await this.getExistingSessionFile(t);if(!e){Y(Error(`appendEntry: session file not found for other session ${t}`));return}r=e}if(e.type===`summary`)this.enqueueWrite(r,e);else if(e.type===`custom-title`)this.enqueueWrite(r,e);else if(e.type===`ai-title`)this.enqueueWrite(r,e);else if(e.type===`last-prompt`)this.enqueueWrite(r,e);else if(e.type===`task-summary`)this.enqueueWrite(r,e);else if(e.type===`tag`)this.enqueueWrite(r,e);else if(e.type===`agent-name`)this.enqueueWrite(r,e);else if(e.type===`agent-color`)this.enqueueWrite(r,e);else if(e.type===`agent-setting`)this.enqueueWrite(r,e);else if(e.type===`pr-link`)this.enqueueWrite(r,e);else if(e.type===`file-history-snapshot`)this.enqueueWrite(r,e);else if(e.type===`attribution-snapshot`)this.enqueueWrite(r,e);else if(e.type===`speculation-accept`)this.enqueueWrite(r,e);else if(e.type===`mode`)this.enqueueWrite(r,e);else if(e.type===`worktree-state`)this.enqueueWrite(r,e);else if(e.type===`content-replacement`){let t=e.agentId?_6(e.agentId):r;this.enqueueWrite(t,e)}else if(e.type===`marble-origami-commit`)this.enqueueWrite(r,e);else if(e.type===`marble-origami-snapshot`)this.enqueueWrite(r,e);else if(e.type===`goal`)this.enqueueWrite(r,e);else if(e.type===`goal-cleared`)this.enqueueWrite(r,e);else{let n=await q6(t);if(e.type===`queue-operation`)this.enqueueWrite(r,e);else{let i=e.isSidechain&&e.agentId!==void 0,a=i?_6(Pj(e.agentId)):r,o=!n.has(e.uuid);(i||o)&&(this.enqueueWrite(a,e),i||(n.add(e.uuid),u6(e)&&await this.persistToRemote(t,e)))}}}ensureCurrentSessionFile(){return this.sessionFile===null&&(this.sessionFile=p6()),this.sessionFile}async getExistingSessionFile(e){let t=this.existingSessionFiles.get(e);if(t)return t;let n=m6(e);try{if(await Yc(n),this.existingSessionFiles.size>=p8){let e=this.existingSessionFiles.keys().next().value;e!==void 0&&this.existingSessionFiles.delete(e)}return this.existingSessionFiles.set(e,n),n}catch(e){if(Ri(e))return null;throw e}}async persistToRemote(e,t){if(!rnt()&&this.internalEventWriter){try{await this.internalEventWriter(`transcript`,t,{...sv(t)&&{isCompaction:!0},...t.agentId&&{agentId:t.agentId}})}catch{K(`Failed to write transcript as internal event`)}return}}setInternalEventWriter(e){this.internalEventWriter=e,K(`CCR v2 internal event writer registered for transcript persistence`),this.FLUSH_INTERVAL_MS=Crt}setInternalEventReader(e){this.internalEventReader=e,K(`CCR v2 internal event reader registered for session resume`)}setInternalSubagentEventReader(e){this.internalSubagentEventReader=e,K(`CCR v2 subagent event reader registered for session resume`)}getInternalEventReader(){return this.internalEventReader}getInternalSubagentEventReader(){return this.internalSubagentEventReader}},m8=[`"type":"summary"`,`"type":"custom-title"`,`"type":"tag"`,`"type":"agent-name"`,`"type":"agent-color"`,`"type":"agent-setting"`,`"type":"mode"`,`"type":"worktree-state"`,`"type":"goal"`,`"type":"goal-cleared"`,`"type":"pr-link"`].map(e=>Buffer.from(e)),Trt=25,h8=new Map,g8=50}));function v8(e){return e.toLowerCase()}function Ert(e){let t=xn(e),n=v8(t),r=[{dir:xn(X(ti(),`.workmate`,`skills`)),prefix:`/.workmate/skills/`},{dir:xn(X(cc(),`.workmate`,`skills`)),prefix:`~/.workmate/skills/`}];for(let{dir:e,prefix:i}of r){let r=v8(e);for(let a of[bc,`/`])if(n.startsWith(r+a.toLowerCase())){let n=t.slice(e.length+a.length),r=n.indexOf(`/`),o=bc===`\\`?n.indexOf(`\\`):-1,s=r===-1?o:o===-1?r:Math.min(r,o);if(s<=0)return null;let c=n.slice(0,s);return!c||c===`.`||c.includes(`..`)||/[*?[\]]/.test(c)?null:{skillName:c,pattern:`${i+c}/**`}}}return null}function Drt(e,t){if(Ma()===`windows`){let n=Vt(e),r=Vt(t);return _c.relative(n,r)}return _c.relative(e,t)}function Ort(e){return Ma()===`windows`?Vt(e):e}function krt(){return tr.map(e=>Vn(e)).filter(e=>e!==void 0)}function Art(e){let t=v8(xn(e));return t.endsWith(`${bc}.workmate${bc}settings.json`)||t.endsWith(`${bc}.workmate${bc}settings.local.json`)?!0:krt().some(e=>v8(e)===t)}function jrt(e){if(Art(e))return!0;let t=X(ti(),`.workmate`,`commands`),n=X(ti(),`.workmate`,`agents`),r=X(ti(),`.workmate`,`skills`);return D8(e,t)||D8(e,n)||D8(e,r)}function Mrt(e){let t=X(Pd(),Dd()),n=hc(e);return n.startsWith(t)&&n.endsWith(`.md`)}function y8(){return X(u8(U()),Wr(),`session-memory`)+bc}function b8(){return X(y8(),`summary.md`)}function Nrt(e){return hc(e).startsWith(y8())}function Prt(e){let t=u8(U()),n=hc(e);return n===t||n.startsWith(t+bc)}function x8(){return!1}function Frt(){return Ma()===`windows`?`claude`:`claude-${process.getuid?.()??0}`}function S8(){return X(R8(),at(ti()))+bc}function C8(){return X(S8(),Wr(),`scratchpad`)}async function Irt(){if(!x8())throw Error(`Scratchpad directory feature is not enabled`);let e=J(),t=C8();return await e.mkdir(t,{mode:448}),t}function Lrt(e){if(!x8())return!1;let t=C8(),n=hc(e);return n===t||n.startsWith(t+bc)}function Rrt(e){let t=xn(e).split(bc),n=t.at(-1);if(e.startsWith(`\\\\`)||e.startsWith(`//`))return!0;for(let e=0;e<t.length;e++){let n=t[e],r=v8(n);for(let n of Krt)if(r===v8(n)){if(n===`.workmate`){let n=t[e+1];if(n&&v8(n)===`worktrees`)break}return!0}}if(n){let e=v8(n);if(Grt.some(t=>v8(t)===e))return!0}return!1}function zrt(e){return!!((Ma()===`windows`||Ma()===`wsl`)&&e.indexOf(`:`,2)!==-1||/~\d/.test(e)||e.startsWith(`\\\\?\\`)||e.startsWith(`\\\\.\\`)||e.startsWith(`//?/`)||e.startsWith(`//./`)||/[.\s]+$/.test(e)||/\.(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i.test(e)||/(^|\/|\\)\.{3,}(\/|\\|$)/.test(e)||jv(e))}function w8(e,t){let n=t??Di(e);for(let t of n)if(zrt(t))return{safe:!1,message:`Work Mate requested permissions to write to ${e}, which contains a suspicious Windows path pattern that requires manual approval.`,classifierApprovable:!1};for(let t of n)if(jrt(t))return{safe:!1,message:`Work Mate requested permissions to write to ${e}, but you haven't granted it yet.`,classifierApprovable:!0};for(let t of n)if(Rrt(t))return{safe:!1,message:`Work Mate requested permissions to edit ${e} which is a sensitive file.`,classifierApprovable:!0};return{safe:!0}}function T8(e){return new Set([ti(),...e.additionalWorkingDirectories.keys()])}function E8(e,t,n){let r=n??Di(e),i=Array.from(T8(t)).flatMap(e=>qrt(e));return r.every(e=>i.some(t=>D8(e,t)))}function D8(e,t){let n=xn(e),r=xn(t),i=n.replace(/^\/private\/var\//,`/var/`).replace(/^\/private\/tmp(\/|$)/,`/tmp$1`),a=r.replace(/^\/private\/var\//,`/var/`).replace(/^\/private\/tmp(\/|$)/,`/tmp$1`),o=v8(i),s=Drt(v8(a),o);return s===``||!sr(s)&&!_c.isAbsolute(s)}function Brt(e){switch(e){case`cliArg`:case`command`:case`session`:return xn(ti());case`userSettings`:case`policySettings`:case`projectSettings`:case`localSettings`:case`flagSettings`:return gn(e)}}function O8(e){return _c.join(L8,e)}function Vrt({patternRoot:e,pattern:t,rootPath:n}){let r=_c.join(e,t);if(e===n)return O8(t);if(r.startsWith(`${n}${L8}`))return O8(r.slice(n.length));{let r=_c.relative(n,e);return!r||r.startsWith(`..${L8}`)||r===`..`?null:O8(_c.join(r,t))}}function k8(e,t){let n=new Set(e.get(null)??[]);for(let[r,i]of e.entries())if(r!==null)for(let e of i){let i=Vrt({patternRoot:r,pattern:e,rootPath:t});i&&n.add(i)}return Array.from(n)}function A8(e){let t=Urt(e,`read`,`deny`),n=new Map;for(let[e,r]of t.entries())n.set(e,Array.from(r.keys()));return n}function Hrt(e,t){if(e.startsWith(`${L8}${L8}`)){let t=e.slice(1);if(Ma()===`windows`&&t.match(/^\/[a-z]\//i)){let e=t[1]?.toUpperCase()??`C`,n=t.slice(2),r=`${e}:\\`;return{relativePattern:n.startsWith(`/`)?n.slice(1):n,root:r}}return{relativePattern:t,root:L8}}else if(e.startsWith(`~${L8}`))return{relativePattern:e.slice(1),root:cc().normalize(`NFC`)};else if(e.startsWith(L8))return{relativePattern:e,root:Brt(t)};let n=e;return e.startsWith(`.${L8}`)&&(n=e.slice(2)),{relativePattern:n,root:null}}function Urt(e,t,n){let r=D9(e,(()=>{switch(t){case`edit`:return xs;case`read`:return os}})(),n),i=new Map;for(let[e,t]of r.entries()){let{relativePattern:n,root:r}=Hrt(e,t.source),a=i.get(r);a===void 0&&(a=new Map,i.set(r,a)),a.set(n,t)}return i}function j8(e,t,n,r){let i=xn(e);Ma()===`windows`&&i.includes(`\\`)&&(i=Vt(i));let a=Urt(t,n,r);for(let[e,t]of a.entries()){let n=Array.from(t.keys()).map(e=>{let t=e;return t.endsWith(`/**`)&&(t=t.slice(0,-3)),t}),r=(0,Wrt.default)().add(n),a=Drt(e??U(),i??U());if(a.startsWith(`..${L8}`)||!a)continue;let o=r.test(a);if(o.ignored&&o.rule){let e=o.rule.pattern,n=`${e}/**`;return t.has(n)?t.get(n)??null:t.get(e)??null}}return null}function M8(e,t,n){if(typeof e.getPath!=`function`)return{behavior:`ask`,message:`Work Mate requested permissions to use ${e.name}, but you haven't granted it yet.`};let r=e.getPath(t),i=Di(r);for(let e of i)if(e.startsWith(`\\\\`)||e.startsWith(`//`))return{behavior:`ask`,message:`Work Mate requested permissions to read from ${r}, which appears to be a UNC path that could access network resources.`,decisionReason:{type:`other`,reason:`UNC path detected (defense-in-depth check)`}};for(let e of i)if(zrt(e))return{behavior:`ask`,message:`Work Mate requested permissions to read from ${r}, which contains a suspicious Windows path pattern that requires manual approval.`,decisionReason:{type:`other`,reason:`Path contains suspicious Windows-specific patterns (alternate data streams, short names, long path prefixes, or three or more consecutive dots) that require manual verification`}};for(let e of i){let t=j8(e,n,`read`,`deny`);if(t)return{behavior:`deny`,message:`Permission to read ${r} has been denied.`,decisionReason:{type:`rule`,rule:t}}}for(let e of i){let t=j8(e,n,`read`,`ask`);if(t)return{behavior:`ask`,message:`Work Mate requested permissions to read from ${r}, but you haven't granted it yet.`,decisionReason:{type:`rule`,rule:t}}}let a=N8(e,t,n,i);if(a.behavior===`allow`)return a;if(E8(r,n,i))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`mode`,mode:`default`}};let o=I8(xn(r),t);if(o.behavior!==`passthrough`)return o;let s=j8(r,n,`read`,`allow`);return s?{behavior:`allow`,updatedInput:t,decisionReason:{type:`rule`,rule:s}}:{behavior:`ask`,message:`Work Mate requested permissions to read from ${r}, but you haven't granted it yet.`,suggestions:P8(r,`read`,n,i),decisionReason:{type:`workingDir`,reason:`Path is outside allowed working directories`}}}function N8(e,t,n,r){if(typeof e.getPath!=`function`)return{behavior:`ask`,message:`Work Mate requested permissions to use ${e.name}, but you haven't granted it yet.`};let i=e.getPath(t),a=r??Di(i);for(let e of a){let t=j8(e,n,`edit`,`deny`);if(t)return{behavior:`deny`,message:`Permission to edit ${i} has been denied.`,decisionReason:{type:`rule`,rule:t}}}let o=F8(xn(i),t);if(o.behavior!==`passthrough`)return o;let s=j8(i,{...n,alwaysAllowRules:{session:n.alwaysAllowRules.session??[]}},`edit`,`allow`);if(s){let e=s.ruleValue.ruleContent;if(e&&(e.startsWith(`/.workmate/**`.slice(0,-2))||e.startsWith(`~/.workmate/**`.slice(0,-2)))&&!e.includes(`..`)&&e.endsWith(`/**`))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`rule`,rule:s}}}let c=w8(i,a);if(!c.safe){let e=Ert(i),t=e?[{type:`addRules`,rules:[{toolName:xs,ruleContent:e.pattern}],behavior:`allow`,destination:`session`}]:P8(i,`write`,n,a),r=c;return{behavior:`ask`,message:r.message,suggestions:t,decisionReason:{type:`safetyCheck`,reason:r.message,classifierApprovable:r.classifierApprovable}}}for(let e of a){let t=j8(e,n,`edit`,`ask`);if(t)return{behavior:`ask`,message:`Work Mate requested permissions to write to ${i}, but you haven't granted it yet.`,decisionReason:{type:`rule`,rule:t}}}let l=E8(i,n,a);if(n.mode===`acceptEdits`&&l)return{behavior:`allow`,updatedInput:t,decisionReason:{type:`mode`,mode:n.mode}};let u=j8(i,n,`edit`,`allow`);return u?{behavior:`allow`,updatedInput:t,decisionReason:{type:`rule`,rule:u}}:{behavior:`ask`,message:`Work Mate requested permissions to write to ${i}, but you haven't granted it yet.`,suggestions:P8(i,`write`,n,a),decisionReason:l?void 0:{type:`workingDir`,reason:`Path is outside allowed working directories`}}}function P8(e,t,n,r){let i=!E8(e,n,r);if(t===`read`&&i)return Di(wn(e)).map(e=>Tj(e,`session`)).filter(e=>e!==void 0);let a=n.mode==="default"||n.mode===`plan`;if(t===`write`||t===`create`){let t=a?[{type:`setMode`,mode:`acceptEdits`,destination:`session`}]:[];if(i){let n=Di(wn(e));t.push({type:`addDirectories`,directories:n,destination:`session`})}return t}return a?[{type:`setMode`,mode:`acceptEdits`,destination:`session`}]:[]}function F8(e,t){let n=hc(e);if(Mrt(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Plan files for current session are allowed for writing`}};if(Lrt(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Scratchpad files for current session are allowed for writing`}};let r=process.env.WORKMATE_JOB_DIR;if(r){let n=X(m(),`jobs`),i=Di(r).map(hc),a=Di(n).map(hc);if(i.every(e=>a.some(t=>e.startsWith(t+bc)))&&Di(e).every(e=>{let t=hc(e);return i.some(e=>t===e||t.startsWith(e+bc))}))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Job directory files for current job are allowed for writing`}}}return vd(n)?{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Agent memory files are allowed for writing`}}:!qre()&&Zi(n)?{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`auto memory files are allowed for writing`}}:v8(n)===v8(X(ti(),`.workmate`,`launch.json`))?{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Preview launch config is allowed for writing`}}:{behavior:`passthrough`,message:``}}function I8(e,t){let n=hc(e);if(Nrt(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Session memory files are allowed for reading`}};if(Prt(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Project directory files are allowed for reading`}};if(Mrt(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Plan files for current session are allowed for reading`}};let r=tx(),i=r.endsWith(bc)?r:r+bc;if(n===r||n.startsWith(i))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Tool result files are allowed for reading`}};if(Lrt(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Scratchpad files for current session are allowed for reading`}};let a=S8();if(n.startsWith(a))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Project temp directory files are allowed for reading`}};if(vd(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Agent memory files are allowed for reading`}};if(Zi(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`auto memory files are allowed for reading`}};let o=X(m(),`tasks`)+bc;if(n===o.slice(0,-1)||n.startsWith(o))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Task files are allowed for reading`}};let s=X(m(),`teams`)+bc;if(n===s.slice(0,-1)||n.startsWith(s))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Team files are allowed for reading`}};let c=z8()+bc;return n.startsWith(c)?{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Bundled skill reference files are allowed for reading`}}:{behavior:`passthrough`,message:``}}var Wrt,Grt,Krt,L8,R8,z8,qrt,B8=n((()=>{Wrt=r(ce(),1),d(),zi(),bd(),Es(),H(),As(),ui(),g(),ki(),Wn(),Fd(),Pa(),_8(),Rn(),Ln(),Gv(),fx(),ht(),Ej(),j9(),Grt=[`.gitconfig`,`.gitmodules`,`.bashrc`,`.bash_profile`,`.zshrc`,`.zprofile`,`.profile`,`.ripgreprc`,`.mcp.json`,`.workmate.json`],Krt=[`.git`,`.vscode`,`.idea`,`.workmate`],L8=_c.sep,R8=u(function(){let e=process.env.WORKMATE_TMPDIR||lc(),t=J(),n=e;try{n=t.realpathSync(e)}catch{}return X(n,Frt())+bc}),z8=u(function(){let e=Ic(16).toString(`hex`);return X(R8(),`bundled-skills`,`0.0.32`,e)}),qrt=u(Di)}));function V8(){return X8===void 0&&(X8=X(S8(),Wr(),`tasks`)),X8}async function H8(){await Hc(V8(),{recursive:!0})}function U8(e){return X(V8(),`${e}.output`)}function W8(e){return Z8.add(e),e.finally(()=>Z8.delete(e)).catch(()=>{}),e}async function Jrt(){for(;;){try{for(D($8,this)||(await H8(),k($8,this,await Uc(D(Q8,this),process.platform===`win32`?`a`:Dc.O_WRONLY|Dc.O_APPEND|Dc.O_CREAT|q8)));await S(a5,this,Yrt).call(this),D(e5,this).length!==0;);}finally{if(D($8,this)){let e=D($8,this);k($8,this,null),await e.close()}}if(!D(e5,this).length)break}}function Yrt(){return D($8,this).appendFile(S(a5,this,Xrt).call(this))}function Xrt(){let e=D(e5,this).splice(0,D(e5,this).length),t=0;for(let n of e)t+=Buffer.byteLength(n,`utf8`);let n=Buffer.allocUnsafe(t),r=0;for(let t of e)r+=n.write(t,r,`utf8`);return n}async function Zrt(){try{await S(a5,this,Jrt).call(this)}catch(e){if(Y(e),D(e5,this).length>0)try{await S(a5,this,Jrt).call(this)}catch(e){Y(e)}}finally{let e=D(i5,this);k(r5,this,null),k(i5,this,null),e()}}function G8(e){return W8((async()=>{let t=o5.get(e);t&&(await t.flush(),o5.delete(e))})())}async function Qrt(e,t,n=J8){try{let r=await Ni(U8(e),t,n);return r?{content:r.content,newOffset:t+r.bytesRead}:{content:``,newOffset:t}}catch(e){return yi(e)===`ENOENT`||Y(e),{content:``,newOffset:t}}}async function $rt(e,t=J8){try{let{content:n,bytesTotal:r,bytesRead:i}=await Ei(U8(e),t);return r>i?`[${Math.round((r-i)/1024)}KB of earlier output omitted]\n${n}`:n}catch(e){return yi(e)===`ENOENT`||Y(e),``}}function eit(e){return W8((async()=>{await H8();let t=U8(e);return await(await Uc(t,process.platform===`win32`?`wx`:Dc.O_WRONLY|Dc.O_CREAT|Dc.O_EXCL|q8)).close(),t})())}function K8(e,t){return W8((async()=>{try{await H8();let n=U8(e);try{await Xc(t,n)}catch{await Zc(n),await Xc(t,n)}return n}catch(t){return Y(t),eit(e)}})())}var q8,J8,Y8,X8,Z8,Q8,$8,e5,t5,n5,r5,i5,a5,tit,o5,s5=n((()=>{H(),gi(),ki(),wa(),B8(),A(),C(),T(),w(),E(),q8=Dc.O_NOFOLLOW??0,J8=8*1024*1024,Y8=5*1024*1024*1024,Z8=new Set,Q8=new WeakMap,$8=new WeakMap,e5=new WeakMap,t5=new WeakMap,n5=new WeakMap,r5=new WeakMap,i5=new WeakMap,a5=new WeakSet,tit=class{constructor(e){ee(this,a5),O(this,Q8,void 0),O(this,$8,null),O(this,e5,[]),O(this,t5,0),O(this,n5,!1),O(this,r5,null),O(this,i5,null),k(Q8,this,U8(e))}append(e){D(n5,this)||(k(t5,this,D(t5,this)+e.length),D(t5,this)>5368709120?(k(n5,this,!0),D(e5,this).push(`
3064
+ `),{encoding:`utf8`})}catch{}})}shouldSkipPersistence(){let e=h(process.env.TEST_ENABLE_SESSION_PERSISTENCE);return b6()===`test`&&!e||yn()?.cleanupPeriodDays===0||Ar()||h(process.env.WORKMATE_SKIP_PROMPT_HISTORY)}async materializeSessionFile(){if(!this.shouldSkipPersistence()&&(this.ensureCurrentSessionFile(),this.reAppendSessionMetadata(),this.pendingEntries.length>0)){let e=this.pendingEntries;this.pendingEntries=[];for(let t of e)await this.appendEntry(t)}}async insertMessageChain(e,t=!1,n,r,i){return this.trackWrite(async()=>{let a=r??null;this.sessionFile===null&&e.some(e=>e.type===`user`||e.type===`assistant`)&&await this.materializeSessionFile();let o;try{o=await Jt()}catch{o=void 0}let s=Wr(),c=Pr().get(s);for(let r of e){let e=sv(r),l=a;r.type===`user`&&`sourceToolAssistantUUID`in r&&r.sourceToolAssistantUUID&&(l=r.sourceToolAssistantUUID);let u={parentUuid:e?null:l,logicalParentUuid:e?a:void 0,isSidechain:t,agentName:i?.agentName,promptId:r.type===`user`?Xte()??void 0:void 0,agentId:n,...r,userType:x6(),entrypoint:pnt(),cwd:U(),sessionId:s,timestamp:new Date().toISOString(),version:brt,gitBranch:o,slug:c};await this.appendEntry(u),d6(r)&&(a=r.uuid)}if(!t){let t=k6(e);if(t){let e=t.replace(/\n/g,` `).trim();this.currentSessionLastPrompt=e.length>200?`${e.slice(0,200).trim()}…`:e}}})}async insertFileHistorySnapshot(e,t,n){return this.trackWrite(async()=>{let r={type:`file-history-snapshot`,messageId:e,snapshot:t,isSnapshotUpdate:n};await this.appendEntry(r)})}async insertQueueOperation(e){return this.trackWrite(async()=>{await this.appendEntry(e)})}async insertAttributionSnapshot(e){return this.trackWrite(async()=>{await this.appendEntry(e)})}async insertContentReplacement(e,t){return this.trackWrite(async()=>{let n={type:`content-replacement`,sessionId:Wr(),agentId:t,replacements:e};await this.appendEntry(n)})}async appendEntry(e,t=Wr()){if(this.shouldSkipPersistence())return;let n=t===Wr(),r;if(n){if(this.sessionFile===null){this.pendingEntries.push(e);return}r=this.sessionFile}else{let e=await this.getExistingSessionFile(t);if(!e){Y(Error(`appendEntry: session file not found for other session ${t}`));return}r=e}if(e.type===`summary`)this.enqueueWrite(r,e);else if(e.type===`custom-title`)this.enqueueWrite(r,e);else if(e.type===`ai-title`)this.enqueueWrite(r,e);else if(e.type===`last-prompt`)this.enqueueWrite(r,e);else if(e.type===`task-summary`)this.enqueueWrite(r,e);else if(e.type===`tag`)this.enqueueWrite(r,e);else if(e.type===`agent-name`)this.enqueueWrite(r,e);else if(e.type===`agent-color`)this.enqueueWrite(r,e);else if(e.type===`agent-setting`)this.enqueueWrite(r,e);else if(e.type===`pr-link`)this.enqueueWrite(r,e);else if(e.type===`file-history-snapshot`)this.enqueueWrite(r,e);else if(e.type===`attribution-snapshot`)this.enqueueWrite(r,e);else if(e.type===`speculation-accept`)this.enqueueWrite(r,e);else if(e.type===`mode`)this.enqueueWrite(r,e);else if(e.type===`worktree-state`)this.enqueueWrite(r,e);else if(e.type===`content-replacement`){let t=e.agentId?_6(e.agentId):r;this.enqueueWrite(t,e)}else if(e.type===`marble-origami-commit`)this.enqueueWrite(r,e);else if(e.type===`marble-origami-snapshot`)this.enqueueWrite(r,e);else if(e.type===`goal`)this.enqueueWrite(r,e);else if(e.type===`goal-cleared`)this.enqueueWrite(r,e);else{let n=await q6(t);if(e.type===`queue-operation`)this.enqueueWrite(r,e);else{let i=e.isSidechain&&e.agentId!==void 0,a=i?_6(Pj(e.agentId)):r,o=!n.has(e.uuid);(i||o)&&(this.enqueueWrite(a,e),i||(n.add(e.uuid),u6(e)&&await this.persistToRemote(t,e)))}}}ensureCurrentSessionFile(){return this.sessionFile===null&&(this.sessionFile=p6()),this.sessionFile}async getExistingSessionFile(e){let t=this.existingSessionFiles.get(e);if(t)return t;let n=m6(e);try{if(await Yc(n),this.existingSessionFiles.size>=p8){let e=this.existingSessionFiles.keys().next().value;e!==void 0&&this.existingSessionFiles.delete(e)}return this.existingSessionFiles.set(e,n),n}catch(e){if(Ri(e))return null;throw e}}async persistToRemote(e,t){if(!rnt()&&this.internalEventWriter){try{await this.internalEventWriter(`transcript`,t,{...sv(t)&&{isCompaction:!0},...t.agentId&&{agentId:t.agentId}})}catch{K(`Failed to write transcript as internal event`)}return}}setInternalEventWriter(e){this.internalEventWriter=e,K(`CCR v2 internal event writer registered for transcript persistence`),this.FLUSH_INTERVAL_MS=Crt}setInternalEventReader(e){this.internalEventReader=e,K(`CCR v2 internal event reader registered for session resume`)}setInternalSubagentEventReader(e){this.internalSubagentEventReader=e,K(`CCR v2 subagent event reader registered for session resume`)}getInternalEventReader(){return this.internalEventReader}getInternalSubagentEventReader(){return this.internalSubagentEventReader}},m8=[`"type":"summary"`,`"type":"custom-title"`,`"type":"tag"`,`"type":"agent-name"`,`"type":"agent-color"`,`"type":"agent-setting"`,`"type":"mode"`,`"type":"worktree-state"`,`"type":"goal"`,`"type":"goal-cleared"`,`"type":"pr-link"`].map(e=>Buffer.from(e)),Trt=25,h8=new Map,g8=50}));function v8(e){return e.toLowerCase()}function Ert(e){let t=xn(e),n=v8(t),r=[{dir:xn(X(ti(),`.workmate`,`skills`)),prefix:`/.workmate/skills/`},{dir:xn(X(cc(),`.workmate`,`skills`)),prefix:`~/.workmate/skills/`}];for(let{dir:e,prefix:i}of r){let r=v8(e);for(let a of[bc,`/`])if(n.startsWith(r+a.toLowerCase())){let n=t.slice(e.length+a.length),r=n.indexOf(`/`),o=bc===`\\`?n.indexOf(`\\`):-1,s=r===-1?o:o===-1?r:Math.min(r,o);if(s<=0)return null;let c=n.slice(0,s);return!c||c===`.`||c.includes(`..`)||/[*?[\]]/.test(c)?null:{skillName:c,pattern:`${i+c}/**`}}}return null}function Drt(e,t){if(Ma()===`windows`){let n=Vt(e),r=Vt(t);return _c.relative(n,r)}return _c.relative(e,t)}function Ort(e){return Ma()===`windows`?Vt(e):e}function krt(){return tr.map(e=>Vn(e)).filter(e=>e!==void 0)}function Art(e){let t=v8(xn(e));return t.endsWith(`${bc}.workmate${bc}settings.json`)||t.endsWith(`${bc}.workmate${bc}settings.local.json`)?!0:krt().some(e=>v8(e)===t)}function jrt(e){if(Art(e))return!0;let t=X(ti(),`.workmate`,`commands`),n=X(ti(),`.workmate`,`agents`),r=X(ti(),`.workmate`,`skills`);return D8(e,t)||D8(e,n)||D8(e,r)}function Mrt(e){let t=X(Pd(),Dd()),n=hc(e);return n.startsWith(t)&&n.endsWith(`.md`)}function y8(){return X(u8(U()),Wr(),`session-memory`)+bc}function b8(){return X(y8(),`summary.md`)}function Nrt(e){return hc(e).startsWith(y8())}function Prt(e){let t=u8(U()),n=hc(e);return n===t||n.startsWith(t+bc)}function x8(){return!1}function Frt(){return Ma()===`windows`?`claude`:`claude-${process.getuid?.()??0}`}function S8(){return X(R8(),at(ti()))+bc}function C8(){return X(S8(),Wr(),`scratchpad`)}async function Irt(){if(!x8())throw Error(`Scratchpad directory feature is not enabled`);let e=J(),t=C8();return await e.mkdir(t,{mode:448}),t}function Lrt(e){if(!x8())return!1;let t=C8(),n=hc(e);return n===t||n.startsWith(t+bc)}function Rrt(e){let t=xn(e).split(bc),n=t.at(-1);if(e.startsWith(`\\\\`)||e.startsWith(`//`))return!0;for(let e=0;e<t.length;e++){let n=t[e],r=v8(n);for(let n of Krt)if(r===v8(n)){if(n===`.workmate`){let n=t[e+1];if(n&&v8(n)===`worktrees`)break}return!0}}if(n){let e=v8(n);if(Grt.some(t=>v8(t)===e))return!0}return!1}function zrt(e){return!!((Ma()===`windows`||Ma()===`wsl`)&&e.indexOf(`:`,2)!==-1||/~\d/.test(e)||e.startsWith(`\\\\?\\`)||e.startsWith(`\\\\.\\`)||e.startsWith(`//?/`)||e.startsWith(`//./`)||/[.\s]+$/.test(e)||/\.(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i.test(e)||/(^|\/|\\)\.{3,}(\/|\\|$)/.test(e)||jv(e))}function w8(e,t){let n=t??Di(e);for(let t of n)if(zrt(t))return{safe:!1,message:`Work Mate requested permissions to write to ${e}, which contains a suspicious Windows path pattern that requires manual approval.`,classifierApprovable:!1};for(let t of n)if(jrt(t))return{safe:!1,message:`Work Mate requested permissions to write to ${e}, but you haven't granted it yet.`,classifierApprovable:!0};for(let t of n)if(Rrt(t))return{safe:!1,message:`Work Mate requested permissions to edit ${e} which is a sensitive file.`,classifierApprovable:!0};return{safe:!0}}function T8(e){return new Set([ti(),...e.additionalWorkingDirectories.keys()])}function E8(e,t,n){let r=n??Di(e),i=Array.from(T8(t)).flatMap(e=>qrt(e));return r.every(e=>i.some(t=>D8(e,t)))}function D8(e,t){let n=xn(e),r=xn(t),i=n.replace(/^\/private\/var\//,`/var/`).replace(/^\/private\/tmp(\/|$)/,`/tmp$1`),a=r.replace(/^\/private\/var\//,`/var/`).replace(/^\/private\/tmp(\/|$)/,`/tmp$1`),o=v8(i),s=Drt(v8(a),o);return s===``||!sr(s)&&!_c.isAbsolute(s)}function Brt(e){switch(e){case`cliArg`:case`command`:case`session`:return xn(ti());case`userSettings`:case`policySettings`:case`projectSettings`:case`localSettings`:case`flagSettings`:return gn(e)}}function O8(e){return _c.join(L8,e)}function Vrt({patternRoot:e,pattern:t,rootPath:n}){let r=_c.join(e,t);if(e===n)return O8(t);if(r.startsWith(`${n}${L8}`))return O8(r.slice(n.length));{let r=_c.relative(n,e);return!r||r.startsWith(`..${L8}`)||r===`..`?null:O8(_c.join(r,t))}}function k8(e,t){let n=new Set(e.get(null)??[]);for(let[r,i]of e.entries())if(r!==null)for(let e of i){let i=Vrt({patternRoot:r,pattern:e,rootPath:t});i&&n.add(i)}return Array.from(n)}function A8(e){let t=Urt(e,`read`,`deny`),n=new Map;for(let[e,r]of t.entries())n.set(e,Array.from(r.keys()));return n}function Hrt(e,t){if(e.startsWith(`${L8}${L8}`)){let t=e.slice(1);if(Ma()===`windows`&&t.match(/^\/[a-z]\//i)){let e=t[1]?.toUpperCase()??`C`,n=t.slice(2),r=`${e}:\\`;return{relativePattern:n.startsWith(`/`)?n.slice(1):n,root:r}}return{relativePattern:t,root:L8}}else if(e.startsWith(`~${L8}`))return{relativePattern:e.slice(1),root:cc().normalize(`NFC`)};else if(e.startsWith(L8))return{relativePattern:e,root:Brt(t)};let n=e;return e.startsWith(`.${L8}`)&&(n=e.slice(2)),{relativePattern:n,root:null}}function Urt(e,t,n){let r=D9(e,(()=>{switch(t){case`edit`:return xs;case`read`:return os}})(),n),i=new Map;for(let[e,t]of r.entries()){let{relativePattern:n,root:r}=Hrt(e,t.source),a=i.get(r);a===void 0&&(a=new Map,i.set(r,a)),a.set(n,t)}return i}function j8(e,t,n,r){let i=xn(e);Ma()===`windows`&&i.includes(`\\`)&&(i=Vt(i));let a=Urt(t,n,r);for(let[e,t]of a.entries()){let n=Array.from(t.keys()).map(e=>{let t=e;return t.endsWith(`/**`)&&(t=t.slice(0,-3)),t}),r=(0,Wrt.default)().add(n),a=Drt(e??U(),i??U());if(a.startsWith(`..${L8}`)||!a)continue;let o=r.test(a);if(o.ignored&&o.rule){let e=o.rule.pattern,n=`${e}/**`;return t.has(n)?t.get(n)??null:t.get(e)??null}}return null}function M8(e,t,n){if(typeof e.getPath!=`function`)return{behavior:`ask`,message:`Work Mate requested permissions to use ${e.name}, but you haven't granted it yet.`};let r=e.getPath(t),i=Di(r);for(let e of i)if(e.startsWith(`\\\\`)||e.startsWith(`//`))return{behavior:`ask`,message:`Work Mate requested permissions to read from ${r}, which appears to be a UNC path that could access network resources.`,decisionReason:{type:`other`,reason:`UNC path detected (defense-in-depth check)`}};for(let e of i)if(zrt(e))return{behavior:`ask`,message:`Work Mate requested permissions to read from ${r}, which contains a suspicious Windows path pattern that requires manual approval.`,decisionReason:{type:`other`,reason:`Path contains suspicious Windows-specific patterns (alternate data streams, short names, long path prefixes, or three or more consecutive dots) that require manual verification`}};for(let e of i){let t=j8(e,n,`read`,`deny`);if(t)return{behavior:`deny`,message:`Permission to read ${r} has been denied.`,decisionReason:{type:`rule`,rule:t}}}for(let e of i){let t=j8(e,n,`read`,`ask`);if(t)return{behavior:`ask`,message:`Work Mate requested permissions to read from ${r}, but you haven't granted it yet.`,decisionReason:{type:`rule`,rule:t}}}let a=N8(e,t,n,i);if(a.behavior===`allow`)return a;if(E8(r,n,i))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`mode`,mode:`default`}};let o=I8(xn(r),t);if(o.behavior!==`passthrough`)return o;let s=j8(r,n,`read`,`allow`);return s?{behavior:`allow`,updatedInput:t,decisionReason:{type:`rule`,rule:s}}:{behavior:`ask`,message:`Work Mate requested permissions to read from ${r}, but you haven't granted it yet.`,suggestions:P8(r,`read`,n,i),decisionReason:{type:`workingDir`,reason:`Path is outside allowed working directories`}}}function N8(e,t,n,r){if(typeof e.getPath!=`function`)return{behavior:`ask`,message:`Work Mate requested permissions to use ${e.name}, but you haven't granted it yet.`};let i=e.getPath(t),a=r??Di(i);for(let e of a){let t=j8(e,n,`edit`,`deny`);if(t)return{behavior:`deny`,message:`Permission to edit ${i} has been denied.`,decisionReason:{type:`rule`,rule:t}}}let o=F8(xn(i),t);if(o.behavior!==`passthrough`)return o;let s=j8(i,{...n,alwaysAllowRules:{session:n.alwaysAllowRules.session??[]}},`edit`,`allow`);if(s){let e=s.ruleValue.ruleContent;if(e&&(e.startsWith(`/.workmate/**`.slice(0,-2))||e.startsWith(`~/.workmate/**`.slice(0,-2)))&&!e.includes(`..`)&&e.endsWith(`/**`))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`rule`,rule:s}}}let c=w8(i,a);if(!c.safe){let e=Ert(i),t=e?[{type:`addRules`,rules:[{toolName:xs,ruleContent:e.pattern}],behavior:`allow`,destination:`session`}]:P8(i,`write`,n,a),r=c;return{behavior:`ask`,message:r.message,suggestions:t,decisionReason:{type:`safetyCheck`,reason:r.message,classifierApprovable:r.classifierApprovable}}}for(let e of a){let t=j8(e,n,`edit`,`ask`);if(t)return{behavior:`ask`,message:`Work Mate requested permissions to write to ${i}, but you haven't granted it yet.`,decisionReason:{type:`rule`,rule:t}}}let l=E8(i,n,a);if(n.mode===`acceptEdits`&&l)return{behavior:`allow`,updatedInput:t,decisionReason:{type:`mode`,mode:n.mode}};let u=j8(i,n,`edit`,`allow`);return u?{behavior:`allow`,updatedInput:t,decisionReason:{type:`rule`,rule:u}}:{behavior:`ask`,message:`Work Mate requested permissions to write to ${i}, but you haven't granted it yet.`,suggestions:P8(i,`write`,n,a),decisionReason:l?void 0:{type:`workingDir`,reason:`Path is outside allowed working directories`}}}function P8(e,t,n,r){let i=!E8(e,n,r);if(t===`read`&&i)return Di(wn(e)).map(e=>Tj(e,`session`)).filter(e=>e!==void 0);let a=n.mode==="default"||n.mode===`plan`;if(t===`write`||t===`create`){let t=a?[{type:`setMode`,mode:`acceptEdits`,destination:`session`}]:[];if(i){let n=Di(wn(e));t.push({type:`addDirectories`,directories:n,destination:`session`})}return t}return a?[{type:`setMode`,mode:`acceptEdits`,destination:`session`}]:[]}function F8(e,t){let n=hc(e);if(Mrt(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Plan files for current session are allowed for writing`}};if(Lrt(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Scratchpad files for current session are allowed for writing`}};let r=process.env.WORKMATE_JOB_DIR;if(r){let n=X(m(),`jobs`),i=Di(r).map(hc),a=Di(n).map(hc);if(i.every(e=>a.some(t=>e.startsWith(t+bc)))&&Di(e).every(e=>{let t=hc(e);return i.some(e=>t===e||t.startsWith(e+bc))}))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Job directory files for current job are allowed for writing`}}}return vd(n)?{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Agent memory files are allowed for writing`}}:!qre()&&Zi(n)?{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`auto memory files are allowed for writing`}}:v8(n)===v8(X(ti(),`.workmate`,`launch.json`))?{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Preview launch config is allowed for writing`}}:{behavior:`passthrough`,message:``}}function I8(e,t){let n=hc(e);if(Nrt(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Session memory files are allowed for reading`}};if(Prt(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Project directory files are allowed for reading`}};if(Mrt(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Plan files for current session are allowed for reading`}};let r=tx(),i=r.endsWith(bc)?r:r+bc;if(n===r||n.startsWith(i))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Tool result files are allowed for reading`}};if(Lrt(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Scratchpad files for current session are allowed for reading`}};let a=S8();if(n.startsWith(a))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Project temp directory files are allowed for reading`}};if(vd(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Agent memory files are allowed for reading`}};if(Zi(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`auto memory files are allowed for reading`}};let o=X(m(),`tasks`)+bc;if(n===o.slice(0,-1)||n.startsWith(o))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Task files are allowed for reading`}};let s=X(m(),`teams`)+bc;if(n===s.slice(0,-1)||n.startsWith(s))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Team files are allowed for reading`}};let c=z8()+bc;return n.startsWith(c)?{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Bundled skill reference files are allowed for reading`}}:{behavior:`passthrough`,message:``}}var Wrt,Grt,Krt,L8,R8,z8,qrt,B8=n((()=>{Wrt=r(ce(),1),d(),zi(),bd(),Es(),H(),As(),ui(),g(),ki(),Wn(),Fd(),Pa(),_8(),Rn(),Ln(),Gv(),fx(),ht(),Ej(),j9(),Grt=[`.gitconfig`,`.gitmodules`,`.bashrc`,`.bash_profile`,`.zshrc`,`.zprofile`,`.profile`,`.ripgreprc`,`.mcp.json`,`.workmate.json`],Krt=[`.git`,`.vscode`,`.idea`,`.workmate`],L8=_c.sep,R8=u(function(){let e=process.env.WORKMATE_TMPDIR||lc(),t=J(),n=e;try{n=t.realpathSync(e)}catch{}return X(n,Frt())+bc}),z8=u(function(){let e=Ic(16).toString(`hex`);return X(R8(),`bundled-skills`,`0.0.33`,e)}),qrt=u(Di)}));function V8(){return X8===void 0&&(X8=X(S8(),Wr(),`tasks`)),X8}async function H8(){await Hc(V8(),{recursive:!0})}function U8(e){return X(V8(),`${e}.output`)}function W8(e){return Z8.add(e),e.finally(()=>Z8.delete(e)).catch(()=>{}),e}async function Jrt(){for(;;){try{for(D($8,this)||(await H8(),k($8,this,await Uc(D(Q8,this),process.platform===`win32`?`a`:Dc.O_WRONLY|Dc.O_APPEND|Dc.O_CREAT|q8)));await S(a5,this,Yrt).call(this),D(e5,this).length!==0;);}finally{if(D($8,this)){let e=D($8,this);k($8,this,null),await e.close()}}if(!D(e5,this).length)break}}function Yrt(){return D($8,this).appendFile(S(a5,this,Xrt).call(this))}function Xrt(){let e=D(e5,this).splice(0,D(e5,this).length),t=0;for(let n of e)t+=Buffer.byteLength(n,`utf8`);let n=Buffer.allocUnsafe(t),r=0;for(let t of e)r+=n.write(t,r,`utf8`);return n}async function Zrt(){try{await S(a5,this,Jrt).call(this)}catch(e){if(Y(e),D(e5,this).length>0)try{await S(a5,this,Jrt).call(this)}catch(e){Y(e)}}finally{let e=D(i5,this);k(r5,this,null),k(i5,this,null),e()}}function G8(e){return W8((async()=>{let t=o5.get(e);t&&(await t.flush(),o5.delete(e))})())}async function Qrt(e,t,n=J8){try{let r=await Ni(U8(e),t,n);return r?{content:r.content,newOffset:t+r.bytesRead}:{content:``,newOffset:t}}catch(e){return yi(e)===`ENOENT`||Y(e),{content:``,newOffset:t}}}async function $rt(e,t=J8){try{let{content:n,bytesTotal:r,bytesRead:i}=await Ei(U8(e),t);return r>i?`[${Math.round((r-i)/1024)}KB of earlier output omitted]\n${n}`:n}catch(e){return yi(e)===`ENOENT`||Y(e),``}}function eit(e){return W8((async()=>{await H8();let t=U8(e);return await(await Uc(t,process.platform===`win32`?`wx`:Dc.O_WRONLY|Dc.O_CREAT|Dc.O_EXCL|q8)).close(),t})())}function K8(e,t){return W8((async()=>{try{await H8();let n=U8(e);try{await Xc(t,n)}catch{await Zc(n),await Xc(t,n)}return n}catch(t){return Y(t),eit(e)}})())}var q8,J8,Y8,X8,Z8,Q8,$8,e5,t5,n5,r5,i5,a5,tit,o5,s5=n((()=>{H(),gi(),ki(),wa(),B8(),A(),C(),T(),w(),E(),q8=Dc.O_NOFOLLOW??0,J8=8*1024*1024,Y8=5*1024*1024*1024,Z8=new Set,Q8=new WeakMap,$8=new WeakMap,e5=new WeakMap,t5=new WeakMap,n5=new WeakMap,r5=new WeakMap,i5=new WeakMap,a5=new WeakSet,tit=class{constructor(e){ee(this,a5),O(this,Q8,void 0),O(this,$8,null),O(this,e5,[]),O(this,t5,0),O(this,n5,!1),O(this,r5,null),O(this,i5,null),k(Q8,this,U8(e))}append(e){D(n5,this)||(k(t5,this,D(t5,this)+e.length),D(t5,this)>5368709120?(k(n5,this,!0),D(e5,this).push(`
3065
3065
  [output truncated: exceeded 5GB disk cap]
3066
3066
  `)):D(e5,this).push(e),D(r5,this)||(k(r5,this,new Promise(e=>{k(i5,this,e)})),W8(S(a5,this,Zrt).call(this))))}flush(){return D(r5,this)??Promise.resolve()}cancel(){D(e5,this).length=0}},o5=new Map}));function nit(e){return e===`completed`||e===`failed`||e===`killed`}function rit(e){return iit[e]??`x`}function c5(e){let t=rit(e),n=Ic(8),r=t;for(let e=0;e<8;e++)r+=ait[n[e]%36];return r}function l5(e,t,n,r){return{id:e,type:t,status:`pending`,description:n,toolUseId:r,startTime:Date.now(),outputFile:U8(e),outputOffset:0,notified:!1}}var iit,ait,u5=n((()=>{s5(),iit={local_bash:`b`,local_agent:`a`,local_workflow:`w`,dream:`d`},ait=`0123456789abcdefghijklmnopqrstuvwxyz`}));function oit(e,t){return t?`${e} ${t}`:e}function sit(e){let t=typeof e==`string`?e:e.toString();D(y5,this)?D(v5,this).writeStderr(t):D(v5,this).writeStdout(t)}function cit(e){D(F5,e)&&D(N5,e)?D(N5,e).call(e,e.background.bind(e)):S(z5,e,p5).call(e,h5)}function lit(){D(M5,this).reason!==`interrupt`&&this.kill()}function uit(e,t){let n=e??(t===`SIGTERM`?144:1);S(z5,this,d5).call(this,n)}function dit(){S(z5,this,d5).call(this,1)}function d5(e){D(L5,this)&&(D(L5,this).call(this,e),k(L5,this,null))}function f5(){S(z5,this,fit).call(this);let e=D(O5,this);e&&(clearTimeout(e),k(O5,this,null));let t=D(R5,this);t&&(D(M5,this).removeEventListener(`abort`,t),k(R5,this,null))}function fit(){D(k5,this)&&(clearInterval(D(k5,this)),k(k5,this,null))}function pit(){k(k5,this,setInterval(()=>{Yc(this.taskOutput.path).then(e=>{e.size>D(j5,this)&&D(C5,this)===`backgrounded`&&D(k5,this)!==null&&(k(A5,this,!0),S(z5,this,fit).call(this),S(z5,this,p5).call(this,m5))},()=>{})},bit)),D(k5,this).unref()}function mit(){k(R5,this,S(z5,this,lit).bind(this)),D(M5,this).addEventListener(`abort`,D(R5,this),{once:!0}),D(D5,this).once(`exit`,S(z5,this,uit).bind(this)),D(D5,this).once(`error`,S(z5,this,dit).bind(this)),k(O5,this,setTimeout(cit,D(P5,this),this));let e=new Promise(e=>{k(L5,this,e)});return new Promise(t=>{k(I5,this,t),e.then(S(z5,this,hit).bind(this))})}async function hit(e){S(z5,this,f5).call(this),(D(C5,this)===`running`||D(C5,this)===`backgrounded`)&&k(C5,this,`completed`);let t={code:e,stdout:await this.taskOutput.getStdout(),stderr:this.taskOutput.getStderr(),interrupted:e===m5,backgroundTaskId:D(w5,this)};this.taskOutput.stdoutToFile&&!D(w5,this)&&(this.taskOutput.outputFileRedundant?this.taskOutput.deleteOutputFile():(t.outputFilePath=this.taskOutput.path,t.outputFileSize=this.taskOutput.outputFileSize,t.outputTaskId=this.taskOutput.taskId)),D(A5,this)?t.stderr=oit(`Background command killed: output file exceeded 5GB`,t.stderr):e===h5&&(t.stderr=oit(`Command timed out after ${Ua(D(P5,this))}`,t.stderr));let n=D(I5,this);n&&(k(I5,this,null),n(t))}function p5(e){k(C5,this,`killed`),D(D5,this).pid&&(0,yit.default)(D(D5,this).pid,`SIGKILL`),S(z5,this,d5).call(this,e??m5)}function git(e,t,n,r,i=!1,a=Y8){return new xit(e,t,n,r,i,a)}function _it(e,t){return new Sit({backgroundTaskId:e,...t})}function vit(e){let t=new Jy(c5(`local_bash`),null);return{status:`completed`,result:Promise.resolve({code:1,stdout:``,stderr:e,interrupted:!1,preSpawnError:e}),taskOutput:t,background(){return!1},kill(){},cleanup(){}}}var yit,m5,h5,bit,g5,_5,v5,y5,b5,x5,S5,C5,w5,T5,E5,D5,O5,k5,A5,j5,M5,N5,P5,F5,I5,L5,R5,z5,xit,Sit,Cit=n((()=>{yit=r(yue(),1),u5(),Ra(),s5(),Qy(),A(),C(),E(),T(),w(),b(),m5=137,h5=143,bit=5e3,g5=new WeakMap,_5=new WeakMap,v5=new WeakMap,y5=new WeakMap,b5=new WeakMap,x5=new WeakSet,S5=class{constructor(e,t,n){ee(this,x5),O(this,g5,void 0),O(this,_5,!1),O(this,v5,void 0),O(this,y5,void 0),O(this,b5,S(x5,this,sit).bind(this)),k(g5,this,e),k(v5,this,t),k(y5,this,n),e.setEncoding(`utf-8`),e.on(`data`,D(b5,this))}cleanup(){D(_5,this)||(k(_5,this,!0),D(g5,this).removeListener(`data`,D(b5,this)),k(g5,this,null),k(v5,this,null),k(b5,this,()=>{}))}},C5=new WeakMap,w5=new WeakMap,T5=new WeakMap,E5=new WeakMap,D5=new WeakMap,O5=new WeakMap,k5=new WeakMap,A5=new WeakMap,j5=new WeakMap,M5=new WeakMap,N5=new WeakMap,P5=new WeakMap,F5=new WeakMap,I5=new WeakMap,L5=new WeakMap,R5=new WeakMap,z5=new WeakSet,xit=class{constructor(e,t,n,r,i=!1,a=Y8){ee(this,z5),O(this,C5,`running`),O(this,w5,void 0),O(this,T5,void 0),O(this,E5,void 0),O(this,D5,void 0),O(this,O5,null),O(this,k5,null),O(this,A5,!1),O(this,j5,void 0),O(this,M5,void 0),O(this,N5,void 0),O(this,P5,void 0),O(this,F5,void 0),O(this,I5,null),O(this,L5,null),O(this,R5,null),x(this,`taskOutput`,void 0),x(this,`result`,void 0),x(this,`onTimeout`,void 0),k(D5,this,e),k(M5,this,t),k(P5,this,n),k(F5,this,i),k(j5,this,a),this.taskOutput=r,k(E5,this,e.stderr?new S5(e.stderr,r,!0):null),k(T5,this,e.stdout?new S5(e.stdout,r,!1):null),i&&(this.onTimeout=e=>{k(N5,this,e)}),this.result=S(z5,this,mit).call(this)}get status(){return D(C5,this)}kill(){S(z5,this,p5).call(this)}background(e){return D(C5,this)===`running`?(k(w5,this,e),k(C5,this,`backgrounded`),S(z5,this,f5).call(this),this.taskOutput.stdoutToFile?S(z5,this,pit).call(this):this.taskOutput.spillToDisk(),!0):!1}cleanup(){D(T5,this)?.cleanup(),D(E5,this)?.cleanup(),this.taskOutput.clear(),S(z5,this,f5).call(this),k(D5,this,null),k(M5,this,null),k(N5,this,void 0)}},Sit=class{constructor(e){x(this,`status`,`killed`),x(this,`result`,void 0),x(this,`taskOutput`,void 0),this.taskOutput=new Jy(c5(`local_bash`),null),this.result=Promise.resolve({code:e?.code??145,stdout:``,stderr:e?.stderr??`Command aborted before execution`,interrupted:!0,backgroundTaskId:e?.backgroundTaskId})}background(){return!1}kill(){}cleanup(){}}})),B5,V5,wit=n((()=>{It(),rt(),B5=R(()=>pt.enum([`allow`,`deny`,`ask`])),V5=R(()=>pt.object({toolName:pt.string(),ruleContent:pt.string().optional()}))})),H5,U5,Tit=n((()=>{It(),rt(),Rt(),wit(),H5=R(()=>pt.enum([`userSettings`,`projectSettings`,`localSettings`,`session`,`cliArg`])),U5=R(()=>pt.discriminatedUnion(`type`,[pt.object({type:pt.literal(`addRules`),rules:pt.array(V5()),behavior:B5(),destination:H5()}),pt.object({type:pt.literal(`replaceRules`),rules:pt.array(V5()),behavior:B5(),destination:H5()}),pt.object({type:pt.literal(`removeRules`),rules:pt.array(V5()),behavior:B5(),destination:H5()}),pt.object({type:pt.literal(`setMode`),mode:kee(),destination:H5()}),pt.object({type:pt.literal(`addDirectories`),directories:pt.array(pt.string()),destination:H5()}),pt.object({type:pt.literal(`removeDirectories`),directories:pt.array(pt.string()),destination:H5()})]))}));function W5(e){return!(`async`in e&&e.async===!0)}function G5(e){return`async`in e&&e.async===!0}var Eit,Dit,K5,Oit=n((()=>{It(),rt(),Pn(),wit(),Tit(),Eit=R(()=>z({prompt:B(),message:B(),options:I(z({key:B(),label:B(),description:B().optional()}))})),Dit=R(()=>z({continue:Ot().describe(`Whether Work Mate should continue after hook (default: true)`).optional(),suppressOutput:Ot().describe(`Hide stdout from transcript (default: false)`).optional(),stopReason:B().describe(`Message shown when continue is false`).optional(),decision:bt([`approve`,`block`]).optional(),reason:B().describe(`Explanation for the decision`).optional(),systemMessage:B().describe(`Warning message shown to the user`).optional(),hookSpecificOutput:_n([z({hookEventName:L(`PreToolUse`),permissionDecision:B5().optional(),permissionDecisionReason:B().optional(),updatedInput:dn(B(),Fn()).optional(),additionalContext:B().optional()}),z({hookEventName:L(`UserPromptSubmit`),additionalContext:B().optional()}),z({hookEventName:L(`SessionStart`),additionalContext:B().optional(),initialUserMessage:B().optional(),watchPaths:I(B()).describe(`Absolute paths to watch for FileChanged hooks`).optional()}),z({hookEventName:L(`Setup`),additionalContext:B().optional()}),z({hookEventName:L(`SubagentStart`),additionalContext:B().optional()}),z({hookEventName:L(`PostToolUse`),additionalContext:B().optional(),updatedMCPToolOutput:Fn().describe(`Updates the output for MCP tools`).optional()}),z({hookEventName:L(`PostToolUseFailure`),additionalContext:B().optional()}),z({hookEventName:L(`PermissionDenied`),retry:Ot().optional()}),z({hookEventName:L(`Notification`),additionalContext:B().optional()}),z({hookEventName:L(`PermissionRequest`),decision:_n([z({behavior:L(`allow`),updatedInput:dn(B(),Fn()).optional(),updatedPermissions:I(U5()).optional()}),z({behavior:L(`deny`),message:B().optional(),interrupt:Ot().optional()})])}),z({hookEventName:L(`Elicitation`),action:bt([`accept`,`decline`,`cancel`]).optional(),content:dn(B(),Fn()).optional()}),z({hookEventName:L(`ElicitationResult`),action:bt([`accept`,`decline`,`cancel`]).optional(),content:dn(B(),Fn()).optional()}),z({hookEventName:L(`CwdChanged`),watchPaths:I(B()).describe(`Absolute paths to watch for FileChanged hooks`).optional()}),z({hookEventName:L(`FileChanged`),watchPaths:I(B()).describe(`Absolute paths to watch for FileChanged hooks`).optional()}),z({hookEventName:L(`WorktreeCreate`),worktreePath:B()})]).optional()})),K5=R(()=>_n([z({async:L(!0),asyncTimeout:V().optional()}),Dit()]))}));function q5(e,t){let{signalB:n,timeoutMs:r}=t??{},i=HT();if(e?.aborted||n?.aborted)return i.abort(),{signal:i.signal,cleanup:()=>{}};let a,o=()=>{a!==void 0&&clearTimeout(a),i.abort()};return r!==void 0&&(a=setTimeout(o,r),a.unref?.()),e?.addEventListener(`abort`,o),n?.addEventListener(`abort`,o),{signal:i.signal,cleanup:()=>{a!==void 0&&clearTimeout(a),e?.removeEventListener(`abort`,o),n?.removeEventListener(`abort`,o)}}}var J5=n((()=>{GT()}));function kit(e,t){return S2(e,t)}function Ait(){return{...Wae,inputSchema:Y5(),inputJSONSchema:{type:`object`,properties:{ok:{type:`boolean`,description:`Whether the condition was met`},reason:{type:`string`,description:`Reason, if the condition was not met`}},required:[`ok`],additionalProperties:!1},async prompt(){return`Use this tool to return your verification result. You MUST call this tool exactly once at the end of your response.`}}}function jit(e,t){KVe(e,t,`Stop`,``,e=>q9e(e,ws),`You MUST call the ${ws} tool to complete this request. Call this tool now.`,{timeout:5e3})}var Y5,X5=n((()=>{It(),ls(),C2(),rt(),v3(),OY(),Y5=R(()=>z({ok:Ot().describe(`Whether the condition was met`),reason:B().describe(`Reason, if the condition was not met`).optional()}))}));async function Mit(e,t,n,r,i,a,o,s){let c=s||`hook-${Lc()}`;try{let s=kit(e.prompt,r);K(`Hooks: Processing prompt hook with prompt: ${s}`);let l=Q({content:s}),u=o&&o.length>0?[...o,l]:[l];K(`Hooks: Querying model with ${u.length} messages`);let{signal:d,cleanup:f}=q5(i,{timeoutMs:e.timeout?e.timeout*1e3:3e4});try{let r=await Z7({messages:u,systemPrompt:t_([`You are evaluating a hook in Work Mate.
3067
3067
 
@@ -3074,7 +3074,7 @@ Use as few steps as possible - be efficient and direct.
3074
3074
 
3075
3075
  When done, return your result using the ${ws} tool with:
3076
3076
  - ok: true if the condition is met
3077
- - ok: false with reason if the condition is not met`]),c=e.model??zo(),g=Pj(`hook-agent-${Lc()}`),_={...a,agentId:g,abortController:f,options:{...a.options,tools:i,mainLoopModel:c,isNonInteractiveSession:!0,thinkingConfig:{type:`disabled`}},setInProgressToolUseIDs:()=>{},getAppState(){let e=a.getAppState(),t=e.toolPermissionContext.alwaysAllowRules.session??[];return{...e,toolPermissionContext:{...e.toolPermissionContext,mode:`dontAsk`,alwaysAllowRules:{...e.toolPermissionContext.alwaysAllowRules,session:[...t,`Read(/${u})`]}}}}};jit(a.setAppState,g);let v=null,y=0,b=!1;for await(let e of t0({messages:s,systemPrompt:o,userContext:{},systemContext:{},canUseTool:A9,toolUseContext:_,querySource:`hook_agent`}))if(Net(e,()=>{},e=>a.setResponseLength(t=>t+e.length),a.setStreamMode??(()=>{}),()=>{}),!(e.type===`stream_event`||e.type===`stream_request_start`)){if(e.type===`assistant`&&(y++,y>=50)){b=!0,K(`Hooks: Agent turn ${y} hit max turns, aborting`),f.abort();break}if(Pit(e)){let t=Y5().safeParse(e.attachment.data);if(t.success){v=t.data,K(`Hooks: Got structured output: ${W(v)}`),f.abort();break}}}return p.removeEventListener(`abort`,h),m(),DY(a.setAppState,g),v?v.ok?(K(`Hooks: Agent hook condition was met`),Date.now()-d,{hook:e,outcome:`success`,message:a2({type:`hook_success`,hookName:t,toolUseID:l,hookEvent:n,content:``})}):(K(`Hooks: Agent hook condition was not met: ${v.reason}`),{hook:e,outcome:`blocking`,blockingError:{blockingError:`Agent hook condition was not met: ${v.reason}`,command:e.prompt}}):b?(K(`Hooks: Agent hook did not complete within 50 turns`),Date.now()-d,{hook:e,outcome:`cancelled`}):(K(`Hooks: Agent hook did not return structured output`),Date.now()-d,{hook:e,outcome:`cancelled`})}catch(t){if(p.removeEventListener(`abort`,h),m(),g.aborted)return{hook:e,outcome:`cancelled`};throw t}}catch(r){let i=G(r);return K(`Hooks: Agent hook error: ${i}`),Date.now()-d,{hook:e,outcome:`non_blocking_error`,message:a2({type:`hook_non_blocking_error`,hookName:t,toolUseID:l,hookEvent:n,stderr:`Error executing agent hook: ${i}`,stdout:``,exitCode:1})}}}var Iit=n((()=>{n0(),La(),Ms(),ls(),k1(),Fj(),GT(),g2(),J5(),q(),gi(),v3(),wo(),j9(),_8(),Li(),Iw(),X5(),OY()}));function Lit(e){let t=hce(e);return t===4?Rit(e):t===6&&zit(e)}function Rit(e){let t=e.split(`.`).map(Number),[n,r]=t;return t.length!==4||n===void 0||r===void 0||t.some(e=>Number.isNaN(e))||n===127?!1:n===0||n===10||n===169&&r===254||n===172&&r>=16&&r<=31||n===100&&r>=64&&r<=127||n===192&&r===168}function zit(e){let t=e.toLowerCase();if(t===`::1`)return!1;if(t===`::`)return!0;let n=Vit(t);if(n!==null)return Rit(n);if(t.startsWith(`fc`)||t.startsWith(`fd`))return!0;let r=t.split(`:`)[0];return!!(r&&r.length===4&&r>=`fe80`&&r<=`febf`)}function Bit(e){let t=[];if(e.includes(`.`)){let n=e.lastIndexOf(`:`),r=e.slice(n+1);e=e.slice(0,n);let i=r.split(`.`).map(Number);if(i.length!==4||i.some(e=>!Number.isInteger(e)||e<0||e>255))return null;t=[i[0]<<8|i[1],i[2]<<8|i[3]]}let n=e.indexOf(`::`),r,i;if(n===-1)r=e.split(`:`),i=[];else{let t=e.slice(0,n),a=e.slice(n+2);r=t===``?[]:t.split(`:`),i=a===``?[]:a.split(`:`)}let a=8-t.length-r.length-i.length;if(a<0)return null;let o=[...r,...Array(a).fill(`0`),...i].map(e=>parseInt(e,16));return o.some(e=>Number.isNaN(e)||e<0||e>65535)?null:(o.push(...t),o.length===8?o:null)}function Vit(e){let t=Bit(e);if(!t)return null;if(t[0]===0&&t[1]===0&&t[2]===0&&t[3]===0&&t[4]===0&&t[5]===65535){let e=t[6],n=t[7];return`${e>>8}.${e&255}.${n>>8}.${n&255}`}return null}function Hit(e,t,n){let r=`all`in t&&t.all===!0,i=hce(e);if(i!==0){if(Lit(e)){n(Uit(e,e),``);return}let t=i===6?6:4;r?n(null,[{address:e,family:t}]):n(null,e,t);return}jce(e,{all:!0},(t,i)=>{if(t){n(t,``);return}for(let{address:t}of i)if(Lit(t)){n(Uit(e,t),``);return}let a=i[0];if(!a){n(Object.assign(Error(`ENOTFOUND ${e}`),{code:`ENOTFOUND`,hostname:e}),``);return}let o=a.family===6?6:4;r?n(null,i.map(e=>({address:e.address,family:e.family===6?6:4}))):n(null,a.address,o)})}function Uit(e,t){let n=Error(`HTTP hook blocked: ${e} resolves to ${t} (private/link-local address). Loopback (127.0.0.1, ::1) is allowed for local dev.`);return Object.assign(n,{code:`ERR_HTTP_HOOK_BLOCKED_ADDRESS`,hostname:e,address:t})}var Wit=n((()=>{}));async function Git(){let{SandboxManager:e}=await import(`./sandbox-adapter-BNLLtZ41.js`);if(!e.isSandboxingEnabled())return;await e.waitForNetworkInitialization();let t=e.getProxyPort();if(t)return{host:`127.0.0.1`,port:t,protocol:`http`}}function Kit(){let e=rr();return{allowedUrls:e.allowedHttpHookUrls,allowedEnvVars:e.httpHookAllowedEnvVars}}function qit(e,t){let n=t.replace(/[.+?^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`.*`);return RegExp(`^${n}$`).test(e)}function Jit(e){return e.replace(/[\r\n\x00]/g,``)}function Yit(e,t){return Jit(e.replace(/\$\{([A-Z_][A-Z0-9_]*)\}|\$([A-Z_][A-Z0-9_]*)/g,(e,n,r)=>{let i=n??r;return t.has(i)?process.env[i]??``:(K(`Hooks: env var $${i} not in allowedEnvVars, skipping interpolation`,{level:`warn`}),``)}))}async function Xit(e,t,n,r){let i=Kit();if(i.allowedUrls!==void 0&&!i.allowedUrls.some(t=>qit(e.url,t))){let t=`HTTP hook blocked: ${e.url} does not match any pattern in allowedHttpHookUrls`;return K(t,{level:`warn`}),{ok:!1,body:``,error:t}}let{signal:a,cleanup:o}=q5(r,{timeoutMs:e.timeout?e.timeout*1e3:Zit});try{let t={"Content-Type":`application/json`};if(e.headers){let n=e.allowedEnvVars??[],r=i.allowedEnvVars===void 0?n:n.filter(e=>i.allowedEnvVars.includes(e)),a=new Set(r);for(let[n,r]of Object.entries(e.headers))t[n]=Yit(r,a)}let r=await Git(),s=!r&&toe()!==void 0&&!noe(e.url);K(r?`Hooks: HTTP hook POST to ${e.url} (via sandbox proxy :${r.port})`:s?`Hooks: HTTP hook POST to ${e.url} (via env-var proxy)`:`Hooks: HTTP hook POST to ${e.url}`);let c=await ue.post(e.url,n,{headers:t,signal:a,responseType:`text`,validateStatus:()=>!0,maxRedirects:0,proxy:r??!1,lookup:r||s?void 0:Hit});o();let l=c.data??``;return K(`Hooks: HTTP hook response status ${c.status}, body length ${l.length}`),{ok:c.status>=200&&c.status<300,statusCode:c.status,body:l}}catch(e){if(o(),a.aborted)return{ok:!1,body:``,aborted:!0};let t=G(e);return K(`Hooks: HTTP hook error: ${t}`,{level:`error`}),{ok:!1,body:``,error:t}}}var Zit,Qit=n((()=>{de(),J5(),q(),gi(),zs(),Ln(),Wit(),Zit=600*1e3}));function $it(){let e=process.env.WORKMATE_SESSIONEND_HOOKS_TIMEOUT_MS,t=e?parseInt(e,10):NaN;return Number.isFinite(t)&&t>0?t:Bat}function eat({processId:e,hookId:t,shellCommand:n,asyncResponse:r,hookEvent:i,hookName:a,command:o,asyncRewake:s,pluginId:c}){return s?(n.result.then(async e=>{await new Promise(e=>setImmediate(e));let r=await n.taskOutput.getStdout(),o=n.taskOutput.getStderr();n.cleanup(),G0({hookId:t,hookName:a,hookEvent:i,output:r+o,stdout:r,stderr:o,exitCode:e.code,outcome:e.code===0?`success`:`error`}),e.code===2&&sE({value:r3(`Stop hook blocking error from command "${a}": ${o||r}`),mode:`task-notification`})}),!0):n.background(e)?(y6e({processId:e,hookId:t,asyncResponse:r,hookEvent:i,hookName:a,command:o,shellCommand:n,pluginId:c}),!0):!1}function Z5(){return!kr()&&!Yi()}function Q5(e,t,n){let r=t??Wr(),i=n?.agentType??jne();return{session_id:r,transcript_path:m6(r),cwd:U(),permission_mode:e,agent_id:n?.agentId,agent_type:i}}function tat(e){let t=Si(e),n=K5().safeParse(t);return n.success?(K(`Successfully parsed and validated hook JSON output`),{json:n.data}):{validationError:`Hook JSON output validation failed:\n${n.error.issues.map(e=>` - ${e.path.join(`.`)}: ${e.message}`).join(`
3077
+ - ok: false with reason if the condition is not met`]),c=e.model??zo(),g=Pj(`hook-agent-${Lc()}`),_={...a,agentId:g,abortController:f,options:{...a.options,tools:i,mainLoopModel:c,isNonInteractiveSession:!0,thinkingConfig:{type:`disabled`}},setInProgressToolUseIDs:()=>{},getAppState(){let e=a.getAppState(),t=e.toolPermissionContext.alwaysAllowRules.session??[];return{...e,toolPermissionContext:{...e.toolPermissionContext,mode:`dontAsk`,alwaysAllowRules:{...e.toolPermissionContext.alwaysAllowRules,session:[...t,`Read(/${u})`]}}}}};jit(a.setAppState,g);let v=null,y=0,b=!1;for await(let e of t0({messages:s,systemPrompt:o,userContext:{},systemContext:{},canUseTool:A9,toolUseContext:_,querySource:`hook_agent`}))if(Net(e,()=>{},e=>a.setResponseLength(t=>t+e.length),a.setStreamMode??(()=>{}),()=>{}),!(e.type===`stream_event`||e.type===`stream_request_start`)){if(e.type===`assistant`&&(y++,y>=50)){b=!0,K(`Hooks: Agent turn ${y} hit max turns, aborting`),f.abort();break}if(Pit(e)){let t=Y5().safeParse(e.attachment.data);if(t.success){v=t.data,K(`Hooks: Got structured output: ${W(v)}`),f.abort();break}}}return p.removeEventListener(`abort`,h),m(),DY(a.setAppState,g),v?v.ok?(K(`Hooks: Agent hook condition was met`),Date.now()-d,{hook:e,outcome:`success`,message:a2({type:`hook_success`,hookName:t,toolUseID:l,hookEvent:n,content:``})}):(K(`Hooks: Agent hook condition was not met: ${v.reason}`),{hook:e,outcome:`blocking`,blockingError:{blockingError:`Agent hook condition was not met: ${v.reason}`,command:e.prompt}}):b?(K(`Hooks: Agent hook did not complete within 50 turns`),Date.now()-d,{hook:e,outcome:`cancelled`}):(K(`Hooks: Agent hook did not return structured output`),Date.now()-d,{hook:e,outcome:`cancelled`})}catch(t){if(p.removeEventListener(`abort`,h),m(),g.aborted)return{hook:e,outcome:`cancelled`};throw t}}catch(r){let i=G(r);return K(`Hooks: Agent hook error: ${i}`),Date.now()-d,{hook:e,outcome:`non_blocking_error`,message:a2({type:`hook_non_blocking_error`,hookName:t,toolUseID:l,hookEvent:n,stderr:`Error executing agent hook: ${i}`,stdout:``,exitCode:1})}}}var Iit=n((()=>{n0(),La(),Ms(),ls(),k1(),Fj(),GT(),g2(),J5(),q(),gi(),v3(),wo(),j9(),_8(),Li(),Iw(),X5(),OY()}));function Lit(e){let t=hce(e);return t===4?Rit(e):t===6&&zit(e)}function Rit(e){let t=e.split(`.`).map(Number),[n,r]=t;return t.length!==4||n===void 0||r===void 0||t.some(e=>Number.isNaN(e))||n===127?!1:n===0||n===10||n===169&&r===254||n===172&&r>=16&&r<=31||n===100&&r>=64&&r<=127||n===192&&r===168}function zit(e){let t=e.toLowerCase();if(t===`::1`)return!1;if(t===`::`)return!0;let n=Vit(t);if(n!==null)return Rit(n);if(t.startsWith(`fc`)||t.startsWith(`fd`))return!0;let r=t.split(`:`)[0];return!!(r&&r.length===4&&r>=`fe80`&&r<=`febf`)}function Bit(e){let t=[];if(e.includes(`.`)){let n=e.lastIndexOf(`:`),r=e.slice(n+1);e=e.slice(0,n);let i=r.split(`.`).map(Number);if(i.length!==4||i.some(e=>!Number.isInteger(e)||e<0||e>255))return null;t=[i[0]<<8|i[1],i[2]<<8|i[3]]}let n=e.indexOf(`::`),r,i;if(n===-1)r=e.split(`:`),i=[];else{let t=e.slice(0,n),a=e.slice(n+2);r=t===``?[]:t.split(`:`),i=a===``?[]:a.split(`:`)}let a=8-t.length-r.length-i.length;if(a<0)return null;let o=[...r,...Array(a).fill(`0`),...i].map(e=>parseInt(e,16));return o.some(e=>Number.isNaN(e)||e<0||e>65535)?null:(o.push(...t),o.length===8?o:null)}function Vit(e){let t=Bit(e);if(!t)return null;if(t[0]===0&&t[1]===0&&t[2]===0&&t[3]===0&&t[4]===0&&t[5]===65535){let e=t[6],n=t[7];return`${e>>8}.${e&255}.${n>>8}.${n&255}`}return null}function Hit(e,t,n){let r=`all`in t&&t.all===!0,i=hce(e);if(i!==0){if(Lit(e)){n(Uit(e,e),``);return}let t=i===6?6:4;r?n(null,[{address:e,family:t}]):n(null,e,t);return}jce(e,{all:!0},(t,i)=>{if(t){n(t,``);return}for(let{address:t}of i)if(Lit(t)){n(Uit(e,t),``);return}let a=i[0];if(!a){n(Object.assign(Error(`ENOTFOUND ${e}`),{code:`ENOTFOUND`,hostname:e}),``);return}let o=a.family===6?6:4;r?n(null,i.map(e=>({address:e.address,family:e.family===6?6:4}))):n(null,a.address,o)})}function Uit(e,t){let n=Error(`HTTP hook blocked: ${e} resolves to ${t} (private/link-local address). Loopback (127.0.0.1, ::1) is allowed for local dev.`);return Object.assign(n,{code:`ERR_HTTP_HOOK_BLOCKED_ADDRESS`,hostname:e,address:t})}var Wit=n((()=>{}));async function Git(){let{SandboxManager:e}=await import(`./sandbox-adapter-DHCb-L3c.js`);if(!e.isSandboxingEnabled())return;await e.waitForNetworkInitialization();let t=e.getProxyPort();if(t)return{host:`127.0.0.1`,port:t,protocol:`http`}}function Kit(){let e=rr();return{allowedUrls:e.allowedHttpHookUrls,allowedEnvVars:e.httpHookAllowedEnvVars}}function qit(e,t){let n=t.replace(/[.+?^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`.*`);return RegExp(`^${n}$`).test(e)}function Jit(e){return e.replace(/[\r\n\x00]/g,``)}function Yit(e,t){return Jit(e.replace(/\$\{([A-Z_][A-Z0-9_]*)\}|\$([A-Z_][A-Z0-9_]*)/g,(e,n,r)=>{let i=n??r;return t.has(i)?process.env[i]??``:(K(`Hooks: env var $${i} not in allowedEnvVars, skipping interpolation`,{level:`warn`}),``)}))}async function Xit(e,t,n,r){let i=Kit();if(i.allowedUrls!==void 0&&!i.allowedUrls.some(t=>qit(e.url,t))){let t=`HTTP hook blocked: ${e.url} does not match any pattern in allowedHttpHookUrls`;return K(t,{level:`warn`}),{ok:!1,body:``,error:t}}let{signal:a,cleanup:o}=q5(r,{timeoutMs:e.timeout?e.timeout*1e3:Zit});try{let t={"Content-Type":`application/json`};if(e.headers){let n=e.allowedEnvVars??[],r=i.allowedEnvVars===void 0?n:n.filter(e=>i.allowedEnvVars.includes(e)),a=new Set(r);for(let[n,r]of Object.entries(e.headers))t[n]=Yit(r,a)}let r=await Git(),s=!r&&toe()!==void 0&&!noe(e.url);K(r?`Hooks: HTTP hook POST to ${e.url} (via sandbox proxy :${r.port})`:s?`Hooks: HTTP hook POST to ${e.url} (via env-var proxy)`:`Hooks: HTTP hook POST to ${e.url}`);let c=await ue.post(e.url,n,{headers:t,signal:a,responseType:`text`,validateStatus:()=>!0,maxRedirects:0,proxy:r??!1,lookup:r||s?void 0:Hit});o();let l=c.data??``;return K(`Hooks: HTTP hook response status ${c.status}, body length ${l.length}`),{ok:c.status>=200&&c.status<300,statusCode:c.status,body:l}}catch(e){if(o(),a.aborted)return{ok:!1,body:``,aborted:!0};let t=G(e);return K(`Hooks: HTTP hook error: ${t}`,{level:`error`}),{ok:!1,body:``,error:t}}}var Zit,Qit=n((()=>{de(),J5(),q(),gi(),zs(),Ln(),Wit(),Zit=600*1e3}));function $it(){let e=process.env.WORKMATE_SESSIONEND_HOOKS_TIMEOUT_MS,t=e?parseInt(e,10):NaN;return Number.isFinite(t)&&t>0?t:Bat}function eat({processId:e,hookId:t,shellCommand:n,asyncResponse:r,hookEvent:i,hookName:a,command:o,asyncRewake:s,pluginId:c}){return s?(n.result.then(async e=>{await new Promise(e=>setImmediate(e));let r=await n.taskOutput.getStdout(),o=n.taskOutput.getStderr();n.cleanup(),G0({hookId:t,hookName:a,hookEvent:i,output:r+o,stdout:r,stderr:o,exitCode:e.code,outcome:e.code===0?`success`:`error`}),e.code===2&&sE({value:r3(`Stop hook blocking error from command "${a}": ${o||r}`),mode:`task-notification`})}),!0):n.background(e)?(y6e({processId:e,hookId:t,asyncResponse:r,hookEvent:i,hookName:a,command:o,shellCommand:n,pluginId:c}),!0):!1}function Z5(){return!kr()&&!Yi()}function Q5(e,t,n){let r=t??Wr(),i=n?.agentType??jne();return{session_id:r,transcript_path:m6(r),cwd:U(),permission_mode:e,agent_id:n?.agentId,agent_type:i}}function tat(e){let t=Si(e),n=K5().safeParse(t);return n.success?(K(`Successfully parsed and validated hook JSON output`),{json:n.data}):{validationError:`Hook JSON output validation failed:\n${n.error.issues.map(e=>` - ${e.path.join(`.`)}: ${e.message}`).join(`
3078
3078
  `)}\n\nThe hook's output was: ${W(t,null,2)}`}}function nat(e){let t=e.trim();if(!t.startsWith(`{`))return K(`Hook output does not start with {, treating as plain text`),{plainText:e};try{let n=tat(t);if(`json`in n)return n;let r=`${n.validationError}\n\nExpected schema:\n${W({continue:`boolean (optional)`,suppressOutput:`boolean (optional)`,stopReason:`string (optional)`,decision:`"approve" | "block" (optional)`,reason:`string (optional)`,systemMessage:`string (optional)`,permissionDecision:`"allow" | "deny" | "ask" (optional)`,hookSpecificOutput:{"for PreToolUse":{hookEventName:`"PreToolUse"`,permissionDecision:`"allow" | "deny" | "ask" (optional)`,permissionDecisionReason:`string (optional)`,updatedInput:`object (optional) - Modified tool input to use`},"for UserPromptSubmit":{hookEventName:`"UserPromptSubmit"`,additionalContext:`string (required)`},"for PostToolUse":{hookEventName:`"PostToolUse"`,additionalContext:`string (optional)`}}},null,2)}`;return K(r),{plainText:e,validationError:r}}catch(t){return K(`Failed to parse hook output as JSON: ${t}`),{plainText:e}}}function rat(e){let t=e.trim();if(t===``){let e=K5().safeParse({});if(e.success)return K(`HTTP hook returned empty body, treating as empty JSON object`),{json:e.data}}if(!t.startsWith(`{`)){let e=`HTTP hook must return JSON, but got non-JSON response body: ${t.length>200?`${t.slice(0,200)}\u2026`:t}`;return K(e),{validationError:e}}try{let e=tat(t);return`json`in e||K(e.validationError),e}catch(e){let t=`HTTP hook must return valid JSON, but parsing failed: ${e}`;return K(t),{validationError:t}}}function $5({json:e,command:t,hookName:n,toolUseID:r,hookEvent:i,expectedHookEvent:a,stdout:o,stderr:s,exitCode:c,durationMs:l}){let u={},d=e,f=d;if(f.continue===!1&&(u.preventContinuation=!0,f.stopReason&&(u.stopReason=f.stopReason)),d.decision)switch(d.decision){case`approve`:u.permissionBehavior=`allow`;break;case`block`:u.permissionBehavior=`deny`,u.blockingError={blockingError:d.reason||`Blocked by hook`,command:t};break;default:throw Error(`Unknown hook decision type: ${d.decision}. Valid types are: approve, block`)}if(d.systemMessage&&(u.systemMessage=d.systemMessage),d.hookSpecificOutput?.hookEventName===`PreToolUse`&&d.hookSpecificOutput.permissionDecision)switch(d.hookSpecificOutput.permissionDecision){case`allow`:u.permissionBehavior=`allow`;break;case`deny`:u.permissionBehavior=`deny`,u.blockingError={blockingError:d.reason||`Blocked by hook`,command:t};break;case`ask`:u.permissionBehavior=`ask`;break;default:throw Error(`Unknown hook permissionDecision type: ${d.hookSpecificOutput.permissionDecision}. Valid types are: allow, deny, ask`)}if(u.permissionBehavior!==void 0&&d.reason!==void 0&&(u.hookPermissionDecisionReason=d.reason),d.hookSpecificOutput){if(a&&d.hookSpecificOutput.hookEventName!==a)throw Error(`Hook returned incorrect event name: expected '${a}' but got '${d.hookSpecificOutput.hookEventName}'. Full stdout: ${W(d,null,2)}`);switch(d.hookSpecificOutput.hookEventName){case`PreToolUse`:if(d.hookSpecificOutput.permissionDecision)switch(d.hookSpecificOutput.permissionDecision){case`allow`:u.permissionBehavior=`allow`;break;case`deny`:u.permissionBehavior=`deny`,u.blockingError={blockingError:d.hookSpecificOutput.permissionDecisionReason||d.reason||`Blocked by hook`,command:t};break;case`ask`:u.permissionBehavior=`ask`;break}u.hookPermissionDecisionReason=d.hookSpecificOutput.permissionDecisionReason,d.hookSpecificOutput.updatedInput&&(u.updatedInput=d.hookSpecificOutput.updatedInput),u.additionalContext=d.hookSpecificOutput.additionalContext;break;case`UserPromptSubmit`:u.additionalContext=d.hookSpecificOutput.additionalContext;break;case`SessionStart`:u.additionalContext=d.hookSpecificOutput.additionalContext,u.initialUserMessage=d.hookSpecificOutput.initialUserMessage,`watchPaths`in d.hookSpecificOutput&&d.hookSpecificOutput.watchPaths&&(u.watchPaths=d.hookSpecificOutput.watchPaths);break;case`Setup`:u.additionalContext=d.hookSpecificOutput.additionalContext;break;case`SubagentStart`:u.additionalContext=d.hookSpecificOutput.additionalContext;break;case`PostToolUse`:u.additionalContext=d.hookSpecificOutput.additionalContext,d.hookSpecificOutput.updatedMCPToolOutput&&(u.updatedMCPToolOutput=d.hookSpecificOutput.updatedMCPToolOutput);break;case`PostToolUseFailure`:u.additionalContext=d.hookSpecificOutput.additionalContext;break;case`PermissionDenied`:u.retry=d.hookSpecificOutput.retry;break;case`PermissionRequest`:d.hookSpecificOutput.decision&&(u.permissionRequestResult=d.hookSpecificOutput.decision,u.permissionBehavior=d.hookSpecificOutput.decision.behavior===`allow`?`allow`:`deny`,d.hookSpecificOutput.decision.behavior===`allow`&&d.hookSpecificOutput.decision.updatedInput&&(u.updatedInput=d.hookSpecificOutput.decision.updatedInput));break;case`Elicitation`:d.hookSpecificOutput.action&&(u.elicitationResponse={action:d.hookSpecificOutput.action,content:d.hookSpecificOutput.content},d.hookSpecificOutput.action===`decline`&&(u.blockingError={blockingError:d.reason||`Elicitation denied by hook`,command:t}));break;case`ElicitationResult`:d.hookSpecificOutput.action&&(u.elicitationResultResponse={action:d.hookSpecificOutput.action,content:d.hookSpecificOutput.content},d.hookSpecificOutput.action===`decline`&&(u.blockingError={blockingError:d.reason||`Elicitation result blocked by hook`,command:t}));break}}return{...u,message:u.blockingError?a2({type:`hook_blocking_error`,hookName:n,toolUseID:r,hookEvent:i,blockingError:u.blockingError}):a2({type:`hook_success`,hookName:n,toolUseID:r,hookEvent:i,content:``,stdout:o,stderr:s,exitCode:c,command:t,durationMs:l})}}async function e7(e,t,n,r,i,a,o,s,c,l,u,d){let f=t===`SessionStart`||t===`Setup`||t===`SessionEnd`,p=Date.now(),m,h=!1,g=Ma()===`windows`,_=e.shell??`bash`,v=_===`powershell`,y=g&&!v?e=>Vt(e):e=>e,b=Hr(),x=e.command,S;if(s){if(!await qt(s))throw Error(`Plugin directory does not exist: ${s}`+(c?` (${c} — run /plugin to reinstall)`:``));let e=y(s);if(x=x.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g,()=>e),c){let e=y(ny(c));x=x.replace(/\$\{CLAUDE_PLUGIN_DATA\}/g,()=>e)}c&&(S=lI(c),x=sI(x,S))}g&&!v&&x.trim().match(/\.sh(\s|$|")/)&&(x.trim().startsWith(`bash `)||(x=`bash ${x}`));let C=!v&&process.env.WORKMATE_SHELL_PREFIX?H_e(process.env.WORKMATE_SHELL_PREFIX,x):x,w=e.timeout?e.timeout*1e3:g7,T={...Mb(),CLAUDE_PROJECT_DIR:y(b)};if(s&&(T.CLAUDE_PLUGIN_ROOT=y(s),c&&(T.CLAUDE_PLUGIN_DATA=y(ny(c)))),S)for(let[e,t]of Object.entries(S)){let n=e.replace(/[^A-Za-z0-9_]/g,`_`).toUpperCase();T[`CLAUDE_PLUGIN_OPTION_${n}`]=String(t)}l&&(T.CLAUDE_PLUGIN_ROOT=y(l)),!v&&(t===`SessionStart`||t===`Setup`||t===`CwdChanged`||t===`FileChanged`)&&o!==void 0&&(T.CLAUDE_ENV_FILE=await a_e(t,o));let E=U(),D=await qt(E)?E:ti();D!==E&&K(`Hooks: cwd ${E} not found, falling back to original cwd`,{level:`warn`});let O=C;if(!v&&Eg.isSandboxingEnabled())try{O=await Eg.wrapWithSandbox(C,void 0,{network:{allowedDomains:[],deniedDomains:[]},filesystem:{allowWrite:[`/`],denyWrite:[],allowRead:[],denyRead:[]}},i),K(`Hook command sandboxed (network-only): ${e.command}`,{level:`verbose`})}catch(e){K(`Failed to sandbox hook command, running unsandboxed: ${G(e)}`,{level:`warn`})}let k;if(_===`powershell`){let t=await Vb();if(!t)throw Error(`Hook "${e.command}" has shell: 'powershell' but no PowerShell executable (pwsh or powershell) was found on PATH. Install PowerShell, or remove "shell": "powershell" to use bash.`);k=$c(t,ove(C),{env:T,cwd:D,windowsHide:!0})}else{let e=!g||Iee();k=$c(O,[],{env:T,cwd:D,shell:e,windowsHide:!0})}let A=new Jy(`hook_${k.pid}`,null),ee=git(k,i,w,A),te=!1,ne=!1;if((e.async||e.asyncRewake)&&!u){let i=`async_hook_${k.pid}`;if(K(`Hooks: Config-based async hook, backgrounding process ${i}`),k.stdin.write(`${r}\n`,`utf8`),k.stdin.end(),ne=!0,eat({processId:i,hookId:a,shellCommand:ee,asyncResponse:{async:!0,asyncTimeout:w},hookEvent:t,hookName:n,command:e.command,asyncRewake:e.asyncRewake,pluginId:c}))return{stdout:``,stderr:``,output:``,status:0,backgrounded:!0}}let re=``,ie=``,ae=``;k.stdout.setEncoding(`utf8`),k.stderr.setEncoding(`utf8`);let j=!1,oe=null,se=new Promise(e=>{oe=e}),ce=new Set,M=Promise.resolve(),N=``;k.stdout.on(`data`,r=>{if(re+=r,ae+=r,d){N+=r;let e=N.split(`
3079
3079
  `);N=e.pop()??``;for(let t of e){let e=t.trim();if(e)try{let t=Si(e),n=Eit().safeParse(t);if(n.success){ce.add(e),K(`Hooks: Detected prompt request from hook: ${e}`);let t=n.data,r=d;M=M.then(async()=>{try{let e=await r(t);k.stdin.write(`${W(e)}\n`,`utf8`)}catch(e){K(`Hooks: Prompt request handling failed: ${e}`),k.stdin.destroy()}})}}catch{}}}if(!j){let r=Ja(re).trim();if(!r.includes(`}`))return;j=!0,K(`Hooks: Checking first line for async: ${r}`);try{let i=Si(r);if(K(`Hooks: Parsed initial response: ${W(i)}`),G5(i)&&!u){let r=`async_hook_${k.pid}`;K(`Hooks: Detected async hook, backgrounding process ${r}`),eat({processId:r,hookId:a,shellCommand:ee,asyncResponse:i,hookEvent:t,hookName:n,command:e.command,pluginId:c})&&(te=!0,oe?.({stdout:re,stderr:ie,output:ae,status:0}))}else G5(i)&&u?K(`Hooks: Detected async hook but forceSyncExecution is true, waiting for completion`):K(`Hooks: Initial response is not async, continuing normal processing`)}catch(e){K(`Hooks: Failed to parse initial response as JSON: ${e}`)}}}),k.stderr.on(`data`,e=>{ie+=e,ae+=e});let le=h6e({hookId:a,hookName:n,hookEvent:t,getOutput:async()=>({stdout:re,stderr:ie,output:ae})}),ue=new Promise(e=>{k.stdout.on(`end`,()=>e())}),de=new Promise(e=>{k.stderr.on(`end`,()=>e())}),fe=ne?Promise.resolve():new Promise((e,t)=>{k.stdin.on(`error`,e=>{d?K(`Hooks: stdin error during prompt flow (likely process exited): ${e}`):t(e)}),k.stdin.write(`${r}\n`,`utf8`),d||k.stdin.end(),e()}),pe=new Promise((e,t)=>{k.on(`error`,t)}),me=new Promise(e=>{let t=null;k.on(`close`,n=>{t=n??1,Promise.all([ue,de]).then(()=>{e({stdout:ce.size===0?re:re.split(`
3080
3080
  `).filter(e=>!ce.has(e.trim())).join(`
@@ -3271,8 +3271,8 @@ The user context may include a \`terminalFocus\` field indicating whether the us
3271
3271
  `)].filter(Boolean)}function est(e,t){if(Object.entries(t).length===0)return e;let{agentsMd:n,...r}=t,i=[];n&&i.push(Q({content:`<project-instructions>\n${n}\n</project-instructions>\n`,isMeta:!0}));let a=Object.entries(r);return a.length>0&&i.push(Q({content:`<system-reminder>\nAs you answer the user's questions, you can use the following context:\n${a.map(([e,t])=>`# ${e}\n${t}`).join(`
3272
3272
  `)}
3273
3273
 
3274
- IMPORTANT: this context may or may not be relevant to your tasks. You should not respond to this context unless it is highly relevant to your task.\n</system-reminder>\n`,isMeta:!0})),[...i,...e]}async function tst(e,t){if(Got())return;let[{tools:n},r,i,a]=await Promise.all([CVe(e),O1(t),pO(),fO()]);(a.gitStatus?.length??0)+(i.agentsMd?.length??0);let o=U(),s=k8(A8(t),o);await Toe(o,AbortSignal.timeout(1e3),s);let c=0,l=0,u=r.filter(e=>!e.isMcp);n.length,u.length;let d=new Set;for(let e of n){let t=e.name.split(`__`);t.length>=3&&t[1]&&d.add(t[1])}d.size;for(let e of n){let t=`inputJSONSchema`in e&&e.inputJSONSchema?e.inputJSONSchema:NO(e.inputSchema);c+=C3(W(t))}for(let e of u){let t=`inputJSONSchema`in e&&e.inputJSONSchema?e.inputJSONSchema:NO(e.inputSchema);l+=C3(W(t))}}function nst(e,t,n){switch(e.name){case es:{let e=Ad(n),r=kd(n);return Md(),e===null?t:{...t,plan:e,planFilePath:r}}case dB.name:{let e=dB.inputSchema.parse(t),{command:n,timeout:r,description:i}=e,a=U(),o=n.replace(`cd ${a} && `,``);Ma()===`windows`&&(o=o.replace(`cd ${Vt(a)} && `,``)),o=o.replace(/\\\\;/g,`\\;`),/^echo\s+["']?[^|&;><]*["']?$/i.test(o.trim());let s=`run_in_background`in e?e.run_in_background:void 0;return{command:o,description:i,...r!==void 0&&{timeout:r},...i!==void 0&&{description:i},...s!==void 0&&{run_in_background:s},...`dangerouslyDisableSandbox`in e&&e.dangerouslyDisableSandbox!==void 0&&{dangerouslyDisableSandbox:e.dangerouslyDisableSandbox}}}case RX.name:{let e=RX.inputSchema.parse(t),{file_path:n,edits:r}=fCe({file_path:e.file_path,edits:[{old_string:e.old_string,new_string:e.new_string,replace_all:e.replace_all}]});return{replace_all:r[0].replace_all,file_path:n,old_string:r[0].old_string,new_string:r[0].new_string}}case HI.name:{let e=HI.inputSchema.parse(t),n=/\.(md|mdx)$/i.test(e.file_path);return{file_path:e.file_path,content:n?e.content:kw(e.content)}}case Yt:{let e=t,n=e.task_id??e.agentId??e.bash_id,r=e.timeout??(typeof e.wait_up_to==`number`?e.wait_up_to*1e3:void 0);return{task_id:n??``,block:e.block??!0,timeout:r??3e4}}default:return t}}function rst(e,t){switch(e.name){case es:if(t&&typeof t==`object`&&(`plan`in t||`planFilePath`in t)){let{plan:e,planFilePath:n,...r}=t;return r}return t;case RX.name:if(t&&typeof t==`object`&&`edits`in t){let{old_string:e,new_string:n,replace_all:r,...i}=t;return i}return t;default:return t}}var U7,W7=n((()=>{V7(),mO(),Kot(),La(),wY(),fB(),zX(),Fw(),UI(),k1(),Xu(),O3(),Ds(),gt(),Wg(),ui(),q(),g(),v3(),mo(),B8(),Fd(),Pa(),Gs(),Li(),Yot(),ht(),FO(),U7=!1}));function ist(e){let{hasThinking:t=!1,isRedactThinkingActive:n=!1,clearAllThinking:r=!1}=e??{},i=[];t&&!n&&i.push({type:`clear_thinking_20251015`,keep:r?{type:`thinking_turns`,value:1}:`all`});let a=process.env.USE_API_CLEAR_TOOL_RESULTS===void 0||h(process.env.USE_API_CLEAR_TOOL_RESULTS),o=h(process.env.USE_API_CLEAR_TOOL_USES);if(!a&&!o)return i.length>0?{edits:i}:void 0;if(a){let e=process.env.API_MAX_INPUT_TOKENS?parseInt(process.env.API_MAX_INPUT_TOKENS,10):G7,t=process.env.API_TARGET_INPUT_TOKENS?parseInt(process.env.API_TARGET_INPUT_TOKENS,10):K7,n={type:`clear_tool_uses_20250919`,trigger:{type:`input_tokens`,value:e},clear_at_least:{type:`input_tokens`,value:e-t},clear_tool_inputs:ast};i.push(n)}if(o){let e=process.env.API_MAX_INPUT_TOKENS?parseInt(process.env.API_MAX_INPUT_TOKENS,10):G7,t=process.env.API_TARGET_INPUT_TOKENS?parseInt(process.env.API_TARGET_INPUT_TOKENS,10):K7,n={type:`clear_tool_uses_20250919`,trigger:{type:`input_tokens`,value:e},clear_at_least:{type:`input_tokens`,value:e-t},exclude_tools:ost};i.push(n)}return i.length>0?{edits:i}:void 0}var G7,K7,ast,ost,sst=n((()=>{Es(),As(),Is(),Jo(),Go(),hs(),Ps(),g(),G7=18e4,K7=4e4,ast=[...wae,Yo,ts,os],ost=[xs,ss,_s]})),cst,lst=n((()=>{cst={providerId:`bedrock`,parseHeaders(e){let t=[],n=e.get(`x-amzn-bedrock-quota-remaining`),r=e.get(`x-amzn-bedrock-quota-reset`);if(n!==null){let e=Number(n);if(Number.isFinite(e)&&e>=0&&e<=1){let n=r===null?0:Number(r);t.push({kind:`throttle`,label:`Throttle`,utilization:1-e,...Number.isFinite(n)&&n>0?{resetsAt:n}:{}})}}return t}}}));function ust(e,t){let n=-1;for(let t=0;t<e.length;t++){let r=e[t];r&&typeof r==`object`&&`type`in r&&r.type===`tool_result`&&(n=t)}if(n>=0){let r=n+1;e.splice(r,0,t),r===e.length-1&&e.push({type:`text`,text:`.`})}else{let n=Math.max(0,e.length-1);e.splice(n,0,t)}}var dst=n((()=>{})),fst=n((()=>{E_()}));function pst(e){if(e instanceof _i){let t=e.error;if(t?.error?.message)return t.error.message}return e instanceof Error?e.message:String(e)}function mst({headers:e,baseUrl:t}){if(e){let t=[];e.forEach((e,n)=>t.push(n));for(let[e,{prefixes:n}]of Object.entries(bst))if(n.some(e=>t.some(t=>t.startsWith(e))))return e}if(t)try{let e=new URL(t).hostname.toLowerCase();for(let[t,n]of Object.entries(xst))if(n.some(t=>e.endsWith(t)))return t}catch{}}function q7(){return{...process.env.ANTHROPIC_BASE_URL?{baseUrl:process.env.ANTHROPIC_BASE_URL}:{},...process.env.ANTHROPIC_MODEL?{envModel:process.env.ANTHROPIC_MODEL}:{},...process.env.ANTHROPIC_SMALL_FAST_MODEL?{envSmallFastModel:process.env.ANTHROPIC_SMALL_FAST_MODEL}:{}}}function hst(){let e=new Date(`2026-09-23T14:24:20.510Z`).getTime();if(!isNaN(e))return Math.floor((Date.now()-e)/6e4)}function gst({model:e,messagesLength:t,temperature:n,betas:r,permissionMode:i,querySource:a,queryTracking:o,thinkingConfig:s,fastMode:c,previousRequestId:l}){s?.type;let u=s?.type===`enabled`?s.budgetTokens:void 0;uo(),hst(),{...r?.length?{betas:r.join(`,`)}:{}},{...o?{queryChainId:o.chainId,queryDepth:o.depth}:{}},{...u!==void 0&&{thinkingBudgetTokens:u}},{...l?{previousRequestId:l}:{},...q7()}}function _st({error:e,model:t,messageCount:n,messageTokens:r,durationMs:i,durationMsIncludingRetries:a,attempt:o,requestId:s,clientRequestId:c,didFallBackToNonStreaming:l,promptCategory:u,headers:d,queryTracking:f,querySource:p,llmSpan:m,fastMode:h,previousRequestId:g}){let _=mst({headers:e instanceof _i&&e.headers?e.headers:d,baseUrl:process.env.ANTHROPIC_BASE_URL}),v=pst(e),y=e instanceof _i?String(e.status):void 0;swe(e);let b=S_(e);if(b){let e=b.isSSLError?` (SSL error)`:``;K(`Connection error details: code=${b.code}${e}, message=${b.message}`,{level:`error`})}let x=Rj();c&&K(`API error x-client-request-id=${c} (give this to the API team for server-log lookup)`,{level:`error`}),Y(e),uo(),{...x?{invokingRequestId:x.invokingRequestId,invocationKind:x.invocationKind}:{}},{...u?{promptCategory:u}:{},..._?{gateway:_}:{},...f?{queryChainId:f.chainId,queryDepth:f.depth}:{},...p?{querySource:p}:{}},{...g?{previousRequestId:g}:{},...q7()},$s(`api_error`,{model:t,error:v,status_code:String(y),duration_ms:String(i),attempt:String(o),speed:h?`fast`:`normal`}),qoe(m,{success:!1,statusCode:y?parseInt(y,10):void 0,error:v,attempt:o})}function vst({model:e,preNormalizedModel:t,messageCount:n,messageTokens:r,usage:i,durationMs:a,durationMsIncludingRetries:o,attempt:s,ttftMs:c,requestId:l,stopReason:u,costUSD:d,didFallBackToNonStreaming:f,querySource:p,gateway:m,queryTracking:h,permissionMode:g,globalCacheStrategy:_,textContentLength:v,thinkingContentLength:y,toolUseContentLengths:b,fastMode:x,previousRequestId:S,betas:C}){kr();let w=gre();process.argv.includes(`-p`)||process.argv.includes(`--print`);let T=Date.now(),E=Lr();E===null||T-E;let D=Rj();({...t===e?{}:{preNormalizedModel:t},...C?.length?{betas:C.join(`,`)}:{}}),i.input_tokens,i.output_tokens,i.cache_read_input_tokens,i.cache_creation_input_tokens,hst(),uo(),{...D?{invokingRequestId:D.invokingRequestId,invocationKind:D.invocationKind}:{}},process.stdout.isTTY,{...m?{gateway:m}:{},...h?{queryChainId:h.chainId,queryDepth:h.depth}:{}},{..._?{globalCacheStrategy:_}:{},...v===void 0?{}:{textContentLength:v},...y===void 0?{}:{thinkingContentLength:y},...b===void 0?{}:{toolUseContentLengths:W(b)}},{...S?{previousRequestId:S}:{},...w?{isPostCompaction:w}:{},...q7()},Yr(T)}function yst({model:e,preNormalizedModel:t,start:n,startIncludingRetries:r,ttftMs:i,usage:a,attempt:o,messageCount:s,messageTokens:c,requestId:l,stopReason:u,didFallBackToNonStreaming:d,querySource:f,headers:p,costUSD:m,queryTracking:h,permissionMode:g,newMessages:_,llmSpan:v,globalCacheStrategy:y,requestSetupMs:b,attemptStartTimes:x,fastMode:S,previousRequestId:C,betas:w}){let T=mst({headers:p,baseUrl:process.env.ANTHROPIC_BASE_URL}),E,D,O;if(_){let e=0,t=0,n=!1,r={};for(let i of _){let a=Array.isArray(i.message.content)?i.message.content:[];for(let i of a)if(typeof i!=`string`){if(i.type===`text`)e+=i.text.length;else if(i.type===`thinking`)t+=i.thinking.length;else if(i.type===`tool_use`||i.type===`server_tool_use`||i.type===`mcp_tool_use`){let e=W(i.input).length,t=Ys(i.name);r[t]=(r[t]??0)+e,n=!0}}}E=e,D=t>0?t:void 0,O=n?r:void 0}let k=Date.now()-n,A=Date.now()-r;rre(A,k),vst({model:e,preNormalizedModel:t,messageCount:s,messageTokens:c,usage:a,durationMs:k,durationMsIncludingRetries:A,attempt:o,ttftMs:i,requestId:l,stopReason:u,costUSD:m,didFallBackToNonStreaming:d,querySource:f,gateway:T,queryTracking:h,permissionMode:g,globalCacheStrategy:y,textContentLength:E,thinkingContentLength:D,toolUseContentLengths:O,fastMode:S,previousRequestId:C,betas:w}),$s(`api_request`,{model:e,input_tokens:String(a.input_tokens),output_tokens:String(a.output_tokens),cache_read_tokens:String(a.cache_read_input_tokens),cache_creation_tokens:String(a.cache_creation_input_tokens),cost_usd:String(m),duration_ms:String(k),speed:S?`fast`:`normal`});let ee,te;Xs()&&_&&(ee=_.flatMap(e=>{let t=e.message.content;return Array.isArray(t)?t.filter(e=>typeof e!=`string`&&e.type===`text`).map(e=>e.text):[]}).join(`
3275
- `)||void 0,te=_.some(e=>{let t=e.message.content;return Array.isArray(t)?t.some(e=>typeof e!=`string`&&e.type===`tool_use`):!1})),qoe(v,{success:!0,inputTokens:a.input_tokens,outputTokens:a.output_tokens,cacheReadTokens:a.cache_read_input_tokens,cacheCreationTokens:a.cache_creation_input_tokens,attempt:o,modelOutput:ee,thinkingOutput:void 0,hasToolCall:te,ttftMs:i??void 0,requestSetupMs:b,attemptStartTimes:x})}var bst,xst,Sst=n((()=>{hi(),H(),q(),wa(),mo(),Li(),nc(),ec(),Bj(),La(),Qs(),fst(),iD(),LE(),bst={litellm:{prefixes:[`x-litellm-`]},helicone:{prefixes:[`helicone-`]},portkey:{prefixes:[`x-portkey-`]},"cloudflare-ai-gateway":{prefixes:[`cf-aig-`]},kong:{prefixes:[`x-kong-`]},braintrust:{prefixes:[`x-bt-`]}},xst={databricks:[`.cloud.databricks.com`,`.azuredatabricks.net`,`.gcp.databricks.com`]}}));function J7(e){let t=process.env.WORKMATE_EXTRA_BODY,n={};if(t)try{let e=mn(t);e&&typeof e==`object`&&!Array.isArray(e)?n={...e}:K(`WORKMATE_EXTRA_BODY env var must be a JSON object, but was given ${t}`,{level:`error`})}catch(e){K(`Error parsing WORKMATE_EXTRA_BODY: ${G(e)}`,{level:`error`})}if(e&&e.length>0)if(n.anthropic_beta&&Array.isArray(n.anthropic_beta)){let t=n.anthropic_beta,r=e.filter(e=>!t.includes(e));n.anthropic_beta=[...t,...r]}else n.anthropic_beta=e;return n}function Cst(e){return!(h(process.env.DISABLE_PROMPT_CACHING)||h(process.env.DISABLE_PROMPT_CACHING_HAIKU)&&e===zo()||h(process.env.DISABLE_PROMPT_CACHING_SONNET)&&e===Po()||h(process.env.DISABLE_PROMPT_CACHING_OPUS)&&e===kie())}function Y7({scope:e,querySource:t}={}){return{type:`ephemeral`,...wst(t)&&{ttl:`1h`},...e===`global`&&{scope:e}}}function wst(e){if(lo()===`bedrock`&&h(process.env.ENABLE_PROMPT_CACHING_1H_BEDROCK))return!0;let t=vne();if(t===null&&(t=!1,are(t)),!t)return!1;let n=Lne();return n===null&&(n={}.allowlist??[],hne(n)),e!==void 0&&n.some(t=>t.endsWith(`*`)?e.startsWith(t.slice(0,-1)):e===t)}function Tst(e,t,n){!e||`task_budget`in t||!Lg()||(t.task_budget={type:`tokens`,total:e.total,...e.remaining!==void 0&&{remaining:e.remaining}},n.includes(`task-budgets-2026-03-13`)||n.push(Cie))}function X7(){let e={},t=process.env.WORKMATE_EXTRA_METADATA;if(t){let n=mn(t,!1);n&&typeof n==`object`&&!Array.isArray(n)?e=n:K(`WORKMATE_EXTRA_METADATA env var must be a JSON object, but was given ${t}`,{level:`error`})}return{user_id:W({...e,device_id:Yre(),account_uuid:``,session_id:Wr()})}}function Est(e,t=!1,n,r){return t?typeof e.message.content==`string`?{role:`user`,content:[{type:`text`,text:e.message.content,...n&&{cache_control:Y7({querySource:r})}}]}:{role:`user`,content:e.message.content.map((t,i)=>({...t,...i===e.message.content.length-1&&n?{cache_control:Y7({querySource:r})}:{}}))}:{role:`user`,content:Array.isArray(e.message.content)?[...e.message.content]:e.message.content}}function Dst(e,t=!1,n,r){return t?typeof e.message.content==`string`?{role:`assistant`,content:[{type:`text`,text:e.message.content,...n&&{cache_control:Y7({querySource:r})}}]}:{role:`assistant`,content:e.message.content.map((t,i)=>{let a=Ost(t);return{...a,...i===e.message.content.length-1&&a.type!==`thinking`&&a.type!==`redacted_thinking`&&!Zu(a)&&n?{cache_control:Y7({querySource:r})}:{}}})}:{role:`assistant`,content:typeof e.message.content==`string`?e.message.content:e.message.content.map(Ost)}}function Ost(e){if(typeof e==`string`||!(`_geminiThoughtSignature`in e))return e;let{_geminiThoughtSignature:t,...n}=e;return n}async function Z7({messages:e,systemPrompt:t,thinkingConfig:n,tools:r,signal:i,options:a}){let o;for await(let s of Het(e,async function*(){yield*Fst(e,t,n,r,i,a)}))s.type===`assistant`&&(o=s);if(!o)throw i.aborted?new Ti:Error(`No assistant message found`);return o}async function*kst({messages:e,systemPrompt:t,thinkingConfig:n,tools:r,signal:i,options:a}){return yield*Het(e,async function*(){yield*Fst(e,t,n,r,i,a)})}function Ast(){return parseInt(process.env.API_TIMEOUT_MS||``,10)||(h(process.env.WORKMATE_REMOTE)?12e4:3e5)}async function*jst(e,t,n,r,i,a){let o=Ast(),s=sD(()=>Bo({maxRetries:0,model:e.model,fetchOverride:e.fetchOverride,source:e.source}),async(a,s,c)=>{let l=Date.now(),u=n(c);i(u),r(s,l,u.max_tokens);let d=Vst(u,Ust);try{return await a.beta.messages.create({...d,model:_o(d.model)},{signal:t.signal,timeout:o})}catch(t){throw t instanceof Ti?t:(Cn(`error`,`cli_nonstreaming_fallback_error`),e.model,t instanceof Error&&t.name,t)}},{model:t.model,fallbackModel:t.fallbackModel,thinkingConfig:t.thinkingConfig,...Jf()&&{fastMode:t.fastMode},signal:t.signal,initialConsecutive529Errors:t.initialConsecutive529Errors,querySource:t.querySource}),c;do c=await s.next(),!c.done&&c.value.type===`system`&&(yield c.value);while(!c.done);return c.value}function Mst(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.type===`assistant`&&n.requestId)return n.requestId}}function Q7(e){return e.type===`image`||e.type===`document`}function Nst(e){return e.type===`tool_result`}function Pst(e,t){let n=0;for(let t of e)if(Array.isArray(t.message.content)){for(let e of t.message.content)if(Q7(e)&&n++,Nst(e)&&Array.isArray(e.content))for(let t of e.content)Q7(t)&&n++}return n-=t,n<=0?e:e.map(e=>{if(n<=0)return e;let t=e.message.content;if(!Array.isArray(t))return e;let r=n,i=t.map(e=>{if(n<=0||!Nst(e)||!Array.isArray(e.content))return e;let t=e.content.filter(e=>n>0&&Q7(e)?(n--,!1):!0);return t.length===e.content.length?e:{...e,content:t}}).filter(e=>n>0&&Q7(e)?(n--,!1):!0);return r===n?e:{...e,message:{...e.message,content:i}}})}async function*Fst(e,t,n,r,i,a){let o=Mst(e),s=lo()===`bedrock`&&a.model.includes(`application-inference-profile`)?await co(a.model)??a.model:a.model;F1(`query_tool_schema_build_start`);let c=a.querySource.startsWith(`repl_main_thread`)||a.querySource.startsWith(`agent:`)||a.querySource===`sdk`||a.querySource===`hook_agent`||a.querySource===`verification_agent`,l=zg(a.model,{isAgenticQuery:c});qg()&&l.push(Mie);let u;if(c&&qg()){let e=a.advisorModel,t=Npe();if(t!==void 0&&_o(t.baseModel)===_o(a.model)&&(e=t.advisorModel),e){let t=_o(Vo(e));Yg(a.model)?Xg(t)?(u=t,K(`[AdvisorTool] Server-side tool enabled with ${u} as the advisor model`)):K(`[AdvisorTool] Skipping advisor - ${t} is not a valid advisor model`):K(`[AdvisorTool] Skipping advisor - base model ${a.model} does not support advisor`)}}let d=await UO(a.model,r,a.getToolPermissionContext,a.agents,`query`),f=new Set;if(d)for(let e of r)vs(e)&&f.add(e.name);d&&f.size===0&&!a.hasPendingMcpServers&&(K(`Tool search disabled: no deferred tools available to search`),d=!1);let p;p=d?r.filter(e=>!!(!f.has(e.name)||us(e,`SearchExtraTools`))):r.filter(e=>!us(e,Ss));let m=Rg(),g=m&&p.some(e=>e.isMcp===!0);m&&!l.includes(`prompt-caching-scope-2026-01-05`)&&l.push(ho);let _=m?g?`none`:`system_prompt`:`none`,v=await Promise.all(p.map(e=>H7(e,{getToolPermissionContext:a.getToolPermissionContext,tools:r,agents:a.agents,allowedAgentTypes:a.allowedAgentTypes,model:a.model})));d&&K(`Dynamic tool loading: 0/${f.size} deferred tools in API tools array (all via ExecuteExtraTool)`),F1(`query_tool_schema_build_end`),e.length,F1(`query_message_normalization_start`);let y=d3(e,p);if(F1(`query_message_normalization_end`),d||(y=y.map(e=>{switch(e.type){case`user`:return P9e(e);case`assistant`:return F9e(e);default:return e}})),y=V9e(y),l.includes(`advisor-tool-2026-03-01`)||(y=H9e(y)),y=Pst(y,100),lo()===`openai`){let{queryModelOpenAI:e}=await import(`./openai-BoYbxtOG.js`);yield*e(y,t,r,i,a);return}if(lo()===`gemini`){let{queryModelGemini:e}=await import(`./gemini-BzN-GtAf.js`);yield*e(y,t,p,i,a,n);return}if(lo()===`grok`){let{queryModelGrok:e}=await import(`./grok-jsEI7sLT.js`);yield*e(y,t,p,i,a);return}if(y.length,d&&!KO()){let e=r.filter(e=>f.has(e.name)).map(Jae).sort().join(`
3274
+ IMPORTANT: this context may or may not be relevant to your tasks. You should not respond to this context unless it is highly relevant to your task.\n</system-reminder>\n`,isMeta:!0})),[...i,...e]}async function tst(e,t){if(Got())return;let[{tools:n},r,i,a]=await Promise.all([CVe(e),O1(t),pO(),fO()]);(a.gitStatus?.length??0)+(i.agentsMd?.length??0);let o=U(),s=k8(A8(t),o);await Toe(o,AbortSignal.timeout(1e3),s);let c=0,l=0,u=r.filter(e=>!e.isMcp);n.length,u.length;let d=new Set;for(let e of n){let t=e.name.split(`__`);t.length>=3&&t[1]&&d.add(t[1])}d.size;for(let e of n){let t=`inputJSONSchema`in e&&e.inputJSONSchema?e.inputJSONSchema:NO(e.inputSchema);c+=C3(W(t))}for(let e of u){let t=`inputJSONSchema`in e&&e.inputJSONSchema?e.inputJSONSchema:NO(e.inputSchema);l+=C3(W(t))}}function nst(e,t,n){switch(e.name){case es:{let e=Ad(n),r=kd(n);return Md(),e===null?t:{...t,plan:e,planFilePath:r}}case dB.name:{let e=dB.inputSchema.parse(t),{command:n,timeout:r,description:i}=e,a=U(),o=n.replace(`cd ${a} && `,``);Ma()===`windows`&&(o=o.replace(`cd ${Vt(a)} && `,``)),o=o.replace(/\\\\;/g,`\\;`),/^echo\s+["']?[^|&;><]*["']?$/i.test(o.trim());let s=`run_in_background`in e?e.run_in_background:void 0;return{command:o,description:i,...r!==void 0&&{timeout:r},...i!==void 0&&{description:i},...s!==void 0&&{run_in_background:s},...`dangerouslyDisableSandbox`in e&&e.dangerouslyDisableSandbox!==void 0&&{dangerouslyDisableSandbox:e.dangerouslyDisableSandbox}}}case RX.name:{let e=RX.inputSchema.parse(t),{file_path:n,edits:r}=fCe({file_path:e.file_path,edits:[{old_string:e.old_string,new_string:e.new_string,replace_all:e.replace_all}]});return{replace_all:r[0].replace_all,file_path:n,old_string:r[0].old_string,new_string:r[0].new_string}}case HI.name:{let e=HI.inputSchema.parse(t),n=/\.(md|mdx)$/i.test(e.file_path);return{file_path:e.file_path,content:n?e.content:kw(e.content)}}case Yt:{let e=t,n=e.task_id??e.agentId??e.bash_id,r=e.timeout??(typeof e.wait_up_to==`number`?e.wait_up_to*1e3:void 0);return{task_id:n??``,block:e.block??!0,timeout:r??3e4}}default:return t}}function rst(e,t){switch(e.name){case es:if(t&&typeof t==`object`&&(`plan`in t||`planFilePath`in t)){let{plan:e,planFilePath:n,...r}=t;return r}return t;case RX.name:if(t&&typeof t==`object`&&`edits`in t){let{old_string:e,new_string:n,replace_all:r,...i}=t;return i}return t;default:return t}}var U7,W7=n((()=>{V7(),mO(),Kot(),La(),wY(),fB(),zX(),Fw(),UI(),k1(),Xu(),O3(),Ds(),gt(),Wg(),ui(),q(),g(),v3(),mo(),B8(),Fd(),Pa(),Gs(),Li(),Yot(),ht(),FO(),U7=!1}));function ist(e){let{hasThinking:t=!1,isRedactThinkingActive:n=!1,clearAllThinking:r=!1}=e??{},i=[];t&&!n&&i.push({type:`clear_thinking_20251015`,keep:r?{type:`thinking_turns`,value:1}:`all`});let a=process.env.USE_API_CLEAR_TOOL_RESULTS===void 0||h(process.env.USE_API_CLEAR_TOOL_RESULTS),o=h(process.env.USE_API_CLEAR_TOOL_USES);if(!a&&!o)return i.length>0?{edits:i}:void 0;if(a){let e=process.env.API_MAX_INPUT_TOKENS?parseInt(process.env.API_MAX_INPUT_TOKENS,10):G7,t=process.env.API_TARGET_INPUT_TOKENS?parseInt(process.env.API_TARGET_INPUT_TOKENS,10):K7,n={type:`clear_tool_uses_20250919`,trigger:{type:`input_tokens`,value:e},clear_at_least:{type:`input_tokens`,value:e-t},clear_tool_inputs:ast};i.push(n)}if(o){let e=process.env.API_MAX_INPUT_TOKENS?parseInt(process.env.API_MAX_INPUT_TOKENS,10):G7,t=process.env.API_TARGET_INPUT_TOKENS?parseInt(process.env.API_TARGET_INPUT_TOKENS,10):K7,n={type:`clear_tool_uses_20250919`,trigger:{type:`input_tokens`,value:e},clear_at_least:{type:`input_tokens`,value:e-t},exclude_tools:ost};i.push(n)}return i.length>0?{edits:i}:void 0}var G7,K7,ast,ost,sst=n((()=>{Es(),As(),Is(),Jo(),Go(),hs(),Ps(),g(),G7=18e4,K7=4e4,ast=[...wae,Yo,ts,os],ost=[xs,ss,_s]})),cst,lst=n((()=>{cst={providerId:`bedrock`,parseHeaders(e){let t=[],n=e.get(`x-amzn-bedrock-quota-remaining`),r=e.get(`x-amzn-bedrock-quota-reset`);if(n!==null){let e=Number(n);if(Number.isFinite(e)&&e>=0&&e<=1){let n=r===null?0:Number(r);t.push({kind:`throttle`,label:`Throttle`,utilization:1-e,...Number.isFinite(n)&&n>0?{resetsAt:n}:{}})}}return t}}}));function ust(e,t){let n=-1;for(let t=0;t<e.length;t++){let r=e[t];r&&typeof r==`object`&&`type`in r&&r.type===`tool_result`&&(n=t)}if(n>=0){let r=n+1;e.splice(r,0,t),r===e.length-1&&e.push({type:`text`,text:`.`})}else{let n=Math.max(0,e.length-1);e.splice(n,0,t)}}var dst=n((()=>{})),fst=n((()=>{E_()}));function pst(e){if(e instanceof _i){let t=e.error;if(t?.error?.message)return t.error.message}return e instanceof Error?e.message:String(e)}function mst({headers:e,baseUrl:t}){if(e){let t=[];e.forEach((e,n)=>t.push(n));for(let[e,{prefixes:n}]of Object.entries(bst))if(n.some(e=>t.some(t=>t.startsWith(e))))return e}if(t)try{let e=new URL(t).hostname.toLowerCase();for(let[t,n]of Object.entries(xst))if(n.some(t=>e.endsWith(t)))return t}catch{}}function q7(){return{...process.env.ANTHROPIC_BASE_URL?{baseUrl:process.env.ANTHROPIC_BASE_URL}:{},...process.env.ANTHROPIC_MODEL?{envModel:process.env.ANTHROPIC_MODEL}:{},...process.env.ANTHROPIC_SMALL_FAST_MODEL?{envSmallFastModel:process.env.ANTHROPIC_SMALL_FAST_MODEL}:{}}}function hst(){let e=new Date(`2026-10-30T05:16:57.659Z`).getTime();if(!isNaN(e))return Math.floor((Date.now()-e)/6e4)}function gst({model:e,messagesLength:t,temperature:n,betas:r,permissionMode:i,querySource:a,queryTracking:o,thinkingConfig:s,fastMode:c,previousRequestId:l}){s?.type;let u=s?.type===`enabled`?s.budgetTokens:void 0;uo(),hst(),{...r?.length?{betas:r.join(`,`)}:{}},{...o?{queryChainId:o.chainId,queryDepth:o.depth}:{}},{...u!==void 0&&{thinkingBudgetTokens:u}},{...l?{previousRequestId:l}:{},...q7()}}function _st({error:e,model:t,messageCount:n,messageTokens:r,durationMs:i,durationMsIncludingRetries:a,attempt:o,requestId:s,clientRequestId:c,didFallBackToNonStreaming:l,promptCategory:u,headers:d,queryTracking:f,querySource:p,llmSpan:m,fastMode:h,previousRequestId:g}){let _=mst({headers:e instanceof _i&&e.headers?e.headers:d,baseUrl:process.env.ANTHROPIC_BASE_URL}),v=pst(e),y=e instanceof _i?String(e.status):void 0;swe(e);let b=S_(e);if(b){let e=b.isSSLError?` (SSL error)`:``;K(`Connection error details: code=${b.code}${e}, message=${b.message}`,{level:`error`})}let x=Rj();c&&K(`API error x-client-request-id=${c} (give this to the API team for server-log lookup)`,{level:`error`}),Y(e),uo(),{...x?{invokingRequestId:x.invokingRequestId,invocationKind:x.invocationKind}:{}},{...u?{promptCategory:u}:{},..._?{gateway:_}:{},...f?{queryChainId:f.chainId,queryDepth:f.depth}:{},...p?{querySource:p}:{}},{...g?{previousRequestId:g}:{},...q7()},$s(`api_error`,{model:t,error:v,status_code:String(y),duration_ms:String(i),attempt:String(o),speed:h?`fast`:`normal`}),qoe(m,{success:!1,statusCode:y?parseInt(y,10):void 0,error:v,attempt:o})}function vst({model:e,preNormalizedModel:t,messageCount:n,messageTokens:r,usage:i,durationMs:a,durationMsIncludingRetries:o,attempt:s,ttftMs:c,requestId:l,stopReason:u,costUSD:d,didFallBackToNonStreaming:f,querySource:p,gateway:m,queryTracking:h,permissionMode:g,globalCacheStrategy:_,textContentLength:v,thinkingContentLength:y,toolUseContentLengths:b,fastMode:x,previousRequestId:S,betas:C}){kr();let w=gre();process.argv.includes(`-p`)||process.argv.includes(`--print`);let T=Date.now(),E=Lr();E===null||T-E;let D=Rj();({...t===e?{}:{preNormalizedModel:t},...C?.length?{betas:C.join(`,`)}:{}}),i.input_tokens,i.output_tokens,i.cache_read_input_tokens,i.cache_creation_input_tokens,hst(),uo(),{...D?{invokingRequestId:D.invokingRequestId,invocationKind:D.invocationKind}:{}},process.stdout.isTTY,{...m?{gateway:m}:{},...h?{queryChainId:h.chainId,queryDepth:h.depth}:{}},{..._?{globalCacheStrategy:_}:{},...v===void 0?{}:{textContentLength:v},...y===void 0?{}:{thinkingContentLength:y},...b===void 0?{}:{toolUseContentLengths:W(b)}},{...S?{previousRequestId:S}:{},...w?{isPostCompaction:w}:{},...q7()},Yr(T)}function yst({model:e,preNormalizedModel:t,start:n,startIncludingRetries:r,ttftMs:i,usage:a,attempt:o,messageCount:s,messageTokens:c,requestId:l,stopReason:u,didFallBackToNonStreaming:d,querySource:f,headers:p,costUSD:m,queryTracking:h,permissionMode:g,newMessages:_,llmSpan:v,globalCacheStrategy:y,requestSetupMs:b,attemptStartTimes:x,fastMode:S,previousRequestId:C,betas:w}){let T=mst({headers:p,baseUrl:process.env.ANTHROPIC_BASE_URL}),E,D,O;if(_){let e=0,t=0,n=!1,r={};for(let i of _){let a=Array.isArray(i.message.content)?i.message.content:[];for(let i of a)if(typeof i!=`string`){if(i.type===`text`)e+=i.text.length;else if(i.type===`thinking`)t+=i.thinking.length;else if(i.type===`tool_use`||i.type===`server_tool_use`||i.type===`mcp_tool_use`){let e=W(i.input).length,t=Ys(i.name);r[t]=(r[t]??0)+e,n=!0}}}E=e,D=t>0?t:void 0,O=n?r:void 0}let k=Date.now()-n,A=Date.now()-r;rre(A,k),vst({model:e,preNormalizedModel:t,messageCount:s,messageTokens:c,usage:a,durationMs:k,durationMsIncludingRetries:A,attempt:o,ttftMs:i,requestId:l,stopReason:u,costUSD:m,didFallBackToNonStreaming:d,querySource:f,gateway:T,queryTracking:h,permissionMode:g,globalCacheStrategy:y,textContentLength:E,thinkingContentLength:D,toolUseContentLengths:O,fastMode:S,previousRequestId:C,betas:w}),$s(`api_request`,{model:e,input_tokens:String(a.input_tokens),output_tokens:String(a.output_tokens),cache_read_tokens:String(a.cache_read_input_tokens),cache_creation_tokens:String(a.cache_creation_input_tokens),cost_usd:String(m),duration_ms:String(k),speed:S?`fast`:`normal`});let ee,te;Xs()&&_&&(ee=_.flatMap(e=>{let t=e.message.content;return Array.isArray(t)?t.filter(e=>typeof e!=`string`&&e.type===`text`).map(e=>e.text):[]}).join(`
3275
+ `)||void 0,te=_.some(e=>{let t=e.message.content;return Array.isArray(t)?t.some(e=>typeof e!=`string`&&e.type===`tool_use`):!1})),qoe(v,{success:!0,inputTokens:a.input_tokens,outputTokens:a.output_tokens,cacheReadTokens:a.cache_read_input_tokens,cacheCreationTokens:a.cache_creation_input_tokens,attempt:o,modelOutput:ee,thinkingOutput:void 0,hasToolCall:te,ttftMs:i??void 0,requestSetupMs:b,attemptStartTimes:x})}var bst,xst,Sst=n((()=>{hi(),H(),q(),wa(),mo(),Li(),nc(),ec(),Bj(),La(),Qs(),fst(),iD(),LE(),bst={litellm:{prefixes:[`x-litellm-`]},helicone:{prefixes:[`helicone-`]},portkey:{prefixes:[`x-portkey-`]},"cloudflare-ai-gateway":{prefixes:[`cf-aig-`]},kong:{prefixes:[`x-kong-`]},braintrust:{prefixes:[`x-bt-`]}},xst={databricks:[`.cloud.databricks.com`,`.azuredatabricks.net`,`.gcp.databricks.com`]}}));function J7(e){let t=process.env.WORKMATE_EXTRA_BODY,n={};if(t)try{let e=mn(t);e&&typeof e==`object`&&!Array.isArray(e)?n={...e}:K(`WORKMATE_EXTRA_BODY env var must be a JSON object, but was given ${t}`,{level:`error`})}catch(e){K(`Error parsing WORKMATE_EXTRA_BODY: ${G(e)}`,{level:`error`})}if(e&&e.length>0)if(n.anthropic_beta&&Array.isArray(n.anthropic_beta)){let t=n.anthropic_beta,r=e.filter(e=>!t.includes(e));n.anthropic_beta=[...t,...r]}else n.anthropic_beta=e;return n}function Cst(e){return!(h(process.env.DISABLE_PROMPT_CACHING)||h(process.env.DISABLE_PROMPT_CACHING_HAIKU)&&e===zo()||h(process.env.DISABLE_PROMPT_CACHING_SONNET)&&e===Po()||h(process.env.DISABLE_PROMPT_CACHING_OPUS)&&e===kie())}function Y7({scope:e,querySource:t}={}){return{type:`ephemeral`,...wst(t)&&{ttl:`1h`},...e===`global`&&{scope:e}}}function wst(e){if(lo()===`bedrock`&&h(process.env.ENABLE_PROMPT_CACHING_1H_BEDROCK))return!0;let t=vne();if(t===null&&(t=!1,are(t)),!t)return!1;let n=Lne();return n===null&&(n={}.allowlist??[],hne(n)),e!==void 0&&n.some(t=>t.endsWith(`*`)?e.startsWith(t.slice(0,-1)):e===t)}function Tst(e,t,n){!e||`task_budget`in t||!Lg()||(t.task_budget={type:`tokens`,total:e.total,...e.remaining!==void 0&&{remaining:e.remaining}},n.includes(`task-budgets-2026-03-13`)||n.push(Cie))}function X7(){let e={},t=process.env.WORKMATE_EXTRA_METADATA;if(t){let n=mn(t,!1);n&&typeof n==`object`&&!Array.isArray(n)?e=n:K(`WORKMATE_EXTRA_METADATA env var must be a JSON object, but was given ${t}`,{level:`error`})}return{user_id:W({...e,device_id:Yre(),account_uuid:``,session_id:Wr()})}}function Est(e,t=!1,n,r){return t?typeof e.message.content==`string`?{role:`user`,content:[{type:`text`,text:e.message.content,...n&&{cache_control:Y7({querySource:r})}}]}:{role:`user`,content:e.message.content.map((t,i)=>({...t,...i===e.message.content.length-1&&n?{cache_control:Y7({querySource:r})}:{}}))}:{role:`user`,content:Array.isArray(e.message.content)?[...e.message.content]:e.message.content}}function Dst(e,t=!1,n,r){return t?typeof e.message.content==`string`?{role:`assistant`,content:[{type:`text`,text:e.message.content,...n&&{cache_control:Y7({querySource:r})}}]}:{role:`assistant`,content:e.message.content.map((t,i)=>{let a=Ost(t);return{...a,...i===e.message.content.length-1&&a.type!==`thinking`&&a.type!==`redacted_thinking`&&!Zu(a)&&n?{cache_control:Y7({querySource:r})}:{}}})}:{role:`assistant`,content:typeof e.message.content==`string`?e.message.content:e.message.content.map(Ost)}}function Ost(e){if(typeof e==`string`||!(`_geminiThoughtSignature`in e))return e;let{_geminiThoughtSignature:t,...n}=e;return n}async function Z7({messages:e,systemPrompt:t,thinkingConfig:n,tools:r,signal:i,options:a}){let o;for await(let s of Het(e,async function*(){yield*Fst(e,t,n,r,i,a)}))s.type===`assistant`&&(o=s);if(!o)throw i.aborted?new Ti:Error(`No assistant message found`);return o}async function*kst({messages:e,systemPrompt:t,thinkingConfig:n,tools:r,signal:i,options:a}){return yield*Het(e,async function*(){yield*Fst(e,t,n,r,i,a)})}function Ast(){return parseInt(process.env.API_TIMEOUT_MS||``,10)||(h(process.env.WORKMATE_REMOTE)?12e4:3e5)}async function*jst(e,t,n,r,i,a){let o=Ast(),s=sD(()=>Bo({maxRetries:0,model:e.model,fetchOverride:e.fetchOverride,source:e.source}),async(a,s,c)=>{let l=Date.now(),u=n(c);i(u),r(s,l,u.max_tokens);let d=Vst(u,Ust);try{return await a.beta.messages.create({...d,model:_o(d.model)},{signal:t.signal,timeout:o})}catch(t){throw t instanceof Ti?t:(Cn(`error`,`cli_nonstreaming_fallback_error`),e.model,t instanceof Error&&t.name,t)}},{model:t.model,fallbackModel:t.fallbackModel,thinkingConfig:t.thinkingConfig,...Jf()&&{fastMode:t.fastMode},signal:t.signal,initialConsecutive529Errors:t.initialConsecutive529Errors,querySource:t.querySource}),c;do c=await s.next(),!c.done&&c.value.type===`system`&&(yield c.value);while(!c.done);return c.value}function Mst(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.type===`assistant`&&n.requestId)return n.requestId}}function Q7(e){return e.type===`image`||e.type===`document`}function Nst(e){return e.type===`tool_result`}function Pst(e,t){let n=0;for(let t of e)if(Array.isArray(t.message.content)){for(let e of t.message.content)if(Q7(e)&&n++,Nst(e)&&Array.isArray(e.content))for(let t of e.content)Q7(t)&&n++}return n-=t,n<=0?e:e.map(e=>{if(n<=0)return e;let t=e.message.content;if(!Array.isArray(t))return e;let r=n,i=t.map(e=>{if(n<=0||!Nst(e)||!Array.isArray(e.content))return e;let t=e.content.filter(e=>n>0&&Q7(e)?(n--,!1):!0);return t.length===e.content.length?e:{...e,content:t}}).filter(e=>n>0&&Q7(e)?(n--,!1):!0);return r===n?e:{...e,message:{...e.message,content:i}}})}async function*Fst(e,t,n,r,i,a){let o=Mst(e),s=lo()===`bedrock`&&a.model.includes(`application-inference-profile`)?await co(a.model)??a.model:a.model;F1(`query_tool_schema_build_start`);let c=a.querySource.startsWith(`repl_main_thread`)||a.querySource.startsWith(`agent:`)||a.querySource===`sdk`||a.querySource===`hook_agent`||a.querySource===`verification_agent`,l=zg(a.model,{isAgenticQuery:c});qg()&&l.push(Mie);let u;if(c&&qg()){let e=a.advisorModel,t=Npe();if(t!==void 0&&_o(t.baseModel)===_o(a.model)&&(e=t.advisorModel),e){let t=_o(Vo(e));Yg(a.model)?Xg(t)?(u=t,K(`[AdvisorTool] Server-side tool enabled with ${u} as the advisor model`)):K(`[AdvisorTool] Skipping advisor - ${t} is not a valid advisor model`):K(`[AdvisorTool] Skipping advisor - base model ${a.model} does not support advisor`)}}let d=await UO(a.model,r,a.getToolPermissionContext,a.agents,`query`),f=new Set;if(d)for(let e of r)vs(e)&&f.add(e.name);d&&f.size===0&&!a.hasPendingMcpServers&&(K(`Tool search disabled: no deferred tools available to search`),d=!1);let p;p=d?r.filter(e=>!!(!f.has(e.name)||us(e,`SearchExtraTools`))):r.filter(e=>!us(e,Ss));let m=Rg(),g=m&&p.some(e=>e.isMcp===!0);m&&!l.includes(`prompt-caching-scope-2026-01-05`)&&l.push(ho);let _=m?g?`none`:`system_prompt`:`none`,v=await Promise.all(p.map(e=>H7(e,{getToolPermissionContext:a.getToolPermissionContext,tools:r,agents:a.agents,allowedAgentTypes:a.allowedAgentTypes,model:a.model})));d&&K(`Dynamic tool loading: 0/${f.size} deferred tools in API tools array (all via ExecuteExtraTool)`),F1(`query_tool_schema_build_end`),e.length,F1(`query_message_normalization_start`);let y=d3(e,p);if(F1(`query_message_normalization_end`),d||(y=y.map(e=>{switch(e.type){case`user`:return P9e(e);case`assistant`:return F9e(e);default:return e}})),y=V9e(y),l.includes(`advisor-tool-2026-03-01`)||(y=H9e(y)),y=Pst(y,100),lo()===`openai`){let{queryModelOpenAI:e}=await import(`./openai-BbDLbcxR.js`);yield*e(y,t,r,i,a);return}if(lo()===`gemini`){let{queryModelGemini:e}=await import(`./gemini-DsQxIwTq.js`);yield*e(y,t,p,i,a,n);return}if(lo()===`grok`){let{queryModelGrok:e}=await import(`./grok-DIsSHEKU.js`);yield*e(y,t,p,i,a);return}if(y.length,d&&!KO()){let e=r.filter(e=>f.has(e.name)).map(Jae).sort().join(`
3276
3276
  `);if(e){let t=new Set(e.split(`
3277
3277
  `));if([...t].some(e=>!n9.has(e))){n9.clear();for(let e of t)n9.add(e);y=[...y,Q({content:`<system-reminder>\n<available-deferred-tools>\n${e}\n</available-deferred-tools>\nIMPORTANT: The tools listed above are deferred-loading — they are NOT in your tool list. To use them, you MUST first discover a tool via SearchExtraTools, then invoke it with ExecuteExtraTool.\n\nSearchExtraTools and ExecuteExtraTool are core tools already in your tool list right now — call them directly, do NOT use Bash/Glob to find them.\n\nSteps:\n1. SearchExtraTools({"query": "select:<tool_name>"}) — discover the tool and its schema\n2. ExecuteExtraTool({"tool_name": "<name>", "params": {...}}) — invoke it with correct parameters\n</system-reminder>`,isMeta:!0})]}}}t=t_([Wu(),Uu({isNonInteractive:a.isNonInteractiveSession,hasAppendSystemPrompt:a.hasAppendSystemPrompt}),...t,...u?[Zg]:[]].filter(Boolean));{let e=moe(),n=hoe();if(jc(e)||jc(n)){let n=Lc();if(t=t_([...t,`<!-- cache-break nonce: ${n} -->`]),jc(e))try{$se(e)}catch{}}}Zot(t);let b=a.enablePromptCaching??Cst(a.model),x=Bst(t,b,{skipGlobalCacheForSystemPrompt:g,querySource:a.querySource}),S=l.length>0,C=[...a.extraToolSchemas??[]];u&&C.push({type:`advisor_20260301`,name:`advisor`,model:u});let w=[...v,...C],T=Jf()&&Yf()&&!$f()&&Zf(a.model)&&!!a.fastMode,E=Qne()===!0;!E&&c&&Lg()&&kT()&&(E=!0,une(!0));let D=nne()===!0;!D&&T&&(D=!0,wre(!0));let O=Wne()===!0;UIe({system:x,toolSchemas:w.filter(e=>!(`defer_loading`in e&&e.defer_loading)),querySource:a.querySource,model:a.model,agentId:a.agentId,fastMode:D,globalCacheStrategy:_,betas:l,autoModeActive:E,isUsingOverage:u0.isUsingOverage??!1,cachedMCEnabled:O,extraBodyParams:J7()});let k=Xs()?{systemPrompt:t.join(`
3278
3278